import ServerError from"./error.mjs";import Activity from"../components/activity.mjs";import Files from"../files/files.mjs";import sessions from"../sessions.mjs";import ProseMirrorAuthority from"../components/prosemirror.mjs";import Document from"../../common/abstract/document.mjs";import{isSubclass}from"../../common/utils/helpers.mjs";export async function handleEvent(e,t,s,o){const r=this.user;if(!r)throw new Error(`Unrecognized User attacked to socket ${this.id} for event ${e}`);let i;s.options=s.options||{};let n={userId:r?.id,request:s};try{n.result=await t(r,s),i=s.broadcast??!0}catch(e){e=new ServerError(e.message,e.stack),logger.error(e),n.error=e,i=!1}return o?(o(n),i&&this.broadcast.emit(e,n)):i&&this.server.emit(e,n),n}export function handleCustomSocket(e,t,{recipients:s}={},o){if(s instanceof Array)for(let o of s){const s=game.users.find((e=>e.id===o));if(s)for(let o of s.sockets)o.emit(e,t,this.user.id)}else this.broadcast.emit(e,t,this.user.id);o instanceof Function&&o()}export function handleMigrateDocumentData(e,t,s){const o=global.db[e];if(isSubclass(o,Document))if("object"==typeof t)try{s({source:o.fromImport(t).toObject()})}catch(e){s({error:e.message})}else s({error:'Invalid Document data provided to "migrateDocumentData" operation'});else s({error:`Invalid Document name "${e}" provided to "migrateDocumentData" operation`})}export async function activate(e,t){const s=e.handshake.query,o={sessionId:null,userId:null},r=sessions.sessions.get(s.session);if(!r)return e.emit("session",null);if(e.session=r,o.sessionId=r.id,game.world&&game.ready){const t=r.worlds[game.world.id],s=game.users.find((e=>e.id===t));s?(e.user=s,e.userId=o.userId=s.id):delete r.worlds[game.world.id]}e.emit("session",o);for(const s of t)s.socket&&e.on(s.socket,(e=>s.handleSocket(r,e)));e.on("getWorldStatus",requestWorldState),Files.socketListeners(e,handleEvent),o.userId&&(Activity.socketListeners(e),e.on("chatBubble",handleCustomSocket.bind(e,"chatBubble")),e.on("av",handleCustomSocket.bind(e,"av")),ProseMirrorAuthority.socketListeners(e),db.DatabaseBackend.socketListeners(e),db.Scene.socketListeners(e),db.JournalEntry.socketListeners(e),db.Playlist.socketListeners(e),db.FogExploration.socketListeners(e),db.Actor.socketListeners(e),db.Region.socketListeners(e),packages.World.socketListeners(e,handleEvent),e.on("migrateDocumentData",handleMigrateDocumentData))}function requestWorldState(e){return e(game.world&&game.ready)}