@vielzeug/tavern 26.11.11 → 26.11.13

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.
@@ -1 +1 @@
1
- {"version":3,"file":"tavern.iife.js","names":["createMeshHost","meshQrCodec","MeshPairingError","createMeshGuest","exports","tappers","stopped","tapper","event","options","handler","message","opts","error","DEFAULT_MAX_MESSAGE_BYTES","raw","id","name","subjectId","args","host","_vielzeug_mesh","closed","flushScheduled","off","detach","snapshot","command","peerId","payload","decoded","text","wire","notice","guest","mounted","ended","subject","answer"],"sources":["../src/_tappers.ts","../src/errors.ts","../src/index.ts"],"sourcesContent":["/**\n * The `tap()` machinery shared by the host and guest handles. Kept private: the\n * public contract is each handle's `tap` method and its event union, not this.\n *\n * Follows the repo observability rules: zero overhead with no tappers, handler\n * errors swallowed, auto-detach on an abort signal, and a no-op unsubscribe once\n * the handle has stopped.\n */\nexport interface Tappers<E extends { readonly type: string }> {\n /** Emits to every tapper; a no-op when none are registered. */\n emit(event: E): void;\n /** Drops every tapper and makes later `tap` calls no-ops. Idempotent. */\n stop(): void;\n tap(handler: (event: E) => void, options?: { readonly signal?: AbortSignal }): () => void;\n}\n\nexport function createTappers<E extends { readonly type: string }>(): Tappers<E> {\n const tappers = new Set<(event: E) => void>();\n let stopped = false;\n\n return {\n emit(event): void {\n if (tappers.size === 0) return;\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect session behavior.\n }\n }\n },\n stop(): void {\n stopped = true;\n tappers.clear();\n },\n tap(handler, options): () => void {\n if (stopped || options?.signal?.aborted) return () => {};\n const detach = (): void => {\n tappers.delete(handler);\n };\n tappers.add(handler);\n options?.signal?.addEventListener('abort', detach, { once: true });\n return detach;\n },\n };\n}\n","/**\n * Base class for all tavern errors.\n * Use `instanceof TavernError` to catch any tavern-originated error in one branch.\n */\nexport class TavernError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** A pairing code the consumer pasted could not be used: a user-input mistake, not a bug. */\nexport class TavernPairingError extends TavernError {}\n\n/**\n * Thrown when a stopped host or an ended guest session is used again. Mirrors\n * mesh's `MeshDisposedError` inside the tavern error hierarchy, so\n * `instanceof TavernError` catches every tavern failure in one branch.\n */\nexport class TavernDisposedError extends TavernError {}\n","import {\n createMeshGuest,\n createMeshHost,\n type MeshAnswer,\n type MeshInvitation,\n MeshPairingError,\n type MeshPeer,\n type MeshProtocol,\n type MeshRtcFactory,\n meshQrCodec,\n} from '@vielzeug/mesh';\n\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernError, TavernPairingError } from './errors';\n\nexport { TavernDisposedError, TavernError, TavernPairingError };\n\n/**\n * Reclassifies a mesh pairing failure as the tavern-level user mistake it is:\n * the code the consumer pasted could not be used. The message is preserved and\n * the original error is chained as `cause`.\n */\nfunction toPairingError(error: unknown): TavernPairingError {\n const message = error instanceof Error ? error.message : 'That code could not be read.';\n return new TavernPairingError(message, { cause: error });\n}\n\n/**\n * Table sessions over `@vielzeug/mesh`: one host owns the canonical state of a subject, guests\n * mirror it and forward every command through the host's command table, so guest actions follow\n * exactly the same code path as host actions.\n *\n * The consumer supplies the seams, which commands exist, how subject state is read and mounted,\n * how notices cross between the wire and the local UI. Tavern owns the pairing, the protocol,\n * command validation, snapshot broadcasting, notice relaying, and presence.\n */\n\n/** What the host can do on behalf of a guest. */\nexport interface TavernCommands {\n /** Applies the command; throwing rejects the guest with the error's message. */\n apply(name: string, args: readonly unknown[]): unknown;\n /** Whether a command name is known; unknown names reject without applying. */\n has(name: string): boolean;\n}\n\n/**\n * How the host reads and watches the subject it is sharing. All three close over whatever\n * subject state the consumer owns: the host routes by `subjectId`, not by a subject object.\n */\nexport interface TavernSubjects {\n /** Subscribes to local changes of the hosted subject: the re-broadcast trigger. */\n onChanged(listener: () => void): () => void;\n /** Subscribes to the hosted subject's removal: hosting ends when it fires. */\n onRemoved(listener: () => void): () => void;\n /** Reads the snapshot to broadcast; null while the subject is missing. */\n snapshot(): unknown;\n}\n\n/**\n * Notice relay between host and guests. Notices cross the wire as opaque values: each client\n * translates locally.\n *\n * **Echo guard**: a tab that both hosts and guests must guard against re-broadcasting a\n * wire-originated notice back to its own guests: `fromWire` emits locally, the host's local\n * subscription picks it up, and without a guard it would loop. The consumer owns this guard\n * because only they know their local event system; one boolean set during `fromWire` and\n * checked in `toWire` is sufficient.\n */\nexport interface TavernNotices {\n /** Re-emits a received wire notice locally. */\n fromWire(wire: unknown): void;\n /** Serializes a local notice for the wire; null skips this one. */\n toWire(notice: unknown): unknown | null;\n}\n\ninterface WireProtocol extends MeshProtocol {\n toGuest: {\n notice: unknown;\n rejected: { commandId: string; message: string };\n snapshot: unknown;\n };\n toHost: {\n command: { args: unknown[]; id: string; name: string; subjectId: string };\n };\n}\n\n/** Notable host moments reported through {@link TavernHost.tap}. */\nexport type TavernHostEvent =\n | { readonly peer: MeshPeer; readonly type: 'peer-joined' }\n | { readonly peer: MeshPeer; readonly reason?: string; readonly type: 'peer-left' }\n | { readonly error: unknown; readonly message: string; readonly type: 'warning' };\n\n/** Notable guest moments reported through {@link TavernGuest.tap}. */\nexport type TavernGuestEvent =\n | { readonly commandId: string; readonly message: string; readonly type: 'rejected' }\n | { readonly error: unknown; readonly message: string; readonly type: 'warning' };\n\n/** Snapshots can be large; the default mesh frame cap is too tight for whole documents. */\nconst DEFAULT_MAX_MESSAGE_BYTES = 512 * 1024;\n\nconst commandId = (): string => `cmd-${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36)}`;\n\n/** Runtime guard for the wire command shape: the protocol is Tavern's, so Tavern validates it. */\nfunction parseWireCommand(raw: unknown): { args: unknown[]; id: string; name: string; subjectId: string } | null {\n if (typeof raw !== 'object' || raw === null) return null;\n const { args, id, name, subjectId } = raw as Record<string, unknown>;\n if (typeof id !== 'string' || typeof name !== 'string' || typeof subjectId !== 'string' || !Array.isArray(args)) {\n return null;\n }\n return { args, id, name, subjectId };\n}\n\n// ---------------------------------------------------------------------------\n// Host\n// ---------------------------------------------------------------------------\n\nexport interface TavernHostOptions {\n commands: TavernCommands;\n notices?: TavernNotices;\n /**\n * Hosting ended: the subject was removed or the host was disposed. Fires exactly\n * once. This is a lifecycle transition, not observability: presence, transport\n * warnings, and the peer list all belong to {@link TavernHost.tap} and\n * {@link TavernHost.peers}.\n */\n onEnded?(): void;\n rtc?: MeshRtcFactory;\n /** The id of the subject being hosted: guest commands targeting anything else reject. */\n subjectId: string;\n subjects: TavernSubjects;\n}\n\nexport interface TavernHost {\n /** Consumes a guest's answer code; resolves with the peer once the channel is open. */\n acceptAnswerText(text: string): Promise<MeshPeer>;\n /** Produces a single-use invitation code, QR-compact when the environment allows. */\n createInvitationText(): Promise<string>;\n /** `AbortSignal` aborted when hosting ends. */\n readonly disposalSignal: AbortSignal;\n /** Stops hosting: closes every channel and detaches all subscriptions. */\n dispose(): void;\n /** Whether hosting has ended: the subject was removed or `dispose()` ran. */\n readonly disposed: boolean;\n kick(peerId: string): void;\n /** The guests currently connected: read it from a `peer-joined`/`peer-left` tap event. */\n readonly peers: readonly MeshPeer[];\n /** Relays one local notice to every guest; the serializer decides what crosses.\n * A notice relayed after hosting ended is dropped, not thrown: it is ephemeral\n * UI state with no audience left, unlike the control-plane methods, which fail\n * with `TavernDisposedError` so a leaked handle surfaces. */\n relayNotice(notice: unknown): void;\n /** Subscribes to {@link TavernHostEvent}s. Handler errors are swallowed; the\n * subscription detaches when `signal` aborts or hosting ends. */\n tap(handler: (event: TavernHostEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;\n /** Delegates to `dispose()`. Enables `using` declarations. */\n [Symbol.dispose](): void;\n}\n\n/**\n * Starts hosting one subject. Every guest command is validated and applied through the\n * command table; local changes re-broadcast the snapshot (coalesced on a microtask); removal\n * ends the session.\n */\nexport function hostTavern(options: TavernHostOptions): TavernHost {\n const host = createMeshHost<WireProtocol>({\n maxMessageBytes: DEFAULT_MAX_MESSAGE_BYTES,\n rtc: options.rtc,\n });\n const tappers = createTappers<TavernHostEvent>();\n let closed = false;\n let flushScheduled = false;\n\n const close = (): void => {\n if (closed) return;\n closed = true;\n for (const off of detach.splice(0)) off();\n host.dispose();\n tappers.stop();\n options.onEnded?.();\n };\n const disposedError = (): TavernDisposedError => new TavernDisposedError('This host has stopped.');\n const warn = (error: unknown): void => {\n tappers.emit({ error, message: error instanceof Error ? error.message : String(error), type: 'warning' });\n };\n\n /** Reads the snapshot for a broadcast; a throwing read warns instead of crashing the host. */\n const readSnapshot = (): unknown => {\n try {\n return options.subjects.snapshot();\n } catch (error) {\n warn(error);\n return null;\n }\n };\n\n /** Coalesces broadcasts on a microtask so bursts of local changes ship one snapshot. */\n const broadcastSnapshot = (): void => {\n if (closed || flushScheduled) return;\n flushScheduled = true;\n queueMicrotask(() => {\n flushScheduled = false;\n if (closed) return;\n const snapshot = readSnapshot();\n if (snapshot !== null && snapshot !== undefined) host.broadcast('snapshot', snapshot);\n });\n };\n\n /**\n * Applies a guest command through the command table: the same table the host's own UI\n * calls, so an unknown name, a foreign subject id or a rule violation is all the host\n * can ever reject with.\n */\n const handleGuestCommand = (peerId: string, raw: unknown): void => {\n const command = parseWireCommand(raw);\n if (!command || !options.commands.has(command.name) || command.subjectId !== options.subjectId) {\n host.send(peerId, 'rejected', {\n commandId: command?.id ?? '',\n message: 'The host rejected an unknown or out-of-session command.',\n });\n return;\n }\n try {\n options.commands.apply(command.name, command.args);\n } catch (error) {\n host.send(peerId, 'rejected', {\n commandId: command.id,\n message: error instanceof Error ? error.message : 'The host could not apply the command.',\n });\n }\n };\n\n const detach = [\n host.on('command', ({ peerId, payload }) => handleGuestCommand(peerId, payload)),\n options.subjects.onChanged(broadcastSnapshot),\n options.subjects.onRemoved(close),\n host.tap((event) => {\n if (event.type === 'peer-joined') {\n const snapshot = readSnapshot();\n if (snapshot !== null && snapshot !== undefined) host.send(event.peer.id, 'snapshot', snapshot);\n tappers.emit({ peer: event.peer, type: 'peer-joined' });\n }\n if (event.type === 'peer-left') tappers.emit({ peer: event.peer, reason: event.reason, type: 'peer-left' });\n if (event.type === 'error') warn(event.error);\n }),\n ];\n\n return {\n acceptAnswerText: async (text: string): Promise<MeshPeer> => {\n if (closed) throw disposedError();\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(text);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!('proof' in decoded)) {\n throw new TavernPairingError('That code is an invitation, not a guest answer.');\n }\n try {\n return await host.acceptAnswer(decoded);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n },\n createInvitationText: async () => {\n if (closed) throw disposedError();\n return meshQrCodec.encode(await host.createInvitation());\n },\n get disposalSignal() {\n return host.disposalSignal;\n },\n dispose: close,\n get disposed() {\n return closed;\n },\n kick: (peerId: string): void => {\n if (closed) throw disposedError();\n host.kick(peerId);\n },\n get peers(): readonly MeshPeer[] {\n return [...host.peers.values()];\n },\n relayNotice: (notice: unknown): void => {\n if (closed) return;\n const wire = options.notices ? options.notices.toWire(notice) : null;\n if (wire !== null && wire !== undefined) host.broadcast('notice', wire);\n },\n tap: tappers.tap,\n [Symbol.dispose]() {\n close();\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Guest\n// ---------------------------------------------------------------------------\n\nexport interface TavernGuestOptions<Mounted> {\n /** The invitation code the host produced. */\n invitationText: string;\n /**\n * Mounts a received snapshot; the mounted value, or null to ignore. The snapshot arrives\n * as parsed JSON: validate before trusting it.\n */\n mount(snapshot: unknown): Mounted | null;\n /** The guest's display name on the channel. */\n name: string;\n notices?: TavernNotices;\n /**\n * The channel ended after joining; the mounted value is passed for unmounting.\n * Lifecycle, not observability: rejections and transport warnings belong to\n * {@link TavernGuest.tap}. `onJoined` and `onFailed` stay callbacks for the same\n * reason: they fire while {@link joinTavern} is still resolving, before the\n * consumer can hold the handle and register a tapper.\n */\n onEnded?(subject: Mounted): void;\n /** The host never accepted the answer in time. */\n onFailed?(reason: string): void;\n /** The mounted value once the first snapshot arrives. */\n onJoined?(subject: Mounted): void;\n rtc?: MeshRtcFactory;\n}\n\nexport interface TavernGuest {\n /** `AbortSignal` aborted when the session ends. */\n readonly disposalSignal: AbortSignal;\n /** Leaves the session and drops the channel. */\n dispose(): void;\n /** Whether the session has ended: the channel dropped or `dispose()` ran. */\n readonly disposed: boolean;\n /**\n * Forwards a command to the host. The subject id is the consumer's routing key: the host\n * rejects commands that do not name the subject it is hosting.\n * Throws `TavernDisposedError` after the session has ended.\n */\n sendCommand(subjectId: string, name: string, args: readonly unknown[]): void;\n /** Subscribes to {@link TavernGuestEvent}s. Handler errors are swallowed; the\n * subscription detaches when `signal` aborts or the session ends. */\n tap(handler: (event: TavernGuestEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;\n /** Delegates to `dispose()`. Enables `using` declarations. */\n [Symbol.dispose](): void;\n}\n\n/**\n * Joins a session as a guest: consumes the host's invitation and returns the answer code to\n * show back. The session goes live once the host accepts the answer and the first snapshot\n * mounts; disposing the guest (or the channel dropping) ends it exactly once.\n */\nexport async function joinTavern<Mounted>(\n options: TavernGuestOptions<Mounted>,\n): Promise<{ answerText: string; guest: TavernGuest }> {\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(options.invitationText);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!('secret' in decoded)) {\n throw new TavernPairingError('That code is not a session invitation.');\n }\n\n const guest = createMeshGuest<WireProtocol>({\n maxMessageBytes: DEFAULT_MAX_MESSAGE_BYTES,\n rtc: options.rtc,\n });\n const tappers = createTappers<TavernGuestEvent>();\n let mounted: Mounted | null = null;\n let ended = false;\n\n /** Ends the session exactly once: from the channel dropping or an explicit dispose. */\n const endSession = (): void => {\n if (ended) return;\n ended = true;\n const subject = mounted;\n mounted = null;\n for (const off of detach.splice(0)) off();\n guest.dispose();\n tappers.stop();\n if (subject !== null) options.onEnded?.(subject);\n };\n\n const detach = [\n guest.on('snapshot', ({ payload }) => {\n const subject = options.mount(payload);\n if (subject === null || ended) return;\n if (mounted === null) {\n mounted = subject;\n options.onJoined?.(subject);\n }\n }),\n guest.on('notice', ({ payload }) => {\n options.notices?.fromWire(payload);\n }),\n guest.on('rejected', ({ payload }) => {\n tappers.emit({\n commandId: payload.commandId,\n message: payload.message || 'The host rejected the action.',\n type: 'rejected',\n });\n }),\n guest.tap((event) => {\n if (event.type !== 'status-change' && event.type !== 'peer-status-change') return;\n if (event.type === 'peer-status-change' && event.peerId !== guest.host?.id) return;\n if (event.status === 'failed' && mounted === null && !ended) {\n options.onFailed?.('The host did not accept the answer in time.');\n }\n if (event.status === 'disconnected' || event.status === 'failed') endSession();\n }),\n guest.tap((event) => {\n if (event.type === 'error') {\n tappers.emit({ error: event.error, message: event.error.message, type: 'warning' });\n }\n }),\n ];\n\n try {\n const answer = await guest.acceptInvitation(decoded, { name: options.name });\n return {\n answerText: await meshQrCodec.encode(answer),\n guest: {\n get disposalSignal() {\n return guest.disposalSignal;\n },\n dispose: endSession,\n get disposed() {\n return ended;\n },\n sendCommand: (subjectId: string, name: string, args: readonly unknown[]): void => {\n if (ended) throw new TavernDisposedError('The session has ended.');\n guest.send('command', { args: [...args], id: commandId(), name, subjectId });\n },\n tap: tappers.tap,\n [Symbol.dispose]() {\n endSession();\n },\n },\n };\n } catch (error) {\n // A failed join must not leave the node and its subscriptions behind.\n endSession();\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n}\n"],"mappings":"A,uFAgBA,SAAgB,eAAiE,CAC/E,IAAMK,EAAU,IAAI,IAChBC,EAAU,GAEd,MAAO,CACL,KAAK,EAAa,CAChB,GAAID,EAAQ,OAAS,EACrB,IAAK,IAAME,KAAUF,EACnB,GAAI,CACFE,EAAOC,CAAK,CACd,MAAQ,CAER,CAEJ,EACA,MAAa,CACX,EAAU,GACVH,EAAQ,MAAM,CAChB,EACA,IAAI,EAA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,OAAS,sBAAwBA,EAAM,SAAW0B,EAAM,MAAM,KACpE1B,EAAM,SAAW,UAAY2B,IAAY,MAAQ,CAACC,GACpD3B,EAAQ,WAAW,6CAA6C,GAE9DD,EAAM,SAAW,gBAAkBA,EAAM,SAAW,WAAU,WAAW,EAC/E,CAAC,EACD0B,EAAM,IAAK,GAAU,CACf1B,EAAM,OAAS,SACjBH,EAAQ,KAAK,CAAE,MAAOG,EAAM,MAAO,QAASA,EAAM,MAAM,QAAS,KAAM,SAAU,CAAC,CAEtF,CAAC,CACH,EAEA,GAAI,CACF,IAAM8B,EAAS,MAAMJ,EAAM,iBAAiBJ,EAAS,CAAE,KAAMrB,EAAQ,IAAK,CAAC,EAC3E,MAAO,CACL,WAAY,MAAMR,EAAAA,YAAY,OAAOqC,CAAM,EAC3C,MAAO,CACL,IAAI,gBAAiB,CACnB,OAAOJ,EAAM,cACf,EACA,QAAS,WACT,IAAI,UAAW,CACb,OAAOE,CACT,EACA,aAAc,EAAmB,EAAc,IAAmC,CAChF,GAAIA,EAAO,MAAM,IAAI,oBAAoB,wBAAwB,EACjEF,EAAM,KAAK,UAAW,CAAE,KAAM,CAAC,GAAGf,CAAI,EAAG,GAAI,UAAU,EAAG,OAAM,WAAU,CAAC,CAC7E,EACA,IAAKd,EAAQ,IACb,CAAC,OAAO,UAAW,CACjB,WAAW,CACb,CACF,CACF,CACF,OAASQ,EAAO,CAGd,MADA,WAAW,EACLA,aAAiBX,EAAAA,iBAAmB,eAAeW,CAAK,EAAIA,CACpE,CACF,C"}
1
+ {"version":3,"file":"tavern.iife.js","names":["meshQrCodec","MeshPairingError","createMeshGuest","createMeshHost","meshQrCodec","MeshPairingError","exports","message","opts","DEFAULT_MAX_MESSAGE_BYTES","raw","id","name","args","error","decoded","tappers","stopped","tapper","event","options","handler","_vielzeug_mesh","guest","mounted","ended","resolveReady","rejectReady","ready","resolve","reject","subject","off","detach","earlyExit","payload","answer","wrapped","host","closed","flushScheduled","snapshot","command","peerId","table","apply","code","wire","notice"],"sources":["../src/errors.ts","../src/_protocol.ts","../src/_tappers.ts","../src/guest.ts","../src/host.ts"],"sourcesContent":["/**\n * Base class for all tavern errors.\n * Use `instanceof TavernError` to catch any tavern-originated error in one branch.\n */\nexport class TavernError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** A pairing code the consumer pasted could not be used: a user-input mistake, not a bug. */\nexport class TavernPairingError extends TavernError {}\n\n/**\n * Thrown when a stopped host or an ended guest session is used again. Mirrors\n * mesh's `MeshDisposedError` inside the tavern error hierarchy, so\n * `instanceof TavernError` catches every tavern failure in one branch.\n */\nexport class TavernDisposedError extends TavernError {}\n","import type { MeshAnswer, MeshInvitation, MeshProtocol } from '@vielzeug/mesh';\n\nimport { TavernPairingError } from './errors';\n\n/** Snapshots can be large; the default mesh frame cap is too tight for whole documents. */\nexport const DEFAULT_MAX_MESSAGE_BYTES = 512 * 1024;\n\n/** What travels guest to host: a named command and its arguments, tagged for rejection. */\nexport interface WireCommand {\n readonly args: unknown[];\n readonly id: string;\n readonly name: string;\n}\n\nexport interface WireProtocol extends MeshProtocol {\n toGuest: {\n notice: unknown;\n rejected: { commandId: string; message: string };\n snapshot: unknown;\n };\n toHost: {\n command: WireCommand;\n };\n}\n\nexport const commandId = (): string => `cmd-${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36)}`;\n\n/** Runtime guard for the wire command shape: the protocol is Tavern's, so Tavern validates it. */\nexport function parseWireCommand(raw: unknown): WireCommand | null {\n if (typeof raw !== 'object' || raw === null) return null;\n const { args, id, name } = raw as Record<string, unknown>;\n if (typeof id !== 'string' || typeof name !== 'string' || !Array.isArray(args)) return null;\n return { args, id, name };\n}\n\n/**\n * Reclassifies a mesh pairing failure as the tavern-level user mistake it is:\n * the code the consumer pasted could not be used. The message is preserved and\n * the original error is chained as `cause`.\n */\nexport function toPairingError(error: unknown): TavernPairingError {\n const message = error instanceof Error ? error.message : 'That code could not be read.';\n return new TavernPairingError(message, { cause: error });\n}\n\n/** narrows a decoded pairing code to the guest's half of the handshake. */\nexport function isMeshAnswer(decoded: MeshInvitation | MeshAnswer): decoded is MeshAnswer {\n return 'proof' in decoded;\n}\n\n/** narrows a decoded pairing code to the host's half of the handshake. */\nexport function isMeshInvitation(decoded: MeshInvitation | MeshAnswer): decoded is MeshInvitation {\n return 'secret' in decoded;\n}\n","/**\n * The `tap()` machinery shared by the host and guest handles. Kept private: the\n * public contract is each handle's `tap` method and its event union, not this.\n *\n * Follows the repo observability rules: zero overhead with no tappers, handler\n * errors swallowed, auto-detach on an abort signal, and a no-op unsubscribe once\n * the handle has stopped.\n */\nexport interface Tappers<E extends { readonly type: string }> {\n /** Emits to every tapper; a no-op when none are registered. */\n emit(event: E): void;\n /** Drops every tapper and makes later `tap` calls no-ops. Idempotent. */\n stop(): void;\n tap(handler: (event: E) => void, options?: { readonly signal?: AbortSignal }): () => void;\n}\n\nexport function createTappers<E extends { readonly type: string }>(): Tappers<E> {\n const tappers = new Set<(event: E) => void>();\n let stopped = false;\n\n return {\n emit(event): void {\n if (tappers.size === 0) return;\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect session behavior.\n }\n }\n },\n stop(): void {\n stopped = true;\n tappers.clear();\n },\n tap(handler, options): () => void {\n if (stopped || options?.signal?.aborted) return () => {};\n const detach = (): void => {\n tappers.delete(handler);\n };\n tappers.add(handler);\n options?.signal?.addEventListener('abort', detach, { once: true });\n return detach;\n },\n };\n}\n","import { createMeshGuest, type MeshAnswer, type MeshInvitation, MeshPairingError, meshQrCodec } from '@vielzeug/mesh';\nimport { commandId, DEFAULT_MAX_MESSAGE_BYTES, isMeshInvitation, toPairingError, type WireProtocol } from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernError, TavernPairingError } from './errors';\nimport type { TavernGuestEvent, TavernGuestOptions, TavernJoinResult } from './types';\n\n/**\n * Joins a session as a guest: consumes the host's invitation code and returns the answer\n * code to show back. The session goes live once the host accepts the answer and the first\n * snapshot mounts; that transition settles {@link TavernJoinResult.ready}. Disposing the\n * guest (or the channel dropping) ends the session exactly once.\n */\nexport async function joinTavern<Mounted>(options: TavernGuestOptions<Mounted>): Promise<TavernJoinResult<Mounted>> {\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(options.invitationCode);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshInvitation(decoded)) {\n throw new TavernPairingError('That code is not a session invitation.');\n }\n\n const guest = createMeshGuest<WireProtocol>({\n maxMessageBytes: DEFAULT_MAX_MESSAGE_BYTES,\n rtc: options.rtc,\n });\n const tappers = createTappers<TavernGuestEvent>();\n let mounted: Mounted | null = null;\n let ended = false;\n let resolveReady!: (subject: Mounted) => void;\n let rejectReady!: (error: Error) => void;\n const ready = new Promise<Mounted>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n // A ready the consumer never awaits must not surface as an unhandled rejection.\n void ready.catch(() => undefined);\n\n /** Ends the session exactly once: from the channel dropping or an explicit dispose. */\n const endSession = (earlyExit: Error): void => {\n if (ended) return;\n ended = true;\n const subject = mounted;\n mounted = null;\n for (const off of detach.splice(0)) off();\n guest.dispose();\n tappers.emit({ type: 'dispose' });\n tappers.stop();\n if (subject !== null) options.onEnded?.(subject);\n else rejectReady(earlyExit);\n };\n\n const detach = [\n guest.on('snapshot', ({ payload }) => {\n const subject = options.mount(payload);\n if (subject === null || ended) return;\n if (mounted === null) {\n mounted = subject;\n resolveReady(subject);\n }\n }),\n guest.on('notice', ({ payload }) => {\n options.onNotice?.(payload);\n }),\n guest.on('rejected', ({ payload }) => {\n tappers.emit({\n commandId: payload.commandId,\n message: payload.message || 'The host rejected the action.',\n type: 'rejected',\n });\n }),\n guest.tap((event) => {\n // A failed ICE negotiation before the channel opens surfaces only as the raw\n // ice-state event; once a channel exists, mesh reports failed/disconnected statuses.\n if (event.type === 'ice-state' && event.state === 'failed') {\n endSession(new TavernError('The connection to the host failed.'));\n return;\n }\n if (event.type !== 'status-change' && event.type !== 'peer-status-change') return;\n if (event.type === 'peer-status-change' && event.peerId !== guest.host?.id) return;\n if (event.status === 'failed') endSession(new TavernError('The host did not accept the answer in time.'));\n if (event.status === 'disconnected') endSession(new TavernError('The host closed the session.'));\n }),\n guest.tap((event) => {\n if (event.type === 'error') {\n tappers.emit({ error: event.error, message: event.error.message, type: 'warning' });\n }\n }),\n ];\n\n try {\n const answer = await guest.acceptInvitation(decoded, { name: options.name });\n return {\n answerCode: await meshQrCodec.encode(answer),\n guest: {\n get disposalSignal() {\n return guest.disposalSignal;\n },\n dispose: () => endSession(new TavernDisposedError('The guest left before the first snapshot arrived.')),\n get disposed() {\n return ended;\n },\n sendCommand: (name: string, args: readonly unknown[] = []): void => {\n if (ended) throw new TavernDisposedError('The session has ended.');\n guest.send('command', { args: [...args], id: commandId(), name });\n },\n tap: tappers.tap,\n [Symbol.dispose]() {\n endSession(new TavernDisposedError('The guest left before the first snapshot arrived.'));\n },\n },\n ready,\n };\n } catch (error) {\n // A failed join must not leave the node and its subscriptions behind.\n const wrapped = error instanceof MeshPairingError ? toPairingError(error) : error;\n endSession(wrapped instanceof Error ? wrapped : new TavernError('The invitation could not be accepted.'));\n throw wrapped;\n }\n}\n","import {\n createMeshHost,\n type MeshAnswer,\n type MeshInvitation,\n MeshPairingError,\n type MeshPeer,\n meshQrCodec,\n} from '@vielzeug/mesh';\nimport {\n DEFAULT_MAX_MESSAGE_BYTES,\n isMeshAnswer,\n parseWireCommand,\n toPairingError,\n type WireProtocol,\n} from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernPairingError } from './errors';\nimport type { TavernHost, TavernHostEvent, TavernHostOptions } from './types';\n\n/**\n * Starts hosting one subject over mesh. Every guest command is validated and applied\n * through the command table; local changes re-broadcast the snapshot (coalesced on a\n * microtask); removal ends the session.\n */\nexport function hostTavern(options: TavernHostOptions): TavernHost {\n const host = createMeshHost<WireProtocol>({\n maxMessageBytes: DEFAULT_MAX_MESSAGE_BYTES,\n rtc: options.rtc,\n });\n const tappers = createTappers<TavernHostEvent>();\n let closed = false;\n let flushScheduled = false;\n\n const close = (): void => {\n if (closed) return;\n closed = true;\n for (const off of detach.splice(0)) off();\n host.dispose();\n tappers.emit({ type: 'dispose' });\n tappers.stop();\n options.onEnded?.();\n };\n const disposedError = (): TavernDisposedError => new TavernDisposedError('This host has stopped.');\n const warn = (error: unknown): void => {\n tappers.emit({ error, message: error instanceof Error ? error.message : String(error), type: 'warning' });\n };\n\n /** Reads the snapshot for a broadcast; a throwing read warns instead of crashing the host. */\n const readSnapshot = (): unknown => {\n try {\n return options.subject.snapshot();\n } catch (error) {\n warn(error);\n return null;\n }\n };\n\n /** Coalesces broadcasts on a microtask so bursts of local changes ship one snapshot. */\n const broadcastSnapshot = (): void => {\n if (closed || flushScheduled) return;\n flushScheduled = true;\n queueMicrotask(() => {\n flushScheduled = false;\n if (closed) return;\n const snapshot = readSnapshot();\n if (snapshot !== null && snapshot !== undefined) host.broadcast('snapshot', snapshot);\n });\n };\n\n /**\n * Applies a guest command through the command table: the same table the host's own UI\n * calls, so an unknown name or a rule violation is all the host can ever reject with.\n */\n const handleGuestCommand = (peerId: string, raw: unknown): void => {\n const command = parseWireCommand(raw);\n if (!command) {\n host.send(peerId, 'rejected', { commandId: '', message: 'That command could not be read.' });\n return;\n }\n // Own-property lookup only: a guest must not reach Object.prototype members.\n const table = options.commands;\n const apply = table && Object.hasOwn(table, command.name) ? table[command.name] : undefined;\n if (typeof apply !== 'function') {\n host.send(peerId, 'rejected', {\n commandId: command.id,\n message: `The host has no command named \"${command.name}\".`,\n });\n return;\n }\n try {\n apply(command.args);\n } catch (error) {\n host.send(peerId, 'rejected', {\n commandId: command.id,\n message: error instanceof Error ? error.message : 'The host could not apply the command.',\n });\n }\n };\n\n const detach = [\n host.on('command', ({ peerId, payload }) => handleGuestCommand(peerId, payload)),\n options.subject.onChanged(broadcastSnapshot),\n options.subject.onRemoved(close),\n host.tap((event) => {\n if (event.type === 'peer-joined') {\n const snapshot = readSnapshot();\n if (snapshot !== null && snapshot !== undefined) host.send(event.peer.id, 'snapshot', snapshot);\n tappers.emit({ peer: event.peer, type: 'peer-joined' });\n }\n if (event.type === 'peer-left') tappers.emit({ peer: event.peer, reason: event.reason, type: 'peer-left' });\n if (event.type === 'error') warn(event.error);\n }),\n ];\n\n return {\n acceptAnswerCode: async (code: string): Promise<MeshPeer> => {\n if (closed) throw disposedError();\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(code);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshAnswer(decoded)) {\n throw new TavernPairingError('That code is an invitation, not a guest answer.');\n }\n try {\n return await host.acceptAnswer(decoded);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n },\n createInvitationCode: async () => {\n if (closed) throw disposedError();\n return meshQrCodec.encode(await host.createInvitation());\n },\n get disposalSignal() {\n return host.disposalSignal;\n },\n dispose: close,\n get disposed() {\n return closed;\n },\n kick: (peerId: string): void => {\n if (closed) throw disposedError();\n host.kick(peerId);\n },\n get peers(): readonly MeshPeer[] {\n return [...host.peers.values()];\n },\n relayNotice: (notice: unknown): void => {\n if (closed) return;\n const wire = options.serializeNotice ? options.serializeNotice(notice) : null;\n if (wire !== null && wire !== undefined) host.broadcast('notice', wire);\n },\n tap: tappers.tap,\n [Symbol.dispose]() {\n close();\n },\n };\n}\n"],"mappings":"A,uFAIA,IAAa,YAAb,cAAiC,KAAM,CACrC,YAAY,EAAiB,EAAqB,CAChD,MAAMO,EAASC,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAGa,mBAAb,cAAwC,WAAY,CAAC,EAOxC,oBAAb,cAAyC,WAAY,CAAC,ECfzCC,EAA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,KAAO,GAAyB,CAC9B,GAAIA,EAAQ,MAAM,cAAc,EAChCD,EAAK,KAAKK,CAAM,CAClB,EACA,IAAI,OAA6B,CAC/B,MAAO,CAAC,GAAGL,EAAK,MAAM,OAAO,CAAC,CAChC,EACA,YAAc,GAA0B,CACtC,GAAIC,EAAQ,OACZ,IAAMQ,EAAO3B,EAAQ,gBAAkBA,EAAQ,gBAAgB4B,CAAM,EAAI,KACrED,GAAS,MAA4BT,EAAK,UAAU,SAAUS,CAAI,CACxE,EACA,IAAK/B,EAAQ,IACb,CAAC,OAAO,UAAW,CACjB,MAAM,CACR,CACF,CACF,C"}
package/dist/tavern.js CHANGED
@@ -1,4 +1,28 @@
1
1
  import { MeshPairingError as e, createMeshGuest as t, createMeshHost as n, meshQrCodec as r } from "@vielzeug/mesh";
2
+ // src/errors.ts
3
+ var TavernError = class extends Error {
4
+ constructor(e, t) {
5
+ super(e, t), this.name = new.target.name, Object.setPrototypeOf(this, new.target.prototype);
6
+ }
7
+ }, TavernPairingError = class extends TavernError {}, TavernDisposedError = class extends TavernError {}, i = 524288, commandId = () => `cmd-${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36)}`;
8
+ function parseWireCommand(e) {
9
+ if (typeof e != "object" || !e) return null;
10
+ let { args: t, id: n, name: r } = e;
11
+ return typeof n != "string" || typeof r != "string" || !Array.isArray(t) ? null : {
12
+ args: t,
13
+ id: n,
14
+ name: r
15
+ };
16
+ }
17
+ function toPairingError(e) {
18
+ return new TavernPairingError(e instanceof Error ? e.message : "That code could not be read.", { cause: e });
19
+ }
20
+ function isMeshAnswer(e) {
21
+ return "proof" in e;
22
+ }
23
+ function isMeshInvitation(e) {
24
+ return "secret" in e;
25
+ }
2
26
  // src/_tappers.ts
3
27
  function createTappers() {
4
28
  let e = /* @__PURE__ */ new Set(), t = !1;
@@ -20,27 +44,88 @@ function createTappers() {
20
44
  }
21
45
  };
22
46
  }
23
- // src/errors.ts
24
- var TavernError = class extends Error {
25
- constructor(e, t) {
26
- super(e, t), this.name = new.target.name, Object.setPrototypeOf(this, new.target.prototype);
47
+ // src/guest.ts
48
+ async function joinTavern(n) {
49
+ let a;
50
+ try {
51
+ a = await r.decode(n.invitationCode);
52
+ } catch (t) {
53
+ throw t instanceof e ? toPairingError(t) : t;
54
+ }
55
+ if (!isMeshInvitation(a)) throw new TavernPairingError("That code is not a session invitation.");
56
+ let o = t({
57
+ maxMessageBytes: i,
58
+ rtc: n.rtc
59
+ }), s = createTappers(), c = null, l = !1, u, d, f = new Promise((e, t) => {
60
+ u = e, d = t;
61
+ });
62
+ f.catch(() => void 0);
63
+ let endSession = (e) => {
64
+ if (l) return;
65
+ l = !0;
66
+ let t = c;
67
+ c = null;
68
+ for (let e of p.splice(0)) e();
69
+ o.dispose(), s.emit({ type: "dispose" }), s.stop(), t === null ? d(e) : n.onEnded?.(t);
70
+ }, p = [
71
+ o.on("snapshot", ({ payload: e }) => {
72
+ let t = n.mount(e);
73
+ t === null || l || c === null && (c = t, u(t));
74
+ }),
75
+ o.on("notice", ({ payload: e }) => {
76
+ n.onNotice?.(e);
77
+ }),
78
+ o.on("rejected", ({ payload: e }) => {
79
+ s.emit({
80
+ commandId: e.commandId,
81
+ message: e.message || "The host rejected the action.",
82
+ type: "rejected"
83
+ });
84
+ }),
85
+ o.tap((e) => {
86
+ e.type === "ice-state" && e.state === "failed" ? endSession(new TavernError("The connection to the host failed.")) : e.type !== "status-change" && e.type !== "peer-status-change" || e.type === "peer-status-change" && e.peerId !== o.host?.id || (e.status === "failed" && endSession(new TavernError("The host did not accept the answer in time.")), e.status === "disconnected" && endSession(new TavernError("The host closed the session.")));
87
+ }),
88
+ o.tap((e) => {
89
+ e.type === "error" && s.emit({
90
+ error: e.error,
91
+ message: e.error.message,
92
+ type: "warning"
93
+ });
94
+ })
95
+ ];
96
+ try {
97
+ let e = await o.acceptInvitation(a, { name: n.name });
98
+ return {
99
+ answerCode: await r.encode(e),
100
+ guest: {
101
+ get disposalSignal() {
102
+ return o.disposalSignal;
103
+ },
104
+ dispose: () => endSession(new TavernDisposedError("The guest left before the first snapshot arrived.")),
105
+ get disposed() {
106
+ return l;
107
+ },
108
+ sendCommand: (e, t = []) => {
109
+ if (l) throw new TavernDisposedError("The session has ended.");
110
+ o.send("command", {
111
+ args: [...t],
112
+ id: commandId(),
113
+ name: e
114
+ });
115
+ },
116
+ tap: s.tap,
117
+ [Symbol.dispose]() {
118
+ endSession(new TavernDisposedError("The guest left before the first snapshot arrived."));
119
+ }
120
+ },
121
+ ready: f
122
+ };
123
+ } catch (t) {
124
+ let n = t instanceof e ? toPairingError(t) : t;
125
+ throw endSession(n instanceof Error ? n : new TavernError("The invitation could not be accepted.")), n;
27
126
  }
28
- }, TavernPairingError = class extends TavernError {}, TavernDisposedError = class extends TavernError {};
29
- // src/index.ts
30
- function toPairingError(e) {
31
- return new TavernPairingError(e instanceof Error ? e.message : "That code could not be read.", { cause: e });
32
- }
33
- var i = 524288, commandId = () => `cmd-${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36)}`;
34
- function parseWireCommand(e) {
35
- if (typeof e != "object" || !e) return null;
36
- let { args: t, id: n, name: r, subjectId: i } = e;
37
- return typeof n != "string" || typeof r != "string" || typeof i != "string" || !Array.isArray(t) ? null : {
38
- args: t,
39
- id: n,
40
- name: r,
41
- subjectId: i
42
- };
43
127
  }
128
+ // src/host.ts
44
129
  function hostTavern(t) {
45
130
  let a = n({
46
131
  maxMessageBytes: i,
@@ -49,7 +134,7 @@ function hostTavern(t) {
49
134
  if (!s) {
50
135
  s = !0;
51
136
  for (let e of l.splice(0)) e();
52
- a.dispose(), o.stop(), t.onEnded?.();
137
+ a.dispose(), o.emit({ type: "dispose" }), o.stop(), t.onEnded?.();
53
138
  }
54
139
  }, disposedError = () => new TavernDisposedError("This host has stopped."), warn = (e) => {
55
140
  o.emit({
@@ -59,7 +144,7 @@ function hostTavern(t) {
59
144
  });
60
145
  }, readSnapshot = () => {
61
146
  try {
62
- return t.subjects.snapshot();
147
+ return t.subject.snapshot();
63
148
  } catch (e) {
64
149
  return warn(e), null;
65
150
  }
@@ -71,12 +156,20 @@ function hostTavern(t) {
71
156
  }));
72
157
  }, handleGuestCommand = (e, n) => {
73
158
  let r = parseWireCommand(n);
74
- if (!r || !t.commands.has(r.name) || r.subjectId !== t.subjectId) a.send(e, "rejected", {
75
- commandId: r?.id ?? "",
76
- message: "The host rejected an unknown or out-of-session command."
159
+ if (!r) {
160
+ a.send(e, "rejected", {
161
+ commandId: "",
162
+ message: "That command could not be read."
163
+ });
164
+ return;
165
+ }
166
+ let i = t.commands, o = i && Object.hasOwn(i, r.name) ? i[r.name] : void 0;
167
+ if (typeof o != "function") a.send(e, "rejected", {
168
+ commandId: r.id,
169
+ message: `The host has no command named "${r.name}".`
77
170
  });
78
171
  else try {
79
- t.commands.apply(r.name, r.args);
172
+ o(r.args);
80
173
  } catch (t) {
81
174
  a.send(e, "rejected", {
82
175
  commandId: r.id,
@@ -85,8 +178,8 @@ function hostTavern(t) {
85
178
  }
86
179
  }, l = [
87
180
  a.on("command", ({ peerId: e, payload: t }) => handleGuestCommand(e, t)),
88
- t.subjects.onChanged(broadcastSnapshot),
89
- t.subjects.onRemoved(close),
181
+ t.subject.onChanged(broadcastSnapshot),
182
+ t.subject.onRemoved(close),
90
183
  a.tap((e) => {
91
184
  if (e.type === "peer-joined") {
92
185
  let t = readSnapshot();
@@ -103,7 +196,7 @@ function hostTavern(t) {
103
196
  })
104
197
  ];
105
198
  return {
106
- acceptAnswerText: async (t) => {
199
+ acceptAnswerCode: async (t) => {
107
200
  if (s) throw disposedError();
108
201
  let n;
109
202
  try {
@@ -111,14 +204,14 @@ function hostTavern(t) {
111
204
  } catch (t) {
112
205
  throw t instanceof e ? toPairingError(t) : t;
113
206
  }
114
- if (!("proof" in n)) throw new TavernPairingError("That code is an invitation, not a guest answer.");
207
+ if (!isMeshAnswer(n)) throw new TavernPairingError("That code is an invitation, not a guest answer.");
115
208
  try {
116
209
  return await a.acceptAnswer(n);
117
210
  } catch (t) {
118
211
  throw t instanceof e ? toPairingError(t) : t;
119
212
  }
120
213
  },
121
- createInvitationText: async () => {
214
+ createInvitationCode: async () => {
122
215
  if (s) throw disposedError();
123
216
  return r.encode(await a.createInvitation());
124
217
  },
@@ -138,7 +231,7 @@ function hostTavern(t) {
138
231
  },
139
232
  relayNotice: (e) => {
140
233
  if (s) return;
141
- let n = t.notices ? t.notices.toWire(e) : null;
234
+ let n = t.serializeNotice ? t.serializeNotice(e) : null;
142
235
  n != null && a.broadcast("notice", n);
143
236
  },
144
237
  tap: o.tap,
@@ -147,81 +240,6 @@ function hostTavern(t) {
147
240
  }
148
241
  };
149
242
  }
150
- async function joinTavern(n) {
151
- let a;
152
- try {
153
- a = await r.decode(n.invitationText);
154
- } catch (t) {
155
- throw t instanceof e ? toPairingError(t) : t;
156
- }
157
- if (!("secret" in a)) throw new TavernPairingError("That code is not a session invitation.");
158
- let o = t({
159
- maxMessageBytes: i,
160
- rtc: n.rtc
161
- }), s = createTappers(), c = null, l = !1, endSession = () => {
162
- if (l) return;
163
- l = !0;
164
- let e = c;
165
- c = null;
166
- for (let e of u.splice(0)) e();
167
- o.dispose(), s.stop(), e !== null && n.onEnded?.(e);
168
- }, u = [
169
- o.on("snapshot", ({ payload: e }) => {
170
- let t = n.mount(e);
171
- t === null || l || c === null && (c = t, n.onJoined?.(t));
172
- }),
173
- o.on("notice", ({ payload: e }) => {
174
- n.notices?.fromWire(e);
175
- }),
176
- o.on("rejected", ({ payload: e }) => {
177
- s.emit({
178
- commandId: e.commandId,
179
- message: e.message || "The host rejected the action.",
180
- type: "rejected"
181
- });
182
- }),
183
- o.tap((e) => {
184
- e.type !== "status-change" && e.type !== "peer-status-change" || e.type === "peer-status-change" && e.peerId !== o.host?.id || (e.status === "failed" && c === null && !l && n.onFailed?.("The host did not accept the answer in time."), (e.status === "disconnected" || e.status === "failed") && endSession());
185
- }),
186
- o.tap((e) => {
187
- e.type === "error" && s.emit({
188
- error: e.error,
189
- message: e.error.message,
190
- type: "warning"
191
- });
192
- })
193
- ];
194
- try {
195
- let e = await o.acceptInvitation(a, { name: n.name });
196
- return {
197
- answerText: await r.encode(e),
198
- guest: {
199
- get disposalSignal() {
200
- return o.disposalSignal;
201
- },
202
- dispose: endSession,
203
- get disposed() {
204
- return l;
205
- },
206
- sendCommand: (e, t, n) => {
207
- if (l) throw new TavernDisposedError("The session has ended.");
208
- o.send("command", {
209
- args: [...n],
210
- id: commandId(),
211
- name: t,
212
- subjectId: e
213
- });
214
- },
215
- tap: s.tap,
216
- [Symbol.dispose]() {
217
- endSession();
218
- }
219
- }
220
- };
221
- } catch (t) {
222
- throw endSession(), t instanceof e ? toPairingError(t) : t;
223
- }
224
- }
225
243
  export { TavernDisposedError, TavernError, TavernPairingError, hostTavern, joinTavern };
226
244
 
227
245
  //# sourceMappingURL=tavern.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tavern.js","names":["tappers","stopped","tapper","event","options","handler","message","opts","error","DEFAULT_MAX_MESSAGE_BYTES","raw","id","name","subjectId","args","host","createMeshHost","closed","flushScheduled","off","detach","snapshot","command","peerId","payload","decoded","meshQrCodec","text","MeshPairingError","wire","notice","guest","createMeshGuest","mounted","ended","subject","answer"],"sources":["../src/_tappers.ts","../src/errors.ts","../src/index.ts"],"sourcesContent":["/**\n * The `tap()` machinery shared by the host and guest handles. Kept private: the\n * public contract is each handle's `tap` method and its event union, not this.\n *\n * Follows the repo observability rules: zero overhead with no tappers, handler\n * errors swallowed, auto-detach on an abort signal, and a no-op unsubscribe once\n * the handle has stopped.\n */\nexport interface Tappers<E extends { readonly type: string }> {\n /** Emits to every tapper; a no-op when none are registered. */\n emit(event: E): void;\n /** Drops every tapper and makes later `tap` calls no-ops. Idempotent. */\n stop(): void;\n tap(handler: (event: E) => void, options?: { readonly signal?: AbortSignal }): () => void;\n}\n\nexport function createTappers<E extends { readonly type: string }>(): Tappers<E> {\n const tappers = new Set<(event: E) => void>();\n let stopped = false;\n\n return {\n emit(event): void {\n if (tappers.size === 0) return;\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect session behavior.\n }\n }\n },\n stop(): void {\n stopped = true;\n tappers.clear();\n },\n tap(handler, options): () => void {\n if (stopped || options?.signal?.aborted) return () => {};\n const detach = (): void => {\n tappers.delete(handler);\n };\n tappers.add(handler);\n options?.signal?.addEventListener('abort', detach, { once: true });\n return detach;\n },\n };\n}\n","/**\n * Base class for all tavern errors.\n * Use `instanceof TavernError` to catch any tavern-originated error in one branch.\n */\nexport class TavernError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** A pairing code the consumer pasted could not be used: a user-input mistake, not a bug. */\nexport class TavernPairingError extends TavernError {}\n\n/**\n * Thrown when a stopped host or an ended guest session is used again. Mirrors\n * mesh's `MeshDisposedError` inside the tavern error hierarchy, so\n * `instanceof TavernError` catches every tavern failure in one branch.\n */\nexport class TavernDisposedError extends TavernError {}\n","import {\n createMeshGuest,\n createMeshHost,\n type MeshAnswer,\n type MeshInvitation,\n MeshPairingError,\n type MeshPeer,\n type MeshProtocol,\n type MeshRtcFactory,\n meshQrCodec,\n} from '@vielzeug/mesh';\n\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernError, TavernPairingError } from './errors';\n\nexport { TavernDisposedError, TavernError, TavernPairingError };\n\n/**\n * Reclassifies a mesh pairing failure as the tavern-level user mistake it is:\n * the code the consumer pasted could not be used. The message is preserved and\n * the original error is chained as `cause`.\n */\nfunction toPairingError(error: unknown): TavernPairingError {\n const message = error instanceof Error ? error.message : 'That code could not be read.';\n return new TavernPairingError(message, { cause: error });\n}\n\n/**\n * Table sessions over `@vielzeug/mesh`: one host owns the canonical state of a subject, guests\n * mirror it and forward every command through the host's command table, so guest actions follow\n * exactly the same code path as host actions.\n *\n * The consumer supplies the seams, which commands exist, how subject state is read and mounted,\n * how notices cross between the wire and the local UI. Tavern owns the pairing, the protocol,\n * command validation, snapshot broadcasting, notice relaying, and presence.\n */\n\n/** What the host can do on behalf of a guest. */\nexport interface TavernCommands {\n /** Applies the command; throwing rejects the guest with the error's message. */\n apply(name: string, args: readonly unknown[]): unknown;\n /** Whether a command name is known; unknown names reject without applying. */\n has(name: string): boolean;\n}\n\n/**\n * How the host reads and watches the subject it is sharing. All three close over whatever\n * subject state the consumer owns: the host routes by `subjectId`, not by a subject object.\n */\nexport interface TavernSubjects {\n /** Subscribes to local changes of the hosted subject: the re-broadcast trigger. */\n onChanged(listener: () => void): () => void;\n /** Subscribes to the hosted subject's removal: hosting ends when it fires. */\n onRemoved(listener: () => void): () => void;\n /** Reads the snapshot to broadcast; null while the subject is missing. */\n snapshot(): unknown;\n}\n\n/**\n * Notice relay between host and guests. Notices cross the wire as opaque values: each client\n * translates locally.\n *\n * **Echo guard**: a tab that both hosts and guests must guard against re-broadcasting a\n * wire-originated notice back to its own guests: `fromWire` emits locally, the host's local\n * subscription picks it up, and without a guard it would loop. The consumer owns this guard\n * because only they know their local event system; one boolean set during `fromWire` and\n * checked in `toWire` is sufficient.\n */\nexport interface TavernNotices {\n /** Re-emits a received wire notice locally. */\n fromWire(wire: unknown): void;\n /** Serializes a local notice for the wire; null skips this one. */\n toWire(notice: unknown): unknown | null;\n}\n\ninterface WireProtocol extends MeshProtocol {\n toGuest: {\n notice: unknown;\n rejected: { commandId: string; message: string };\n snapshot: unknown;\n };\n toHost: {\n command: { args: unknown[]; id: string; name: string; subjectId: string };\n };\n}\n\n/** Notable host moments reported through {@link TavernHost.tap}. */\nexport type TavernHostEvent =\n | { readonly peer: MeshPeer; readonly type: 'peer-joined' }\n | { readonly peer: MeshPeer; readonly reason?: string; readonly type: 'peer-left' }\n | { readonly error: unknown; readonly message: string; readonly type: 'warning' };\n\n/** Notable guest moments reported through {@link TavernGuest.tap}. */\nexport type TavernGuestEvent =\n | { readonly commandId: string; readonly message: string; readonly type: 'rejected' }\n | { readonly error: unknown; readonly message: string; readonly type: 'warning' };\n\n/** Snapshots can be large; the default mesh frame cap is too tight for whole documents. */\nconst DEFAULT_MAX_MESSAGE_BYTES = 512 * 1024;\n\nconst commandId = (): string => `cmd-${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36)}`;\n\n/** Runtime guard for the wire command shape: the protocol is Tavern's, so Tavern validates it. */\nfunction parseWireCommand(raw: unknown): { args: unknown[]; id: string; name: string; subjectId: string } | null {\n if (typeof raw !== 'object' || raw === null) return null;\n const { args, id, name, subjectId } = raw as Record<string, unknown>;\n if (typeof id !== 'string' || typeof name !== 'string' || typeof subjectId !== 'string' || !Array.isArray(args)) {\n return null;\n }\n return { args, id, name, subjectId };\n}\n\n// ---------------------------------------------------------------------------\n// Host\n// ---------------------------------------------------------------------------\n\nexport interface TavernHostOptions {\n commands: TavernCommands;\n notices?: TavernNotices;\n /**\n * Hosting ended: the subject was removed or the host was disposed. Fires exactly\n * once. This is a lifecycle transition, not observability: presence, transport\n * warnings, and the peer list all belong to {@link TavernHost.tap} and\n * {@link TavernHost.peers}.\n */\n onEnded?(): void;\n rtc?: MeshRtcFactory;\n /** The id of the subject being hosted: guest commands targeting anything else reject. */\n subjectId: string;\n subjects: TavernSubjects;\n}\n\nexport interface TavernHost {\n /** Consumes a guest's answer code; resolves with the peer once the channel is open. */\n acceptAnswerText(text: string): Promise<MeshPeer>;\n /** Produces a single-use invitation code, QR-compact when the environment allows. */\n createInvitationText(): Promise<string>;\n /** `AbortSignal` aborted when hosting ends. */\n readonly disposalSignal: AbortSignal;\n /** Stops hosting: closes every channel and detaches all subscriptions. */\n dispose(): void;\n /** Whether hosting has ended: the subject was removed or `dispose()` ran. */\n readonly disposed: boolean;\n kick(peerId: string): void;\n /** The guests currently connected: read it from a `peer-joined`/`peer-left` tap event. */\n readonly peers: readonly MeshPeer[];\n /** Relays one local notice to every guest; the serializer decides what crosses.\n * A notice relayed after hosting ended is dropped, not thrown: it is ephemeral\n * UI state with no audience left, unlike the control-plane methods, which fail\n * with `TavernDisposedError` so a leaked handle surfaces. */\n relayNotice(notice: unknown): void;\n /** Subscribes to {@link TavernHostEvent}s. Handler errors are swallowed; the\n * subscription detaches when `signal` aborts or hosting ends. */\n tap(handler: (event: TavernHostEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;\n /** Delegates to `dispose()`. Enables `using` declarations. */\n [Symbol.dispose](): void;\n}\n\n/**\n * Starts hosting one subject. Every guest command is validated and applied through the\n * command table; local changes re-broadcast the snapshot (coalesced on a microtask); removal\n * ends the session.\n */\nexport function hostTavern(options: TavernHostOptions): TavernHost {\n const host = createMeshHost<WireProtocol>({\n maxMessageBytes: DEFAULT_MAX_MESSAGE_BYTES,\n rtc: options.rtc,\n });\n const tappers = createTappers<TavernHostEvent>();\n let closed = false;\n let flushScheduled = false;\n\n const close = (): void => {\n if (closed) return;\n closed = true;\n for (const off of detach.splice(0)) off();\n host.dispose();\n tappers.stop();\n options.onEnded?.();\n };\n const disposedError = (): TavernDisposedError => new TavernDisposedError('This host has stopped.');\n const warn = (error: unknown): void => {\n tappers.emit({ error, message: error instanceof Error ? error.message : String(error), type: 'warning' });\n };\n\n /** Reads the snapshot for a broadcast; a throwing read warns instead of crashing the host. */\n const readSnapshot = (): unknown => {\n try {\n return options.subjects.snapshot();\n } catch (error) {\n warn(error);\n return null;\n }\n };\n\n /** Coalesces broadcasts on a microtask so bursts of local changes ship one snapshot. */\n const broadcastSnapshot = (): void => {\n if (closed || flushScheduled) return;\n flushScheduled = true;\n queueMicrotask(() => {\n flushScheduled = false;\n if (closed) return;\n const snapshot = readSnapshot();\n if (snapshot !== null && snapshot !== undefined) host.broadcast('snapshot', snapshot);\n });\n };\n\n /**\n * Applies a guest command through the command table: the same table the host's own UI\n * calls, so an unknown name, a foreign subject id or a rule violation is all the host\n * can ever reject with.\n */\n const handleGuestCommand = (peerId: string, raw: unknown): void => {\n const command = parseWireCommand(raw);\n if (!command || !options.commands.has(command.name) || command.subjectId !== options.subjectId) {\n host.send(peerId, 'rejected', {\n commandId: command?.id ?? '',\n message: 'The host rejected an unknown or out-of-session command.',\n });\n return;\n }\n try {\n options.commands.apply(command.name, command.args);\n } catch (error) {\n host.send(peerId, 'rejected', {\n commandId: command.id,\n message: error instanceof Error ? error.message : 'The host could not apply the command.',\n });\n }\n };\n\n const detach = [\n host.on('command', ({ peerId, payload }) => handleGuestCommand(peerId, payload)),\n options.subjects.onChanged(broadcastSnapshot),\n options.subjects.onRemoved(close),\n host.tap((event) => {\n if (event.type === 'peer-joined') {\n const snapshot = readSnapshot();\n if (snapshot !== null && snapshot !== undefined) host.send(event.peer.id, 'snapshot', snapshot);\n tappers.emit({ peer: event.peer, type: 'peer-joined' });\n }\n if (event.type === 'peer-left') tappers.emit({ peer: event.peer, reason: event.reason, type: 'peer-left' });\n if (event.type === 'error') warn(event.error);\n }),\n ];\n\n return {\n acceptAnswerText: async (text: string): Promise<MeshPeer> => {\n if (closed) throw disposedError();\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(text);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!('proof' in decoded)) {\n throw new TavernPairingError('That code is an invitation, not a guest answer.');\n }\n try {\n return await host.acceptAnswer(decoded);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n },\n createInvitationText: async () => {\n if (closed) throw disposedError();\n return meshQrCodec.encode(await host.createInvitation());\n },\n get disposalSignal() {\n return host.disposalSignal;\n },\n dispose: close,\n get disposed() {\n return closed;\n },\n kick: (peerId: string): void => {\n if (closed) throw disposedError();\n host.kick(peerId);\n },\n get peers(): readonly MeshPeer[] {\n return [...host.peers.values()];\n },\n relayNotice: (notice: unknown): void => {\n if (closed) return;\n const wire = options.notices ? options.notices.toWire(notice) : null;\n if (wire !== null && wire !== undefined) host.broadcast('notice', wire);\n },\n tap: tappers.tap,\n [Symbol.dispose]() {\n close();\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Guest\n// ---------------------------------------------------------------------------\n\nexport interface TavernGuestOptions<Mounted> {\n /** The invitation code the host produced. */\n invitationText: string;\n /**\n * Mounts a received snapshot; the mounted value, or null to ignore. The snapshot arrives\n * as parsed JSON: validate before trusting it.\n */\n mount(snapshot: unknown): Mounted | null;\n /** The guest's display name on the channel. */\n name: string;\n notices?: TavernNotices;\n /**\n * The channel ended after joining; the mounted value is passed for unmounting.\n * Lifecycle, not observability: rejections and transport warnings belong to\n * {@link TavernGuest.tap}. `onJoined` and `onFailed` stay callbacks for the same\n * reason: they fire while {@link joinTavern} is still resolving, before the\n * consumer can hold the handle and register a tapper.\n */\n onEnded?(subject: Mounted): void;\n /** The host never accepted the answer in time. */\n onFailed?(reason: string): void;\n /** The mounted value once the first snapshot arrives. */\n onJoined?(subject: Mounted): void;\n rtc?: MeshRtcFactory;\n}\n\nexport interface TavernGuest {\n /** `AbortSignal` aborted when the session ends. */\n readonly disposalSignal: AbortSignal;\n /** Leaves the session and drops the channel. */\n dispose(): void;\n /** Whether the session has ended: the channel dropped or `dispose()` ran. */\n readonly disposed: boolean;\n /**\n * Forwards a command to the host. The subject id is the consumer's routing key: the host\n * rejects commands that do not name the subject it is hosting.\n * Throws `TavernDisposedError` after the session has ended.\n */\n sendCommand(subjectId: string, name: string, args: readonly unknown[]): void;\n /** Subscribes to {@link TavernGuestEvent}s. Handler errors are swallowed; the\n * subscription detaches when `signal` aborts or the session ends. */\n tap(handler: (event: TavernGuestEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;\n /** Delegates to `dispose()`. Enables `using` declarations. */\n [Symbol.dispose](): void;\n}\n\n/**\n * Joins a session as a guest: consumes the host's invitation and returns the answer code to\n * show back. The session goes live once the host accepts the answer and the first snapshot\n * mounts; disposing the guest (or the channel dropping) ends it exactly once.\n */\nexport async function joinTavern<Mounted>(\n options: TavernGuestOptions<Mounted>,\n): Promise<{ answerText: string; guest: TavernGuest }> {\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(options.invitationText);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!('secret' in decoded)) {\n throw new TavernPairingError('That code is not a session invitation.');\n }\n\n const guest = createMeshGuest<WireProtocol>({\n maxMessageBytes: DEFAULT_MAX_MESSAGE_BYTES,\n rtc: options.rtc,\n });\n const tappers = createTappers<TavernGuestEvent>();\n let mounted: Mounted | null = null;\n let ended = false;\n\n /** Ends the session exactly once: from the channel dropping or an explicit dispose. */\n const endSession = (): void => {\n if (ended) return;\n ended = true;\n const subject = mounted;\n mounted = null;\n for (const off of detach.splice(0)) off();\n guest.dispose();\n tappers.stop();\n if (subject !== null) options.onEnded?.(subject);\n };\n\n const detach = [\n guest.on('snapshot', ({ payload }) => {\n const subject = options.mount(payload);\n if (subject === null || ended) return;\n if (mounted === null) {\n mounted = subject;\n options.onJoined?.(subject);\n }\n }),\n guest.on('notice', ({ payload }) => {\n options.notices?.fromWire(payload);\n }),\n guest.on('rejected', ({ payload }) => {\n tappers.emit({\n commandId: payload.commandId,\n message: payload.message || 'The host rejected the action.',\n type: 'rejected',\n });\n }),\n guest.tap((event) => {\n if (event.type !== 'status-change' && event.type !== 'peer-status-change') return;\n if (event.type === 'peer-status-change' && event.peerId !== guest.host?.id) return;\n if (event.status === 'failed' && mounted === null && !ended) {\n options.onFailed?.('The host did not accept the answer in time.');\n }\n if (event.status === 'disconnected' || event.status === 'failed') endSession();\n }),\n guest.tap((event) => {\n if (event.type === 'error') {\n tappers.emit({ error: event.error, message: event.error.message, type: 'warning' });\n }\n }),\n ];\n\n try {\n const answer = await guest.acceptInvitation(decoded, { name: options.name });\n return {\n answerText: await meshQrCodec.encode(answer),\n guest: {\n get disposalSignal() {\n return guest.disposalSignal;\n },\n dispose: endSession,\n get disposed() {\n return ended;\n },\n sendCommand: (subjectId: string, name: string, args: readonly unknown[]): void => {\n if (ended) throw new TavernDisposedError('The session has ended.');\n guest.send('command', { args: [...args], id: commandId(), name, subjectId });\n },\n tap: tappers.tap,\n [Symbol.dispose]() {\n endSession();\n },\n },\n };\n } catch (error) {\n // A failed join must not leave the node and its subscriptions behind.\n endSession();\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n}\n"],"mappings":";;AAgBA,SAAgB,gBAAiE;CAC/E,IAAMA,oBAAU,IAAI,IAAwB,GACxCC,IAAU;CAEd,OAAO;EACL,KAAK,GAAa;GAChB,IAAID,EAAQ,SAAS,GACrB,KAAK,IAAME,KAAUF,GACnB,IAAI;IACF,EAAOG,CAAK;GACd,QAAQ,CAER;EAEJ;EACA,OAAa;GAEX,AADA,IAAU,IACVH,EAAQ,MAAM;EAChB;EACA,IAAI,GAAS,GAAqB;GAChC,IAAIC,KAAWG,GAAS,QAAQ,SAAS,aAAa,CAAC;GACvD,IAAM,eAAqB;IACzB,EAAQ,OAAOC,CAAO;GACxB;GAGA,OAFAL,EAAQ,IAAIK,CAAO,GACnBD,GAAS,QAAQ,iBAAiB,SAAS,QAAQ,EAAE,MAAM,GAAK,CAAC,GAC1D;EACT;CACF;AACF;;ACzCA,IAAa,cAAb,cAAiC,MAAM;CACrC,YAAY,GAAiB,GAAqB;EAGhD,AAFA,MAAME,GAASC,CAAI,GACnB,KAAK,OAAO,WAAW,MACvB,OAAO,eAAe,MAAM,WAAW,SAAS;CAClD;AACF,GAGa,qBAAb,cAAwC,YAAY,CAAC,GAOxC,sBAAb,cAAyC,YAAY,CAAC;;ACEtD,SAAS,eAAe,GAAoC;CAE1D,OAAO,IAAI,mBADKC,aAAiB,QAAQA,EAAM,UAAU,gCAClB,EAAE,OAAOA,EAAM,CAAC;AACzD;AAyEA,IAAMC,IAA4B,QAE5B,kBAA0B,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,GAAG,EAAE,IAAI,KAAK,IAAI,CAAC,CAAC,SAAS,EAAE;AAGvG,SAAS,iBAAiB,GAAuF;CAC/G,IAAI,OAAOC,KAAQ,aAAYA,GAAc,OAAO;CACpD,IAA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A,WAAW,GACLA,aAAiBoB,IAAmB,eAAepB,CAAK,IAAIA;CACpE;AACF"}
1
+ {"version":3,"file":"tavern.js","names":["message","opts","DEFAULT_MAX_MESSAGE_BYTES","raw","id","name","args","error","decoded","tappers","stopped","tapper","event","options","handler","meshQrCodec","MeshPairingError","guest","createMeshGuest","mounted","ended","resolveReady","rejectReady","ready","resolve","reject","subject","off","detach","earlyExit","payload","answer","wrapped","host","createMeshHost","closed","flushScheduled","snapshot","command","peerId","table","apply","code","wire","notice"],"sources":["../src/errors.ts","../src/_protocol.ts","../src/_tappers.ts","../src/guest.ts","../src/host.ts"],"sourcesContent":["/**\n * Base class for all tavern errors.\n * Use `instanceof TavernError` to catch any tavern-originated error in one branch.\n */\nexport class TavernError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** A pairing code the consumer pasted could not be used: a user-input mistake, not a bug. */\nexport class TavernPairingError extends TavernError {}\n\n/**\n * Thrown when a stopped host or an ended guest session is used again. Mirrors\n * mesh's `MeshDisposedError` inside the tavern error hierarchy, so\n * `instanceof TavernError` catches every tavern failure in one branch.\n */\nexport class TavernDisposedError extends TavernError {}\n","import type { MeshAnswer, MeshInvitation, MeshProtocol } from '@vielzeug/mesh';\n\nimport { TavernPairingError } from './errors';\n\n/** Snapshots can be large; the default mesh frame cap is too tight for whole documents. */\nexport const DEFAULT_MAX_MESSAGE_BYTES = 512 * 1024;\n\n/** What travels guest to host: a named command and its arguments, tagged for rejection. */\nexport interface WireCommand {\n readonly args: unknown[];\n readonly id: string;\n readonly name: string;\n}\n\nexport interface WireProtocol extends MeshProtocol {\n toGuest: {\n notice: unknown;\n rejected: { commandId: string; message: string };\n snapshot: unknown;\n };\n toHost: {\n command: WireCommand;\n };\n}\n\nexport const commandId = (): string => `cmd-${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36)}`;\n\n/** Runtime guard for the wire command shape: the protocol is Tavern's, so Tavern validates it. */\nexport function parseWireCommand(raw: unknown): WireCommand | null {\n if (typeof raw !== 'object' || raw === null) return null;\n const { args, id, name } = raw as Record<string, unknown>;\n if (typeof id !== 'string' || typeof name !== 'string' || !Array.isArray(args)) return null;\n return { args, id, name };\n}\n\n/**\n * Reclassifies a mesh pairing failure as the tavern-level user mistake it is:\n * the code the consumer pasted could not be used. The message is preserved and\n * the original error is chained as `cause`.\n */\nexport function toPairingError(error: unknown): TavernPairingError {\n const message = error instanceof Error ? error.message : 'That code could not be read.';\n return new TavernPairingError(message, { cause: error });\n}\n\n/** narrows a decoded pairing code to the guest's half of the handshake. */\nexport function isMeshAnswer(decoded: MeshInvitation | MeshAnswer): decoded is MeshAnswer {\n return 'proof' in decoded;\n}\n\n/** narrows a decoded pairing code to the host's half of the handshake. */\nexport function isMeshInvitation(decoded: MeshInvitation | MeshAnswer): decoded is MeshInvitation {\n return 'secret' in decoded;\n}\n","/**\n * The `tap()` machinery shared by the host and guest handles. Kept private: the\n * public contract is each handle's `tap` method and its event union, not this.\n *\n * Follows the repo observability rules: zero overhead with no tappers, handler\n * errors swallowed, auto-detach on an abort signal, and a no-op unsubscribe once\n * the handle has stopped.\n */\nexport interface Tappers<E extends { readonly type: string }> {\n /** Emits to every tapper; a no-op when none are registered. */\n emit(event: E): void;\n /** Drops every tapper and makes later `tap` calls no-ops. Idempotent. */\n stop(): void;\n tap(handler: (event: E) => void, options?: { readonly signal?: AbortSignal }): () => void;\n}\n\nexport function createTappers<E extends { readonly type: string }>(): Tappers<E> {\n const tappers = new Set<(event: E) => void>();\n let stopped = false;\n\n return {\n emit(event): void {\n if (tappers.size === 0) return;\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect session behavior.\n }\n }\n },\n stop(): void {\n stopped = true;\n tappers.clear();\n },\n tap(handler, options): () => void {\n if (stopped || options?.signal?.aborted) return () => {};\n const detach = (): void => {\n tappers.delete(handler);\n };\n tappers.add(handler);\n options?.signal?.addEventListener('abort', detach, { once: true });\n return detach;\n },\n };\n}\n","import { createMeshGuest, type MeshAnswer, type MeshInvitation, MeshPairingError, meshQrCodec } from '@vielzeug/mesh';\nimport { commandId, DEFAULT_MAX_MESSAGE_BYTES, isMeshInvitation, toPairingError, type WireProtocol } from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernError, TavernPairingError } from './errors';\nimport type { TavernGuestEvent, TavernGuestOptions, TavernJoinResult } from './types';\n\n/**\n * Joins a session as a guest: consumes the host's invitation code and returns the answer\n * code to show back. The session goes live once the host accepts the answer and the first\n * snapshot mounts; that transition settles {@link TavernJoinResult.ready}. Disposing the\n * guest (or the channel dropping) ends the session exactly once.\n */\nexport async function joinTavern<Mounted>(options: TavernGuestOptions<Mounted>): Promise<TavernJoinResult<Mounted>> {\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(options.invitationCode);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshInvitation(decoded)) {\n throw new TavernPairingError('That code is not a session invitation.');\n }\n\n const guest = createMeshGuest<WireProtocol>({\n maxMessageBytes: DEFAULT_MAX_MESSAGE_BYTES,\n rtc: options.rtc,\n });\n const tappers = createTappers<TavernGuestEvent>();\n let mounted: Mounted | null = null;\n let ended = false;\n let resolveReady!: (subject: Mounted) => void;\n let rejectReady!: (error: Error) => void;\n const ready = new Promise<Mounted>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n // A ready the consumer never awaits must not surface as an unhandled rejection.\n void ready.catch(() => undefined);\n\n /** Ends the session exactly once: from the channel dropping or an explicit dispose. */\n const endSession = (earlyExit: Error): void => {\n if (ended) return;\n ended = true;\n const subject = mounted;\n mounted = null;\n for (const off of detach.splice(0)) off();\n guest.dispose();\n tappers.emit({ type: 'dispose' });\n tappers.stop();\n if (subject !== null) options.onEnded?.(subject);\n else rejectReady(earlyExit);\n };\n\n const detach = [\n guest.on('snapshot', ({ payload }) => {\n const subject = options.mount(payload);\n if (subject === null || ended) return;\n if (mounted === null) {\n mounted = subject;\n resolveReady(subject);\n }\n }),\n guest.on('notice', ({ payload }) => {\n options.onNotice?.(payload);\n }),\n guest.on('rejected', ({ payload }) => {\n tappers.emit({\n commandId: payload.commandId,\n message: payload.message || 'The host rejected the action.',\n type: 'rejected',\n });\n }),\n guest.tap((event) => {\n // A failed ICE negotiation before the channel opens surfaces only as the raw\n // ice-state event; once a channel exists, mesh reports failed/disconnected statuses.\n if (event.type === 'ice-state' && event.state === 'failed') {\n endSession(new TavernError('The connection to the host failed.'));\n return;\n }\n if (event.type !== 'status-change' && event.type !== 'peer-status-change') return;\n if (event.type === 'peer-status-change' && event.peerId !== guest.host?.id) return;\n if (event.status === 'failed') endSession(new TavernError('The host did not accept the answer in time.'));\n if (event.status === 'disconnected') endSession(new TavernError('The host closed the session.'));\n }),\n guest.tap((event) => {\n if (event.type === 'error') {\n tappers.emit({ error: event.error, message: event.error.message, type: 'warning' });\n }\n }),\n ];\n\n try {\n const answer = await guest.acceptInvitation(decoded, { name: options.name });\n return {\n answerCode: await meshQrCodec.encode(answer),\n guest: {\n get disposalSignal() {\n return guest.disposalSignal;\n },\n dispose: () => endSession(new TavernDisposedError('The guest left before the first snapshot arrived.')),\n get disposed() {\n return ended;\n },\n sendCommand: (name: string, args: readonly unknown[] = []): void => {\n if (ended) throw new TavernDisposedError('The session has ended.');\n guest.send('command', { args: [...args], id: commandId(), name });\n },\n tap: tappers.tap,\n [Symbol.dispose]() {\n endSession(new TavernDisposedError('The guest left before the first snapshot arrived.'));\n },\n },\n ready,\n };\n } catch (error) {\n // A failed join must not leave the node and its subscriptions behind.\n const wrapped = error instanceof MeshPairingError ? toPairingError(error) : error;\n endSession(wrapped instanceof Error ? wrapped : new TavernError('The invitation could not be accepted.'));\n throw wrapped;\n }\n}\n","import {\n createMeshHost,\n type MeshAnswer,\n type MeshInvitation,\n MeshPairingError,\n type MeshPeer,\n meshQrCodec,\n} from '@vielzeug/mesh';\nimport {\n DEFAULT_MAX_MESSAGE_BYTES,\n isMeshAnswer,\n parseWireCommand,\n toPairingError,\n type WireProtocol,\n} from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernPairingError } from './errors';\nimport type { TavernHost, TavernHostEvent, TavernHostOptions } from './types';\n\n/**\n * Starts hosting one subject over mesh. Every guest command is validated and applied\n * through the command table; local changes re-broadcast the snapshot (coalesced on a\n * microtask); removal ends the session.\n */\nexport function hostTavern(options: TavernHostOptions): TavernHost {\n const host = createMeshHost<WireProtocol>({\n maxMessageBytes: DEFAULT_MAX_MESSAGE_BYTES,\n rtc: options.rtc,\n });\n const tappers = createTappers<TavernHostEvent>();\n let closed = false;\n let flushScheduled = false;\n\n const close = (): void => {\n if (closed) return;\n closed = true;\n for (const off of detach.splice(0)) off();\n host.dispose();\n tappers.emit({ type: 'dispose' });\n tappers.stop();\n options.onEnded?.();\n };\n const disposedError = (): TavernDisposedError => new TavernDisposedError('This host has stopped.');\n const warn = (error: unknown): void => {\n tappers.emit({ error, message: error instanceof Error ? error.message : String(error), type: 'warning' });\n };\n\n /** Reads the snapshot for a broadcast; a throwing read warns instead of crashing the host. */\n const readSnapshot = (): unknown => {\n try {\n return options.subject.snapshot();\n } catch (error) {\n warn(error);\n return null;\n }\n };\n\n /** Coalesces broadcasts on a microtask so bursts of local changes ship one snapshot. */\n const broadcastSnapshot = (): void => {\n if (closed || flushScheduled) return;\n flushScheduled = true;\n queueMicrotask(() => {\n flushScheduled = false;\n if (closed) return;\n const snapshot = readSnapshot();\n if (snapshot !== null && snapshot !== undefined) host.broadcast('snapshot', snapshot);\n });\n };\n\n /**\n * Applies a guest command through the command table: the same table the host's own UI\n * calls, so an unknown name or a rule violation is all the host can ever reject with.\n */\n const handleGuestCommand = (peerId: string, raw: unknown): void => {\n const command = parseWireCommand(raw);\n if (!command) {\n host.send(peerId, 'rejected', { commandId: '', message: 'That command could not be read.' });\n return;\n }\n // Own-property lookup only: a guest must not reach Object.prototype members.\n const table = options.commands;\n const apply = table && Object.hasOwn(table, command.name) ? table[command.name] : undefined;\n if (typeof apply !== 'function') {\n host.send(peerId, 'rejected', {\n commandId: command.id,\n message: `The host has no command named \"${command.name}\".`,\n });\n return;\n }\n try {\n apply(command.args);\n } catch (error) {\n host.send(peerId, 'rejected', {\n commandId: command.id,\n message: error instanceof Error ? error.message : 'The host could not apply the command.',\n });\n }\n };\n\n const detach = [\n host.on('command', ({ peerId, payload }) => handleGuestCommand(peerId, payload)),\n options.subject.onChanged(broadcastSnapshot),\n options.subject.onRemoved(close),\n host.tap((event) => {\n if (event.type === 'peer-joined') {\n const snapshot = readSnapshot();\n if (snapshot !== null && snapshot !== undefined) host.send(event.peer.id, 'snapshot', snapshot);\n tappers.emit({ peer: event.peer, type: 'peer-joined' });\n }\n if (event.type === 'peer-left') tappers.emit({ peer: event.peer, reason: event.reason, type: 'peer-left' });\n if (event.type === 'error') warn(event.error);\n }),\n ];\n\n return {\n acceptAnswerCode: async (code: string): Promise<MeshPeer> => {\n if (closed) throw disposedError();\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(code);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshAnswer(decoded)) {\n throw new TavernPairingError('That code is an invitation, not a guest answer.');\n }\n try {\n return await host.acceptAnswer(decoded);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n },\n createInvitationCode: async () => {\n if (closed) throw disposedError();\n return meshQrCodec.encode(await host.createInvitation());\n },\n get disposalSignal() {\n return host.disposalSignal;\n },\n dispose: close,\n get disposed() {\n return closed;\n },\n kick: (peerId: string): void => {\n if (closed) throw disposedError();\n host.kick(peerId);\n },\n get peers(): readonly MeshPeer[] {\n return [...host.peers.values()];\n },\n relayNotice: (notice: unknown): void => {\n if (closed) return;\n const wire = options.serializeNotice ? options.serializeNotice(notice) : null;\n if (wire !== null && wire !== undefined) host.broadcast('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