@colyseus/core 0.18.18 → 0.18.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/Room.cjs +4 -4
- package/build/Room.cjs.map +2 -2
- package/build/Room.mjs +4 -4
- package/build/Room.mjs.map +2 -2
- package/build/RoomPlugin.cjs +34 -17
- package/build/RoomPlugin.cjs.map +2 -2
- package/build/RoomPlugin.mjs +34 -17
- package/build/RoomPlugin.mjs.map +2 -2
- package/package.json +6 -6
- package/src/Room.ts +8 -8
- package/src/RoomPlugin.ts +46 -21
package/build/RoomPlugin.cjs
CHANGED
|
@@ -170,29 +170,46 @@ function installPluginHookWrappers(ctor, layout) {
|
|
|
170
170
|
if (before.length === 0 && after.length === 0) {
|
|
171
171
|
continue;
|
|
172
172
|
}
|
|
173
|
-
|
|
174
|
-
proto[hook] = async function(...args) {
|
|
175
|
-
const lookup = (k) => k.startsWith(DEP_KEY_PREFIX) ? this._autoPlugins[k] : this.plugins[k];
|
|
176
|
-
for (const k of before) {
|
|
177
|
-
const p = lookup(k);
|
|
178
|
-
await p[hook].call(p, ...args);
|
|
179
|
-
}
|
|
180
|
-
let result;
|
|
181
|
-
if (original) {
|
|
182
|
-
result = await original.apply(this, args);
|
|
183
|
-
}
|
|
184
|
-
for (const k of after) {
|
|
185
|
-
const p = lookup(k);
|
|
186
|
-
await p[hook].call(p, ...args);
|
|
187
|
-
}
|
|
188
|
-
return result;
|
|
189
|
-
};
|
|
173
|
+
proto[hook] = composePluginHook(hook, before, after, proto[hook]);
|
|
190
174
|
}
|
|
191
175
|
}
|
|
176
|
+
function wrapOwnHooks(room, layout) {
|
|
177
|
+
for (const hook of PLUGIN_LIFECYCLE_KEYS) {
|
|
178
|
+
const { before, after } = layout.hooks[hook];
|
|
179
|
+
if (before.length === 0 && after.length === 0) {
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
if (!Object.hasOwn(room, hook)) {
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
room[hook] = composePluginHook(hook, before, after, room[hook]);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
function composePluginHook(hook, before, after, original) {
|
|
189
|
+
return async function(...args) {
|
|
190
|
+
const lookup = (k) => k.startsWith(DEP_KEY_PREFIX) ? this._autoPlugins[k] : this.plugins[k];
|
|
191
|
+
for (const k of before) {
|
|
192
|
+
const p = lookup(k);
|
|
193
|
+
await p[hook].call(p, ...args);
|
|
194
|
+
}
|
|
195
|
+
let result;
|
|
196
|
+
if (original) {
|
|
197
|
+
result = await original.apply(this, args);
|
|
198
|
+
}
|
|
199
|
+
for (const k of after) {
|
|
200
|
+
const p = lookup(k);
|
|
201
|
+
await p[hook].call(p, ...args);
|
|
202
|
+
}
|
|
203
|
+
return result;
|
|
204
|
+
};
|
|
205
|
+
}
|
|
192
206
|
function setupRoomPlugins(room) {
|
|
193
207
|
const plugins = room.plugins;
|
|
194
208
|
const layout = resolveOrComputeLayout(room.constructor, plugins);
|
|
195
209
|
attachRoomReference(room, plugins);
|
|
210
|
+
if (layout) {
|
|
211
|
+
wrapOwnHooks(room, layout);
|
|
212
|
+
}
|
|
196
213
|
if (layout && layout.autoDeps.length > 0) {
|
|
197
214
|
room._autoPlugins = instantiateAutoDeps(room, layout);
|
|
198
215
|
}
|
package/build/RoomPlugin.cjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/RoomPlugin.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Room plugins.\n *\n * A plugin is a composable extension to a Room \u2014 it can declare message\n * handlers, attach lifecycle hooks, and expose public methods that the\n * room can call (`this.plugins.<key>.someMethod()`). The framework\n * instantiates one plugin per room, sets `this.room` after the room is\n * constructed, then merges the plugin's `messages` with the room's own\n * and wires its lifecycle hooks alongside the room's.\n *\n * Example: a tiny chat plugin contributing a single message handler:\n *\n * class ChatPlugin extends RoomPlugin {\n * private history: string[] = [];\n * constructor(private opts: { historyLimit: number }) { super(); }\n *\n * messages = {\n * chat: (client: Client, msg: { text: string }) => {\n * this.history.push(msg.text);\n * if (this.history.length > this.opts.historyLimit) this.history.shift();\n * this.room.broadcast('chat', { from: client.userId, text: msg.text });\n * },\n * };\n *\n * // Public \u2014 callable as `this.plugins.chat.getHistory()` from the room\n * getHistory(): readonly string[] { return this.history; }\n * }\n *\n * Use via `definePlugins`:\n *\n * class MyRoom extends Room<{ state: MyState }> {\n * plugins = definePlugins({\n * chat: new ChatPlugin({ historyLimit: 100 }),\n * });\n * }\n */\nimport type { Room } from './Room.ts';\nimport type { AuthContext, Client } from './Transport.ts';\nimport type { Messages } from '@colyseus/shared-types';\n\n/**\n * Ordering hint for a plugin's lifecycle hook relative to the room's own\n * hook. Sensible per-hook defaults are applied when omitted (see\n * `Room.__init` for the exact ordering policy).\n *\n * onCreate / onAuth / onJoin \u2192 plugins run BEFORE room (guards + setup)\n * onLeave / onDispose \u2192 plugins run AFTER room (capture final state)\n */\nexport interface RoomPluginOrder {\n onCreate?: 'before' | 'after';\n onAuth?: 'before' | 'after';\n onJoin?: 'before' | 'after';\n onLeave?: 'before' | 'after';\n onDispose?: 'before' | 'after';\n}\n\n/**\n * Base class for room plugins. Subclass to define a plugin; the framework\n * sets `this.room` after the host room is fully constructed.\n *\n * Don't access `this.room` from the plugin's constructor \u2014 it hasn't been\n * wired yet. Everything room-dependent goes in `onCreate` / `onJoin` /\n * etc. or in public methods that are called from the room post-init.\n *\n * @typeParam This - The Room subclass this plugin is attached to. Narrow\n * for schema-driven plugins that need a specific state shape, e.g.\n * `class PhysicsPlugin extends RoomPlugin<Room<{ state: PhysicsContract }>>`.\n */\nexport abstract class RoomPlugin<This extends Room = Room> {\n /**\n * Live room reference. Wired by the framework at __init, AFTER the\n * room's own construction \u2014 accessing it from the plugin's\n * constructor throws.\n */\n protected readonly room!: This;\n\n /**\n * Canonical key for the plugin when registered via `definePlugins([...])`.\n * Declared on the subclass with `as const` so the literal type flows\n * into `room.plugins.<key>`:\n *\n * class ChatPlugin extends RoomPlugin {\n * readonly pluginName = 'chat' as const;\n * }\n *\n * Optional under the keyed-record form (`definePlugins({ chat: ... })`),\n * required under the array form. Must stay `public` so `extends` /\n * `keyof` can see the literal \u2014 those are blind to protected from\n * outside the class. End-user autocomplete hides it via `Omit` in\n * `definePlugins`'s return type.\n *\n * For multi-instance use, accept the name at construction:\n *\n * readonly pluginName: string;\n * constructor(name = 'chat') { super(); this.pluginName = name; }\n */\n readonly pluginName?: string;\n\n /**\n * Declarative message handlers \u2014 merged into the room's `messages` at\n * __init. Conflict against the room's own key: room wins. Conflict\n * between two plugins: throws at __init.\n */\n protected messages?: Messages<This>;\n\n /** Optional per-hook ordering vs the room's own hook. */\n protected order?: RoomPluginOrder;\n\n // Lifecycle hooks \u2014 override any subset. `protected` so they don't\n // leak into `this.plugins.<key>.onJoin(...)` autocomplete; subclass\n // overrides must keep `protected` (TS widens to public silently\n // otherwise).\n protected onCreate?(options: any): void | Promise<void>;\n protected onAuth?(client: Client, options: any, context: AuthContext): void | Promise<void>;\n protected onJoin?(client: Client, options?: any): void | Promise<void>;\n protected onLeave?(client: Client, code?: number): void | Promise<void>;\n protected onDispose?(): void | Promise<void>;\n}\n\n/**\n * Plugin-class constructor type used by the `dependencies` static\n * declaration. Constrained to zero-arg constructors because the\n * framework auto-instantiates missing dependencies with no\n * configuration \u2014 plugins that need options can't be auto-included\n * and must be registered explicitly in `definePlugins({...})`.\n */\nexport type RoomPluginClass = new () => RoomPlugin<any>;\n\n/**\n * Static `dependencies` declaration. List other plugin classes this\n * plugin needs alongside it; the framework auto-instantiates any\n * missing ones at room construction time. Transitive deps are\n * resolved recursively. Cycles throw at class-init.\n *\n * Example:\n * class UniqueSessionPlugin extends RoomPlugin {\n * static dependencies: PluginDependencies = [TrackUserSessionsPlugin];\n * }\n */\nexport type PluginDependencies = ReadonlyArray<RoomPluginClass>;\n\n/**\n * Define a Room's plugin record. The framework wires plugins at\n * `__init` \u2014 first construct of the class computes the layout\n * (cached on the constructor) and installs hook wrappers on the\n * prototype. The `const T` modifier preserves literal types so\n * `this.plugins.<key>.method()` autocompletes against each plugin's\n * specific subclass.\n */\n// Pulls each plugin's `pluginName` literal as the record key. Subclass\n// must narrow with `as const` \u2014 plain `string` resolves to `never`\n// and the entry is dropped (callers see a TS error on\n// `plugins.<thatKey>`).\ntype ExtractPluginName<P> = P extends { pluginName: infer K }\n ? (K extends string ? K : never)\n : never;\n\n/** Hide `pluginName` from end-user autocomplete on `this.plugins.<key>`. */\ntype PluginPublicSurface<P> = Omit<P, 'pluginName'>;\n\ntype PluginsArrayToRecord<T extends readonly RoomPlugin<any>[]> = {\n [P in T[number] as ExtractPluginName<P>]: PluginPublicSurface<P>;\n};\n\n/**\n * Array form (recommended). Each plugin declares its own canonical\n * key via `readonly pluginName = '...' as const`; the framework\n * turns the array into a typed record so `plugins.<pluginName>`\n * autocompletes the right instance type.\n *\n * class GameRoom extends Room {\n * plugins = definePlugins([\n * new ChatPlugin(), // pluginName: 'chat'\n * new UniqueSessionPlugin({ max: 1 }), // pluginName: 'uniqueSession'\n * ]);\n * }\n * this.plugins.chat.send('hi');\n *\n * Throws at runtime if any plugin is missing `pluginName` or if two\n * plugins resolve to the same key.\n */\nexport function definePlugins<const T extends readonly RoomPlugin<any>[]>(\n plugins: T,\n): PluginsArrayToRecord<T>;\n\n/**\n * Record form (legacy / multi-instance escape hatch). The caller\n * chooses the key per-room. Useful when registering two instances of\n * the same plugin class without configuring `pluginName` per\n * instance \u2014 e.g. `{ adminChat: new ChatPlugin(), playerChat: new ChatPlugin() }`.\n */\nexport function definePlugins<const T extends Record<string, RoomPlugin<any>>>(\n plugins: T,\n): { [K in keyof T]: PluginPublicSurface<T[K]> };\n\nexport function definePlugins(plugins: any): any {\n if (!Array.isArray(plugins)) { return plugins; }\n const out: Record<string, RoomPlugin> = {};\n for (const p of plugins) {\n const key = p['pluginName'];\n if (typeof key !== 'string' || key.length === 0) {\n throw new Error(\n `[Room] plugin ${p.constructor.name} is missing a 'pluginName' field. ` +\n `Declare \\`readonly pluginName = '<key>' as const\\` on the class, ` +\n `or register it via the keyed-record form \\`definePlugins({ <key>: <plugin> })\\`.`,\n );\n }\n if (out[key]) {\n throw new Error(\n `[Room] two plugins resolve to pluginName \"${key}\". Configure one of ` +\n `them via constructor argument, or use the keyed-record form to disambiguate.`,\n );\n }\n out[key] = p;\n }\n return out;\n}\n\n/**\n * Lifecycle hook keys recognized by the framework \u2014 used internally to\n * separate \"framework-recognized methods\" from \"user-defined public\n * methods\" when wiring a plugin into a room. Exported for the test\n * harness; downstream code should not need it.\n */\nexport const PLUGIN_LIFECYCLE_KEYS = ['onCreate', 'onAuth', 'onJoin', 'onLeave', 'onDispose'] as const;\nexport type PluginLifecycleKey = (typeof PLUGIN_LIFECYCLE_KEYS)[number];\n\n/**\n * Test helper \u2014 attach a stub or fake room to a plugin so its methods\n * and lifecycle hooks can be exercised in isolation without spinning up\n * a real Colyseus server.\n *\n * const plugin = new ChatPlugin({ historyLimit: 5 });\n * const room = attachToTestRoom(plugin, { broadcast: sinon.spy() });\n * await plugin.messages!.chat!.call(plugin, { userId: 'u1' }, { text: 'hi' });\n *\n * The second arg is shallow-merged onto the stub so tests only declare\n * the room properties they actually exercise. Returns the room stub for\n * post-call assertions.\n */\nexport function attachToTestRoom<This extends Room, R extends Partial<This>>(\n plugin: RoomPlugin<This>,\n roomStub: R = {} as R,\n): R {\n (plugin as any).room = roomStub;\n return roomStub;\n}\n\n// ---------------------------------------------------------------------------\n// Layout machinery \u2014 used by Room.__init to set plugins up once per class.\n// Lives in this file (rather than Room.ts) so the plugin-related types and\n// helpers stay co-located. These are framework internals; callers outside\n// `@colyseus/core` should not depend on them.\n// ---------------------------------------------------------------------------\n\n/**\n * Precomputed plugin layout for a Room subclass \u2014 populated on first\n * construct, cached on the constructor. Hook wrappers are installed\n * on the prototype in the same pass (see `installPluginHookWrappers`).\n *\n * @internal\n */\nexport interface PluginLayout {\n /** Per-hook participation: which plugin keys run before/after the room's own hook. */\n hooks: Record<PluginLifecycleKey, { before: string[]; after: string[] }>;\n /** Message key \u2192 plugin key. Conflict detection ran when this was built. */\n messageOwners: Map<string, string>;\n /** Sentinel-keyed plugin classes to instantiate per room. */\n autoDeps: Array<{ key: string; ctor: RoomPluginClass }>;\n}\n\n/** Sentinel prefix for framework-instantiated deps. The colon prevents\n * collisions with any JS identifier the user could use as a key. */\nconst DEP_KEY_PREFIX = '__dep:';\n\n/**\n * Default before/after policy for lifecycle hooks vs the room's own\n * hook. Plugins can override per-hook via the `order` field on the\n * plugin instance.\n *\n * onCreate / onAuth / onJoin \u2192 plugins run BEFORE room (guards + setup)\n * onLeave / onDispose \u2192 plugins run AFTER room (capture final state)\n *\n * @internal\n */\nexport const DEFAULT_PLUGIN_ORDER: Record<PluginLifecycleKey, 'before' | 'after'> = {\n onCreate: 'before',\n onAuth: 'before',\n onJoin: 'before',\n onLeave: 'after',\n onDispose: 'after',\n};\n\n/**\n * Walk the room's plugin instances and produce the lifecycle + message\n * layout for the Room class. Called once per Room subclass \u2014 on the\n * first construct \u2014 and the result is cached on the constructor. Throws\n * on duplicate message keys (named both plugin keys) so the failure is\n * visible at class-init rather than at first message dispatch.\n *\n * Returns `null` when no plugins participate in any hook AND none\n * declare a message \u2014 distinguishes \"computed, nothing to do\" from\n * \"not computed yet\" in the `__pluginLayout` cache.\n *\n * @internal\n */\nexport function computePluginLayout(plugins: Record<string, RoomPlugin>): PluginLayout | null {\n // Resolve `static dependencies` closures over the user's record.\n // Returns an expanded list (user + auto-deps), the auto-dep\n // class table for per-room instantiation, and a unified view of\n // entries to iterate when computing hooks / message owners.\n const resolved = resolveDependencies(plugins);\n\n const hooks = {} as Record<PluginLifecycleKey, { before: string[]; after: string[] }>;\n let anyHook = false;\n\n for (const hook of PLUGIN_LIFECYCLE_KEYS) {\n const before: string[] = [];\n const after: string[] = [];\n for (const { key, plugin } of resolved.entries) {\n if (typeof plugin[hook] !== 'function') { continue; }\n // Bracket access \u2014 `order` and `messages` are protected; TS\n // skips visibility checks on indexed access.\n const order = plugin['order']?.[hook] ?? DEFAULT_PLUGIN_ORDER[hook];\n (order === 'before' ? before : after).push(key);\n anyHook = true;\n }\n hooks[hook] = { before, after };\n }\n\n const messageOwners = new Map<string, string>();\n for (const { key, plugin } of resolved.entries) {\n const messages = plugin['messages'];\n if (!messages) { continue; }\n for (const messageKey of Object.keys(messages)) {\n const prior = messageOwners.get(messageKey);\n if (prior !== undefined) {\n throw new Error(\n `[Room] message key \"${messageKey}\" declared by multiple plugins: ` +\n `\"${prior}\" and \"${key}\". Resolve by giving one of them a ` +\n `different key, or override on the room's own \\`messages\\`.`,\n );\n }\n messageOwners.set(messageKey, key);\n }\n }\n\n if (!anyHook && messageOwners.size === 0 && resolved.autoDeps.length === 0) { return null; }\n return { hooks, messageOwners, autoDeps: resolved.autoDeps };\n}\n\n/**\n * Walk every plugin's `static dependencies` recursively, instantiating\n * missing classes (zero-arg only). Throws on cycles. Auto-deps are\n * keyed `__dep:<ClassName>` in the returned entries.\n */\nfunction resolveDependencies(plugins: Record<string, RoomPlugin>): {\n entries: Array<{ key: string; plugin: RoomPlugin }>;\n autoDeps: Array<{ key: string; ctor: RoomPluginClass }>;\n} {\n const entries: Array<{ key: string; plugin: RoomPlugin }> = [];\n for (const [key, plugin] of Object.entries(plugins)) {\n entries.push({ key, plugin });\n }\n\n const present = new Set<RoomPluginClass>();\n for (const { plugin } of entries) {\n present.add(plugin.constructor as RoomPluginClass);\n }\n\n const autoDeps: Array<{ key: string; ctor: RoomPluginClass }> = [];\n const visiting = new Set<RoomPluginClass>();\n const path: string[] = [];\n\n function walk(depCtor: RoomPluginClass): void {\n if (present.has(depCtor)) { return; }\n if (visiting.has(depCtor)) {\n const cycle = [...path, depCtor.name].join(' \u2192 ');\n throw new Error(`[Room] plugin dependency cycle: ${cycle}`);\n }\n visiting.add(depCtor);\n path.push(depCtor.name);\n\n // Recurse into deeper deps first \u2192 topological order in `entries`.\n const deeper = (depCtor as any).dependencies as PluginDependencies | undefined;\n if (Array.isArray(deeper)) {\n for (const inner of deeper) { walk(inner); }\n }\n\n let instance: RoomPlugin;\n try { instance = new depCtor(); }\n catch (err: any) {\n throw new Error(\n `[Room] auto-included plugin \"${depCtor.name}\" must be ` +\n `constructible with no arguments. If it needs options, ` +\n `register it explicitly in definePlugins({...}). ` +\n `(cause: ${err?.message ?? err})`,\n );\n }\n const key = DEP_KEY_PREFIX + depCtor.name;\n entries.push({ key, plugin: instance });\n autoDeps.push({ key, ctor: depCtor });\n present.add(depCtor);\n\n visiting.delete(depCtor);\n path.pop();\n }\n\n // Snapshot before mutating \u2014 transitive deps are handled recursively\n // inside `walk()`.\n const userEntriesSnapshot = entries.slice();\n for (const { plugin } of userEntriesSnapshot) {\n const deps = (plugin.constructor as any).dependencies as PluginDependencies | undefined;\n if (!Array.isArray(deps)) { continue; }\n for (const depCtor of deps) { walk(depCtor); }\n }\n\n return { entries, autoDeps };\n}\n\n/**\n * Install one wrapper per participating hook on the Room subclass's\n * prototype. The wrapper closes over plugin KEYS (resolved to refs at\n * call time) and invokes the captured original room hook between the\n * before/after plugin runs.\n *\n * @internal\n */\nexport function installPluginHookWrappers(\n ctor: { prototype: any },\n layout: PluginLayout | null,\n): void {\n if (layout === null) { return; }\n const proto = ctor.prototype;\n for (const hook of PLUGIN_LIFECYCLE_KEYS) {\n const { before, after } = layout.hooks[hook];\n if (before.length === 0 && after.length === 0) { continue; }\n\n const original = proto[hook] as Function | undefined;\n proto[hook] = async function (\n this: { plugins?: Record<string, RoomPlugin>; _autoPlugins?: Record<string, RoomPlugin> },\n ...args: any[]\n ) {\n // User plugins live on `this.plugins`, auto-deps (sentinel-keyed)\n // on `this._autoPlugins` \u2014 kept separate so user types stay clean.\n const lookup = (k: string): RoomPlugin =>\n (k.startsWith(DEP_KEY_PREFIX) ? this._autoPlugins![k] : this.plugins![k]);\n for (const k of before) {\n const p = lookup(k);\n await (p[hook] as Function).call(p, ...args);\n }\n let result: unknown;\n if (original) { result = await original.apply(this, args); }\n for (const k of after) {\n const p = lookup(k);\n await (p[hook] as Function).call(p, ...args);\n }\n return result;\n };\n }\n}\n\n/** Structural shape used by `setupRoomPlugins` \u2014 avoids a Room import\n * so the dependency graph stays one-way (Room \u2192 RoomPlugin). */\ninterface RoomPluginHost {\n plugins?: Record<string, RoomPlugin<any>>;\n _autoPlugins?: Record<string, RoomPlugin<any>>;\n messages?: Record<string, Function> | any;\n constructor: { __pluginLayout?: PluginLayout | null; prototype: any };\n}\n\n/**\n * Wire a Room instance's plugins. Once-per-class layout (hook\n * participation, message owners, dep resolution) is cached on the\n * constructor; per-instance work attaches `room` refs, instantiates\n * auto-deps, and merges plugin messages.\n *\n * @internal\n */\nexport function setupRoomPlugins(room: RoomPluginHost): void {\n const plugins = room.plugins!;\n const layout = resolveOrComputeLayout(room.constructor, plugins);\n\n attachRoomReference(room, plugins);\n\n if (layout && layout.autoDeps.length > 0) {\n room._autoPlugins = instantiateAutoDeps(room, layout);\n }\n\n if (layout && layout.messageOwners.size > 0) {\n mergePluginMessages(room, layout);\n }\n\n Object.freeze(plugins);\n if (room._autoPlugins) { Object.freeze(room._autoPlugins); }\n}\n\n/**\n * Read cached layout for this subclass, or compute + install on\n * first construct. `hasOwnProperty` so a subclass that redeclares\n * `plugins` doesn't inherit the parent's wrapping.\n */\nfunction resolveOrComputeLayout(\n ctor: RoomPluginHost['constructor'],\n plugins: Record<string, RoomPlugin>,\n): PluginLayout | null | undefined {\n if (Object.prototype.hasOwnProperty.call(ctor, '__pluginLayout')) {\n return ctor.__pluginLayout;\n }\n const layout = computePluginLayout(plugins);\n installPluginHookWrappers(ctor, layout);\n ctor.__pluginLayout = layout;\n return layout;\n}\n\n/** Wire `plugin.room = room` on every user-explicit plugin. */\nfunction attachRoomReference(\n room: RoomPluginHost,\n plugins: Record<string, RoomPlugin>,\n): void {\n for (const plugin of Object.values(plugins)) {\n (plugin as any).room = room;\n }\n}\n\n/**\n * Build `_autoPlugins` \u2014 one fresh instance per `static dependencies`\n * entry. Kept separate from `room.plugins` so sentinel keys\n * (`__dep:<ClassName>`) don't leak into the user's typed view.\n */\nfunction instantiateAutoDeps(\n room: RoomPluginHost,\n layout: PluginLayout,\n): Record<string, RoomPlugin> {\n const auto: Record<string, RoomPlugin> = {};\n for (const { key, ctor: depCtor } of layout.autoDeps) {\n const instance = new depCtor();\n (instance as any).room = room;\n auto[key] = instance;\n }\n return auto;\n}\n\n/**\n * Copy plugin message handlers into `room.messages` (room's own key\n * wins; plugin-vs-plugin conflicts already threw at layout time).\n */\nfunction mergePluginMessages(\n room: RoomPluginHost,\n layout: PluginLayout,\n): void {\n const plugins = room.plugins!;\n for (const [messageKey, pluginKey] of layout.messageOwners) {\n if (room.messages?.[messageKey]) { continue; }\n const source = pluginKey.startsWith(DEP_KEY_PREFIX)\n ? room._autoPlugins![pluginKey]\n : plugins[pluginKey];\n const handler = source['messages']?.[messageKey];\n if (handler !== undefined) {\n (room.messages ??= {} as any)[messageKey] = handler;\n }\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoEO,IAAe,aAAf,MAAoD;AAiD3D;AA8EO,SAAS,cAAc,SAAmB;AAC/C,MAAI,CAAC,MAAM,QAAQ,OAAO,GAAG;AAAE,WAAO;AAAA,EAAS;AAC/C,QAAM,MAAkC,CAAC;AACzC,aAAW,KAAK,SAAS;AACvB,UAAM,MAAM,EAAE,YAAY;AAC1B,QAAI,OAAO,QAAQ,YAAY,IAAI,WAAW,GAAG;AAC/C,YAAM,IAAI;AAAA,QACR,iBAAiB,EAAE,YAAY,IAAI;AAAA,MAGrC;AAAA,IACF;AACA,QAAI,IAAI,GAAG,GAAG;AACZ,YAAM,IAAI;AAAA,QACR,6CAA6C,GAAG;AAAA,MAElD;AAAA,IACF;AACA,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CAAC;AACpC,YAAQ,IAAI,OAAO;AAEnB,aAAS,OAAO,OAAO;AACvB,SAAK,IAAI;AAAA,EACX;AAIA,QAAM,sBAAsB,QAAQ,MAAM;AAC1C,aAAW,EAAE,OAAO,KAAK,qBAAqB;AAC5C,UAAM,OAAQ,OAAO,YAAoB;AACzC,QAAI,CAAC,MAAM,QAAQ,IAAI,GAAG;AAAE;AAAA,IAAU;AACtC,eAAW,WAAW,MAAM;AAAE,WAAK,OAAO;AAAA,IAAG;AAAA,EAC/C;AAEA,SAAO,EAAE,SAAS,SAAS;AAC7B;AAUO,SAAS,0BACd,MACA,QACM;AACN,MAAI,WAAW,MAAM;AAAE;AAAA,EAAQ;AAC/B,QAAM,QAAQ,KAAK;AACnB,aAAW,QAAQ,uBAAuB;AACxC,UAAM,EAAE,QAAQ,MAAM,IAAI,OAAO,MAAM,IAAI;AAC3C,QAAI,OAAO,WAAW,KAAK,MAAM,WAAW,GAAG;AAAE;AAAA,IAAU;
|
|
4
|
+
"sourcesContent": ["/**\n * Room plugins.\n *\n * A plugin is a composable extension to a Room \u2014 it can declare message\n * handlers, attach lifecycle hooks, and expose public methods that the\n * room can call (`this.plugins.<key>.someMethod()`). The framework\n * instantiates one plugin per room, sets `this.room` after the room is\n * constructed, then merges the plugin's `messages` with the room's own\n * and wires its lifecycle hooks alongside the room's.\n *\n * Example: a tiny chat plugin contributing a single message handler:\n *\n * class ChatPlugin extends RoomPlugin {\n * private history: string[] = [];\n * constructor(private opts: { historyLimit: number }) { super(); }\n *\n * messages = {\n * chat: (client: Client, msg: { text: string }) => {\n * this.history.push(msg.text);\n * if (this.history.length > this.opts.historyLimit) this.history.shift();\n * this.room.broadcast('chat', { from: client.userId, text: msg.text });\n * },\n * };\n *\n * // Public \u2014 callable as `this.plugins.chat.getHistory()` from the room\n * getHistory(): readonly string[] { return this.history; }\n * }\n *\n * Use via `definePlugins`:\n *\n * class MyRoom extends Room<{ state: MyState }> {\n * plugins = definePlugins({\n * chat: new ChatPlugin({ historyLimit: 100 }),\n * });\n * }\n */\nimport type { Room } from './Room.ts';\nimport type { AuthContext, Client } from './Transport.ts';\nimport type { Messages } from '@colyseus/shared-types';\n\n/**\n * Ordering hint for a plugin's lifecycle hook relative to the room's own\n * hook. Sensible per-hook defaults are applied when omitted (see\n * `Room.__init` for the exact ordering policy).\n *\n * onCreate / onAuth / onJoin \u2192 plugins run BEFORE room (guards + setup)\n * onLeave / onDispose \u2192 plugins run AFTER room (capture final state)\n */\nexport interface RoomPluginOrder {\n onCreate?: 'before' | 'after';\n onAuth?: 'before' | 'after';\n onJoin?: 'before' | 'after';\n onLeave?: 'before' | 'after';\n onDispose?: 'before' | 'after';\n}\n\n/**\n * Base class for room plugins. Subclass to define a plugin; the framework\n * sets `this.room` after the host room is fully constructed.\n *\n * Don't access `this.room` from the plugin's constructor \u2014 it hasn't been\n * wired yet. Everything room-dependent goes in `onCreate` / `onJoin` /\n * etc. or in public methods that are called from the room post-init.\n *\n * @typeParam This - The Room subclass this plugin is attached to. Narrow\n * for schema-driven plugins that need a specific state shape, e.g.\n * `class PhysicsPlugin extends RoomPlugin<Room<{ state: PhysicsContract }>>`.\n */\nexport abstract class RoomPlugin<This extends Room = Room> {\n /**\n * Live room reference. Wired by the framework at __init, AFTER the\n * room's own construction \u2014 accessing it from the plugin's\n * constructor throws.\n */\n protected readonly room!: This;\n\n /**\n * Canonical key for the plugin when registered via `definePlugins([...])`.\n * Declared on the subclass with `as const` so the literal type flows\n * into `room.plugins.<key>`:\n *\n * class ChatPlugin extends RoomPlugin {\n * readonly pluginName = 'chat' as const;\n * }\n *\n * Optional under the keyed-record form (`definePlugins({ chat: ... })`),\n * required under the array form. Must stay `public` so `extends` /\n * `keyof` can see the literal \u2014 those are blind to protected from\n * outside the class. End-user autocomplete hides it via `Omit` in\n * `definePlugins`'s return type.\n *\n * For multi-instance use, accept the name at construction:\n *\n * readonly pluginName: string;\n * constructor(name = 'chat') { super(); this.pluginName = name; }\n */\n readonly pluginName?: string;\n\n /**\n * Declarative message handlers \u2014 merged into the room's `messages` at\n * __init. Conflict against the room's own key: room wins. Conflict\n * between two plugins: throws at __init.\n */\n protected messages?: Messages<This>;\n\n /** Optional per-hook ordering vs the room's own hook. */\n protected order?: RoomPluginOrder;\n\n // Lifecycle hooks \u2014 override any subset. `protected` so they don't\n // leak into `this.plugins.<key>.onJoin(...)` autocomplete; subclass\n // overrides must keep `protected` (TS widens to public silently\n // otherwise).\n protected onCreate?(options: any): void | Promise<void>;\n protected onAuth?(client: Client, options: any, context: AuthContext): void | Promise<void>;\n protected onJoin?(client: Client, options?: any): void | Promise<void>;\n protected onLeave?(client: Client, code?: number): void | Promise<void>;\n protected onDispose?(): void | Promise<void>;\n}\n\n/**\n * Plugin-class constructor type used by the `dependencies` static\n * declaration. Constrained to zero-arg constructors because the\n * framework auto-instantiates missing dependencies with no\n * configuration \u2014 plugins that need options can't be auto-included\n * and must be registered explicitly in `definePlugins({...})`.\n */\nexport type RoomPluginClass = new () => RoomPlugin<any>;\n\n/**\n * Static `dependencies` declaration. List other plugin classes this\n * plugin needs alongside it; the framework auto-instantiates any\n * missing ones at room construction time. Transitive deps are\n * resolved recursively. Cycles throw at class-init.\n *\n * Example:\n * class UniqueSessionPlugin extends RoomPlugin {\n * static dependencies: PluginDependencies = [TrackUserSessionsPlugin];\n * }\n */\nexport type PluginDependencies = ReadonlyArray<RoomPluginClass>;\n\n/**\n * Define a Room's plugin record. The framework wires plugins at\n * `__init` \u2014 first construct of the class computes the layout\n * (cached on the constructor) and installs hook wrappers on the\n * prototype. The `const T` modifier preserves literal types so\n * `this.plugins.<key>.method()` autocompletes against each plugin's\n * specific subclass.\n */\n// Pulls each plugin's `pluginName` literal as the record key. Subclass\n// must narrow with `as const` \u2014 plain `string` resolves to `never`\n// and the entry is dropped (callers see a TS error on\n// `plugins.<thatKey>`).\ntype ExtractPluginName<P> = P extends { pluginName: infer K }\n ? (K extends string ? K : never)\n : never;\n\n/** Hide `pluginName` from end-user autocomplete on `this.plugins.<key>`. */\ntype PluginPublicSurface<P> = Omit<P, 'pluginName'>;\n\ntype PluginsArrayToRecord<T extends readonly RoomPlugin<any>[]> = {\n [P in T[number] as ExtractPluginName<P>]: PluginPublicSurface<P>;\n};\n\n/**\n * Array form (recommended). Each plugin declares its own canonical\n * key via `readonly pluginName = '...' as const`; the framework\n * turns the array into a typed record so `plugins.<pluginName>`\n * autocompletes the right instance type.\n *\n * class GameRoom extends Room {\n * plugins = definePlugins([\n * new ChatPlugin(), // pluginName: 'chat'\n * new UniqueSessionPlugin({ max: 1 }), // pluginName: 'uniqueSession'\n * ]);\n * }\n * this.plugins.chat.send('hi');\n *\n * Throws at runtime if any plugin is missing `pluginName` or if two\n * plugins resolve to the same key.\n */\nexport function definePlugins<const T extends readonly RoomPlugin<any>[]>(\n plugins: T,\n): PluginsArrayToRecord<T>;\n\n/**\n * Record form (legacy / multi-instance escape hatch). The caller\n * chooses the key per-room. Useful when registering two instances of\n * the same plugin class without configuring `pluginName` per\n * instance \u2014 e.g. `{ adminChat: new ChatPlugin(), playerChat: new ChatPlugin() }`.\n */\nexport function definePlugins<const T extends Record<string, RoomPlugin<any>>>(\n plugins: T,\n): { [K in keyof T]: PluginPublicSurface<T[K]> };\n\nexport function definePlugins(plugins: any): any {\n if (!Array.isArray(plugins)) { return plugins; }\n const out: Record<string, RoomPlugin> = {};\n for (const p of plugins) {\n const key = p['pluginName'];\n if (typeof key !== 'string' || key.length === 0) {\n throw new Error(\n `[Room] plugin ${p.constructor.name} is missing a 'pluginName' field. ` +\n `Declare \\`readonly pluginName = '<key>' as const\\` on the class, ` +\n `or register it via the keyed-record form \\`definePlugins({ <key>: <plugin> })\\`.`,\n );\n }\n if (out[key]) {\n throw new Error(\n `[Room] two plugins resolve to pluginName \"${key}\". Configure one of ` +\n `them via constructor argument, or use the keyed-record form to disambiguate.`,\n );\n }\n out[key] = p;\n }\n return out;\n}\n\n/**\n * Lifecycle hook keys recognized by the framework \u2014 used internally to\n * separate \"framework-recognized methods\" from \"user-defined public\n * methods\" when wiring a plugin into a room. Exported for the test\n * harness; downstream code should not need it.\n */\nexport const PLUGIN_LIFECYCLE_KEYS = ['onCreate', 'onAuth', 'onJoin', 'onLeave', 'onDispose'] as const;\nexport type PluginLifecycleKey = (typeof PLUGIN_LIFECYCLE_KEYS)[number];\n\n/**\n * Test helper \u2014 attach a stub or fake room to a plugin so its methods\n * and lifecycle hooks can be exercised in isolation without spinning up\n * a real Colyseus server.\n *\n * const plugin = new ChatPlugin({ historyLimit: 5 });\n * const room = attachToTestRoom(plugin, { broadcast: sinon.spy() });\n * await plugin.messages!.chat!.call(plugin, { userId: 'u1' }, { text: 'hi' });\n *\n * The second arg is shallow-merged onto the stub so tests only declare\n * the room properties they actually exercise. Returns the room stub for\n * post-call assertions.\n */\nexport function attachToTestRoom<This extends Room, R extends Partial<This>>(\n plugin: RoomPlugin<This>,\n roomStub: R = {} as R,\n): R {\n (plugin as any).room = roomStub;\n return roomStub;\n}\n\n// ---------------------------------------------------------------------------\n// Layout machinery \u2014 used by Room.__init to set plugins up once per class.\n// Lives in this file (rather than Room.ts) so the plugin-related types and\n// helpers stay co-located. These are framework internals; callers outside\n// `@colyseus/core` should not depend on them.\n// ---------------------------------------------------------------------------\n\n/**\n * Precomputed plugin layout for a Room subclass \u2014 populated on first\n * construct, cached on the constructor. Hook wrappers are installed\n * on the prototype in the same pass (see `installPluginHookWrappers`).\n *\n * @internal\n */\nexport interface PluginLayout {\n /** Per-hook participation: which plugin keys run before/after the room's own hook. */\n hooks: Record<PluginLifecycleKey, { before: string[]; after: string[] }>;\n /** Message key \u2192 plugin key. Conflict detection ran when this was built. */\n messageOwners: Map<string, string>;\n /** Sentinel-keyed plugin classes to instantiate per room. */\n autoDeps: Array<{ key: string; ctor: RoomPluginClass }>;\n}\n\n/** Sentinel prefix for framework-instantiated deps. The colon prevents\n * collisions with any JS identifier the user could use as a key. */\nconst DEP_KEY_PREFIX = '__dep:';\n\n/**\n * Default before/after policy for lifecycle hooks vs the room's own\n * hook. Plugins can override per-hook via the `order` field on the\n * plugin instance.\n *\n * onCreate / onAuth / onJoin \u2192 plugins run BEFORE room (guards + setup)\n * onLeave / onDispose \u2192 plugins run AFTER room (capture final state)\n *\n * @internal\n */\nexport const DEFAULT_PLUGIN_ORDER: Record<PluginLifecycleKey, 'before' | 'after'> = {\n onCreate: 'before',\n onAuth: 'before',\n onJoin: 'before',\n onLeave: 'after',\n onDispose: 'after',\n};\n\n/**\n * Walk the room's plugin instances and produce the lifecycle + message\n * layout for the Room class. Called once per Room subclass \u2014 on the\n * first construct \u2014 and the result is cached on the constructor. Throws\n * on duplicate message keys (named both plugin keys) so the failure is\n * visible at class-init rather than at first message dispatch.\n *\n * Returns `null` when no plugins participate in any hook AND none\n * declare a message \u2014 distinguishes \"computed, nothing to do\" from\n * \"not computed yet\" in the `__pluginLayout` cache.\n *\n * @internal\n */\nexport function computePluginLayout(plugins: Record<string, RoomPlugin>): PluginLayout | null {\n // Resolve `static dependencies` closures over the user's record.\n // Returns an expanded list (user + auto-deps), the auto-dep\n // class table for per-room instantiation, and a unified view of\n // entries to iterate when computing hooks / message owners.\n const resolved = resolveDependencies(plugins);\n\n const hooks = {} as Record<PluginLifecycleKey, { before: string[]; after: string[] }>;\n let anyHook = false;\n\n for (const hook of PLUGIN_LIFECYCLE_KEYS) {\n const before: string[] = [];\n const after: string[] = [];\n for (const { key, plugin } of resolved.entries) {\n if (typeof plugin[hook] !== 'function') { continue; }\n // Bracket access \u2014 `order` and `messages` are protected; TS\n // skips visibility checks on indexed access.\n const order = plugin['order']?.[hook] ?? DEFAULT_PLUGIN_ORDER[hook];\n (order === 'before' ? before : after).push(key);\n anyHook = true;\n }\n hooks[hook] = { before, after };\n }\n\n const messageOwners = new Map<string, string>();\n for (const { key, plugin } of resolved.entries) {\n const messages = plugin['messages'];\n if (!messages) { continue; }\n for (const messageKey of Object.keys(messages)) {\n const prior = messageOwners.get(messageKey);\n if (prior !== undefined) {\n throw new Error(\n `[Room] message key \"${messageKey}\" declared by multiple plugins: ` +\n `\"${prior}\" and \"${key}\". Resolve by giving one of them a ` +\n `different key, or override on the room's own \\`messages\\`.`,\n );\n }\n messageOwners.set(messageKey, key);\n }\n }\n\n if (!anyHook && messageOwners.size === 0 && resolved.autoDeps.length === 0) { return null; }\n return { hooks, messageOwners, autoDeps: resolved.autoDeps };\n}\n\n/**\n * Walk every plugin's `static dependencies` recursively, instantiating\n * missing classes (zero-arg only). Throws on cycles. Auto-deps are\n * keyed `__dep:<ClassName>` in the returned entries.\n */\nfunction resolveDependencies(plugins: Record<string, RoomPlugin>): {\n entries: Array<{ key: string; plugin: RoomPlugin }>;\n autoDeps: Array<{ key: string; ctor: RoomPluginClass }>;\n} {\n const entries: Array<{ key: string; plugin: RoomPlugin }> = [];\n for (const [key, plugin] of Object.entries(plugins)) {\n entries.push({ key, plugin });\n }\n\n const present = new Set<RoomPluginClass>();\n for (const { plugin } of entries) {\n present.add(plugin.constructor as RoomPluginClass);\n }\n\n const autoDeps: Array<{ key: string; ctor: RoomPluginClass }> = [];\n const visiting = new Set<RoomPluginClass>();\n const path: string[] = [];\n\n function walk(depCtor: RoomPluginClass): void {\n if (present.has(depCtor)) { return; }\n if (visiting.has(depCtor)) {\n const cycle = [...path, depCtor.name].join(' \u2192 ');\n throw new Error(`[Room] plugin dependency cycle: ${cycle}`);\n }\n visiting.add(depCtor);\n path.push(depCtor.name);\n\n // Recurse into deeper deps first \u2192 topological order in `entries`.\n const deeper = (depCtor as any).dependencies as PluginDependencies | undefined;\n if (Array.isArray(deeper)) {\n for (const inner of deeper) { walk(inner); }\n }\n\n let instance: RoomPlugin;\n try { instance = new depCtor(); }\n catch (err: any) {\n throw new Error(\n `[Room] auto-included plugin \"${depCtor.name}\" must be ` +\n `constructible with no arguments. If it needs options, ` +\n `register it explicitly in definePlugins({...}). ` +\n `(cause: ${err?.message ?? err})`,\n );\n }\n const key = DEP_KEY_PREFIX + depCtor.name;\n entries.push({ key, plugin: instance });\n autoDeps.push({ key, ctor: depCtor });\n present.add(depCtor);\n\n visiting.delete(depCtor);\n path.pop();\n }\n\n // Snapshot before mutating \u2014 transitive deps are handled recursively\n // inside `walk()`.\n const userEntriesSnapshot = entries.slice();\n for (const { plugin } of userEntriesSnapshot) {\n const deps = (plugin.constructor as any).dependencies as PluginDependencies | undefined;\n if (!Array.isArray(deps)) { continue; }\n for (const depCtor of deps) { walk(depCtor); }\n }\n\n return { entries, autoDeps };\n}\n\n/**\n * Install one wrapper per participating hook on the Room subclass's\n * prototype. The wrapper closes over plugin KEYS (resolved to refs at\n * call time) and invokes the captured original room hook between the\n * before/after plugin runs.\n *\n * @internal\n */\nexport function installPluginHookWrappers(\n ctor: { prototype: any },\n layout: PluginLayout | null,\n): void {\n if (layout === null) { return; }\n const proto = ctor.prototype;\n for (const hook of PLUGIN_LIFECYCLE_KEYS) {\n const { before, after } = layout.hooks[hook];\n if (before.length === 0 && after.length === 0) { continue; }\n proto[hook] = composePluginHook(hook, before, after, proto[hook]);\n }\n}\n\n/**\n * Hooks declared as class fields (`onJoin = () => {}`) are own properties\n * that shadow the prototype wrapper, so wrap them per instance.\n */\nfunction wrapOwnHooks(room: RoomPluginHost, layout: PluginLayout): void {\n for (const hook of PLUGIN_LIFECYCLE_KEYS) {\n const { before, after } = layout.hooks[hook];\n if (before.length === 0 && after.length === 0) { continue; }\n if (!Object.hasOwn(room, hook)) { continue; }\n (room as any)[hook] = composePluginHook(hook, before, after, (room as any)[hook]);\n }\n}\n\n/** Run the `before` plugins, then `original`, then the `after` plugins. */\nfunction composePluginHook(\n hook: PluginLifecycleKey,\n before: string[],\n after: string[],\n original: Function | undefined,\n) {\n return async function (\n this: { plugins?: Record<string, RoomPlugin>; _autoPlugins?: Record<string, RoomPlugin> },\n ...args: any[]\n ) {\n // User plugins live on `this.plugins`, auto-deps (sentinel-keyed)\n // on `this._autoPlugins` \u2014 kept separate so user types stay clean.\n const lookup = (k: string): RoomPlugin =>\n (k.startsWith(DEP_KEY_PREFIX) ? this._autoPlugins![k] : this.plugins![k]);\n for (const k of before) {\n const p = lookup(k);\n await (p[hook] as Function).call(p, ...args);\n }\n let result: unknown;\n if (original) { result = await original.apply(this, args); }\n for (const k of after) {\n const p = lookup(k);\n await (p[hook] as Function).call(p, ...args);\n }\n return result;\n };\n}\n\n/** Structural shape used by `setupRoomPlugins` \u2014 avoids a Room import\n * so the dependency graph stays one-way (Room \u2192 RoomPlugin). */\ninterface RoomPluginHost {\n plugins?: Record<string, RoomPlugin<any>>;\n _autoPlugins?: Record<string, RoomPlugin<any>>;\n messages?: Record<string, Function> | any;\n constructor: { __pluginLayout?: PluginLayout | null; prototype: any };\n}\n\n/**\n * Wire a Room instance's plugins. Once-per-class layout (hook\n * participation, message owners, dep resolution) is cached on the\n * constructor; per-instance work attaches `room` refs, instantiates\n * auto-deps, and merges plugin messages.\n *\n * @internal\n */\nexport function setupRoomPlugins(room: RoomPluginHost): void {\n const plugins = room.plugins!;\n const layout = resolveOrComputeLayout(room.constructor, plugins);\n\n attachRoomReference(room, plugins);\n\n if (layout) {\n wrapOwnHooks(room, layout);\n }\n\n if (layout && layout.autoDeps.length > 0) {\n room._autoPlugins = instantiateAutoDeps(room, layout);\n }\n\n if (layout && layout.messageOwners.size > 0) {\n mergePluginMessages(room, layout);\n }\n\n Object.freeze(plugins);\n if (room._autoPlugins) { Object.freeze(room._autoPlugins); }\n}\n\n/**\n * Read cached layout for this subclass, or compute + install on\n * first construct. `hasOwnProperty` so a subclass that redeclares\n * `plugins` doesn't inherit the parent's wrapping.\n */\nfunction resolveOrComputeLayout(\n ctor: RoomPluginHost['constructor'],\n plugins: Record<string, RoomPlugin>,\n): PluginLayout | null | undefined {\n if (Object.prototype.hasOwnProperty.call(ctor, '__pluginLayout')) {\n return ctor.__pluginLayout;\n }\n const layout = computePluginLayout(plugins);\n installPluginHookWrappers(ctor, layout);\n ctor.__pluginLayout = layout;\n return layout;\n}\n\n/** Wire `plugin.room = room` on every user-explicit plugin. */\nfunction attachRoomReference(\n room: RoomPluginHost,\n plugins: Record<string, RoomPlugin>,\n): void {\n for (const plugin of Object.values(plugins)) {\n (plugin as any).room = room;\n }\n}\n\n/**\n * Build `_autoPlugins` \u2014 one fresh instance per `static dependencies`\n * entry. Kept separate from `room.plugins` so sentinel keys\n * (`__dep:<ClassName>`) don't leak into the user's typed view.\n */\nfunction instantiateAutoDeps(\n room: RoomPluginHost,\n layout: PluginLayout,\n): Record<string, RoomPlugin> {\n const auto: Record<string, RoomPlugin> = {};\n for (const { key, ctor: depCtor } of layout.autoDeps) {\n const instance = new depCtor();\n (instance as any).room = room;\n auto[key] = instance;\n }\n return auto;\n}\n\n/**\n * Copy plugin message handlers into `room.messages` (room's own key\n * wins; plugin-vs-plugin conflicts already threw at layout time).\n */\nfunction mergePluginMessages(\n room: RoomPluginHost,\n layout: PluginLayout,\n): void {\n const plugins = room.plugins!;\n for (const [messageKey, pluginKey] of layout.messageOwners) {\n if (room.messages?.[messageKey]) { continue; }\n const source = pluginKey.startsWith(DEP_KEY_PREFIX)\n ? room._autoPlugins![pluginKey]\n : plugins[pluginKey];\n const handler = source['messages']?.[messageKey];\n if (handler !== undefined) {\n (room.messages ??= {} as any)[messageKey] = handler;\n }\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoEO,IAAe,aAAf,MAAoD;AAiD3D;AA8EO,SAAS,cAAc,SAAmB;AAC/C,MAAI,CAAC,MAAM,QAAQ,OAAO,GAAG;AAAE,WAAO;AAAA,EAAS;AAC/C,QAAM,MAAkC,CAAC;AACzC,aAAW,KAAK,SAAS;AACvB,UAAM,MAAM,EAAE,YAAY;AAC1B,QAAI,OAAO,QAAQ,YAAY,IAAI,WAAW,GAAG;AAC/C,YAAM,IAAI;AAAA,QACR,iBAAiB,EAAE,YAAY,IAAI;AAAA,MAGrC;AAAA,IAC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,QAAM,OAAmC,CAAC;AAC1C,aAAW,EAAE,KAAK,MAAM,QAAQ,KAAK,OAAO,UAAU;AACpD,UAAM,WAAW,IAAI,QAAQ;AAC7B,IAAC,SAAiB,OAAO;AACzB,SAAK,GAAG,IAAI;AAAA,EACd;AACA,SAAO;AACT;AAMA,SAAS,oBACP,MACA,QACM;AACN,QAAM,UAAU,KAAK;AACrB,aAAW,CAAC,YAAY,SAAS,KAAK,OAAO,eAAe;AAC1D,QAAI,KAAK,WAAW,UAAU,GAAG;AAAE;AAAA,IAAU;AAC7C,UAAM,SAAS,UAAU,WAAW,cAAc,IAC9C,KAAK,aAAc,SAAS,IAC5B,QAAQ,SAAS;AACrB,UAAM,UAAU,OAAO,UAAU,IAAI,UAAU;AAC/C,QAAI,YAAY,QAAW;AACzB,OAAC,KAAK,aAAa,CAAC,GAAU,UAAU,IAAI;AAAA,IAC9C;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/build/RoomPlugin.mjs
CHANGED
|
@@ -138,29 +138,46 @@ function installPluginHookWrappers(ctor, layout) {
|
|
|
138
138
|
if (before.length === 0 && after.length === 0) {
|
|
139
139
|
continue;
|
|
140
140
|
}
|
|
141
|
-
|
|
142
|
-
proto[hook] = async function(...args) {
|
|
143
|
-
const lookup = (k) => k.startsWith(DEP_KEY_PREFIX) ? this._autoPlugins[k] : this.plugins[k];
|
|
144
|
-
for (const k of before) {
|
|
145
|
-
const p = lookup(k);
|
|
146
|
-
await p[hook].call(p, ...args);
|
|
147
|
-
}
|
|
148
|
-
let result;
|
|
149
|
-
if (original) {
|
|
150
|
-
result = await original.apply(this, args);
|
|
151
|
-
}
|
|
152
|
-
for (const k of after) {
|
|
153
|
-
const p = lookup(k);
|
|
154
|
-
await p[hook].call(p, ...args);
|
|
155
|
-
}
|
|
156
|
-
return result;
|
|
157
|
-
};
|
|
141
|
+
proto[hook] = composePluginHook(hook, before, after, proto[hook]);
|
|
158
142
|
}
|
|
159
143
|
}
|
|
144
|
+
function wrapOwnHooks(room, layout) {
|
|
145
|
+
for (const hook of PLUGIN_LIFECYCLE_KEYS) {
|
|
146
|
+
const { before, after } = layout.hooks[hook];
|
|
147
|
+
if (before.length === 0 && after.length === 0) {
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
if (!Object.hasOwn(room, hook)) {
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
room[hook] = composePluginHook(hook, before, after, room[hook]);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
function composePluginHook(hook, before, after, original) {
|
|
157
|
+
return async function(...args) {
|
|
158
|
+
const lookup = (k) => k.startsWith(DEP_KEY_PREFIX) ? this._autoPlugins[k] : this.plugins[k];
|
|
159
|
+
for (const k of before) {
|
|
160
|
+
const p = lookup(k);
|
|
161
|
+
await p[hook].call(p, ...args);
|
|
162
|
+
}
|
|
163
|
+
let result;
|
|
164
|
+
if (original) {
|
|
165
|
+
result = await original.apply(this, args);
|
|
166
|
+
}
|
|
167
|
+
for (const k of after) {
|
|
168
|
+
const p = lookup(k);
|
|
169
|
+
await p[hook].call(p, ...args);
|
|
170
|
+
}
|
|
171
|
+
return result;
|
|
172
|
+
};
|
|
173
|
+
}
|
|
160
174
|
function setupRoomPlugins(room) {
|
|
161
175
|
const plugins = room.plugins;
|
|
162
176
|
const layout = resolveOrComputeLayout(room.constructor, plugins);
|
|
163
177
|
attachRoomReference(room, plugins);
|
|
178
|
+
if (layout) {
|
|
179
|
+
wrapOwnHooks(room, layout);
|
|
180
|
+
}
|
|
164
181
|
if (layout && layout.autoDeps.length > 0) {
|
|
165
182
|
room._autoPlugins = instantiateAutoDeps(room, layout);
|
|
166
183
|
}
|
package/build/RoomPlugin.mjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/RoomPlugin.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Room plugins.\n *\n * A plugin is a composable extension to a Room \u2014 it can declare message\n * handlers, attach lifecycle hooks, and expose public methods that the\n * room can call (`this.plugins.<key>.someMethod()`). The framework\n * instantiates one plugin per room, sets `this.room` after the room is\n * constructed, then merges the plugin's `messages` with the room's own\n * and wires its lifecycle hooks alongside the room's.\n *\n * Example: a tiny chat plugin contributing a single message handler:\n *\n * class ChatPlugin extends RoomPlugin {\n * private history: string[] = [];\n * constructor(private opts: { historyLimit: number }) { super(); }\n *\n * messages = {\n * chat: (client: Client, msg: { text: string }) => {\n * this.history.push(msg.text);\n * if (this.history.length > this.opts.historyLimit) this.history.shift();\n * this.room.broadcast('chat', { from: client.userId, text: msg.text });\n * },\n * };\n *\n * // Public \u2014 callable as `this.plugins.chat.getHistory()` from the room\n * getHistory(): readonly string[] { return this.history; }\n * }\n *\n * Use via `definePlugins`:\n *\n * class MyRoom extends Room<{ state: MyState }> {\n * plugins = definePlugins({\n * chat: new ChatPlugin({ historyLimit: 100 }),\n * });\n * }\n */\nimport type { Room } from './Room.ts';\nimport type { AuthContext, Client } from './Transport.ts';\nimport type { Messages } from '@colyseus/shared-types';\n\n/**\n * Ordering hint for a plugin's lifecycle hook relative to the room's own\n * hook. Sensible per-hook defaults are applied when omitted (see\n * `Room.__init` for the exact ordering policy).\n *\n * onCreate / onAuth / onJoin \u2192 plugins run BEFORE room (guards + setup)\n * onLeave / onDispose \u2192 plugins run AFTER room (capture final state)\n */\nexport interface RoomPluginOrder {\n onCreate?: 'before' | 'after';\n onAuth?: 'before' | 'after';\n onJoin?: 'before' | 'after';\n onLeave?: 'before' | 'after';\n onDispose?: 'before' | 'after';\n}\n\n/**\n * Base class for room plugins. Subclass to define a plugin; the framework\n * sets `this.room` after the host room is fully constructed.\n *\n * Don't access `this.room` from the plugin's constructor \u2014 it hasn't been\n * wired yet. Everything room-dependent goes in `onCreate` / `onJoin` /\n * etc. or in public methods that are called from the room post-init.\n *\n * @typeParam This - The Room subclass this plugin is attached to. Narrow\n * for schema-driven plugins that need a specific state shape, e.g.\n * `class PhysicsPlugin extends RoomPlugin<Room<{ state: PhysicsContract }>>`.\n */\nexport abstract class RoomPlugin<This extends Room = Room> {\n /**\n * Live room reference. Wired by the framework at __init, AFTER the\n * room's own construction \u2014 accessing it from the plugin's\n * constructor throws.\n */\n protected readonly room!: This;\n\n /**\n * Canonical key for the plugin when registered via `definePlugins([...])`.\n * Declared on the subclass with `as const` so the literal type flows\n * into `room.plugins.<key>`:\n *\n * class ChatPlugin extends RoomPlugin {\n * readonly pluginName = 'chat' as const;\n * }\n *\n * Optional under the keyed-record form (`definePlugins({ chat: ... })`),\n * required under the array form. Must stay `public` so `extends` /\n * `keyof` can see the literal \u2014 those are blind to protected from\n * outside the class. End-user autocomplete hides it via `Omit` in\n * `definePlugins`'s return type.\n *\n * For multi-instance use, accept the name at construction:\n *\n * readonly pluginName: string;\n * constructor(name = 'chat') { super(); this.pluginName = name; }\n */\n readonly pluginName?: string;\n\n /**\n * Declarative message handlers \u2014 merged into the room's `messages` at\n * __init. Conflict against the room's own key: room wins. Conflict\n * between two plugins: throws at __init.\n */\n protected messages?: Messages<This>;\n\n /** Optional per-hook ordering vs the room's own hook. */\n protected order?: RoomPluginOrder;\n\n // Lifecycle hooks \u2014 override any subset. `protected` so they don't\n // leak into `this.plugins.<key>.onJoin(...)` autocomplete; subclass\n // overrides must keep `protected` (TS widens to public silently\n // otherwise).\n protected onCreate?(options: any): void | Promise<void>;\n protected onAuth?(client: Client, options: any, context: AuthContext): void | Promise<void>;\n protected onJoin?(client: Client, options?: any): void | Promise<void>;\n protected onLeave?(client: Client, code?: number): void | Promise<void>;\n protected onDispose?(): void | Promise<void>;\n}\n\n/**\n * Plugin-class constructor type used by the `dependencies` static\n * declaration. Constrained to zero-arg constructors because the\n * framework auto-instantiates missing dependencies with no\n * configuration \u2014 plugins that need options can't be auto-included\n * and must be registered explicitly in `definePlugins({...})`.\n */\nexport type RoomPluginClass = new () => RoomPlugin<any>;\n\n/**\n * Static `dependencies` declaration. List other plugin classes this\n * plugin needs alongside it; the framework auto-instantiates any\n * missing ones at room construction time. Transitive deps are\n * resolved recursively. Cycles throw at class-init.\n *\n * Example:\n * class UniqueSessionPlugin extends RoomPlugin {\n * static dependencies: PluginDependencies = [TrackUserSessionsPlugin];\n * }\n */\nexport type PluginDependencies = ReadonlyArray<RoomPluginClass>;\n\n/**\n * Define a Room's plugin record. The framework wires plugins at\n * `__init` \u2014 first construct of the class computes the layout\n * (cached on the constructor) and installs hook wrappers on the\n * prototype. The `const T` modifier preserves literal types so\n * `this.plugins.<key>.method()` autocompletes against each plugin's\n * specific subclass.\n */\n// Pulls each plugin's `pluginName` literal as the record key. Subclass\n// must narrow with `as const` \u2014 plain `string` resolves to `never`\n// and the entry is dropped (callers see a TS error on\n// `plugins.<thatKey>`).\ntype ExtractPluginName<P> = P extends { pluginName: infer K }\n ? (K extends string ? K : never)\n : never;\n\n/** Hide `pluginName` from end-user autocomplete on `this.plugins.<key>`. */\ntype PluginPublicSurface<P> = Omit<P, 'pluginName'>;\n\ntype PluginsArrayToRecord<T extends readonly RoomPlugin<any>[]> = {\n [P in T[number] as ExtractPluginName<P>]: PluginPublicSurface<P>;\n};\n\n/**\n * Array form (recommended). Each plugin declares its own canonical\n * key via `readonly pluginName = '...' as const`; the framework\n * turns the array into a typed record so `plugins.<pluginName>`\n * autocompletes the right instance type.\n *\n * class GameRoom extends Room {\n * plugins = definePlugins([\n * new ChatPlugin(), // pluginName: 'chat'\n * new UniqueSessionPlugin({ max: 1 }), // pluginName: 'uniqueSession'\n * ]);\n * }\n * this.plugins.chat.send('hi');\n *\n * Throws at runtime if any plugin is missing `pluginName` or if two\n * plugins resolve to the same key.\n */\nexport function definePlugins<const T extends readonly RoomPlugin<any>[]>(\n plugins: T,\n): PluginsArrayToRecord<T>;\n\n/**\n * Record form (legacy / multi-instance escape hatch). The caller\n * chooses the key per-room. Useful when registering two instances of\n * the same plugin class without configuring `pluginName` per\n * instance \u2014 e.g. `{ adminChat: new ChatPlugin(), playerChat: new ChatPlugin() }`.\n */\nexport function definePlugins<const T extends Record<string, RoomPlugin<any>>>(\n plugins: T,\n): { [K in keyof T]: PluginPublicSurface<T[K]> };\n\nexport function definePlugins(plugins: any): any {\n if (!Array.isArray(plugins)) { return plugins; }\n const out: Record<string, RoomPlugin> = {};\n for (const p of plugins) {\n const key = p['pluginName'];\n if (typeof key !== 'string' || key.length === 0) {\n throw new Error(\n `[Room] plugin ${p.constructor.name} is missing a 'pluginName' field. ` +\n `Declare \\`readonly pluginName = '<key>' as const\\` on the class, ` +\n `or register it via the keyed-record form \\`definePlugins({ <key>: <plugin> })\\`.`,\n );\n }\n if (out[key]) {\n throw new Error(\n `[Room] two plugins resolve to pluginName \"${key}\". Configure one of ` +\n `them via constructor argument, or use the keyed-record form to disambiguate.`,\n );\n }\n out[key] = p;\n }\n return out;\n}\n\n/**\n * Lifecycle hook keys recognized by the framework \u2014 used internally to\n * separate \"framework-recognized methods\" from \"user-defined public\n * methods\" when wiring a plugin into a room. Exported for the test\n * harness; downstream code should not need it.\n */\nexport const PLUGIN_LIFECYCLE_KEYS = ['onCreate', 'onAuth', 'onJoin', 'onLeave', 'onDispose'] as const;\nexport type PluginLifecycleKey = (typeof PLUGIN_LIFECYCLE_KEYS)[number];\n\n/**\n * Test helper \u2014 attach a stub or fake room to a plugin so its methods\n * and lifecycle hooks can be exercised in isolation without spinning up\n * a real Colyseus server.\n *\n * const plugin = new ChatPlugin({ historyLimit: 5 });\n * const room = attachToTestRoom(plugin, { broadcast: sinon.spy() });\n * await plugin.messages!.chat!.call(plugin, { userId: 'u1' }, { text: 'hi' });\n *\n * The second arg is shallow-merged onto the stub so tests only declare\n * the room properties they actually exercise. Returns the room stub for\n * post-call assertions.\n */\nexport function attachToTestRoom<This extends Room, R extends Partial<This>>(\n plugin: RoomPlugin<This>,\n roomStub: R = {} as R,\n): R {\n (plugin as any).room = roomStub;\n return roomStub;\n}\n\n// ---------------------------------------------------------------------------\n// Layout machinery \u2014 used by Room.__init to set plugins up once per class.\n// Lives in this file (rather than Room.ts) so the plugin-related types and\n// helpers stay co-located. These are framework internals; callers outside\n// `@colyseus/core` should not depend on them.\n// ---------------------------------------------------------------------------\n\n/**\n * Precomputed plugin layout for a Room subclass \u2014 populated on first\n * construct, cached on the constructor. Hook wrappers are installed\n * on the prototype in the same pass (see `installPluginHookWrappers`).\n *\n * @internal\n */\nexport interface PluginLayout {\n /** Per-hook participation: which plugin keys run before/after the room's own hook. */\n hooks: Record<PluginLifecycleKey, { before: string[]; after: string[] }>;\n /** Message key \u2192 plugin key. Conflict detection ran when this was built. */\n messageOwners: Map<string, string>;\n /** Sentinel-keyed plugin classes to instantiate per room. */\n autoDeps: Array<{ key: string; ctor: RoomPluginClass }>;\n}\n\n/** Sentinel prefix for framework-instantiated deps. The colon prevents\n * collisions with any JS identifier the user could use as a key. */\nconst DEP_KEY_PREFIX = '__dep:';\n\n/**\n * Default before/after policy for lifecycle hooks vs the room's own\n * hook. Plugins can override per-hook via the `order` field on the\n * plugin instance.\n *\n * onCreate / onAuth / onJoin \u2192 plugins run BEFORE room (guards + setup)\n * onLeave / onDispose \u2192 plugins run AFTER room (capture final state)\n *\n * @internal\n */\nexport const DEFAULT_PLUGIN_ORDER: Record<PluginLifecycleKey, 'before' | 'after'> = {\n onCreate: 'before',\n onAuth: 'before',\n onJoin: 'before',\n onLeave: 'after',\n onDispose: 'after',\n};\n\n/**\n * Walk the room's plugin instances and produce the lifecycle + message\n * layout for the Room class. Called once per Room subclass \u2014 on the\n * first construct \u2014 and the result is cached on the constructor. Throws\n * on duplicate message keys (named both plugin keys) so the failure is\n * visible at class-init rather than at first message dispatch.\n *\n * Returns `null` when no plugins participate in any hook AND none\n * declare a message \u2014 distinguishes \"computed, nothing to do\" from\n * \"not computed yet\" in the `__pluginLayout` cache.\n *\n * @internal\n */\nexport function computePluginLayout(plugins: Record<string, RoomPlugin>): PluginLayout | null {\n // Resolve `static dependencies` closures over the user's record.\n // Returns an expanded list (user + auto-deps), the auto-dep\n // class table for per-room instantiation, and a unified view of\n // entries to iterate when computing hooks / message owners.\n const resolved = resolveDependencies(plugins);\n\n const hooks = {} as Record<PluginLifecycleKey, { before: string[]; after: string[] }>;\n let anyHook = false;\n\n for (const hook of PLUGIN_LIFECYCLE_KEYS) {\n const before: string[] = [];\n const after: string[] = [];\n for (const { key, plugin } of resolved.entries) {\n if (typeof plugin[hook] !== 'function') { continue; }\n // Bracket access \u2014 `order` and `messages` are protected; TS\n // skips visibility checks on indexed access.\n const order = plugin['order']?.[hook] ?? DEFAULT_PLUGIN_ORDER[hook];\n (order === 'before' ? before : after).push(key);\n anyHook = true;\n }\n hooks[hook] = { before, after };\n }\n\n const messageOwners = new Map<string, string>();\n for (const { key, plugin } of resolved.entries) {\n const messages = plugin['messages'];\n if (!messages) { continue; }\n for (const messageKey of Object.keys(messages)) {\n const prior = messageOwners.get(messageKey);\n if (prior !== undefined) {\n throw new Error(\n `[Room] message key \"${messageKey}\" declared by multiple plugins: ` +\n `\"${prior}\" and \"${key}\". Resolve by giving one of them a ` +\n `different key, or override on the room's own \\`messages\\`.`,\n );\n }\n messageOwners.set(messageKey, key);\n }\n }\n\n if (!anyHook && messageOwners.size === 0 && resolved.autoDeps.length === 0) { return null; }\n return { hooks, messageOwners, autoDeps: resolved.autoDeps };\n}\n\n/**\n * Walk every plugin's `static dependencies` recursively, instantiating\n * missing classes (zero-arg only). Throws on cycles. Auto-deps are\n * keyed `__dep:<ClassName>` in the returned entries.\n */\nfunction resolveDependencies(plugins: Record<string, RoomPlugin>): {\n entries: Array<{ key: string; plugin: RoomPlugin }>;\n autoDeps: Array<{ key: string; ctor: RoomPluginClass }>;\n} {\n const entries: Array<{ key: string; plugin: RoomPlugin }> = [];\n for (const [key, plugin] of Object.entries(plugins)) {\n entries.push({ key, plugin });\n }\n\n const present = new Set<RoomPluginClass>();\n for (const { plugin } of entries) {\n present.add(plugin.constructor as RoomPluginClass);\n }\n\n const autoDeps: Array<{ key: string; ctor: RoomPluginClass }> = [];\n const visiting = new Set<RoomPluginClass>();\n const path: string[] = [];\n\n function walk(depCtor: RoomPluginClass): void {\n if (present.has(depCtor)) { return; }\n if (visiting.has(depCtor)) {\n const cycle = [...path, depCtor.name].join(' \u2192 ');\n throw new Error(`[Room] plugin dependency cycle: ${cycle}`);\n }\n visiting.add(depCtor);\n path.push(depCtor.name);\n\n // Recurse into deeper deps first \u2192 topological order in `entries`.\n const deeper = (depCtor as any).dependencies as PluginDependencies | undefined;\n if (Array.isArray(deeper)) {\n for (const inner of deeper) { walk(inner); }\n }\n\n let instance: RoomPlugin;\n try { instance = new depCtor(); }\n catch (err: any) {\n throw new Error(\n `[Room] auto-included plugin \"${depCtor.name}\" must be ` +\n `constructible with no arguments. If it needs options, ` +\n `register it explicitly in definePlugins({...}). ` +\n `(cause: ${err?.message ?? err})`,\n );\n }\n const key = DEP_KEY_PREFIX + depCtor.name;\n entries.push({ key, plugin: instance });\n autoDeps.push({ key, ctor: depCtor });\n present.add(depCtor);\n\n visiting.delete(depCtor);\n path.pop();\n }\n\n // Snapshot before mutating \u2014 transitive deps are handled recursively\n // inside `walk()`.\n const userEntriesSnapshot = entries.slice();\n for (const { plugin } of userEntriesSnapshot) {\n const deps = (plugin.constructor as any).dependencies as PluginDependencies | undefined;\n if (!Array.isArray(deps)) { continue; }\n for (const depCtor of deps) { walk(depCtor); }\n }\n\n return { entries, autoDeps };\n}\n\n/**\n * Install one wrapper per participating hook on the Room subclass's\n * prototype. The wrapper closes over plugin KEYS (resolved to refs at\n * call time) and invokes the captured original room hook between the\n * before/after plugin runs.\n *\n * @internal\n */\nexport function installPluginHookWrappers(\n ctor: { prototype: any },\n layout: PluginLayout | null,\n): void {\n if (layout === null) { return; }\n const proto = ctor.prototype;\n for (const hook of PLUGIN_LIFECYCLE_KEYS) {\n const { before, after } = layout.hooks[hook];\n if (before.length === 0 && after.length === 0) { continue; }\n\n const original = proto[hook] as Function | undefined;\n proto[hook] = async function (\n this: { plugins?: Record<string, RoomPlugin>; _autoPlugins?: Record<string, RoomPlugin> },\n ...args: any[]\n ) {\n // User plugins live on `this.plugins`, auto-deps (sentinel-keyed)\n // on `this._autoPlugins` \u2014 kept separate so user types stay clean.\n const lookup = (k: string): RoomPlugin =>\n (k.startsWith(DEP_KEY_PREFIX) ? this._autoPlugins![k] : this.plugins![k]);\n for (const k of before) {\n const p = lookup(k);\n await (p[hook] as Function).call(p, ...args);\n }\n let result: unknown;\n if (original) { result = await original.apply(this, args); }\n for (const k of after) {\n const p = lookup(k);\n await (p[hook] as Function).call(p, ...args);\n }\n return result;\n };\n }\n}\n\n/** Structural shape used by `setupRoomPlugins` \u2014 avoids a Room import\n * so the dependency graph stays one-way (Room \u2192 RoomPlugin). */\ninterface RoomPluginHost {\n plugins?: Record<string, RoomPlugin<any>>;\n _autoPlugins?: Record<string, RoomPlugin<any>>;\n messages?: Record<string, Function> | any;\n constructor: { __pluginLayout?: PluginLayout | null; prototype: any };\n}\n\n/**\n * Wire a Room instance's plugins. Once-per-class layout (hook\n * participation, message owners, dep resolution) is cached on the\n * constructor; per-instance work attaches `room` refs, instantiates\n * auto-deps, and merges plugin messages.\n *\n * @internal\n */\nexport function setupRoomPlugins(room: RoomPluginHost): void {\n const plugins = room.plugins!;\n const layout = resolveOrComputeLayout(room.constructor, plugins);\n\n attachRoomReference(room, plugins);\n\n if (layout && layout.autoDeps.length > 0) {\n room._autoPlugins = instantiateAutoDeps(room, layout);\n }\n\n if (layout && layout.messageOwners.size > 0) {\n mergePluginMessages(room, layout);\n }\n\n Object.freeze(plugins);\n if (room._autoPlugins) { Object.freeze(room._autoPlugins); }\n}\n\n/**\n * Read cached layout for this subclass, or compute + install on\n * first construct. `hasOwnProperty` so a subclass that redeclares\n * `plugins` doesn't inherit the parent's wrapping.\n */\nfunction resolveOrComputeLayout(\n ctor: RoomPluginHost['constructor'],\n plugins: Record<string, RoomPlugin>,\n): PluginLayout | null | undefined {\n if (Object.prototype.hasOwnProperty.call(ctor, '__pluginLayout')) {\n return ctor.__pluginLayout;\n }\n const layout = computePluginLayout(plugins);\n installPluginHookWrappers(ctor, layout);\n ctor.__pluginLayout = layout;\n return layout;\n}\n\n/** Wire `plugin.room = room` on every user-explicit plugin. */\nfunction attachRoomReference(\n room: RoomPluginHost,\n plugins: Record<string, RoomPlugin>,\n): void {\n for (const plugin of Object.values(plugins)) {\n (plugin as any).room = room;\n }\n}\n\n/**\n * Build `_autoPlugins` \u2014 one fresh instance per `static dependencies`\n * entry. Kept separate from `room.plugins` so sentinel keys\n * (`__dep:<ClassName>`) don't leak into the user's typed view.\n */\nfunction instantiateAutoDeps(\n room: RoomPluginHost,\n layout: PluginLayout,\n): Record<string, RoomPlugin> {\n const auto: Record<string, RoomPlugin> = {};\n for (const { key, ctor: depCtor } of layout.autoDeps) {\n const instance = new depCtor();\n (instance as any).room = room;\n auto[key] = instance;\n }\n return auto;\n}\n\n/**\n * Copy plugin message handlers into `room.messages` (room's own key\n * wins; plugin-vs-plugin conflicts already threw at layout time).\n */\nfunction mergePluginMessages(\n room: RoomPluginHost,\n layout: PluginLayout,\n): void {\n const plugins = room.plugins!;\n for (const [messageKey, pluginKey] of layout.messageOwners) {\n if (room.messages?.[messageKey]) { continue; }\n const source = pluginKey.startsWith(DEP_KEY_PREFIX)\n ? room._autoPlugins![pluginKey]\n : plugins[pluginKey];\n const handler = source['messages']?.[messageKey];\n if (handler !== undefined) {\n (room.messages ??= {} as any)[messageKey] = handler;\n }\n }\n}\n"],
|
|
5
|
-
"mappings": ";AAoEO,IAAe,aAAf,MAAoD;AAiD3D;AA8EO,SAAS,cAAc,SAAmB;AAC/C,MAAI,CAAC,MAAM,QAAQ,OAAO,GAAG;AAAE,WAAO;AAAA,EAAS;AAC/C,QAAM,MAAkC,CAAC;AACzC,aAAW,KAAK,SAAS;AACvB,UAAM,MAAM,EAAE,YAAY;AAC1B,QAAI,OAAO,QAAQ,YAAY,IAAI,WAAW,GAAG;AAC/C,YAAM,IAAI;AAAA,QACR,iBAAiB,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AChC;AAAA,IACF;AACA,UAAM,MAAM,iBAAiB,QAAQ;AACrC,YAAQ,KAAK,EAAE,KAAK,QAAQ,SAAS,CAAC;AACtC,aAAS,KAAK,EAAE,KAAK,MAAM,QAAQ,CAAC;AACpC,YAAQ,IAAI,OAAO;AAEnB,aAAS,OAAO,OAAO;AACvB,SAAK,IAAI;AAAA,EACX;AAIA,QAAM,sBAAsB,QAAQ,MAAM;AAC1C,aAAW,EAAE,OAAO,KAAK,qBAAqB;AAC5C,UAAM,OAAQ,OAAO,YAAoB;AACzC,QAAI,CAAC,MAAM,QAAQ,IAAI,GAAG;AAAE;AAAA,IAAU;AACtC,eAAW,WAAW,MAAM;AAAE,WAAK,OAAO;AAAA,IAAG;AAAA,EAC/C;AAEA,SAAO,EAAE,SAAS,SAAS;AAC7B;AAUO,SAAS,0BACd,MACA,QACM;AACN,MAAI,WAAW,MAAM;AAAE;AAAA,EAAQ;AAC/B,QAAM,QAAQ,KAAK;AACnB,aAAW,QAAQ,uBAAuB;AACxC,UAAM,EAAE,QAAQ,MAAM,IAAI,OAAO,MAAM,IAAI;AAC3C,QAAI,OAAO,WAAW,KAAK,MAAM,WAAW,GAAG;AAAE;AAAA,IAAU;
|
|
4
|
+
"sourcesContent": ["/**\n * Room plugins.\n *\n * A plugin is a composable extension to a Room \u2014 it can declare message\n * handlers, attach lifecycle hooks, and expose public methods that the\n * room can call (`this.plugins.<key>.someMethod()`). The framework\n * instantiates one plugin per room, sets `this.room` after the room is\n * constructed, then merges the plugin's `messages` with the room's own\n * and wires its lifecycle hooks alongside the room's.\n *\n * Example: a tiny chat plugin contributing a single message handler:\n *\n * class ChatPlugin extends RoomPlugin {\n * private history: string[] = [];\n * constructor(private opts: { historyLimit: number }) { super(); }\n *\n * messages = {\n * chat: (client: Client, msg: { text: string }) => {\n * this.history.push(msg.text);\n * if (this.history.length > this.opts.historyLimit) this.history.shift();\n * this.room.broadcast('chat', { from: client.userId, text: msg.text });\n * },\n * };\n *\n * // Public \u2014 callable as `this.plugins.chat.getHistory()` from the room\n * getHistory(): readonly string[] { return this.history; }\n * }\n *\n * Use via `definePlugins`:\n *\n * class MyRoom extends Room<{ state: MyState }> {\n * plugins = definePlugins({\n * chat: new ChatPlugin({ historyLimit: 100 }),\n * });\n * }\n */\nimport type { Room } from './Room.ts';\nimport type { AuthContext, Client } from './Transport.ts';\nimport type { Messages } from '@colyseus/shared-types';\n\n/**\n * Ordering hint for a plugin's lifecycle hook relative to the room's own\n * hook. Sensible per-hook defaults are applied when omitted (see\n * `Room.__init` for the exact ordering policy).\n *\n * onCreate / onAuth / onJoin \u2192 plugins run BEFORE room (guards + setup)\n * onLeave / onDispose \u2192 plugins run AFTER room (capture final state)\n */\nexport interface RoomPluginOrder {\n onCreate?: 'before' | 'after';\n onAuth?: 'before' | 'after';\n onJoin?: 'before' | 'after';\n onLeave?: 'before' | 'after';\n onDispose?: 'before' | 'after';\n}\n\n/**\n * Base class for room plugins. Subclass to define a plugin; the framework\n * sets `this.room` after the host room is fully constructed.\n *\n * Don't access `this.room` from the plugin's constructor \u2014 it hasn't been\n * wired yet. Everything room-dependent goes in `onCreate` / `onJoin` /\n * etc. or in public methods that are called from the room post-init.\n *\n * @typeParam This - The Room subclass this plugin is attached to. Narrow\n * for schema-driven plugins that need a specific state shape, e.g.\n * `class PhysicsPlugin extends RoomPlugin<Room<{ state: PhysicsContract }>>`.\n */\nexport abstract class RoomPlugin<This extends Room = Room> {\n /**\n * Live room reference. Wired by the framework at __init, AFTER the\n * room's own construction \u2014 accessing it from the plugin's\n * constructor throws.\n */\n protected readonly room!: This;\n\n /**\n * Canonical key for the plugin when registered via `definePlugins([...])`.\n * Declared on the subclass with `as const` so the literal type flows\n * into `room.plugins.<key>`:\n *\n * class ChatPlugin extends RoomPlugin {\n * readonly pluginName = 'chat' as const;\n * }\n *\n * Optional under the keyed-record form (`definePlugins({ chat: ... })`),\n * required under the array form. Must stay `public` so `extends` /\n * `keyof` can see the literal \u2014 those are blind to protected from\n * outside the class. End-user autocomplete hides it via `Omit` in\n * `definePlugins`'s return type.\n *\n * For multi-instance use, accept the name at construction:\n *\n * readonly pluginName: string;\n * constructor(name = 'chat') { super(); this.pluginName = name; }\n */\n readonly pluginName?: string;\n\n /**\n * Declarative message handlers \u2014 merged into the room's `messages` at\n * __init. Conflict against the room's own key: room wins. Conflict\n * between two plugins: throws at __init.\n */\n protected messages?: Messages<This>;\n\n /** Optional per-hook ordering vs the room's own hook. */\n protected order?: RoomPluginOrder;\n\n // Lifecycle hooks \u2014 override any subset. `protected` so they don't\n // leak into `this.plugins.<key>.onJoin(...)` autocomplete; subclass\n // overrides must keep `protected` (TS widens to public silently\n // otherwise).\n protected onCreate?(options: any): void | Promise<void>;\n protected onAuth?(client: Client, options: any, context: AuthContext): void | Promise<void>;\n protected onJoin?(client: Client, options?: any): void | Promise<void>;\n protected onLeave?(client: Client, code?: number): void | Promise<void>;\n protected onDispose?(): void | Promise<void>;\n}\n\n/**\n * Plugin-class constructor type used by the `dependencies` static\n * declaration. Constrained to zero-arg constructors because the\n * framework auto-instantiates missing dependencies with no\n * configuration \u2014 plugins that need options can't be auto-included\n * and must be registered explicitly in `definePlugins({...})`.\n */\nexport type RoomPluginClass = new () => RoomPlugin<any>;\n\n/**\n * Static `dependencies` declaration. List other plugin classes this\n * plugin needs alongside it; the framework auto-instantiates any\n * missing ones at room construction time. Transitive deps are\n * resolved recursively. Cycles throw at class-init.\n *\n * Example:\n * class UniqueSessionPlugin extends RoomPlugin {\n * static dependencies: PluginDependencies = [TrackUserSessionsPlugin];\n * }\n */\nexport type PluginDependencies = ReadonlyArray<RoomPluginClass>;\n\n/**\n * Define a Room's plugin record. The framework wires plugins at\n * `__init` \u2014 first construct of the class computes the layout\n * (cached on the constructor) and installs hook wrappers on the\n * prototype. The `const T` modifier preserves literal types so\n * `this.plugins.<key>.method()` autocompletes against each plugin's\n * specific subclass.\n */\n// Pulls each plugin's `pluginName` literal as the record key. Subclass\n// must narrow with `as const` \u2014 plain `string` resolves to `never`\n// and the entry is dropped (callers see a TS error on\n// `plugins.<thatKey>`).\ntype ExtractPluginName<P> = P extends { pluginName: infer K }\n ? (K extends string ? K : never)\n : never;\n\n/** Hide `pluginName` from end-user autocomplete on `this.plugins.<key>`. */\ntype PluginPublicSurface<P> = Omit<P, 'pluginName'>;\n\ntype PluginsArrayToRecord<T extends readonly RoomPlugin<any>[]> = {\n [P in T[number] as ExtractPluginName<P>]: PluginPublicSurface<P>;\n};\n\n/**\n * Array form (recommended). Each plugin declares its own canonical\n * key via `readonly pluginName = '...' as const`; the framework\n * turns the array into a typed record so `plugins.<pluginName>`\n * autocompletes the right instance type.\n *\n * class GameRoom extends Room {\n * plugins = definePlugins([\n * new ChatPlugin(), // pluginName: 'chat'\n * new UniqueSessionPlugin({ max: 1 }), // pluginName: 'uniqueSession'\n * ]);\n * }\n * this.plugins.chat.send('hi');\n *\n * Throws at runtime if any plugin is missing `pluginName` or if two\n * plugins resolve to the same key.\n */\nexport function definePlugins<const T extends readonly RoomPlugin<any>[]>(\n plugins: T,\n): PluginsArrayToRecord<T>;\n\n/**\n * Record form (legacy / multi-instance escape hatch). The caller\n * chooses the key per-room. Useful when registering two instances of\n * the same plugin class without configuring `pluginName` per\n * instance \u2014 e.g. `{ adminChat: new ChatPlugin(), playerChat: new ChatPlugin() }`.\n */\nexport function definePlugins<const T extends Record<string, RoomPlugin<any>>>(\n plugins: T,\n): { [K in keyof T]: PluginPublicSurface<T[K]> };\n\nexport function definePlugins(plugins: any): any {\n if (!Array.isArray(plugins)) { return plugins; }\n const out: Record<string, RoomPlugin> = {};\n for (const p of plugins) {\n const key = p['pluginName'];\n if (typeof key !== 'string' || key.length === 0) {\n throw new Error(\n `[Room] plugin ${p.constructor.name} is missing a 'pluginName' field. ` +\n `Declare \\`readonly pluginName = '<key>' as const\\` on the class, ` +\n `or register it via the keyed-record form \\`definePlugins({ <key>: <plugin> })\\`.`,\n );\n }\n if (out[key]) {\n throw new Error(\n `[Room] two plugins resolve to pluginName \"${key}\". Configure one of ` +\n `them via constructor argument, or use the keyed-record form to disambiguate.`,\n );\n }\n out[key] = p;\n }\n return out;\n}\n\n/**\n * Lifecycle hook keys recognized by the framework \u2014 used internally to\n * separate \"framework-recognized methods\" from \"user-defined public\n * methods\" when wiring a plugin into a room. Exported for the test\n * harness; downstream code should not need it.\n */\nexport const PLUGIN_LIFECYCLE_KEYS = ['onCreate', 'onAuth', 'onJoin', 'onLeave', 'onDispose'] as const;\nexport type PluginLifecycleKey = (typeof PLUGIN_LIFECYCLE_KEYS)[number];\n\n/**\n * Test helper \u2014 attach a stub or fake room to a plugin so its methods\n * and lifecycle hooks can be exercised in isolation without spinning up\n * a real Colyseus server.\n *\n * const plugin = new ChatPlugin({ historyLimit: 5 });\n * const room = attachToTestRoom(plugin, { broadcast: sinon.spy() });\n * await plugin.messages!.chat!.call(plugin, { userId: 'u1' }, { text: 'hi' });\n *\n * The second arg is shallow-merged onto the stub so tests only declare\n * the room properties they actually exercise. Returns the room stub for\n * post-call assertions.\n */\nexport function attachToTestRoom<This extends Room, R extends Partial<This>>(\n plugin: RoomPlugin<This>,\n roomStub: R = {} as R,\n): R {\n (plugin as any).room = roomStub;\n return roomStub;\n}\n\n// ---------------------------------------------------------------------------\n// Layout machinery \u2014 used by Room.__init to set plugins up once per class.\n// Lives in this file (rather than Room.ts) so the plugin-related types and\n// helpers stay co-located. These are framework internals; callers outside\n// `@colyseus/core` should not depend on them.\n// ---------------------------------------------------------------------------\n\n/**\n * Precomputed plugin layout for a Room subclass \u2014 populated on first\n * construct, cached on the constructor. Hook wrappers are installed\n * on the prototype in the same pass (see `installPluginHookWrappers`).\n *\n * @internal\n */\nexport interface PluginLayout {\n /** Per-hook participation: which plugin keys run before/after the room's own hook. */\n hooks: Record<PluginLifecycleKey, { before: string[]; after: string[] }>;\n /** Message key \u2192 plugin key. Conflict detection ran when this was built. */\n messageOwners: Map<string, string>;\n /** Sentinel-keyed plugin classes to instantiate per room. */\n autoDeps: Array<{ key: string; ctor: RoomPluginClass }>;\n}\n\n/** Sentinel prefix for framework-instantiated deps. The colon prevents\n * collisions with any JS identifier the user could use as a key. */\nconst DEP_KEY_PREFIX = '__dep:';\n\n/**\n * Default before/after policy for lifecycle hooks vs the room's own\n * hook. Plugins can override per-hook via the `order` field on the\n * plugin instance.\n *\n * onCreate / onAuth / onJoin \u2192 plugins run BEFORE room (guards + setup)\n * onLeave / onDispose \u2192 plugins run AFTER room (capture final state)\n *\n * @internal\n */\nexport const DEFAULT_PLUGIN_ORDER: Record<PluginLifecycleKey, 'before' | 'after'> = {\n onCreate: 'before',\n onAuth: 'before',\n onJoin: 'before',\n onLeave: 'after',\n onDispose: 'after',\n};\n\n/**\n * Walk the room's plugin instances and produce the lifecycle + message\n * layout for the Room class. Called once per Room subclass \u2014 on the\n * first construct \u2014 and the result is cached on the constructor. Throws\n * on duplicate message keys (named both plugin keys) so the failure is\n * visible at class-init rather than at first message dispatch.\n *\n * Returns `null` when no plugins participate in any hook AND none\n * declare a message \u2014 distinguishes \"computed, nothing to do\" from\n * \"not computed yet\" in the `__pluginLayout` cache.\n *\n * @internal\n */\nexport function computePluginLayout(plugins: Record<string, RoomPlugin>): PluginLayout | null {\n // Resolve `static dependencies` closures over the user's record.\n // Returns an expanded list (user + auto-deps), the auto-dep\n // class table for per-room instantiation, and a unified view of\n // entries to iterate when computing hooks / message owners.\n const resolved = resolveDependencies(plugins);\n\n const hooks = {} as Record<PluginLifecycleKey, { before: string[]; after: string[] }>;\n let anyHook = false;\n\n for (const hook of PLUGIN_LIFECYCLE_KEYS) {\n const before: string[] = [];\n const after: string[] = [];\n for (const { key, plugin } of resolved.entries) {\n if (typeof plugin[hook] !== 'function') { continue; }\n // Bracket access \u2014 `order` and `messages` are protected; TS\n // skips visibility checks on indexed access.\n const order = plugin['order']?.[hook] ?? DEFAULT_PLUGIN_ORDER[hook];\n (order === 'before' ? before : after).push(key);\n anyHook = true;\n }\n hooks[hook] = { before, after };\n }\n\n const messageOwners = new Map<string, string>();\n for (const { key, plugin } of resolved.entries) {\n const messages = plugin['messages'];\n if (!messages) { continue; }\n for (const messageKey of Object.keys(messages)) {\n const prior = messageOwners.get(messageKey);\n if (prior !== undefined) {\n throw new Error(\n `[Room] message key \"${messageKey}\" declared by multiple plugins: ` +\n `\"${prior}\" and \"${key}\". Resolve by giving one of them a ` +\n `different key, or override on the room's own \\`messages\\`.`,\n );\n }\n messageOwners.set(messageKey, key);\n }\n }\n\n if (!anyHook && messageOwners.size === 0 && resolved.autoDeps.length === 0) { return null; }\n return { hooks, messageOwners, autoDeps: resolved.autoDeps };\n}\n\n/**\n * Walk every plugin's `static dependencies` recursively, instantiating\n * missing classes (zero-arg only). Throws on cycles. Auto-deps are\n * keyed `__dep:<ClassName>` in the returned entries.\n */\nfunction resolveDependencies(plugins: Record<string, RoomPlugin>): {\n entries: Array<{ key: string; plugin: RoomPlugin }>;\n autoDeps: Array<{ key: string; ctor: RoomPluginClass }>;\n} {\n const entries: Array<{ key: string; plugin: RoomPlugin }> = [];\n for (const [key, plugin] of Object.entries(plugins)) {\n entries.push({ key, plugin });\n }\n\n const present = new Set<RoomPluginClass>();\n for (const { plugin } of entries) {\n present.add(plugin.constructor as RoomPluginClass);\n }\n\n const autoDeps: Array<{ key: string; ctor: RoomPluginClass }> = [];\n const visiting = new Set<RoomPluginClass>();\n const path: string[] = [];\n\n function walk(depCtor: RoomPluginClass): void {\n if (present.has(depCtor)) { return; }\n if (visiting.has(depCtor)) {\n const cycle = [...path, depCtor.name].join(' \u2192 ');\n throw new Error(`[Room] plugin dependency cycle: ${cycle}`);\n }\n visiting.add(depCtor);\n path.push(depCtor.name);\n\n // Recurse into deeper deps first \u2192 topological order in `entries`.\n const deeper = (depCtor as any).dependencies as PluginDependencies | undefined;\n if (Array.isArray(deeper)) {\n for (const inner of deeper) { walk(inner); }\n }\n\n let instance: RoomPlugin;\n try { instance = new depCtor(); }\n catch (err: any) {\n throw new Error(\n `[Room] auto-included plugin \"${depCtor.name}\" must be ` +\n `constructible with no arguments. If it needs options, ` +\n `register it explicitly in definePlugins({...}). ` +\n `(cause: ${err?.message ?? err})`,\n );\n }\n const key = DEP_KEY_PREFIX + depCtor.name;\n entries.push({ key, plugin: instance });\n autoDeps.push({ key, ctor: depCtor });\n present.add(depCtor);\n\n visiting.delete(depCtor);\n path.pop();\n }\n\n // Snapshot before mutating \u2014 transitive deps are handled recursively\n // inside `walk()`.\n const userEntriesSnapshot = entries.slice();\n for (const { plugin } of userEntriesSnapshot) {\n const deps = (plugin.constructor as any).dependencies as PluginDependencies | undefined;\n if (!Array.isArray(deps)) { continue; }\n for (const depCtor of deps) { walk(depCtor); }\n }\n\n return { entries, autoDeps };\n}\n\n/**\n * Install one wrapper per participating hook on the Room subclass's\n * prototype. The wrapper closes over plugin KEYS (resolved to refs at\n * call time) and invokes the captured original room hook between the\n * before/after plugin runs.\n *\n * @internal\n */\nexport function installPluginHookWrappers(\n ctor: { prototype: any },\n layout: PluginLayout | null,\n): void {\n if (layout === null) { return; }\n const proto = ctor.prototype;\n for (const hook of PLUGIN_LIFECYCLE_KEYS) {\n const { before, after } = layout.hooks[hook];\n if (before.length === 0 && after.length === 0) { continue; }\n proto[hook] = composePluginHook(hook, before, after, proto[hook]);\n }\n}\n\n/**\n * Hooks declared as class fields (`onJoin = () => {}`) are own properties\n * that shadow the prototype wrapper, so wrap them per instance.\n */\nfunction wrapOwnHooks(room: RoomPluginHost, layout: PluginLayout): void {\n for (const hook of PLUGIN_LIFECYCLE_KEYS) {\n const { before, after } = layout.hooks[hook];\n if (before.length === 0 && after.length === 0) { continue; }\n if (!Object.hasOwn(room, hook)) { continue; }\n (room as any)[hook] = composePluginHook(hook, before, after, (room as any)[hook]);\n }\n}\n\n/** Run the `before` plugins, then `original`, then the `after` plugins. */\nfunction composePluginHook(\n hook: PluginLifecycleKey,\n before: string[],\n after: string[],\n original: Function | undefined,\n) {\n return async function (\n this: { plugins?: Record<string, RoomPlugin>; _autoPlugins?: Record<string, RoomPlugin> },\n ...args: any[]\n ) {\n // User plugins live on `this.plugins`, auto-deps (sentinel-keyed)\n // on `this._autoPlugins` \u2014 kept separate so user types stay clean.\n const lookup = (k: string): RoomPlugin =>\n (k.startsWith(DEP_KEY_PREFIX) ? this._autoPlugins![k] : this.plugins![k]);\n for (const k of before) {\n const p = lookup(k);\n await (p[hook] as Function).call(p, ...args);\n }\n let result: unknown;\n if (original) { result = await original.apply(this, args); }\n for (const k of after) {\n const p = lookup(k);\n await (p[hook] as Function).call(p, ...args);\n }\n return result;\n };\n}\n\n/** Structural shape used by `setupRoomPlugins` \u2014 avoids a Room import\n * so the dependency graph stays one-way (Room \u2192 RoomPlugin). */\ninterface RoomPluginHost {\n plugins?: Record<string, RoomPlugin<any>>;\n _autoPlugins?: Record<string, RoomPlugin<any>>;\n messages?: Record<string, Function> | any;\n constructor: { __pluginLayout?: PluginLayout | null; prototype: any };\n}\n\n/**\n * Wire a Room instance's plugins. Once-per-class layout (hook\n * participation, message owners, dep resolution) is cached on the\n * constructor; per-instance work attaches `room` refs, instantiates\n * auto-deps, and merges plugin messages.\n *\n * @internal\n */\nexport function setupRoomPlugins(room: RoomPluginHost): void {\n const plugins = room.plugins!;\n const layout = resolveOrComputeLayout(room.constructor, plugins);\n\n attachRoomReference(room, plugins);\n\n if (layout) {\n wrapOwnHooks(room, layout);\n }\n\n if (layout && layout.autoDeps.length > 0) {\n room._autoPlugins = instantiateAutoDeps(room, layout);\n }\n\n if (layout && layout.messageOwners.size > 0) {\n mergePluginMessages(room, layout);\n }\n\n Object.freeze(plugins);\n if (room._autoPlugins) { Object.freeze(room._autoPlugins); }\n}\n\n/**\n * Read cached layout for this subclass, or compute + install on\n * first construct. `hasOwnProperty` so a subclass that redeclares\n * `plugins` doesn't inherit the parent's wrapping.\n */\nfunction resolveOrComputeLayout(\n ctor: RoomPluginHost['constructor'],\n plugins: Record<string, RoomPlugin>,\n): PluginLayout | null | undefined {\n if (Object.prototype.hasOwnProperty.call(ctor, '__pluginLayout')) {\n return ctor.__pluginLayout;\n }\n const layout = computePluginLayout(plugins);\n installPluginHookWrappers(ctor, layout);\n ctor.__pluginLayout = layout;\n return layout;\n}\n\n/** Wire `plugin.room = room` on every user-explicit plugin. */\nfunction attachRoomReference(\n room: RoomPluginHost,\n plugins: Record<string, RoomPlugin>,\n): void {\n for (const plugin of Object.values(plugins)) {\n (plugin as any).room = room;\n }\n}\n\n/**\n * Build `_autoPlugins` \u2014 one fresh instance per `static dependencies`\n * entry. Kept separate from `room.plugins` so sentinel keys\n * (`__dep:<ClassName>`) don't leak into the user's typed view.\n */\nfunction instantiateAutoDeps(\n room: RoomPluginHost,\n layout: PluginLayout,\n): Record<string, RoomPlugin> {\n const auto: Record<string, RoomPlugin> = {};\n for (const { key, ctor: depCtor } of layout.autoDeps) {\n const instance = new depCtor();\n (instance as any).room = room;\n auto[key] = instance;\n }\n return auto;\n}\n\n/**\n * Copy plugin message handlers into `room.messages` (room's own key\n * wins; plugin-vs-plugin conflicts already threw at layout time).\n */\nfunction mergePluginMessages(\n room: RoomPluginHost,\n layout: PluginLayout,\n): void {\n const plugins = room.plugins!;\n for (const [messageKey, pluginKey] of layout.messageOwners) {\n if (room.messages?.[messageKey]) { continue; }\n const source = pluginKey.startsWith(DEP_KEY_PREFIX)\n ? room._autoPlugins![pluginKey]\n : plugins[pluginKey];\n const handler = source['messages']?.[messageKey];\n if (handler !== undefined) {\n (room.messages ??= {} as any)[messageKey] = handler;\n }\n }\n}\n"],
|
|
5
|
+
"mappings": ";AAoEO,IAAe,aAAf,MAAoD;AAiD3D;AA8EO,SAAS,cAAc,SAAmB;AAC/C,MAAI,CAAC,MAAM,QAAQ,OAAO,GAAG;AAAE,WAAO;AAAA,EAAS;AAC/C,QAAM,MAAkC,CAAC;AACzC,aAAW,KAAK,SAAS;AACvB,UAAM,MAAM,EAAE,YAAY;AAC1B,QAAI,OAAO,QAAQ,YAAY,IAAI,WAAW,GAAG;AAC/C,YAAM,IAAI;AAAA,QACR,iB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ACzB;AACF;AAOA,SAAS,oBACP,MACA,QAC4B;AAC5B,QAAM,OAAmC,CAAC;AAC1C,aAAW,EAAE,KAAK,MAAM,QAAQ,KAAK,OAAO,UAAU;AACpD,UAAM,WAAW,IAAI,QAAQ;AAC7B,IAAC,SAAiB,OAAO;AACzB,SAAK,GAAG,IAAI;AAAA,EACd;AACA,SAAO;AACT;AAMA,SAAS,oBACP,MACA,QACM;AACN,QAAM,UAAU,KAAK;AACrB,aAAW,CAAC,YAAY,SAAS,KAAK,OAAO,eAAe;AAC1D,QAAI,KAAK,WAAW,UAAU,GAAG;AAAE;AAAA,IAAU;AAC7C,UAAM,SAAS,UAAU,WAAW,cAAc,IAC9C,KAAK,aAAc,SAAS,IAC5B,QAAQ,SAAS;AACrB,UAAM,UAAU,OAAO,UAAU,IAAI,UAAU;AAC/C,QAAI,YAAY,QAAW;AACzB,OAAC,KAAK,aAAa,CAAC,GAAU,UAAU,IAAI;AAAA,IAC9C;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@colyseus/core",
|
|
3
|
-
"version": "0.18.
|
|
3
|
+
"version": "0.18.19",
|
|
4
4
|
"description": "Multiplayer Framework for Node.js.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"input": "./src/index.ts",
|
|
@@ -53,24 +53,24 @@
|
|
|
53
53
|
"debug": "^4.3.4",
|
|
54
54
|
"msgpackr": "^2.0.1",
|
|
55
55
|
"nanoid": "^3.3.11",
|
|
56
|
-
"@colyseus/better-call": "^1.3.1",
|
|
57
56
|
"@colyseus/greeting-banner": "^4.0.3",
|
|
57
|
+
"@colyseus/better-call": "^1.3.1",
|
|
58
58
|
"@colyseus/shared-types": "^0.18.3"
|
|
59
59
|
},
|
|
60
60
|
"devDependencies": {
|
|
61
61
|
"@colyseus/schema": "^5.0.8",
|
|
62
62
|
"express": "^5.0.0",
|
|
63
63
|
"vitest": "^3.1.1",
|
|
64
|
-
"@colyseus/redis-
|
|
65
|
-
"@colyseus/tools": "^0.18.
|
|
66
|
-
"@colyseus/redis-
|
|
64
|
+
"@colyseus/redis-driver": "^0.18.5",
|
|
65
|
+
"@colyseus/tools": "^0.18.10",
|
|
66
|
+
"@colyseus/redis-presence": "^0.18.5"
|
|
67
67
|
},
|
|
68
68
|
"peerDependencies": {
|
|
69
69
|
"@colyseus/schema": "^5.0.8",
|
|
70
70
|
"@pm2/io": "^6.1.0",
|
|
71
71
|
"express": "^4.16.0 || ^5.0.0",
|
|
72
72
|
"zod": "^4.1.12",
|
|
73
|
-
"@colyseus/auth": "^0.18.
|
|
73
|
+
"@colyseus/auth": "^0.18.4",
|
|
74
74
|
"@colyseus/better-call": "^1.3.1",
|
|
75
75
|
"@colyseus/ws-transport": "^0.18.4"
|
|
76
76
|
},
|
package/src/Room.ts
CHANGED
|
@@ -451,13 +451,6 @@ export class Room<T extends RoomOptions = RoomOptions> {
|
|
|
451
451
|
.catch((e) => debugAndPrintError(`onDispose error: ${(e && e.stack || e.message || e || 'promise rejected')} (roomId: ${this.roomId})`))
|
|
452
452
|
.finally(() => this._events.emit('disconnect'));
|
|
453
453
|
});
|
|
454
|
-
|
|
455
|
-
/**
|
|
456
|
-
* If `onUncaughtException` is defined, it will automatically catch exceptions
|
|
457
|
-
*/
|
|
458
|
-
if (this.onUncaughtException !== undefined) {
|
|
459
|
-
this.#registerUncaughtExceptionHandlers();
|
|
460
|
-
}
|
|
461
454
|
}
|
|
462
455
|
|
|
463
456
|
/**
|
|
@@ -592,6 +585,12 @@ export class Room<T extends RoomOptions = RoomOptions> {
|
|
|
592
585
|
setupRoomPlugins(this);
|
|
593
586
|
}
|
|
594
587
|
|
|
588
|
+
// After setupRoomPlugins(), so the try/catch covers plugin hooks too.
|
|
589
|
+
// Not in the constructor: subclass fields aren't assigned until it returns.
|
|
590
|
+
if (this.onUncaughtException !== undefined) {
|
|
591
|
+
this.#registerUncaughtExceptionHandlers();
|
|
592
|
+
}
|
|
593
|
+
|
|
595
594
|
// Bind messages to the room
|
|
596
595
|
if (this.messages !== undefined) {
|
|
597
596
|
|
|
@@ -2487,7 +2486,8 @@ export class Room<T extends RoomOptions = RoomOptions> {
|
|
|
2487
2486
|
this.onCreate = wrapTryCatch(this.onCreate.bind(this), onUncaughtException, OnCreateException, 'onCreate', true);
|
|
2488
2487
|
}
|
|
2489
2488
|
|
|
2490
|
-
|
|
2489
|
+
// _onJoin skips onAuth only while it's still Room's default
|
|
2490
|
+
if (this.onAuth !== Room.prototype.onAuth) {
|
|
2491
2491
|
this.onAuth = wrapTryCatch(this.onAuth.bind(this), onUncaughtException, OnAuthException, 'onAuth', true);
|
|
2492
2492
|
}
|
|
2493
2493
|
|
package/src/RoomPlugin.ts
CHANGED
|
@@ -435,31 +435,52 @@ export function installPluginHookWrappers(
|
|
|
435
435
|
for (const hook of PLUGIN_LIFECYCLE_KEYS) {
|
|
436
436
|
const { before, after } = layout.hooks[hook];
|
|
437
437
|
if (before.length === 0 && after.length === 0) { continue; }
|
|
438
|
+
proto[hook] = composePluginHook(hook, before, after, proto[hook]);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
438
441
|
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
const p = lookup(k);
|
|
450
|
-
await (p[hook] as Function).call(p, ...args);
|
|
451
|
-
}
|
|
452
|
-
let result: unknown;
|
|
453
|
-
if (original) { result = await original.apply(this, args); }
|
|
454
|
-
for (const k of after) {
|
|
455
|
-
const p = lookup(k);
|
|
456
|
-
await (p[hook] as Function).call(p, ...args);
|
|
457
|
-
}
|
|
458
|
-
return result;
|
|
459
|
-
};
|
|
442
|
+
/**
|
|
443
|
+
* Hooks declared as class fields (`onJoin = () => {}`) are own properties
|
|
444
|
+
* that shadow the prototype wrapper, so wrap them per instance.
|
|
445
|
+
*/
|
|
446
|
+
function wrapOwnHooks(room: RoomPluginHost, layout: PluginLayout): void {
|
|
447
|
+
for (const hook of PLUGIN_LIFECYCLE_KEYS) {
|
|
448
|
+
const { before, after } = layout.hooks[hook];
|
|
449
|
+
if (before.length === 0 && after.length === 0) { continue; }
|
|
450
|
+
if (!Object.hasOwn(room, hook)) { continue; }
|
|
451
|
+
(room as any)[hook] = composePluginHook(hook, before, after, (room as any)[hook]);
|
|
460
452
|
}
|
|
461
453
|
}
|
|
462
454
|
|
|
455
|
+
/** Run the `before` plugins, then `original`, then the `after` plugins. */
|
|
456
|
+
function composePluginHook(
|
|
457
|
+
hook: PluginLifecycleKey,
|
|
458
|
+
before: string[],
|
|
459
|
+
after: string[],
|
|
460
|
+
original: Function | undefined,
|
|
461
|
+
) {
|
|
462
|
+
return async function (
|
|
463
|
+
this: { plugins?: Record<string, RoomPlugin>; _autoPlugins?: Record<string, RoomPlugin> },
|
|
464
|
+
...args: any[]
|
|
465
|
+
) {
|
|
466
|
+
// User plugins live on `this.plugins`, auto-deps (sentinel-keyed)
|
|
467
|
+
// on `this._autoPlugins` — kept separate so user types stay clean.
|
|
468
|
+
const lookup = (k: string): RoomPlugin =>
|
|
469
|
+
(k.startsWith(DEP_KEY_PREFIX) ? this._autoPlugins![k] : this.plugins![k]);
|
|
470
|
+
for (const k of before) {
|
|
471
|
+
const p = lookup(k);
|
|
472
|
+
await (p[hook] as Function).call(p, ...args);
|
|
473
|
+
}
|
|
474
|
+
let result: unknown;
|
|
475
|
+
if (original) { result = await original.apply(this, args); }
|
|
476
|
+
for (const k of after) {
|
|
477
|
+
const p = lookup(k);
|
|
478
|
+
await (p[hook] as Function).call(p, ...args);
|
|
479
|
+
}
|
|
480
|
+
return result;
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
|
|
463
484
|
/** Structural shape used by `setupRoomPlugins` — avoids a Room import
|
|
464
485
|
* so the dependency graph stays one-way (Room → RoomPlugin). */
|
|
465
486
|
interface RoomPluginHost {
|
|
@@ -483,6 +504,10 @@ export function setupRoomPlugins(room: RoomPluginHost): void {
|
|
|
483
504
|
|
|
484
505
|
attachRoomReference(room, plugins);
|
|
485
506
|
|
|
507
|
+
if (layout) {
|
|
508
|
+
wrapOwnHooks(room, layout);
|
|
509
|
+
}
|
|
510
|
+
|
|
486
511
|
if (layout && layout.autoDeps.length > 0) {
|
|
487
512
|
room._autoPlugins = instantiateAutoDeps(room, layout);
|
|
488
513
|
}
|