iii-browser-sdk 0.24.6 → 0.25.0-alpha.1

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":"index.mjs","names":[],"sources":["../src/errors.ts","../src/iii-constants.ts","../src/iii.ts"],"sourcesContent":["export type RegistrationRejectedInit = {\n code: string\n namespace: string\n worker_name?: string\n function_id?: string\n owner_worker_id: string\n}\n\n/**\n * A terminal registration rejection from the engine. Thrown into every pending\n * invocation and exposed via `getFatalError()` when a worker-name collision\n * (or other non-retryable rejection) closes the connection for good.\n */\nexport class RegistrationRejectedError extends Error {\n public readonly code: string\n public readonly namespace: string\n public readonly worker_name?: string\n public readonly function_id?: string\n public readonly owner_worker_id: string\n\n constructor(init: RegistrationRejectedInit) {\n super(\n `${init.code}: registration rejected for ${init.function_id !== undefined ? `function \"${init.function_id}\"` : `worker \"${init.worker_name ?? '<unknown>'}\"`} in namespace \"${init.namespace}\" (already owned by worker ${init.owner_worker_id})`,\n )\n this.name = 'RegistrationRejectedError'\n this.code = init.code\n this.namespace = init.namespace\n this.worker_name = init.worker_name\n this.function_id = init.function_id\n this.owner_worker_id = init.owner_worker_id\n }\n}\n","/**\n * Constants for the III module.\n */\n\n/**\n * Engine function paths for internal operations.\n *\n * Naming note: `LIST_TRIGGERS` / `INFO_TRIGGERS` cover trigger TYPES\n * (templates). `LIST_REGISTERED_TRIGGERS` / `INFO_REGISTERED_TRIGGERS`\n * cover trigger INSTANCES (subscriber rows). The old\n * `engine::trigger-types::list` builtin has been removed and is now\n * served by `engine::triggers::list`.\n */\nexport const EngineFunctions = {\n LIST_FUNCTIONS: 'engine::functions::list',\n INFO_FUNCTIONS: 'engine::functions::info',\n LIST_WORKERS: 'engine::workers::list',\n INFO_WORKERS: 'engine::workers::info',\n LIST_TRIGGERS: 'engine::triggers::list',\n INFO_TRIGGERS: 'engine::triggers::info',\n LIST_REGISTERED_TRIGGERS: 'engine::registered-triggers::list',\n INFO_REGISTERED_TRIGGERS: 'engine::registered-triggers::info',\n REGISTER_WORKER: 'engine::workers::register',\n} as const\n\n/** Engine trigger types */\nexport const EngineTriggers = {\n FUNCTIONS_AVAILABLE: 'engine::functions-available',\n} as const\n\n/** Connection state for the III WebSocket */\nexport type IIIConnectionState = 'disconnected' | 'connecting' | 'connected' | 'reconnecting' | 'failed'\n\n/** Configuration for WebSocket reconnection behavior */\nexport interface IIIReconnectionConfig {\n /** Starting delay in milliseconds (default: 1000ms) */\n initialDelayMs: number\n /** Maximum delay cap in milliseconds (default: 30000ms) */\n maxDelayMs: number\n /** Exponential backoff multiplier (default: 2) */\n backoffMultiplier: number\n /** Random jitter factor 0-1 (default: 0.3) */\n jitterFactor: number\n /** Maximum retry attempts, -1 for infinite (default: -1) */\n maxRetries: number\n}\n\n/** Default reconnection configuration */\nexport const DEFAULT_BRIDGE_RECONNECTION_CONFIG: IIIReconnectionConfig = {\n initialDelayMs: 1000,\n maxDelayMs: 30000,\n backoffMultiplier: 2,\n jitterFactor: 0.3,\n maxRetries: -1,\n}\n\n/** Default invocation timeout in milliseconds */\nexport const DEFAULT_INVOCATION_TIMEOUT_MS = 30000\n","import { ChannelReader, ChannelWriter } from './channels'\nimport {\n DEFAULT_BRIDGE_RECONNECTION_CONFIG,\n DEFAULT_INVOCATION_TIMEOUT_MS,\n EngineFunctions,\n type IIIConnectionState,\n type IIIReconnectionConfig,\n} from './iii-constants'\nimport {\n type IIIMessage,\n type InvocationResultMessage,\n type InvokeFunctionMessage,\n MessageType,\n type RegisterFunctionMessage,\n type RegisterTriggerMessage,\n type RegisterTriggerTypeMessage,\n type StreamChannelRef,\n type TriggerRegistrationResultMessage,\n type TriggerRequest,\n} from './iii-types'\nimport type { IStream } from './stream'\nimport type { TriggerHandler } from './triggers'\nimport type {\n FunctionRef,\n Invocation,\n ISdk,\n RegisterFunctionOptions,\n RemoteFunctionData,\n RemoteFunctionHandler,\n RemoteTriggerTypeData,\n Trigger,\n TriggerTypeRef,\n} from './types'\nimport { isChannelRef, randomUUID } from './utils'\nimport { RegistrationRejectedError } from './errors'\n\n/** @internal */\nexport type TelemetryOptions = {\n language?: string\n project_name?: string\n framework?: string\n}\n\n/**\n * Configuration options passed to {@link registerWorker}.\n *\n * @example\n * ```typescript\n * const worker = registerWorker('ws://localhost:49135', {\n * invocationTimeoutMs: 10000,\n * reconnectionConfig: { maxRetries: 5 },\n * })\n * ```\n */\nexport type InitOptions = {\n /**\n * Name this worker announces to the engine. Defaults to a unique\n * `browser:<random>` per client: a browser has no pid to disambiguate by, and\n * the engine allows only one live worker per name in a namespace, so two tabs\n * sharing a fixed name would evict each other.\n */\n workerName?: string\n /**\n * Namespace this worker registers under. When omitted the engine applies its\n * `default` namespace. Scopes worker and function registrations so\n * identically-named entries can coexist across namespaces. The browser has no\n * `process.env`, so there is no environment-variable fallback -- pass the\n * option explicitly.\n */\n namespace?: string\n /** Default timeout for `worker.trigger()` invocations in milliseconds. Defaults to `30000`. */\n invocationTimeoutMs?: number\n /**\n * WebSocket reconnection behavior.\n *\n * @see {@link IIIReconnectionConfig} for available fields and defaults.\n */\n reconnectionConfig?: Partial<IIIReconnectionConfig>\n /** Browser WebSocket connections authenticate via query parameters or cookies; the `headers` option is ignored. */\n headers?: Record<string, string>\n}\n\n/** Short random suffix; `crypto.randomUUID` is unavailable on insecure origins. */\nfunction randomId(): string {\n const c = globalThis.crypto\n if (c?.randomUUID) {\n return c.randomUUID().slice(0, 8)\n }\n if (c?.getRandomValues) {\n return Array.from(c.getRandomValues(new Uint8Array(4)))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n }\n return Math.random().toString(16).slice(2, 10)\n}\n\n/**\n * The worker's namespace, refusing one that was named and left blank.\n *\n * Absent and blank mean opposite things. Absent asks for the engine's\n * `default`; blank names a namespace and gives nothing to name it with. Read as\n * absent, the worker registers in `default`, and since a worker's calls and\n * triggers follow its namespace, the whole project quietly serves from a place\n * its declaration never named -- the one thing an operator cannot see by\n * reading the declaration.\n *\n * The browser has no `III_NAMESPACE` to fall back to, so unlike the other SDKs\n * there is only the option here, and an option that was written and left empty\n * is never what someone meant.\n */\n/**\n * The namespace one call or one binding resolves in.\n *\n * `undefined` inherits the worker's. A blank one is refused: named and left\n * empty asks for the opposite of what absent asks for, and the two are only\n * ever confused by accident -- `??` forwards the empty string, Python's `or`\n * coerced it and Go dropped it, so one mistake produced three behaviours.\n */\nfunction callNamespace(\n explicit: string | undefined,\n worker: string | undefined,\n source: string,\n): string | undefined {\n if (explicit !== undefined && explicit.trim() === '') {\n throw new Error(\n `namespace is empty: ${source} was set to ${JSON.stringify(explicit)}. ` +\n \"Give it a name, or leave it unset to stay in this worker's namespace.\",\n )\n }\n return explicit ?? worker\n}\n\n/** Resolve one function invocation without leaking engine and configuration builtins into a worker namespace. */\nfunction invocationNamespace(\n explicit: string | undefined,\n worker: string | undefined,\n functionId: string,\n): string | undefined {\n const namespace = callNamespace(explicit, worker, 'TriggerRequest.namespace')\n return explicit === undefined && (functionId.startsWith('engine::') || functionId.startsWith('configuration::'))\n ? 'default'\n : namespace\n}\n\nfunction resolveNamespace(optionNamespace?: string): string | undefined {\n if (optionNamespace !== undefined && optionNamespace.trim() === '') {\n throw new Error(\n `namespace is empty: options.namespace was set to ${JSON.stringify(optionNamespace)}. ` +\n 'Give it a name, or leave it unset to register in `default`.',\n )\n }\n return optionNamespace\n}\n\nclass Sdk implements ISdk {\n private ws?: WebSocket\n private functions = new Map<string, RemoteFunctionData>()\n private invocations = new Map<string, Invocation & { timeout?: ReturnType<typeof setTimeout> }>()\n private triggers = new Map<string, RegisterTriggerMessage>()\n private triggerTypes = new Map<string, RemoteTriggerTypeData>()\n private messagesToSend: Record<string, unknown>[] = []\n private reconnectTimeout?: ReturnType<typeof setTimeout>\n private invocationTimeoutMs: number\n private reconnectionConfig: IIIReconnectionConfig\n private reconnectAttempt = 0\n private connectionState: IIIConnectionState = 'disconnected'\n private connectionListeners = new Set<(state: IIIConnectionState) => void>()\n private isShuttingDown = false\n private readonly workerName: string\n private readonly namespace?: string\n private workerId?: string\n private reattachToken?: string\n private fatalError?: RegistrationRejectedError\n\n constructor(\n private readonly address: string,\n private readonly options?: InitOptions,\n ) {\n this.workerName = options?.workerName ?? `browser:${randomId()}`\n // No env fallback: the browser has no `process.env`, so the option is the\n // only source -- and the only thing that can be wrong.\n this.namespace = resolveNamespace(options?.namespace)\n this.invocationTimeoutMs = options?.invocationTimeoutMs ?? DEFAULT_INVOCATION_TIMEOUT_MS\n this.reconnectionConfig = {\n ...DEFAULT_BRIDGE_RECONNECTION_CONFIG,\n ...options?.reconnectionConfig,\n }\n\n this.connect()\n }\n\n /**\n * Registers a custom trigger type with the engine. A trigger type defines\n * how external events (HTTP, cron, queue, etc.) map to function invocations.\n *\n * @param triggerType - Trigger type registration input.\n * @param triggerType.id - Unique trigger type identifier.\n * @param triggerType.description - Human-readable description.\n * @param handler - Handler with `registerTrigger` / `unregisterTrigger` callbacks.\n *\n * @example\n * ```typescript\n * worker.registerTriggerType(\n * { id: 'my-trigger', description: 'Custom trigger' },\n * {\n * async registerTrigger({ id, function_id, config }) { },\n * async unregisterTrigger({ id, function_id, config }) { },\n * },\n * )\n * ```\n */\n registerTriggerType = <TConfig>(\n triggerType: Omit<RegisterTriggerTypeMessage, 'message_type'>,\n handler: TriggerHandler<TConfig>,\n ): TriggerTypeRef<TConfig> => {\n this.sendMessage(MessageType.RegisterTriggerType, triggerType, true)\n this.triggerTypes.set(triggerType.id, {\n message: { ...triggerType, message_type: MessageType.RegisterTriggerType },\n handler,\n })\n\n return {\n id: triggerType.id,\n // Pairs a function with its trigger, so it defaults the trigger's namespace\n // to this worker's — otherwise the function lands in the worker's namespace\n // and the trigger in `default`, never resolving it. The low-level\n // `registerTrigger` keeps the engine default (`default`).\n registerTrigger: (functionId: string, config: TConfig) => {\n return this.registerTrigger({\n type: triggerType.id,\n function_id: functionId,\n config,\n namespace: this.namespace,\n })\n },\n registerFunction: (functionId, handler, config) => {\n const ref = this.registerFunction(functionId, handler)\n this.registerTrigger({\n type: triggerType.id,\n function_id: functionId,\n config,\n namespace: this.namespace,\n })\n return ref\n },\n unregister: () => {\n this.unregisterTriggerType(triggerType)\n },\n }\n }\n\n /**\n * Unregisters a previously registered trigger type.\n *\n * @param triggerType - The trigger type to unregister (must match the `id` used during registration).\n */\n unregisterTriggerType = (triggerType: Omit<RegisterTriggerTypeMessage, 'message_type'>): void => {\n this.sendMessage(MessageType.UnregisterTriggerType, triggerType, true)\n this.triggerTypes.delete(triggerType.id)\n }\n\n /**\n * Binds a trigger configuration to a registered function. When the trigger\n * fires, the engine invokes the target function.\n *\n * @param trigger - Trigger registration input.\n * @param trigger.type - Trigger type (e.g. `http`, `durable:subscriber`, `cron`).\n * @param trigger.function_id - ID of the function to invoke.\n * @param trigger.config - Trigger-specific configuration.\n * @returns A {@link Trigger} handle with an `unregister()` method.\n *\n * @example\n * ```typescript\n * const trigger = worker.registerTrigger({\n * type: 'http',\n * function_id: 'greet',\n * config: { api_path: '/greet', http_method: 'GET' },\n * })\n *\n * // Later...\n * trigger.unregister()\n * ```\n */\n registerTrigger = (trigger: Omit<RegisterTriggerMessage, 'message_type' | 'id'>): Trigger => {\n const id = randomUUID()\n const fullTrigger: RegisterTriggerMessage = {\n ...trigger,\n id,\n message_type: MessageType.RegisterTrigger,\n // Unset means this worker's namespace, not the engine's default. A\n // trigger names a function, and the function a worker registers lands in\n // the worker's namespace, so defaulting anywhere else registers a trigger\n // that fires and resolves nothing. Naming another namespace, `default`\n // included, stays a matter of saying so.\n ...(() => {\n const namespace = callNamespace(\n trigger.namespace,\n this.namespace,\n 'RegisterTriggerInput.namespace',\n )\n return namespace !== undefined ? { namespace } : {}\n })(),\n }\n this.sendMessage(MessageType.RegisterTrigger, fullTrigger, true)\n this.triggers.set(id, fullTrigger)\n\n return {\n unregister: () => {\n this.sendMessage(MessageType.UnregisterTrigger, {\n id,\n message_type: MessageType.UnregisterTrigger,\n type: fullTrigger.type,\n })\n this.triggers.delete(id)\n },\n }\n }\n\n /**\n * Registers a function with the engine. The `functionId` is the unique identifier\n * used by triggers and invocations.\n *\n * The handler runs locally in the browser session; HTTP invocation configs\n * are a Node.js SDK feature and are not accepted here.\n *\n * @param functionId - Unique function identifier.\n * @param handlerOrInvocation - Async handler executed when the function is invoked.\n * @param options - Optional function registration options (description, request/response formats, metadata).\n * @returns A {@link FunctionRef} with `id` and `unregister()`.\n *\n * @example\n * ```typescript\n * const fn = worker.registerFunction(\n * 'greet',\n * async (input: { name: string }) => {\n * return { message: `Hello, ${input.name}!` }\n * },\n * { description: 'Greets a user' },\n * )\n * ```\n */\n registerFunction = (\n functionId: string,\n handlerOrInvocation: RemoteFunctionHandler,\n options?: RegisterFunctionOptions,\n ): FunctionRef => {\n if (!functionId || functionId.trim() === '') {\n throw new Error('id is required')\n }\n if (this.functions.has(functionId)) {\n throw new Error(`function id already registered: ${functionId}`)\n }\n\n const fullMessage: RegisterFunctionMessage = {\n ...options,\n id: functionId,\n message_type: MessageType.RegisterFunction,\n }\n\n this.sendMessage(MessageType.RegisterFunction, fullMessage, true)\n\n const handler = handlerOrInvocation as RemoteFunctionHandler\n this.functions.set(functionId, {\n message: fullMessage,\n handler: async (input, _traceparent?: string, _baggage?: string) => {\n return await handler(input)\n },\n })\n\n return {\n id: functionId,\n unregister: () => {\n this.sendMessage(MessageType.UnregisterFunction, { id: functionId }, true)\n this.functions.delete(functionId)\n },\n }\n }\n\n /**\n * @internal Implementation backing the `createChannel` helper in the\n * `iii-browser-sdk/helpers` submodule. Not part of the public `ISdk` surface.\n *\n * Creates a streaming channel pair for worker-to-worker data transfer.\n * Returns a {@link Channel} with a local writer/reader and serializable refs\n * that can be passed as fields in invocation data to other functions.\n */\n __helpers_create_channel = async (bufferSize?: number): Promise<import('./types').Channel> => {\n const result = await this.trigger<{ buffer_size?: number }, { writer: StreamChannelRef; reader: StreamChannelRef }>(\n { function_id: 'engine::channels::create', payload: { buffer_size: bufferSize } },\n )\n\n return {\n writer: new ChannelWriter(this.address, result.writer),\n reader: new ChannelReader(this.address, result.reader),\n writerRef: result.writer,\n readerRef: result.reader,\n }\n }\n\n /**\n * Invokes a remote function. The routing behavior and return type depend\n * on the `action` field of the request.\n *\n * | `action` | Behavior | Return type |\n * |-------------------------------|----------------------------------------------------|----------------------- |\n * | _(none)_ | Synchronous: waits for the function to return | `Promise<TOutput>` |\n * | `TriggerAction.Enqueue(...)` | Async via named queue; engine acknowledges enqueue | `Promise<EnqueueResult>` |\n * | `TriggerAction.Void()` | Fire-and-forget, no response | `Promise<undefined>` |\n *\n * @param request - The trigger request.\n * @param request.function_id - ID of the function to invoke.\n * @param request.payload - Payload to pass to the function.\n * @param request.action - Routing action. Omit for synchronous request/response.\n * @param request.timeoutMs - Override the default invocation timeout.\n * @returns The result of the function invocation.\n *\n * @example\n * ```typescript\n * import { TriggerAction } from 'iii-browser-sdk'\n *\n * // Synchronous\n * const result = await worker.trigger({ function_id: 'get-order', payload: { id: '123' } })\n *\n * // Enqueue\n * const { messageReceiptId } = await worker.trigger({\n * function_id: 'payments::charge',\n * payload: { orderId: '123', amount: 49.99 },\n * action: TriggerAction.Enqueue({ queue: 'payment' }),\n * })\n *\n * // Fire-and-forget\n * worker.trigger({\n * function_id: 'notifications::send',\n * payload: { userId: '123' },\n * action: TriggerAction.Void(),\n * })\n * ```\n */\n // biome-ignore lint/suspicious/noExplicitAny: TOutput defaults to any so untyped calls type-check (the engine cannot express the return type statically)\n trigger = async <TInput = unknown, TOutput = any>(\n request: TriggerRequest<TInput>,\n ): Promise<TOutput> => {\n const { function_id, payload, action, timeoutMs } = request\n // Engine-owned builtins stay in `default`. Other implicit calls stay in\n // this worker's namespace. An explicit request namespace always wins.\n const namespace = invocationNamespace(request.namespace, this.namespace, function_id)\n const effectiveTimeout = timeoutMs ?? this.invocationTimeoutMs\n\n if (action?.type === 'void') {\n this.sendMessage(MessageType.InvokeFunction, {\n function_id,\n data: payload,\n action,\n // Omitted only when this worker has no namespace either.\n ...(namespace !== undefined ? { namespace } : {}),\n })\n return undefined as TOutput\n }\n\n const invocation_id = randomUUID()\n\n return new Promise<TOutput>((resolve, reject) => {\n const timeout = setTimeout(() => {\n const invocation = this.invocations.get(invocation_id)\n if (invocation) {\n this.invocations.delete(invocation_id)\n reject(new Error(`Invocation timeout after ${effectiveTimeout}ms: ${function_id}`))\n }\n }, effectiveTimeout)\n\n this.invocations.set(invocation_id, {\n resolve: (result: TOutput) => {\n clearTimeout(timeout)\n resolve(result)\n },\n reject: (error: unknown) => {\n clearTimeout(timeout)\n reject(error)\n },\n timeout,\n })\n\n this.sendMessage(MessageType.InvokeFunction, {\n invocation_id,\n function_id,\n data: payload,\n action,\n // Omitted only when this worker has no namespace either.\n ...(namespace !== undefined ? { namespace } : {}),\n })\n })\n }\n\n /**\n * @internal Implementation backing the `createStream` helper in the\n * `iii-browser-sdk/helpers` submodule. Not part of the public `ISdk` surface.\n *\n * Registers a custom stream implementation, overriding the engine default\n * for the given stream name.\n */\n __helpers_create_stream = <TData>(streamName: string, stream: IStream<TData>): void => {\n this.registerFunction(`stream::get(${streamName})`, stream.get.bind(stream))\n this.registerFunction(`stream::set(${streamName})`, stream.set.bind(stream))\n this.registerFunction(`stream::delete(${streamName})`, stream.delete.bind(stream))\n this.registerFunction(`stream::list(${streamName})`, stream.list.bind(stream))\n this.registerFunction(`stream::list_groups(${streamName})`, stream.listGroups.bind(stream))\n }\n\n /**\n * The terminal rejection that closed this connection for good, if any. Set\n * only for a non-retryable registration rejection (e.g. a worker-name\n * collision). Mirrors the Node SDK.\n */\n getFatalError = (): RegistrationRejectedError | undefined => this.fatalError\n\n /**\n * Gracefully shutdown the SDK, cleaning up all resources.\n */\n shutdown = async (): Promise<void> => {\n this.isShuttingDown = true\n\n this.clearReconnectTimeout()\n\n for (const [_id, invocation] of this.invocations) {\n if (invocation.timeout) {\n clearTimeout(invocation.timeout)\n }\n invocation.reject(new Error('iii is shutting down'))\n }\n this.invocations.clear()\n\n if (this.ws) {\n this.ws.onopen = null\n this.ws.onclose = null\n this.ws.onerror = null\n this.ws.onmessage = null\n this.ws.close()\n this.ws = undefined\n }\n\n this.setConnectionState('disconnected')\n }\n\n /**\n * Subscribe to connection-state transitions. The handler is fired immediately\n * with the current state, then on every transition. Multiple listeners are\n * supported. Returns an unsubscribe function.\n */\n addConnectionStateListener = (handler: (state: IIIConnectionState) => void): (() => void) => {\n this.connectionListeners.add(handler)\n try {\n handler(this.connectionState)\n } catch (e) {\n console.error('[iii] connection listener threw on initial fire', e)\n }\n return () => {\n this.connectionListeners.delete(handler)\n }\n }\n\n // private methods\n\n private setConnectionState(state: IIIConnectionState): void {\n if (this.connectionState !== state) {\n this.connectionState = state\n for (const handler of this.connectionListeners) {\n try {\n handler(state)\n } catch (e) {\n console.error('[iii] connection listener threw', e)\n }\n }\n }\n }\n\n private connect(): void {\n if (this.isShuttingDown) {\n return\n }\n\n this.setConnectionState('connecting')\n this.ws = new WebSocket(this.address)\n this.ws.onopen = this.onSocketOpen.bind(this)\n this.ws.onclose = this.onSocketClose.bind(this)\n this.ws.onerror = this.onSocketError.bind(this)\n }\n\n private clearReconnectTimeout(): void {\n if (this.reconnectTimeout) {\n clearTimeout(this.reconnectTimeout)\n this.reconnectTimeout = undefined\n }\n }\n\n private scheduleReconnect(): void {\n if (this.isShuttingDown) {\n return\n }\n\n const { maxRetries, initialDelayMs, backoffMultiplier, maxDelayMs, jitterFactor } = this.reconnectionConfig\n\n if (maxRetries !== -1 && this.reconnectAttempt >= maxRetries) {\n this.setConnectionState('failed')\n console.error(`[iii] Max reconnection retries (${maxRetries}) reached, giving up`)\n return\n }\n\n if (this.reconnectTimeout) {\n return\n }\n\n const exponentialDelay = initialDelayMs * backoffMultiplier ** this.reconnectAttempt\n const cappedDelay = Math.min(exponentialDelay, maxDelayMs)\n const jitter = cappedDelay * jitterFactor * (2 * Math.random() - 1)\n const delay = Math.floor(cappedDelay + jitter)\n\n this.setConnectionState('reconnecting')\n console.debug(`[iii] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempt + 1})...`)\n\n this.reconnectTimeout = setTimeout(() => {\n this.reconnectTimeout = undefined\n this.reconnectAttempt++\n this.connect()\n }, delay)\n }\n\n private onSocketError(): void {\n console.error('[iii] WebSocket error')\n }\n\n private onSocketClose(): void {\n if (this.ws) {\n this.ws.onopen = null\n this.ws.onclose = null\n this.ws.onerror = null\n this.ws.onmessage = null\n }\n this.ws = undefined\n\n // A fatal registration rejection (or shutdown) sets `isShuttingDown` and a\n // terminal state before closing the socket. Do not overwrite that state with\n // `disconnected`, and do not schedule a reconnect the engine would only\n // reject again. `scheduleReconnect` already no-ops while shutting down.\n if (this.isShuttingDown) {\n return\n }\n\n this.setConnectionState('disconnected')\n this.scheduleReconnect()\n }\n\n private onSocketOpen(): void {\n this.clearReconnectTimeout()\n this.reconnectAttempt = 0\n this.setConnectionState('connected')\n\n if (this.ws) {\n this.ws.onmessage = this.onMessage.bind(this)\n }\n\n // Reconnect: present the previous engine-assigned identity BEFORE the\n // metadata announce and registration replay so the engine retires the old\n // connection and the replay lands on a clean slate instead of racing its\n // cleanup. This must precede registerWorkerMetadata(): otherwise the old\n // connection still holds this (namespace, worker_name) and the announce\n // would trip WORKER_NAMESPACE_CONFLICT against ourselves. The token proves\n // we ARE that worker (ids alone are publicly listable).\n if (this.workerId) {\n this.sendMessageRaw(\n JSON.stringify({\n type: MessageType.Reattach,\n previous_worker_id: this.workerId,\n reattach_token: this.reattachToken,\n }),\n )\n }\n\n // Announce before registering anything. The engine buffers a connection's\n // registrations until it knows the connection's namespace, which it takes\n // from this call — or, failing that, only after a grace period. Registering\n // first would stall every function behind that grace.\n this.registerWorkerMetadata()\n\n\n this.triggerTypes.forEach(({ message }) => {\n this.sendMessage(MessageType.RegisterTriggerType, message, true)\n })\n this.functions.forEach(({ message }) => {\n this.sendMessage(MessageType.RegisterFunction, message, true)\n })\n this.triggers.forEach((trigger) => {\n this.sendMessage(MessageType.RegisterTrigger, trigger, true)\n })\n\n const pending = this.messagesToSend\n this.messagesToSend = []\n for (const message of pending) {\n if (\n message.type === MessageType.InvokeFunction &&\n typeof message.invocation_id === 'string' &&\n !this.invocations.has(message.invocation_id)\n ) {\n continue\n }\n this.sendMessageRaw(JSON.stringify(message))\n }\n }\n\n private isOpen(): boolean {\n return this.ws?.readyState === WebSocket.OPEN\n }\n\n private sendMessageRaw(data: string): void {\n if (this.ws && this.isOpen()) {\n try {\n this.ws.send(data)\n } catch (error) {\n console.error('[iii] Exception while sending message', error)\n }\n }\n }\n\n private toWireFormat(messageType: MessageType, message: Omit<IIIMessage, 'message_type'>): Record<string, unknown> {\n const { message_type: _, ...rest } = message as Record<string, unknown>\n if (messageType === MessageType.RegisterTrigger && 'type' in message) {\n const { type: triggerType, ...triggerRest } = message as RegisterTriggerMessage\n return { type: messageType, ...triggerRest, trigger_type: triggerType }\n }\n if (messageType === MessageType.UnregisterTrigger && 'type' in message) {\n const { type: triggerType, ...triggerRest } = message as RegisterTriggerMessage\n return { type: messageType, ...triggerRest, trigger_type: triggerType }\n }\n if (messageType === MessageType.TriggerRegistrationResult && 'type' in message) {\n const { type: triggerType, ...resultRest } = message as TriggerRegistrationResultMessage\n return { type: messageType, ...resultRest, trigger_type: triggerType }\n }\n return { type: messageType, ...rest } as Record<string, unknown>\n }\n\n /**\n * Tells the engine who this connection is. Sent on every open, before any\n * registration, so the engine can resolve this connection's namespace and\n * drain its buffered registrations immediately.\n */\n private registerWorkerMetadata(): void {\n this.sendMessage(MessageType.InvokeFunction, {\n function_id: EngineFunctions.REGISTER_WORKER,\n data: {\n runtime: 'browser',\n name: this.workerName,\n os: globalThis.navigator?.userAgent ?? 'browser',\n // Omit when absent so the engine falls back to its `default` namespace.\n ...(this.namespace !== undefined ? { namespace: this.namespace } : {}),\n },\n action: { type: 'void' },\n } as unknown as Omit<IIIMessage, 'message_type'>)\n }\n\n private sendMessage(messageType: MessageType, message: Omit<IIIMessage, 'message_type'>, skipIfClosed = false): void {\n const wireMessage = this.toWireFormat(messageType, message)\n if (this.isOpen()) {\n this.sendMessageRaw(JSON.stringify(wireMessage))\n } else if (!skipIfClosed) {\n this.messagesToSend.push(wireMessage)\n }\n }\n\n private onInvocationResult(invocation_id: string, result: unknown, error: unknown): void {\n const invocation = this.invocations.get(invocation_id)\n\n if (invocation) {\n if (invocation.timeout) {\n clearTimeout(invocation.timeout)\n }\n error ? invocation.reject(error) : invocation.resolve(result)\n }\n\n this.invocations.delete(invocation_id)\n }\n\n private resolveChannelValue(value: unknown): unknown {\n if (isChannelRef(value)) {\n return value.direction === 'read'\n ? new ChannelReader(this.address, value)\n : new ChannelWriter(this.address, value)\n }\n if (Array.isArray(value)) {\n return value.map((item) => this.resolveChannelValue(item))\n }\n if (value !== null && typeof value === 'object') {\n const out: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n out[k] = this.resolveChannelValue(v)\n }\n return out\n }\n return value\n }\n\n private async onInvokeFunction<TInput>(\n invocation_id: string | undefined,\n function_id: string,\n input: TInput,\n traceparent?: string,\n baggage?: string,\n ): Promise<unknown> {\n const fn = this.functions.get(function_id)\n\n const resolvedInput = this.resolveChannelValue(input) as TInput\n\n if (fn?.handler) {\n if (!invocation_id) {\n try {\n await fn.handler(resolvedInput, traceparent, baggage)\n } catch (error) {\n console.error(`[iii] Error invoking function ${function_id}`, error)\n }\n return\n }\n\n try {\n const result = await fn.handler(resolvedInput, traceparent, baggage)\n this.sendMessage(MessageType.InvocationResult, {\n invocation_id,\n function_id,\n result,\n traceparent,\n baggage,\n })\n } catch (error) {\n const isError = error instanceof Error\n this.sendMessage(MessageType.InvocationResult, {\n invocation_id,\n function_id,\n error: {\n code: 'invocation_failed',\n message: isError ? error.message : String(error),\n stacktrace: isError ? error.stack : undefined,\n },\n traceparent,\n baggage,\n })\n }\n } else {\n const errorCode = fn ? 'function_not_invokable' : 'function_not_found'\n const errorMessage = fn ? 'Function is HTTP-invoked and cannot be invoked locally' : 'Function not found'\n if (invocation_id) {\n this.sendMessage(MessageType.InvocationResult, {\n invocation_id,\n function_id,\n error: { code: errorCode, message: errorMessage },\n traceparent,\n baggage,\n })\n }\n }\n }\n\n private async onRegisterTrigger(message: {\n trigger_type: string\n id: string\n function_id: string\n config: unknown\n namespace?: string\n }) {\n const { trigger_type, id, function_id, config, namespace } = message\n const triggerTypeData = this.triggerTypes.get(trigger_type)\n\n if (triggerTypeData) {\n try {\n await triggerTypeData.handler.registerTrigger({ id, function_id, config, namespace })\n this.sendMessage(MessageType.TriggerRegistrationResult, {\n id,\n message_type: MessageType.TriggerRegistrationResult,\n type: trigger_type,\n function_id,\n })\n } catch (error) {\n this.sendMessage(MessageType.TriggerRegistrationResult, {\n id,\n message_type: MessageType.TriggerRegistrationResult,\n type: trigger_type,\n function_id,\n error: { code: 'trigger_registration_failed', message: (error as Error).message },\n })\n }\n } else {\n this.sendMessage(MessageType.TriggerRegistrationResult, {\n id,\n message_type: MessageType.TriggerRegistrationResult,\n type: trigger_type,\n function_id,\n error: { code: 'trigger_type_not_found', message: 'Trigger type not found' },\n })\n }\n }\n\n private async onUnregisterTrigger(message: {\n trigger_type?: string\n id: string\n function_id?: string\n config?: unknown\n }) {\n const trigger_type = message.trigger_type\n if (!trigger_type) return\n\n const triggerTypeData = this.triggerTypes.get(trigger_type)\n if (!triggerTypeData) return\n\n const { id, function_id = '', config } = message\n try {\n await triggerTypeData.handler.unregisterTrigger({ id, function_id, config })\n } catch (error) {\n console.error(`[iii] Error unregistering trigger ${id}`, error)\n }\n }\n\n private onMessage(event: MessageEvent): void {\n let msgType: MessageType\n let message: Record<string, unknown>\n\n try {\n const parsed = JSON.parse(typeof event.data === 'string' ? event.data : '') as Record<string, unknown>\n msgType = parsed.type as MessageType\n const { type: _, ...rest } = parsed\n message = rest\n } catch (error) {\n console.error('[iii] Failed to parse incoming message', error)\n return\n }\n\n if (msgType === MessageType.InvocationResult) {\n const { invocation_id, result, error } = message as InvocationResultMessage\n this.onInvocationResult(invocation_id, result, error)\n } else if (msgType === MessageType.InvokeFunction) {\n const { invocation_id, function_id, data, traceparent, baggage } = message as InvokeFunctionMessage\n this.onInvokeFunction(invocation_id, function_id, data, traceparent, baggage)\n } else if (msgType === MessageType.RegisterTrigger) {\n this.onRegisterTrigger(message as { trigger_type: string; id: string; function_id: string; config: unknown })\n } else if (msgType === MessageType.UnregisterTrigger) {\n this.onUnregisterTrigger(\n message as { trigger_type?: string; id: string; function_id?: string; config?: unknown },\n )\n } else if (msgType === MessageType.RegistrationRejected) {\n this.onRegistrationRejected(\n message as { code: string; namespace: string; worker_name?: string; function_id?: string; owner_worker_id: string },\n )\n } else if (msgType === MessageType.WorkerRegistered) {\n const { worker_id, reattach_token } = message as { worker_id: string; reattach_token?: string }\n this.workerId = worker_id\n this.reattachToken = reattach_token\n }\n }\n\n /**\n * The engine rejected a registration. A `FUNCTION_NAMESPACE_CONFLICT` costs\n * one function and leaves the connection open, so log and keep serving. A\n * `WORKER_NAMESPACE_CONFLICT` means another live worker owns this name in the\n * namespace: it is terminal — stop and do not reconnect (otherwise the engine\n * would only reject the same name again, which with `maxRetries: -1` loops\n * forever).\n */\n private onRegistrationRejected(init: {\n code: string\n namespace: string\n worker_name?: string\n function_id?: string\n owner_worker_id: string\n }): void {\n if (init.code === 'FUNCTION_NAMESPACE_CONFLICT') {\n console.warn(\n `[iii] Function registration rejected: function \"${init.function_id ?? '<unknown>'}\" in namespace \"${init.namespace}\" is already exported by worker ${init.owner_worker_id}. Staying connected and serving the rest.`,\n )\n return\n }\n\n console.error(\n `[iii] Registration rejected (${init.code}): worker \"${init.worker_name}\" in namespace \"${init.namespace}\" is already owned by ${init.owner_worker_id}. Not reconnecting.`,\n )\n // Terminal: suppress reconnect so neither onSocketClose nor scheduleReconnect\n // revives a connection the engine would only reject again.\n this.isShuttingDown = true\n this.clearReconnectTimeout()\n\n // Reject every in-flight invocation now rather than leaving them to time out.\n const error = new RegistrationRejectedError(init)\n this.fatalError = error\n for (const [, invocation] of this.invocations) {\n if (invocation.timeout) {\n clearTimeout(invocation.timeout)\n }\n invocation.reject(error)\n }\n this.invocations.clear()\n\n // Drop the socket. onSocketClose sees `isShuttingDown` and leaves the\n // terminal `failed` state in place instead of overwriting it.\n this.setConnectionState('failed')\n this.ws?.close()\n }\n}\n\n/**\n * Factory object that constructs routing actions for {@link ISdk.trigger}.\n *\n * @example\n * ```typescript\n * import { TriggerAction } from 'iii-browser-sdk'\n *\n * // Enqueue to a named queue\n * worker.trigger({\n * function_id: 'process',\n * payload: { data: 'hello' },\n * action: TriggerAction.Enqueue({ queue: 'jobs' }),\n * })\n *\n * // Fire-and-forget\n * worker.trigger({\n * function_id: 'notify',\n * payload: {},\n * action: TriggerAction.Void(),\n * })\n * ```\n */\nexport const TriggerAction = {\n /**\n * Routes the invocation through a named queue. The engine enqueues the job,\n * acknowledges the caller with `{ messageReceiptId }`, and processes it\n * asynchronously.\n *\n * @param opts - Queue routing options.\n * @param opts.queue - Name of the target queue.\n */\n Enqueue: (opts: { queue: string }) => ({ type: 'enqueue' as const, ...opts }),\n /**\n * Fire-and-forget routing. The engine forwards the invocation without\n * waiting for a response or queuing the job.\n */\n Void: () => ({ type: 'void' as const }),\n} as const\n\n/**\n * Register the worker with a iii instance, returns a connected worker client.\n * The WebSocket connection is established automatically.\n *\n * @param address - WebSocket URL of the III engine (e.g. `ws://localhost:49135`).\n * @param options - Optional {@link InitOptions} for worker name, timeouts, and reconnection.\n * @returns A connected {@link ISdk} instance.\n *\n * @example\n * ```typescript\n * import { registerWorker } from 'iii-browser-sdk'\n *\n * const worker = registerWorker('ws://localhost:49135')\n * ```\n */\nexport const registerWorker = (address: string, options?: InitOptions): ISdk => new Sdk(address, options)\n"],"mappings":";;;;;;;;AAaA,IAAa,4BAAb,cAA+C,MAAM;CAOnD,YAAY,MAAgC;AAC1C,QACE,GAAG,KAAK,KAAK,8BAA8B,KAAK,gBAAgB,SAAY,aAAa,KAAK,YAAY,KAAK,WAAW,KAAK,eAAe,YAAY,GAAG,iB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;;;;;;;;;;;;;;;;AA0BpB,MAAa,gBAAgB;;;;;;;;;CAS3B,UAAU,UAA6B;EAAE,MAAM;EAAoB,GAAG;EAAM;;;;;CAK5E,aAAa,EAAE,MAAM,QAAiB;CACvC;;;;;;;;;;;;;;;;AAiBD,MAAa,kBAAkB,SAAiB,YAAgC,IAAI,IAAI,SAAS,QAAQ"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/errors.ts","../src/iii-constants.ts","../../iii/src/filter/errors.ts","../../iii/src/filter/json.ts","../../iii/src/filter/value.ts","../../iii/src/filter/path.ts","../../iii/src/filter/compile.ts","../../iii/src/filter/index.ts","../src/iii-types.ts","../src/invocation-context.ts","../src/observe-wire.ts","../src/observable.ts","../src/observer-handle.ts","../src/reporter.ts","../src/iii.ts"],"sourcesContent":["export type RegistrationRejectedInit = {\n code: string\n namespace: string\n worker_name?: string\n function_id?: string\n owner_worker_id: string\n}\n\n/**\n * A terminal registration rejection from the engine. Thrown into every pending\n * invocation and exposed via `getFatalError()` when a worker-name collision\n * (or other non-retryable rejection) closes the connection for good.\n */\nexport class RegistrationRejectedError extends Error {\n public readonly code: string\n public readonly namespace: string\n public readonly worker_name?: string\n public readonly function_id?: string\n public readonly owner_worker_id: string\n\n constructor(init: RegistrationRejectedInit) {\n super(\n `${init.code}: registration rejected for ${init.function_id !== undefined ? `function \"${init.function_id}\"` : `worker \"${init.worker_name ?? '<unknown>'}\"`} in namespace \"${init.namespace}\" (already owned by worker ${init.owner_worker_id})`,\n )\n this.name = 'RegistrationRejectedError'\n this.code = init.code\n this.namespace = init.namespace\n this.worker_name = init.worker_name\n this.function_id = init.function_id\n this.owner_worker_id = init.owner_worker_id\n }\n}\n\n/** Fields used to construct an {@link InvocationError}. */\nexport type InvocationErrorInit = {\n code: string\n message: string\n function_id?: string\n stacktrace?: string\n}\n\n/**\n * An error the SDK raises itself for an invocation, with a machine-readable\n * `code`: observe delivery errors (`NOT_OWNER_DELIVERED`,\n * `OBSERVER_NOT_ACTIVE`, `FILTERS_NOT_MATCHED`) and an invalid observe\n * descriptor (`INVALID_OBSERVE_DESCRIPTOR`). Mirrors the Node SDK.\n *\n * A call the engine answers with an error still rejects with the engine's\n * error body (`{ code, message, stacktrace? }`), as in earlier releases, and\n * so does a locally dispatched call whose handler throws: both paths reject\n * with the same value.\n */\nexport class InvocationError extends Error {\n public readonly code: string\n public readonly function_id?: string\n public readonly stacktrace?: string\n\n constructor(init: InvocationErrorInit) {\n super(`${init.code}: ${init.message}`)\n this.name = 'InvocationError'\n this.code = init.code\n this.function_id = init.function_id\n this.stacktrace = init.stacktrace\n }\n}\n\n/**\n * Thrown by an `onObserverAdded` hook to reject an observer with a code of\n * its own (`HTTP_ROUTE_CONFLICT`, `INVALID_CRON_EXPRESSION`, ...); any other\n * error rejects it with `OBSERVE_REJECTED`. Also the error `ObserverHandle.ready()`\n * rejects with when the observer turns `error` or `disposed`.\n *\n * @example\n * ```typescript\n * onObserverAdded(obs) {\n * if (!isValidCron(obs.args.expression)) {\n * throw new ObserveRejection('INVALID_CRON_EXPRESSION', 'invalid day-of-week field')\n * }\n * }\n * ```\n */\nexport class ObserveRejection extends Error {\n public readonly code: string\n\n constructor(code: string, message: string) {\n super(message)\n this.name = 'ObserveRejection'\n this.code = code\n }\n}\n","/**\n * Constants for the III module.\n */\n\n/**\n * Engine function paths for internal operations.\n *\n * Naming note: `LIST_TRIGGERS` / `INFO_TRIGGERS` cover trigger TYPES\n * (templates). `LIST_REGISTERED_TRIGGERS` / `INFO_REGISTERED_TRIGGERS`\n * cover trigger INSTANCES (subscriber rows). The old\n * `engine::trigger-types::list` builtin has been removed and is now\n * served by `engine::triggers::list`.\n */\nexport const EngineFunctions = {\n LIST_FUNCTIONS: 'engine::functions::list',\n INFO_FUNCTIONS: 'engine::functions::info',\n LIST_WORKERS: 'engine::workers::list',\n INFO_WORKERS: 'engine::workers::info',\n LIST_TRIGGERS: 'engine::triggers::list',\n INFO_TRIGGERS: 'engine::triggers::info',\n LIST_REGISTERED_TRIGGERS: 'engine::registered-triggers::list',\n INFO_REGISTERED_TRIGGERS: 'engine::registered-triggers::info',\n REGISTER_WORKER: 'engine::workers::register',\n} as const\n\n/** Engine trigger types */\nexport const EngineTriggers = {\n FUNCTIONS_AVAILABLE: 'engine::functions-available',\n} as const\n\n/** Connection state for the III WebSocket */\nexport type IIIConnectionState = 'disconnected' | 'connecting' | 'connected' | 'reconnecting' | 'failed'\n\n/** Configuration for WebSocket reconnection behavior */\nexport interface IIIReconnectionConfig {\n /** Starting delay in milliseconds (default: 1000ms) */\n initialDelayMs: number\n /** Maximum delay cap in milliseconds (default: 30000ms) */\n maxDelayMs: number\n /** Exponential backoff multiplier (default: 2) */\n backoffMultiplier: number\n /** Random jitter factor 0-1 (default: 0.3) */\n jitterFactor: number\n /** Maximum retry attempts, -1 for infinite (default: -1) */\n maxRetries: number\n}\n\n/** Default reconnection configuration */\nexport const DEFAULT_BRIDGE_RECONNECTION_CONFIG: IIIReconnectionConfig = {\n initialDelayMs: 1000,\n maxDelayMs: 30000,\n backoffMultiplier: 2,\n jitterFactor: 0.3,\n maxRetries: -1,\n}\n\n/** Default invocation timeout in milliseconds */\nexport const DEFAULT_INVOCATION_TIMEOUT_MS = 30000\n","/** Structural limits (filters.md §4, fixtures README \"Limits\"). */\nexport const MAX_DEPTH = 8\nexport const MAX_NODES = 64\nexport const MAX_SET_ITEMS = 256\nexport const MAX_PATH_SEGMENTS = 16\nexport const MAX_ENCODED_BYTES = 8192\n/** Arrays / objects nested in one `$eq` / `$ne` operand or one `$in` / `$nin` item. */\nexport const MAX_LITERAL_DEPTH = 32\n/**\n * Arrays / objects nested in the whole filter (a shared rule, with vectors).\n * The engine's JSON decoder reads 128 levels per message and a filter sits a\n * few levels into its `observe` message (about 124 left), so filters nesting\n * deeper than this cannot be delivered reliably.\n */\nexport const MAX_JSON_DEPTH = 120\n/** Numeric literals in a filter must satisfy `|n| <= 2^53`. */\nexport const MAX_SAFE_LITERAL = 2 ** 53\n\nexport type FilterErrorCode = 'INVALID_FILTER' | 'INVALID_FILTER_PATH'\n\n/** A filter the language rejects. `code` is the protocol error code (protocol.md §4). */\nexport class FilterError extends Error {\n readonly code: FilterErrorCode\n\n constructor(code: FilterErrorCode, message: string) {\n super(message)\n this.name = 'FilterError'\n this.code = code\n }\n\n static invalid(message: string): FilterError {\n return new FilterError('INVALID_FILTER', message)\n }\n}\n","/**\n * The filter as JSON. A filter written in JavaScript must already be JSON:\n * `JSON.stringify` would silently drop or rewrite what is not (an `undefined`\n * clause disappears, a `Map` or a class instance becomes `{}`, `NaN` becomes\n * `null`), and a dropped clause turns a filter into one that matches more.\n * So every value is checked first, and anything JSON would not carry as it is\n * is `INVALID_FILTER`, naming where it is.\n *\n * Pure TypeScript with no Node.js APIs: the browser SDK uses this file too.\n */\nimport { FilterError, MAX_ENCODED_BYTES, MAX_JSON_DEPTH, MAX_SAFE_LITERAL } from './errors'\n\n/** A value to check, or (`leave`) the end of an object / array, which then stops being an ancestor. */\ntype Pending = { value: unknown; at: string; depth: number; leave?: true }\n\nfunction where(at: string): string {\n return at === '' ? 'the filter' : `\\`${at}\\``\n}\n\n/** A string serde_json would refuse (a lone surrogate) is refused here too. */\nfunction checkString(s: string, at: string, what: string): void {\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i)\n if (c < 0xd800 || c > 0xdfff) continue\n const next = s.charCodeAt(i + 1)\n if (c <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) {\n i++\n continue\n }\n throw FilterError.invalid(`${where(at)}: ${what} holds a lone UTF-16 surrogate, which is not valid Unicode`)\n }\n}\n\n/** An object JSON writes member by member: a prototype-less object or one whose prototype is a realm's `Object.prototype`. */\nfunction isPlainObject(v: object): boolean {\n const proto = Object.getPrototypeOf(v)\n return proto === null || Object.getPrototypeOf(proto) === null\n}\n\nfunction describe(v: unknown): string {\n if (typeof v === 'number') return String(v)\n if (typeof v !== 'object' || v === null) return typeof v\n const name = (Object.getPrototypeOf(v) as { constructor?: { name?: unknown } } | null)?.constructor?.name\n return typeof name === 'string' && name !== '' ? `a ${name}` : 'an object'\n}\n\n/**\n * Checks that `src` is JSON as it stands: plain objects (own enumerable data\n * properties, string keys) and dense arrays of strings, finite numbers within\n * ±2^53, booleans and `null`, without cycles (a value shared by two members\n * is fine), nested at most MAX_JSON_DEPTH arrays / objects. Iterative, and\n * bounded by the encoded size limit (every JSON value takes at least one\n * byte, so a value shared many times over is refused quickly).\n */\nexport function checkJson(src: unknown): void {\n const stack: Pending[] = [{ value: src, at: '', depth: 1 }]\n const ancestors = new Set<object>()\n let visited = 0\n while (stack.length > 0) {\n const { value, at, depth, leave } = stack.pop() as Pending\n if (leave) {\n ancestors.delete(value as object)\n continue\n }\n if (++visited > MAX_ENCODED_BYTES) {\n throw FilterError.invalid(`the filter encodes to more than ${MAX_ENCODED_BYTES} bytes`)\n }\n switch (typeof value) {\n case 'boolean':\n continue\n case 'string':\n checkString(value, at, 'a string')\n continue\n case 'number':\n if (!Number.isFinite(value)) {\n throw FilterError.invalid(`${where(at)}: ${value} is not a JSON number`)\n }\n // |n| <= 2^53, so JavaScript and Rust read every literal alike.\n if (Math.abs(value) > MAX_SAFE_LITERAL) {\n throw FilterError.invalid(`${where(at)}: the number ${value} is outside ±2^53`)\n }\n continue\n case 'object': {\n if (value === null) continue\n if (ancestors.has(value)) {\n throw FilterError.invalid(`${where(at)}: a cycle (the value contains itself)`)\n }\n if (depth > MAX_JSON_DEPTH) {\n throw FilterError.invalid(`${where(at)}: the filter nests deeper than ${MAX_JSON_DEPTH} arrays / objects`)\n }\n ancestors.add(value)\n stack.push({ value, at, depth, leave: true })\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n if (!(i in value)) throw FilterError.invalid(`${where(at)}: the array has a hole at ${i}`)\n stack.push({ value: value[i], at: `${at}[${i}]`, depth: depth + 1 })\n }\n continue\n }\n if (!isPlainObject(value)) {\n throw FilterError.invalid(`${where(at)}: ${describe(value)} is not a JSON object (use a plain object)`)\n }\n if (Object.getOwnPropertySymbols(value).length > 0) {\n throw FilterError.invalid(`${where(at)}: symbol keys are not JSON`)\n }\n for (const key of Object.getOwnPropertyNames(value)) {\n const member = at === '' ? key : `${at}.${key}`\n const descriptor = Object.getOwnPropertyDescriptor(value, key)\n if (!descriptor?.enumerable) {\n throw FilterError.invalid(`${where(member)}: a non-enumerable property is not JSON`)\n }\n if (!('value' in descriptor)) {\n throw FilterError.invalid(`${where(member)}: an accessor property is not JSON`)\n }\n checkString(key, member, 'the key')\n stack.push({ value: descriptor.value, at: member, depth: depth + 1 })\n }\n continue\n }\n default:\n // undefined, functions, symbols, BigInt\n throw FilterError.invalid(`${where(at)}: ${describe(value)} is not JSON`)\n }\n }\n}\n\n/** Freezes a parsed JSON value (iteratively): the closures compiled from it share its operands. */\nexport function deepFreeze<T>(value: T): T {\n const stack: unknown[] = [value]\n while (stack.length > 0) {\n const v = stack.pop()\n if (v === null || typeof v !== 'object' || Object.isFrozen(v)) continue\n Object.freeze(v)\n for (const member of Object.values(v as Record<string, unknown>)) stack.push(member)\n }\n return value\n}\n","/**\n * Host values seen through JSON (filters.md §3): the evaluator answers as if\n * the document were `JSON.parse(JSON.stringify(doc))`, without serializing it.\n * Every value is mapped lazily, one step at a time, when a path reaches it.\n *\n * Pure TypeScript with no Node.js APIs: the browser SDK uses this file too.\n */\n\n/** A value as JSON sees it: `undefined` is absent, everything else is JSON-shaped. */\nexport type JsonView = null | boolean | number | string | readonly unknown[] | Record<string, unknown> | undefined\n\nconst hasEnumerable = Object.prototype.propertyIsEnumerable\nconst toStringTag = Object.prototype.toString\n\n/** A `BigInt` read through its JSON encoding (its decimal digits) as a double; beyond the double range, `null`. */\nfunction bigintView(b: bigint): number | null {\n const n = Number(b)\n return Number.isFinite(n) ? n : null\n}\n\n/**\n * Unwraps a boxed primitive (`new Number(1)`), also one from another realm,\n * by its internal slot rather than `instanceof`. Anything else is an object.\n */\nfunction unbox(v: object): JsonView {\n try {\n switch (toStringTag.call(v)) {\n case '[object Number]': {\n const n = Number.prototype.valueOf.call(v)\n return Number.isFinite(n) ? n : null\n }\n case '[object String]':\n return String.prototype.valueOf.call(v)\n case '[object Boolean]':\n return Boolean.prototype.valueOf.call(v)\n case '[object BigInt]':\n return bigintView(BigInt.prototype.valueOf.call(v))\n }\n } catch {\n // a spoofed Symbol.toStringTag: an ordinary object\n }\n return v as Record<string, unknown>\n}\n\n/**\n * One step of `JSON.stringify` (SerializeJSONProperty): `toJSON`, boxed\n * primitives, non-finite numbers, and the values JSON drops. `BigInt` is read\n * through its JSON encoding (its decimal digits), as a double, unless the\n * program installed `BigInt.prototype.toJSON`. Objects and arrays are\n * returned as they are; their members are mapped when a path steps into them.\n *\n * Host code runs here (`toJSON`, getters, Proxy traps) and may throw: the\n * caller of the whole evaluation turns that into a non-match.\n */\nexport function jsonView(value: unknown, key: string): JsonView {\n let v = value\n if (v !== null && (typeof v === 'object' || typeof v === 'function' || typeof v === 'bigint')) {\n const toJSON = (v as { toJSON?: unknown }).toJSON\n if (typeof toJSON === 'function') v = toJSON.call(v, key)\n }\n switch (typeof v) {\n case 'string':\n case 'boolean':\n return v\n case 'number':\n return Number.isFinite(v) ? v : null\n case 'bigint':\n return bigintView(v)\n case 'object': {\n if (v === null) return null\n if (Array.isArray(v)) return v\n const proto = Object.getPrototypeOf(v)\n if (proto === Object.prototype || proto === null) return v as Record<string, unknown>\n return unbox(v)\n }\n default:\n // undefined, functions and symbols: JSON leaves them out\n return undefined\n }\n}\n\n/** Element `index` of an array, as JSON writes it: a member JSON drops is `null`. */\nexport function arrayElement(array: readonly unknown[], index: number): JsonView {\n const v = jsonView(array[index], String(index))\n return v === undefined ? null : v\n}\n\n/** Own enumerable key `key` of an object; inherited properties do not exist. */\nexport function objectMember(object: Record<string, unknown>, key: string): JsonView {\n if (!hasEnumerable.call(object, key)) return undefined\n return jsonView(object[key], key)\n}\n\nexport function isArray(v: JsonView): v is readonly unknown[] {\n return Array.isArray(v)\n}\n\nexport function isObject(v: JsonView): v is Record<string, unknown> {\n return v !== null && typeof v === 'object' && !Array.isArray(v)\n}\n\n/**\n * JSON deep equality between a mapped host value and a filter literal (plain\n * JSON). Numbers compare as doubles (`1 == 1.0`, `-0 == 0`), object key order\n * is ignored, array order is not, and there is no coercion between types.\n * Iterative, so a deeply nested literal cannot overflow the stack.\n */\nexport function jsonEquals(host: JsonView, literal: unknown): boolean {\n if (literal === null || typeof literal !== 'object') return scalarEquals(host, literal)\n const stack: [JsonView, unknown][] = [[host, literal]]\n while (stack.length > 0) {\n const [h, l] = stack.pop() as [JsonView, unknown]\n if (l === null || typeof l !== 'object') {\n if (!scalarEquals(h, l)) return false\n continue\n }\n if (Array.isArray(l)) {\n if (!Array.isArray(h) || h.length !== l.length) return false\n for (let i = 0; i < l.length; i++) stack.push([arrayElement(h, i), l[i]])\n continue\n }\n if (!isObject(h)) return false\n const lit = l as Record<string, unknown>\n const keys = Object.keys(lit)\n for (const k of keys) {\n const member = objectMember(h, k)\n if (member === undefined) return false\n stack.push([member, lit[k]])\n }\n // the host must not hold more members than the literal\n let present = 0\n for (const k of Object.keys(h)) {\n if (jsonView(h[k], k) !== undefined) {\n present++\n if (present > keys.length) return false\n }\n }\n if (present !== keys.length) return false\n }\n return true\n}\n\nfunction scalarEquals(host: JsonView, literal: unknown): boolean {\n if (literal === null) return host === null\n switch (typeof literal) {\n case 'number':\n case 'string':\n case 'boolean':\n return host === literal\n default:\n return false\n }\n}\n\n/**\n * Compares two strings by Unicode code point (UTF-8 byte order), not by\n * UTF-16 code unit as `<` does: a surrogate pair (a code point above U+FFFF)\n * sorts after every BMP character, including U+E000..U+FFFF.\n */\nexport function compareCodePoints(a: string, b: string): number {\n if (a === b) return 0\n const n = a.length < b.length ? a.length : b.length\n for (let i = 0; i < n; i++) {\n let ca = a.charCodeAt(i)\n let cb = b.charCodeAt(i)\n if (ca !== cb) {\n if (ca >= 0xd800 && cb >= 0xd800) {\n // fix up the only range where code unit and code point order differ\n ca = ca >= 0xe000 ? ca - 0x800 : ca + 0x2000\n cb = cb >= 0xe000 ? cb - 0x800 : cb + 0x2000\n }\n return ca < cb ? -1 : 1\n }\n }\n return a.length < b.length ? -1 : a.length > b.length ? 1 : 0\n}\n\n/** `$prefix`: code point by code point, so a prefix never ends inside a surrogate pair. */\nexport function hasCodePointPrefix(s: string, prefix: string): boolean {\n if (!s.startsWith(prefix)) return false\n if (prefix.length === 0 || prefix.length === s.length) return true\n const last = prefix.charCodeAt(prefix.length - 1)\n if (last < 0xd800 || last > 0xdbff) return true\n const next = s.charCodeAt(prefix.length)\n return next < 0xdc00 || next > 0xdfff\n}\n\n/** UTF-8 byte length of a string, without `Buffer` or `TextEncoder`. */\nexport function utf8Length(s: string): number {\n let bytes = 0\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i)\n if (c < 0x80) bytes += 1\n else if (c < 0x800) bytes += 2\n else if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) {\n const d = s.charCodeAt(i + 1)\n if (d >= 0xdc00 && d <= 0xdfff) {\n bytes += 4\n i++\n } else {\n bytes += 3\n }\n } else bytes += 3\n }\n return bytes\n}\n","import { FilterError, MAX_PATH_SEGMENTS } from './errors'\nimport { arrayElement, type JsonView, objectMember } from './value'\n\n/** A path's first segment. `@` is the current `$any` element. */\nexport type Root = 'input' | 'output' | 'error' | 'caller' | 'metadata' | '@'\n\nconst ROOTS: ReadonlySet<string> = new Set(['input', 'output', 'error', 'caller', 'metadata', '@'])\n\n/**\n * One segment after the root. `index` is set when the segment is a canonical\n * decimal (`0` or `[1-9][0-9]*`): it selects an array element, while `key`\n * looks up an object member.\n */\nexport type Segment = { key: string; index: number | undefined }\n\nexport type Path = { root: Root; segments: Segment[] }\n\nconst CANONICAL_INDEX = /^(?:0|[1-9][0-9]*)$/\n\nfunction canonicalIndex(segment: string): number | undefined {\n // Longer than any array can be: never selects an element.\n if (segment.length > 15 || !CANONICAL_INDEX.test(segment)) return undefined\n return Number(segment)\n}\n\nfunction emptySegment(raw: string): FilterError {\n return FilterError.invalid(raw === '' ? 'empty path' : `path \\`${raw}\\`: empty segment`)\n}\n\n/**\n * Parses `root (\".\" segment)*`. `\\.` and `\\\\` escape inside keys; any other\n * backslash sequence, an empty segment or an unknown root is\n * `INVALID_FILTER`. `@` is a root only inside `$any`, where it is the only\n * root allowed.\n */\nexport function parsePath(raw: string, inAny: boolean): Path {\n const parts: string[] = []\n let current = ''\n for (let i = 0; i < raw.length; i++) {\n const c = raw[i]\n if (c === '\\\\') {\n const next = raw[i + 1]\n if (next === '.' || next === '\\\\') {\n current += next\n i++\n } else if (next === undefined) {\n throw FilterError.invalid(`path \\`${raw}\\`: dangling \\`\\\\\\` at the end`)\n } else {\n throw FilterError.invalid(\n `path \\`${raw}\\`: invalid escape \\`\\\\${next}\\` (only \\`\\\\.\\` and \\`\\\\\\\\\\` are allowed)`,\n )\n }\n } else if (c === '.') {\n if (current === '') throw emptySegment(raw)\n parts.push(current)\n current = ''\n } else {\n current += c\n }\n }\n if (current === '') throw emptySegment(raw)\n parts.push(current)\n\n const first = parts[0]\n if (!ROOTS.has(first)) {\n throw FilterError.invalid(\n inAny\n ? `path \\`${raw}\\`: inside \\`$any\\` paths start at \\`@\\`, the current element`\n : `path \\`${raw}\\`: unknown root \\`${first}\\` (expected input, output, error, caller or metadata)`,\n )\n }\n if (first === '@' && !inAny) {\n throw FilterError.invalid(`path \\`${raw}\\`: \\`@\\` paths are only allowed inside \\`$any\\``)\n }\n if (first !== '@' && inAny) {\n throw FilterError.invalid(`path \\`${raw}\\`: inside \\`$any\\` paths start at \\`@\\`, the current element`)\n }\n const segments = parts.slice(1).map((key) => ({ key, index: canonicalIndex(key) }))\n if (segments.length > MAX_PATH_SEGMENTS) {\n throw FilterError.invalid(\n `path \\`${raw}\\`: ${segments.length} segments after the root (limit ${MAX_PATH_SEGMENTS})`,\n )\n }\n return { root: first as Root, segments }\n}\n\n/** The document a filter reads. Roots that are `undefined` are absent. */\nexport type FilterDoc = {\n input?: unknown\n output?: unknown\n error?: unknown\n caller?: unknown\n metadata?: unknown\n}\n\n/** Compiles the path into a resolver; `undefined` means absent. */\nexport function compilePath(path: Path): (doc: FilterDoc, element: JsonView) => JsonView {\n const { root, segments } = path\n const step = (start: JsonView): JsonView => {\n let current = start\n for (let i = 0; i < segments.length; i++) {\n if (current === undefined || current === null || typeof current !== 'object') return undefined\n const segment = segments[i]\n if (Array.isArray(current)) {\n const index = segment.index\n if (index === undefined || index >= current.length) return undefined\n current = arrayElement(current, index)\n } else {\n current = objectMember(current as Record<string, unknown>, segment.key)\n }\n }\n return current\n }\n if (root === '@') return (_doc, element) => step(element)\n // A root is an own enumerable member of the document, like any other key.\n return (doc) => step(objectMember(doc as Record<string, unknown>, root))\n}\n","/**\n * Validation (filters.md §2, §4) and compilation into closures, in one pass.\n *\n * Mirrors `crates/iii-filter` (`parse.rs`, `eval.rs`): the same limits, the\n * same error code (`INVALID_FILTER`) and the same semantics, so a filter\n * evaluated here, in the engine or in another SDK answers the same. The\n * filter must already be JSON (`checkJson`); it is then copied through\n * `JSON.stringify` (also what the encoded size limit is measured on), so\n * what is validated is exactly what travels on the wire.\n *\n * Limits, as the vectors define them:\n * - depth: the top-level filter is at depth 1; the filters of a `$or`, the\n * operand of `$not` and the operand of `$any` are one level deeper than the\n * object holding them; the filters of a `$and` stay at the same level;\n * - nodes: every operator (`$eq` ... `$any`) and every `$or` / `$not` counts\n * one; paths and `$and` are free;\n * - encoded size: the compact JSON of the filter as given, in UTF-8 bytes.\n *\n * Pure TypeScript with no Node.js APIs: the browser SDK uses this file too.\n */\nimport { FilterError, MAX_DEPTH, MAX_ENCODED_BYTES, MAX_LITERAL_DEPTH, MAX_NODES, MAX_SET_ITEMS } from './errors'\nimport { checkJson, deepFreeze } from './json'\nimport { compilePath, type FilterDoc, parsePath, type Root } from './path'\nimport { arrayElement, compareCodePoints, hasCodePointPrefix, type JsonView, jsonEquals, utf8Length } from './value'\n\n/** A compiled filter node: `element` is the current `$any` element (`@`). */\ntype Pred = (doc: FilterDoc, element: JsonView) => boolean\n/** A value operator: `value` is `undefined` when the path is absent. */\ntype OpFn = (value: JsonView, doc: FilterDoc) => boolean\n\ntype JsonObject = Record<string, unknown>\n\nconst VALUE_OPERATORS: ReadonlySet<string> = new Set([\n '$eq',\n '$ne',\n '$in',\n '$nin',\n '$gt',\n '$gte',\n '$lt',\n '$lte',\n '$exists',\n '$prefix',\n '$any',\n])\n\nclass Budget {\n private used = 0\n\n take(): void {\n this.used++\n if (this.used > MAX_NODES) {\n throw FilterError.invalid(`more than ${MAX_NODES} operator / clause nodes`)\n }\n }\n}\n\nfunction isJsonObject(v: unknown): v is JsonObject {\n return v !== null && typeof v === 'object' && !Array.isArray(v)\n}\n\nfunction kind(v: unknown): string {\n if (v === null) return 'null'\n if (Array.isArray(v)) return 'an array'\n switch (typeof v) {\n case 'boolean':\n return 'a boolean'\n case 'number':\n return 'a number'\n case 'string':\n return 'a string'\n default:\n return 'an object'\n }\n}\n\n/**\n * Validates `src` and compiles it. Throws {@link FilterError} with code\n * `INVALID_FILTER` when the filter is not valid.\n *\n * `trusted` skips the encoded size limit, for filters the engine already\n * validated (the normal form it pushes to owners): normalizing can make a\n * filter a little longer than the one written, and JavaScript spells some\n * numbers longer than serde_json, so near the limit the two measurements can\n * disagree, and the engine's is the one that counts.\n */\nexport function compile(\n src: unknown,\n trusted = false,\n): { pred: Pred; roots: Set<Root>; json: JsonObject; matchAll: boolean } {\n let text: string\n try {\n if (src === null || typeof src !== 'object' || Array.isArray(src)) {\n throw FilterError.invalid(`a filter must be a JSON object, found ${src === undefined ? 'nothing' : kind(src)}`)\n }\n checkJson(src)\n text = JSON.stringify(src)\n } catch (error) {\n if (error instanceof FilterError) throw error\n // a Proxy trap or a revoked proxy\n throw FilterError.invalid(`the filter cannot be read: ${error instanceof Error ? error.message : String(error)}`)\n }\n if (!trusted && utf8Length(text) > MAX_ENCODED_BYTES) {\n throw FilterError.invalid(`the filter encodes to more than ${MAX_ENCODED_BYTES} bytes`)\n }\n // Frozen: the compiled closures hold its operands, and `source` hands it out.\n const json = deepFreeze(JSON.parse(text) as JsonObject)\n const roots = new Set<Root>()\n const clauses: Pred[] = []\n collectClauses(json, 1, false, new Budget(), roots, clauses)\n return { pred: and(clauses), roots, json, matchAll: clauses.length === 0 }\n}\n\nfunction parseFilter(src: unknown, depth: number, inAny: boolean, budget: Budget, roots: Set<Root>): Pred {\n const clauses: Pred[] = []\n collectClauses(src, depth, inAny, budget, roots, clauses)\n return and(clauses)\n}\n\nfunction and(clauses: Pred[]): Pred {\n switch (clauses.length) {\n case 0:\n return () => true\n case 1:\n return clauses[0]\n case 2: {\n const [a, b] = clauses\n return (doc, el) => a(doc, el) && b(doc, el)\n }\n default:\n return (doc, el) => {\n for (let i = 0; i < clauses.length; i++) {\n if (!clauses[i](doc, el)) return false\n }\n return true\n }\n }\n}\n\n/**\n * Collects the clauses of `src` and of every filter its `$and`s hold. `$and`\n * adds no depth, so it is walked with an explicit stack.\n */\nfunction collectClauses(\n src: unknown,\n depth: number,\n inAny: boolean,\n budget: Budget,\n roots: Set<Root>,\n out: Pred[],\n): void {\n if (depth > MAX_DEPTH) {\n throw FilterError.invalid(`filters nested deeper than ${MAX_DEPTH} levels`)\n }\n const pending: unknown[] = [src]\n while (pending.length > 0) {\n const current = pending.pop()\n if (!isJsonObject(current)) {\n throw FilterError.invalid(`a filter must be a JSON object, found ${kind(current)}`)\n }\n for (const key of Object.keys(current)) {\n const value = current[key]\n if (key === '$and') {\n const items = filterList('$and', value)\n for (let i = items.length - 1; i >= 0; i--) pending.push(items[i])\n } else if (key === '$or') {\n budget.take()\n const children = filterList('$or', value).map((item) => parseFilter(item, depth + 1, inAny, budget, roots))\n out.push((doc, el) => {\n for (let i = 0; i < children.length; i++) {\n if (children[i](doc, el)) return true\n }\n return false\n })\n } else if (key === '$not') {\n budget.take()\n if (!isJsonObject(value)) {\n throw FilterError.invalid(`\\`$not\\` takes a filter object, found ${kind(value)}`)\n }\n const child = parseFilter(value, depth + 1, inAny, budget, roots)\n out.push((doc, el) => !child(doc, el))\n } else if (VALUE_OPERATORS.has(key)) {\n throw FilterError.invalid(`\\`${key}\\` needs a path: write {\"<path>\": {\"${key}\": ...}}`)\n } else if (key.startsWith('$')) {\n throw FilterError.invalid(`unknown operator \\`${key}\\` (a filter holds paths, \\`$and\\`, \\`$or\\` and \\`$not\\`)`)\n } else {\n const path = parsePath(key, inAny)\n if (path.root !== '@') roots.add(path.root)\n const ops = parseOperatorObject(key, value, depth, budget)\n const resolve = compilePath(path)\n out.push(pathClause(resolve, ops))\n }\n }\n }\n}\n\nfunction pathClause(resolve: (doc: FilterDoc, element: JsonView) => JsonView, ops: OpFn[]): Pred {\n if (ops.length === 1) {\n const op = ops[0]\n return (doc, el) => op(resolve(doc, el), doc)\n }\n return (doc, el) => {\n const value = resolve(doc, el)\n for (let i = 0; i < ops.length; i++) {\n if (!ops[i](value, doc)) return false\n }\n return true\n }\n}\n\nfunction filterList(name: string, value: unknown): unknown[] {\n if (!Array.isArray(value)) {\n throw FilterError.invalid(`\\`${name}\\` takes an array of filters, found ${kind(value)}`)\n }\n if (value.length === 0) {\n throw FilterError.invalid(`\\`${name}\\` takes a non-empty array of filters`)\n }\n return value\n}\n\nfunction parseOperatorObject(path: string, value: unknown, depth: number, budget: Budget): OpFn[] {\n const shorthand = () =>\n FilterError.invalid(`\\`${path}\\`: expected an operator object such as {\"$eq\": ...}; literal values are not allowed`)\n if (!isJsonObject(value)) throw shorthand()\n const names = Object.keys(value)\n if (names.length === 0) throw FilterError.invalid(`\\`${path}\\`: empty operator object`)\n if (names.some((k) => !k.startsWith('$'))) throw shorthand()\n return parseOperators(path, value, depth, budget)\n}\n\n/** The operators of an operator object; `depth` is the level of the object holding them. */\nfunction parseOperators(path: string, map: JsonObject, depth: number, budget: Budget): OpFn[] {\n return Object.keys(map).map((name) => {\n budget.take()\n return parseOperator(path, name, map[name], depth, budget)\n })\n}\n\nfunction parseOperator(path: string, name: string, operand: unknown, depth: number, budget: Budget): OpFn {\n const wrong = (expected: string) =>\n FilterError.invalid(`\\`${path}\\`: \\`${name}\\` takes ${expected}, found ${kind(operand)}`)\n switch (name) {\n // Numbers anywhere in the filter were checked against ±2^53 by `checkJson`.\n case '$eq':\n checkLiteralDepth(path, name, operand)\n return (v) => v !== undefined && jsonEquals(v, operand)\n case '$ne':\n checkLiteralDepth(path, name, operand)\n return (v) => v === undefined || !jsonEquals(v, operand)\n case '$in':\n case '$nin': {\n if (!Array.isArray(operand)) throw wrong('an array')\n if (operand.length > MAX_SET_ITEMS) {\n throw FilterError.invalid(`\\`${path}\\`: \\`${name}\\` has ${operand.length} items (limit ${MAX_SET_ITEMS})`)\n }\n for (const item of operand) checkLiteralDepth(path, name, item)\n const items = operand\n const member = (v: JsonView) => {\n for (let i = 0; i < items.length; i++) {\n if (jsonEquals(v, items[i])) return true\n }\n return false\n }\n return name === '$in' ? (v) => v !== undefined && member(v) : (v) => v === undefined || !member(v)\n }\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte': {\n const accept: (c: number) => boolean =\n name === '$gt' ? (c) => c > 0 : name === '$gte' ? (c) => c >= 0 : name === '$lt' ? (c) => c < 0 : (c) => c <= 0\n if (typeof operand === 'number') {\n const bound = operand\n return (v) => typeof v === 'number' && accept(v < bound ? -1 : v > bound ? 1 : 0)\n }\n if (typeof operand === 'string') {\n const bound = operand\n return (v) => typeof v === 'string' && accept(compareCodePoints(v, bound))\n }\n throw wrong('a number or a string')\n }\n case '$exists': {\n if (typeof operand !== 'boolean') throw wrong('a boolean')\n const expected = operand\n return (v) => (v !== undefined) === expected\n }\n case '$prefix': {\n if (typeof operand !== 'string') throw wrong('a string')\n const prefix = operand\n return (v) => typeof v === 'string' && hasCodePointPrefix(v, prefix)\n }\n case '$any':\n return parseAny(path, operand, depth, budget)\n case '$and':\n case '$or':\n case '$not':\n throw FilterError.invalid(`\\`${path}\\`: \\`${name}\\` combines filters and is not a value operator`)\n default:\n throw FilterError.invalid(`\\`${path}\\`: unknown operator \\`${name}\\``)\n }\n}\n\n/**\n * `$any` takes an operator object (all keys are value operators) or a filter\n * over the element (`@` paths, `$and`, `$or`, `$not`). `{}` is the empty\n * filter: it matches any non-empty array.\n */\nfunction parseAny(path: string, operand: unknown, depth: number, budget: Budget): OpFn {\n if (!isJsonObject(operand)) {\n throw FilterError.invalid(\n `\\`${path}\\`: \\`$any\\` takes an operator object or a filter over \\`@\\`, found ${kind(operand)}`,\n )\n }\n if (depth + 1 > MAX_DEPTH) {\n throw FilterError.invalid(`filters nested deeper than ${MAX_DEPTH} levels`)\n }\n const names = Object.keys(operand)\n if (names.length > 0 && names.every((k) => VALUE_OPERATORS.has(k))) {\n const ops = parseOperators(path, operand, depth + 1, budget)\n return (v, doc) => {\n if (!Array.isArray(v)) return false\n for (let i = 0; i < v.length; i++) {\n const item = arrayElement(v, i)\n let all = true\n for (let j = 0; j < ops.length; j++) {\n if (!ops[j](item, doc)) {\n all = false\n break\n }\n }\n if (all) return true\n }\n return false\n }\n }\n // `@` paths add no root: the `$any` clause's own path names it.\n const node = parseFilter(operand, depth + 1, true, budget, new Set())\n return (v, doc) => {\n if (!Array.isArray(v)) return false\n for (let i = 0; i < v.length; i++) {\n if (node(doc, arrayElement(v, i))) return true\n }\n return false\n }\n}\n\n/**\n * A literal (an `$eq` / `$ne` operand, an `$in` / `$nin` item) nests at most\n * MAX_LITERAL_DEPTH arrays / objects: a scalar is 0, `[]` and `[1]` are 1.\n */\nfunction checkLiteralDepth(path: string, name: string, literal: unknown): void {\n const stack: [unknown, number][] = [[literal, 1]]\n while (stack.length > 0) {\n const [value, level] = stack.pop() as [unknown, number]\n if (value === null || typeof value !== 'object') continue\n if (level > MAX_LITERAL_DEPTH) {\n throw FilterError.invalid(\n `\\`${path}\\`: \\`${name}\\` nests a literal deeper than ${MAX_LITERAL_DEPTH} arrays / objects`,\n )\n }\n for (const member of Object.values(value as Record<string, unknown>)) stack.push([member, level + 1])\n }\n}\n","/**\n * The observer filter language (`iii-filter` v1, filters.md): validation and\n * evaluation for the SDKs, with the same semantics as the engine's Rust\n * evaluator (`crates/iii-filter`).\n *\n * Pure TypeScript with no Node.js APIs: the browser SDK uses these files too.\n */\nimport { compile } from './compile'\nimport type { FilterDoc, Root } from './path'\n\nexport { FilterError, type FilterErrorCode } from './errors'\nexport type { FilterDoc, Root } from './path'\n\n/** A filter object (filters.md §2): paths with explicit operators, `$and`, `$or`, `$not`. */\nexport type FilterSource = Record<string, unknown>\n\n/** A validated filter, compiled once into a closure tree. */\nexport interface CompiledFilter {\n /** The filter as JSON (what travels on the wire). */\n readonly source: FilterSource\n /** `{}`: every document matches. */\n readonly matchAll: boolean\n /** The roots any clause references (`input`, `output`, `error`, `caller`, `metadata`). */\n readonly roots: ReadonlySet<Exclude<Root, '@'>>\n /**\n * Evaluates the filter on a document. Total: it never throws. Host values\n * are read as JSON would write them (`undefined` is absent, a `Date` is its\n * ISO string, a `BigInt` its decimal value); a document whose reading throws\n * (a throwing getter or `toJSON`, a Proxy trap, a revoked proxy) does not\n * match.\n */\n matches(doc: FilterDoc): boolean\n}\n\nexport type CompileOptions = {\n /**\n * The filter was validated by the engine (the normal form it pushes to a\n * function's owner): skip the encoded size limit, which the engine already\n * applied and which JavaScript can measure slightly differently.\n */\n trusted?: boolean\n}\n\n/**\n * Validates and compiles a filter. Throws {@link FilterError}\n * (`INVALID_FILTER`) when it is not valid.\n *\n * @example\n * ```typescript\n * const f = compileFilter({ 'input.amount': { $gte: 500 } })\n * f.matches({ input: { amount: 750 } }) // true\n * ```\n */\nexport function compileFilter(src: unknown, options?: CompileOptions): CompiledFilter {\n const { pred, roots, json, matchAll } = compile(src, options?.trusted === true)\n return {\n source: json,\n matchAll,\n roots: roots as ReadonlySet<Exclude<Root, '@'>>,\n matches: (doc: FilterDoc) => {\n // The one place host exceptions end: every delivery mode answers the same.\n try {\n return pred(doc !== null && typeof doc === 'object' ? doc : {}, undefined)\n } catch {\n return false\n }\n },\n }\n}\n\n/** The filter that matches every document (`{}`). */\nexport const MATCH_ALL: CompiledFilter = compileFilter({})\n","export enum MessageType {\n RegisterFunction = 'registerfunction',\n UnregisterFunction = 'unregisterfunction',\n InvokeFunction = 'invokefunction',\n InvocationResult = 'invocationresult',\n RegisterTriggerType = 'registertriggertype',\n RegisterTrigger = 'registertrigger',\n UnregisterTrigger = 'unregistertrigger',\n UnregisterTriggerType = 'unregistertriggertype',\n TriggerRegistrationResult = 'triggerregistrationresult',\n RegistrationRejected = 'registrationrejected',\n WorkerRegistered = 'workerregistered',\n Reattach = 'reattach',\n /** Observing worker → engine: create (or idempotently replay) an observer. */\n Observe = 'observe',\n /** Observing worker → engine: dispose an observer this connection owns. */\n Unobserve = 'unobserve',\n /** Engine → observing worker: the reply to `observe` (also on replay). */\n ObserveResult = 'observeresult',\n /** Engine → observing worker: an observer's lifecycle transition. */\n ObserverStateChanged = 'observerstatechanged',\n /** Engine → owner: the `registerfunction` ack, with the function's full observer set. */\n FunctionRegistered = 'functionregistered',\n /** Engine → owner: one observer attached to a function this connection hosts. */\n ObserverAdded = 'observeradded',\n /** Engine → owner: one observer detached. */\n ObserverRemoved = 'observerremoved',\n /** Owner → engine: accept (or reject) an added observer. */\n ObserverAck = 'observerack',\n /** Owner → engine: matched local invocations and `obs.emit` events, batched. */\n InvocationsObserved = 'invocationsobserved',\n /** Owner → engine: periodic counts of local invocations and report drops. */\n LocalInvocationStats = 'localinvocationstats',\n}\n\n/**\n * Protocol features (`WorkerRegistered.features` from the engine,\n * `engine::workers::register` `features` from the SDK).\n */\nexport const FEATURE_OBSERVE_V1 = 'observe.v1'\nexport const FEATURE_LOCAL_DISPATCH_V1 = 'local-dispatch.v1'\n/**\n * What this SDK declares in `engine::workers::register`. Not\n * `large-messages.v1`, unlike the other SDKs: a browser receives one 16 MiB\n * WebSocket frame at most.\n */\nexport const SDK_FEATURES: readonly string[] = [FEATURE_OBSERVE_V1, FEATURE_LOCAL_DISPATCH_V1]\n\n/** The error body of an `InvocationResult` (and of observe errors and state reasons). */\nexport type ErrorBody = {\n code: string\n message: string\n stacktrace?: string\n}\n\n/**\n * A wire enum that a newer peer may extend: decoders keep a value they do not\n * know instead of failing the frame.\n */\nexport type OpenEnum<T extends string> = T | (string & {})\n\n/** What an observer ships to its target (`capture`). */\nexport type CaptureWire = OpenEnum<'input' | 'output' | 'error' | 'caller' | 'metadata'>\n/** When an auto observer fires (`on`). */\nexport type ObserveOnWire = OpenEnum<'success' | 'error' | 'complete'>\n/** What the target receives (`deliver`). */\nexport type ObserveDeliverWire = OpenEnum<'envelope' | 'input' | 'output'>\n/** Observer lifecycle state. */\nexport type ObserverStateWire = OpenEnum<'pending' | 'active' | 'suspended' | 'error' | 'disposed'>\n\n/**\n * Who started an invocation. Engine → worker: `worker_id` / `worker_name`\n * are stamped by the engine from the calling connection. Worker → engine:\n * the SDK sends `function_id`, `invocation_id` and `parent` (the caller of the\n * handler the call was made from, one level only).\n */\nexport type CallerWire = {\n worker_id?: string\n worker_name?: string\n function_id?: string\n invocation_id?: string\n parent?: Omit<CallerWire, 'parent'>\n}\n\n/** `InvokeFunction.activation`: present on every activation of an observer's target. */\nexport type ActivationWire = {\n observer_id: string\n activation_id?: string\n}\n\n/** `RegisterFunction.observe`: the part of the observe hooks that travels. Callbacks never do. */\nexport type ObserveDescriptorWire = {\n /** `auto` (default) or `owner`. */\n delivery?: OpenEnum<'auto' | 'owner'>\n /** Owner only: validates the observers' `args` in the engine (`INVALID_ARGS`). */\n args_format?: RegisterFunctionFormat\n /** Phase 5 shim: accept old `registertrigger { trigger_type }` for this type. */\n legacy_trigger_type?: string\n /** Default `true`; `false` makes every `observe` on it fail with `NOT_OBSERVABLE`. */\n allow?: boolean\n}\n\n/** `observe.source`: the left side of `iii.observe`. */\nexport type ObserveSourceWire = {\n function_id: string\n namespace?: string\n args?: Record<string, unknown>\n filters?: Record<string, unknown>\n capture?: CaptureWire[]\n on?: ObserveOnWire\n deliver?: ObserveDeliverWire\n}\n\nexport type ObserveMessage = {\n message_type: MessageType.Observe\n /** Client-generated UUID, stable across replays. */\n id: string\n source: ObserveSourceWire\n target: { function_id: string; namespace?: string }\n metadata?: Record<string, unknown>\n max_fires?: number\n expires_in_ms?: number\n max_in_flight?: number\n}\n\nexport type UnobserveMessage = {\n message_type: MessageType.Unobserve\n id: string\n}\n\nexport type ObserveResultMessage = {\n message_type: MessageType.ObserveResult\n id: string\n state: ObserverStateWire\n error?: ErrorBody\n warnings?: string[]\n}\n\nexport type ObserverStateChangedMessage = {\n message_type: MessageType.ObserverStateChanged\n id: string\n state: ObserverStateWire\n reason?: ErrorBody\n fires: number\n}\n\n/**\n * An observer as its function's owner sees it: never the observer's metadata,\n * policy or connection. `target` is the target function id.\n */\nexport type ObserverInfoWire = {\n id: string\n args: Record<string, unknown>\n /** The observer's filters, normalized by the engine. `{}` matches every event. */\n filters: Record<string, unknown>\n target: string\n capture: CaptureWire[]\n on: ObserveOnWire\n /** Phase 5 shim only: the old trigger config the owner reads as args. */\n legacy?: { trigger_type: string; config: unknown }\n}\n\nexport type FunctionRegisteredMessage = {\n message_type: MessageType.FunctionRegistered\n id: string\n namespace: string\n revision: number\n local_dispatch: boolean\n observers: ObserverInfoWire[]\n}\n\nexport type ObserverAddedMessage = {\n message_type: MessageType.ObserverAdded\n function_id: string\n namespace: string\n revision: number\n observer: ObserverInfoWire\n}\n\nexport type ObserverRemovedMessage = {\n message_type: MessageType.ObserverRemoved\n function_id: string\n namespace: string\n revision: number\n id: string\n}\n\nexport type ObserverAckMessage = {\n message_type: MessageType.ObserverAck\n function_id: string\n namespace?: string\n id: string\n revision: number\n /** Rejects the observer (also a late rejection of an active one). */\n error?: ErrorBody\n}\n\n/** One matched local invocation (auto) or one `obs.emit` event (owner). */\nexport type ObservedItemWire = {\n function_id: string\n namespace?: string\n invocation_id: string\n /** Observer ids whose filters matched (the same event coalesced for several). */\n matched: string[]\n status: OpenEnum<'success' | 'error'>\n /** `null` is a value here: absent means not captured or does not exist. */\n input?: unknown\n output?: unknown\n error?: unknown\n caller?: CallerWire\n metadata?: unknown\n started_at_ms: number\n duration_ms: number\n observe_depth?: number\n traceparent?: string\n baggage?: string\n}\n\nexport type InvocationsObservedMessage = {\n message_type: MessageType.InvocationsObserved\n items: ObservedItemWire[]\n}\n\nexport type LocalFunctionStatsWire = {\n function_id: string\n count: number\n errors?: number\n duration_ms_sum?: number\n}\n\nexport type DroppedReportStatsWire = {\n function_id: string\n /** `BUFFER_FULL` | `TOO_LARGE` (SDK-side drops). */\n reason: string\n count: number\n}\n\nexport type LocalInvocationStatsMessage = {\n message_type: MessageType.LocalInvocationStats\n window_ms: number\n functions: LocalFunctionStatsWire[]\n dropped_reports: DroppedReportStatsWire[]\n}\n\nexport type WorkerRegisteredMessage = {\n message_type: MessageType.WorkerRegistered\n worker_id: string\n /** Secret to present in a reattach frame on reconnect; absent on older engines. */\n reattach_token?: string\n /** Protocol features the engine supports (`observe.v1`, `local-dispatch.v1`); absent on engines older than 0.25. */\n features?: string[]\n}\n\n/** @deprecated Trigger types are replaced by functions with an observe descriptor (`RegisterFunctionMessage.observe`). */\nexport type RegisterTriggerTypeMessage = {\n message_type: MessageType.RegisterTriggerType\n /** Unique identifier for the trigger type (e.g. `state`, `durable:subscriber`). */\n id: string\n /** Human-readable description of what this trigger type does. */\n description: string\n}\n\n/** @deprecated Trigger types are replaced by functions with an observe descriptor. */\nexport type UnregisterTriggerTypeMessage = {\n message_type: MessageType.UnregisterTriggerType\n id: string\n namespace?: string\n}\n\nexport type UnregisterTriggerMessage = {\n message_type: MessageType.UnregisterTrigger\n id: string\n type?: string\n}\n\nexport type TriggerRegistrationResultMessage = {\n message_type: MessageType.TriggerRegistrationResult\n id: string\n type: string\n function_id: string\n result?: unknown\n error?: unknown\n}\n\n/**\n * The engine refused a registration. `FUNCTION_NAMESPACE_CONFLICT` costs one\n * function and leaves the connection open; `WORKER_NAMESPACE_CONFLICT` is\n * terminal — another live worker owns this name in the namespace.\n */\nexport type RegistrationRejectedMessage = {\n message_type: MessageType.RegistrationRejected\n /** Rejection code: `FUNCTION_NAMESPACE_CONFLICT` or `WORKER_NAMESPACE_CONFLICT`. */\n code: string\n /** Namespace the conflict occurred in. */\n namespace: string\n /** Contested worker name. Present only for `WORKER_NAMESPACE_CONFLICT`. */\n worker_name?: string\n /** Contested function id. Present only for `FUNCTION_NAMESPACE_CONFLICT`. */\n function_id?: string\n /** ID of the worker that already owns the name. */\n owner_worker_id: string\n}\n\n/** @deprecated Replaced by the `observe` message (`iii.observe`). */\nexport type RegisterTriggerMessage = {\n /** Wire discriminator; always `MessageType.RegisterTrigger`. */\n message_type: MessageType.RegisterTrigger\n /** Unique trigger identifier, generated by the SDK during registration. */\n id: string\n /** Identifier of the registered trigger type this trigger uses (e.g. `storage::object-created`, `http`). */\n type: string\n /** ID of the function this trigger invokes when it fires. */\n function_id: string\n /** Trigger-type-specific configuration, matching the shape the trigger type expects. */\n config: unknown\n /**\n * Namespace the trigger's target function resolves in.\n *\n * Omitting it does not bind in the engine's default: `registerTrigger` fills\n * it from this worker's namespace, because the function a trigger names is\n * one this worker registered, and that landed in the worker's namespace. Name\n * another namespace, `default` included, to bind elsewhere.\n */\n namespace?: string\n}\n\nexport type RegisterFunctionFormat = {\n /**\n * The name of the parameter\n */\n name?: string\n /**\n * The description of the parameter\n */\n description?: string\n /**\n * The type of the parameter\n */\n type?: 'string' | 'number' | 'boolean' | 'object' | 'array' | 'null' | 'map' | 'integer'\n /**\n * The body of the parameter (for objects)\n */\n properties?: Record<string, unknown>\n /**\n * The items of the parameter (for arrays)\n */\n items?: unknown\n /**\n * Whether the parameter is required\n */\n required?: string[]\n [key: string]: unknown\n}\n\nexport type RegisterFunctionMessage = {\n message_type: MessageType.RegisterFunction\n /**\n * The path of the function (use :: for namespacing, e.g. external::my_lambda)\n */\n id: string\n /**\n * The description of the function\n */\n description?: string\n /**\n * The request format of the function\n */\n request_format?: RegisterFunctionFormat\n /**\n * The response format of the function\n */\n response_format?: RegisterFunctionFormat\n metadata?: Record<string, unknown>\n /**\n * The observe descriptor: how observers of this function are delivered.\n * Only these four fields travel; the hooks stay in the SDK.\n */\n observe?: ObserveDescriptorWire\n}\n\n/**\n * Routing action for {@link TriggerRequest}. Determines how the engine\n * handles the invocation.\n *\n * - `enqueue`: Routes through a named queue for async processing.\n * - `void`: Fire-and-forget, no response.\n */\nexport type TriggerAction = { type: 'enqueue'; queue: string } | { type: 'void' }\n\n/**\n * Input passed to the RBAC auth function during WebSocket upgrade.\n * Contains the HTTP headers, query parameters, and client IP from the\n * connecting worker's upgrade request.\n */\nexport type AuthInput = {\n /** HTTP headers from the WebSocket upgrade request. */\n headers: Record<string, string>\n /** Query parameters from the upgrade URL. Each key maps to an array of values to support repeated keys. */\n query_params: Record<string, string[]>\n /** IP address of the connecting client. */\n ip_address: string\n}\n\n/**\n * Return value from the RBAC auth function. Controls which functions the\n * authenticated worker can invoke and what context is forwarded to the\n * middleware.\n */\nexport type AuthResult = {\n /**\n * Grants scoped to one namespace each: `{ orders: ['svc::*'] }`. A value is an\n * exact function ID or a wildcard, in either the bare (`svc::*`) or the\n * `match(\"svc::*\")` spelling.\n *\n * The keys are also the namespaces the session may declare on\n * `engine::workers::register`. Omit to scope nothing: the session declares any\n * namespace, and only `allowed_functions` and `expose_functions` apply.\n */\n namespaces?: Record<string, string[]>\n /** Additional function IDs to allow beyond the `expose_functions` config, in the `default` namespace only. Put per-namespace grants in `namespaces`. Defaults to `[]` if omitted. */\n allowed_functions?: string[]\n /** Function IDs to deny even if they match `expose_functions`. Takes precedence over allowed. Defaults to `[]` if omitted. */\n forbidden_functions?: string[]\n /** Trigger type IDs the worker may register triggers for. When omitted, all types are allowed. */\n allowed_trigger_types?: string[]\n /** Whether the worker may register new trigger types. Defaults to `false` if omitted. */\n allow_trigger_type_registration?: boolean\n /** Whether the worker may register new functions. Defaults to `true` if omitted. */\n allow_function_registration?: boolean\n /** Arbitrary context forwarded to the middleware function on every invocation. Defaults to `{}` if omitted. */\n context?: Record<string, unknown>\n /** Optional prefix applied to all function IDs registered by this worker. */\n function_registration_prefix?: string\n}\n\n/**\n * Input passed to the RBAC middleware function on every function invocation\n * through the RBAC port. The middleware can inspect, modify, or reject the\n * call before it reaches the target function.\n */\nexport type MiddlewareFunctionInput = {\n /** ID of the function being invoked. */\n function_id: string\n /** Payload sent by the caller. */\n payload: Record<string, unknown>\n /** Routing action, if any. */\n action?: TriggerAction\n /** Auth context returned by the auth function for this session. */\n context: Record<string, unknown>\n /**\n * Target namespace the invoke addressed; forward the call here to stay in the\n * caller's namespace. Absent → the engine's default namespace.\n */\n namespace?: string\n}\n\n/**\n * Input passed to the `on_trigger_type_registration_function_id` hook\n * when a worker attempts to register a new trigger type through the RBAC port.\n * Return an {@link OnTriggerTypeRegistrationResult} with the (possibly mapped)\n * fields, or throw to deny the registration.\n */\nexport type OnTriggerTypeRegistrationInput = {\n /** ID of the trigger type being registered. */\n trigger_type_id: string\n /** Human-readable description of the trigger type. */\n description: string\n /** Auth context from `AuthResult.context` for this session. */\n context: Record<string, unknown>\n}\n\n/**\n * Result returned from the `on_trigger_type_registration_function_id` hook.\n * All fields are optional; omitted fields keep the original value from the\n * registration request.\n */\nexport type OnTriggerTypeRegistrationResult = {\n /** Mapped trigger type ID. */\n trigger_type_id?: string\n /** Mapped description. */\n description?: string\n}\n\n/**\n * Input passed to the `on_trigger_registration_function_id` hook\n * when a worker attempts to register a trigger through the RBAC port.\n * Return an {@link OnTriggerRegistrationResult} with the (possibly mapped)\n * fields, or throw to deny the registration.\n */\nexport type OnTriggerRegistrationInput = {\n /** ID of the trigger being registered. */\n trigger_id: string\n /** Trigger type identifier. */\n trigger_type: string\n /** ID of the function this trigger is bound to. */\n function_id: string\n /** Trigger-specific configuration. */\n config: unknown\n /**\n * Namespace the trigger's target resolves in (explicit, or `default` when\n * absent). The same id can exist in several namespaces, so the hook needs this\n * to authorize per target namespace.\n */\n namespace?: string\n /** Auth context from `AuthResult.context` for this session. */\n context: Record<string, unknown>\n}\n\n/**\n * Result returned from the `on_trigger_registration_function_id` hook.\n * All fields are optional; omitted fields keep the original value from the\n * registration request.\n */\nexport type OnTriggerRegistrationResult = {\n /** Mapped trigger ID. */\n trigger_id?: string\n /** Mapped trigger type. */\n trigger_type?: string\n /** Mapped function ID. */\n function_id?: string\n /** Mapped trigger configuration. */\n config?: unknown\n}\n\n/**\n * Input passed to the `on_function_registration_function_id` hook\n * when a worker attempts to register a function through the RBAC port.\n * Return an {@link OnFunctionRegistrationResult} with the (possibly mapped)\n * fields, or throw to deny the registration.\n */\nexport type OnFunctionRegistrationInput = {\n /** ID of the function being registered. */\n function_id: string\n /** Human-readable description of the function. */\n description?: string\n /** Arbitrary metadata attached to the function. */\n metadata?: Record<string, unknown>\n /**\n * Namespace the function registers in. The same id can exist in several\n * namespaces, so the hook needs this to authorize per namespace.\n */\n namespace?: string\n /** Auth context from `AuthResult.context` for this session. */\n context: Record<string, unknown>\n}\n\n/**\n * Result returned from the `on_function_registration_function_id` hook.\n * All fields are optional; omitted fields keep the original value from the\n * registration request.\n */\nexport type OnFunctionRegistrationResult = {\n /** Mapped function ID. */\n function_id?: string\n /** Mapped description. */\n description?: string\n /** Mapped metadata. */\n metadata?: Record<string, unknown>\n}\n\n/**\n * Result returned when a function is invoked with `TriggerAction.Enqueue`.\n */\nexport type EnqueueResult = {\n /** Unique receipt ID for the enqueued message. */\n messageReceiptId: string\n}\n\n/**\n * Request object passed to {@link ISdk.trigger}.\n *\n * @typeParam TInput - Type of the payload.\n */\nexport type TriggerRequest<TInput = unknown> = {\n /** ID of the function to invoke. */\n function_id: string\n /** Input data passed to the function. */\n payload: TInput\n /** Sets how the trigger is routed. Omit for a synchronous request/response. Specify for a specific routing scheme (e.g. `TriggerAction.Enqueue()`, `TriggerAction.Void()`). */\n action?: TriggerAction\n /** Override the default invocation timeout, in milliseconds. */\n timeoutMs?: number\n /** Namespace to route this invocation to. Omit to inherit this worker's; say `default` to reach the engine's from a namespaced worker. */\n namespace?: string\n /**\n * Per-invocation metadata (any JSON). Travels beside the payload: the\n * handler receives it as its second argument, and observer filters read it\n * as `metadata.*`.\n */\n metadata?: unknown\n /**\n * W3C `traceparent` to continue. The browser SDK has no OpenTelemetry, so it\n * never makes one up: when omitted, a call made inside a handler forwards\n * the `traceparent` that handler was invoked with (see\n * {@link ISdk.currentInvocation}); a top-level call sends none and the engine\n * starts the trace.\n */\n traceparent?: string\n /** W3C `baggage` to send along with `traceparent`; defaults the same way. */\n baggage?: string\n /**\n * `auto` (default) runs a function this worker hosts in-process when the\n * engine confirmed it for local dispatch; `remote` always goes through the\n * engine. Tests use it, and so do callers that rely on engine-side effects.\n */\n dispatch?: 'auto' | 'remote'\n}\n\nexport type InvokeFunctionMessage = {\n message_type: MessageType.InvokeFunction\n /**\n * This is optional for async invocations\n */\n invocation_id?: string\n /**\n * The path of the function\n */\n function_id: string\n /**\n * The data to pass to the function\n */\n data: unknown\n /**\n * W3C trace-context traceparent header for distributed tracing\n */\n traceparent?: string\n /**\n * W3C baggage header for cross-cutting context propagation\n */\n baggage?: string\n /**\n * Trigger action for queue routing or fire-and-forget\n */\n action?: TriggerAction\n /**\n * Namespace to route this invocation to. The engine reads an absent field as\n * its default namespace; a call made through this SDK does not arrive absent,\n * because `trigger` fills it from this worker's namespace.\n */\n namespace?: string\n /** Per-invocation metadata (any JSON); absent means none. */\n metadata?: unknown\n /**\n * Who made the call. Sent by the SDK when the call is made inside a handler;\n * on inbound calls `worker_id` / `worker_name` are stamped by the engine.\n */\n caller?: CallerWire\n /** Depth of the causal chain in observe hops; omitted when 0. */\n observe_depth?: number\n /** Present on every activation of an observer's target; marks an owner delivery (`obs.call`) outbound. */\n activation?: ActivationWire\n}\n\nexport type InvocationResultMessage = {\n message_type: MessageType.InvocationResult\n /**\n * The id of the invocation\n */\n invocation_id: string\n /**\n * The path of the function\n */\n function_id: string\n result?: unknown\n error?: unknown\n /**\n * W3C trace-context traceparent header for distributed tracing\n */\n traceparent?: string\n /**\n * W3C baggage header for cross-cutting context propagation\n */\n baggage?: string\n}\n\nexport type UnregisterFunctionMessage = {\n message_type: MessageType.UnregisterFunction\n id: string\n}\n\n/**\n * Serializable reference to one end of a streaming channel. Can be included\n * in invocation payloads to pass channel endpoints between workers.\n */\nexport type StreamChannelRef = {\n /** Unique channel identifier. */\n channel_id: string\n /** Access key for authentication. */\n access_key: string\n /** Whether this ref is for reading or writing. */\n direction: 'read' | 'write'\n}\n\nexport type IIIMessage =\n | RegisterFunctionMessage\n | UnregisterFunctionMessage\n | InvokeFunctionMessage\n | InvocationResultMessage\n | RegisterTriggerMessage\n | RegisterTriggerTypeMessage\n | UnregisterTriggerMessage\n | UnregisterTriggerTypeMessage\n | TriggerRegistrationResultMessage\n | RegistrationRejectedMessage\n | WorkerRegisteredMessage\n | ObserveMessage\n | UnobserveMessage\n | ObserveResultMessage\n | ObserverStateChangedMessage\n | FunctionRegisteredMessage\n | ObserverAddedMessage\n | ObserverRemovedMessage\n | ObserverAckMessage\n | InvocationsObservedMessage\n | LocalInvocationStatsMessage\n","import type { ActivationWire, CallerWire } from './iii-types'\nimport type { InvocationContext } from './observe-types'\n\n/**\n * The invocation a handler runs in. Set around every handler, remote\n * (`InvokeFunction`) and local (in-process dispatch), and read by outgoing\n * calls (`caller`, `observe_depth`, `traceparent`) and by `obs.emit` /\n * `obs.call`.\n */\nexport type ActiveInvocation = {\n function_id: string\n invocation_id: string\n caller?: CallerWire\n activation?: ActivationWire\n observe_depth: number\n /** The invocation's metadata sidecar: what an emitted event's filters see as `metadata`. */\n metadata?: unknown\n /** The trace context the invocation arrived with: what calls and events made from it carry. */\n traceparent?: string\n baggage?: string\n /** How many local calls deep this invocation is (0 for one that came over the wire). */\n localDepth?: number\n}\n\n/**\n * A local call nested deeper than this goes to the engine instead, so\n * recursion cannot overflow the stack. (Nested local calls made before the\n * first `await` all run on one JavaScript stack; after an `await` the stack\n * starts over, and so does the scope.)\n */\nexport const MAX_LOCAL_DEPTH = 64\n\n/**\n * While the socket is closed, a local call past {@link MAX_LOCAL_DEPTH} cannot\n * go to the engine: it runs here up to this depth (above any realistic\n * fan-out counted as nested), and past it fails at once with\n * `LOCAL_DEPTH_EXCEEDED`, so a runaway recursion neither overflows the stack\n * nor runs forever.\n */\nexport const MAX_OFFLINE_LOCAL_DEPTH = 256\n\n/**\n * How long an invocation that came over the wire (and one re-entered with\n * `withInvocation`) counts as running at most, when it never settles. An\n * observer chain's hops may await far longer than this SDK's own call\n * timeout, and their depth must still reach the calls they make afterwards\n * (the engine's loop guard counts on it). A local call counts as running until\n * its caller's timeout instead.\n */\nexport const MAX_RUNNING_INVOCATION_MS = 10 * 60 * 1000\n\n/**\n * Browsers have no `AsyncLocalStorage` (and `AsyncContext` is not shipped\n * yet), so the context is a synchronous scope: {@link runInContext} sets it\n * while `fn` runs and restores the previous one when `fn` returns. An async\n * handler sees it up to its first `await`; the continuation after an `await`\n * runs from the event loop, outside any scope, so it never sees another\n * invocation's context, only none. `withInvocation` re-enters a captured one.\n *\n * One scope for the whole page, like the Node SDK's one `AsyncLocalStorage`\n * per process: a handler of one worker that calls another worker's\n * `trigger()` is that call's caller.\n */\nlet current: ActiveInvocation | undefined\n\n/** The public views handed out, so `withInvocation(view, fn)` restores everything (metadata included). */\nconst views = new WeakMap<object, ActiveInvocation>()\n\nexport function currentContext(): ActiveInvocation | undefined {\n return current\n}\n\n/**\n * Every invocation whose work is running on this page (handlers, remote and\n * local, and the async `fn` of `withInvocation`), until it settles: one lease\n * per piece of work, because an async `withInvocation` keeps an invocation\n * running alongside its handler. A lease is forgotten at its deadline, so work\n * that never settles does not lend its depth to every later call made on the\n * page; settling one lease never ends another (a late one, after its deadline\n * passed and the invocation was entered again, ends only itself).\n */\nconst running = new Map<ActiveInvocation, Set<{ deadline: number }>>()\n\n/**\n * Marks `ctx` as running for at most `maxAgeMs`; call the returned function\n * when the work settles.\n */\nexport function trackRunning(ctx: ActiveInvocation, maxAgeMs: number): () => void {\n const lease = { deadline: Date.now() + maxAgeMs }\n let leases = running.get(ctx)\n if (!leases) {\n leases = new Set()\n running.set(ctx, leases)\n }\n leases.add(lease)\n return () => {\n const current = running.get(ctx)\n if (!current?.delete(lease)) return\n if (current.size === 0) running.delete(ctx)\n }\n}\n\n/** The running invocations; leases past their deadline are forgotten here. */\nfunction live(): ActiveInvocation[] {\n const now = Date.now()\n const out: ActiveInvocation[] = []\n for (const [ctx, leases] of running) {\n for (const lease of leases) if (lease.deadline <= now) leases.delete(lease)\n if (leases.size === 0) running.delete(ctx)\n else out.push(ctx)\n }\n return out\n}\n\n/** What a fallback attribution lends: the invocation without its metadata sidecar (one object per invocation). */\nconst lent = new WeakMap<ActiveInvocation, ActiveInvocation>()\n\nfunction lend(ctx: ActiveInvocation): ActiveInvocation {\n let view = lent.get(ctx)\n if (!view) {\n const { metadata: _, ...rest } = ctx\n view = rest\n lent.set(ctx, view)\n }\n return view\n}\n\n/**\n * The invocation a call, an emit or a report made now belongs to. Inside a\n * scope, the scope's. Outside any scope (code after an `await`), the running\n * invocation when that is unambiguous: it is the only one running and it is\n * an observe activation. It lends its ids, caller and trace context, never its\n * metadata: filters on `metadata.*` see only what a real scope carries.\n * Otherwise none, and the call carries no `caller`: the SDK cannot tell which\n * handler, if any, made it.\n */\nexport function callContext(): ActiveInvocation | undefined {\n if (current) return current\n const all = live()\n return all.length === 1 && all[0].activation ? lend(all[0]) : undefined\n}\n\n/**\n * The `observe_depth` a call, an emit or a report made now carries. Inside a\n * scope, the scope's. Outside any scope, the deepest running invocation's:\n * the engine's loop guard counts on this depth, so code after an `await`\n * over-counts (a chain may stop earlier than `max_observe_depth`) rather than\n * restart the chain at 0 (an observer cycle would never stop).\n */\nexport function callDepth(): number {\n if (current) return current.observe_depth\n let depth = 0\n for (const ctx of live()) if (ctx.observe_depth > depth) depth = ctx.observe_depth\n return depth\n}\n\n/**\n * The local depth that calls started outside any scope in the current\n * synchronous run share (see {@link callLocalDepth}); cleared on a microtask.\n */\nlet unscopedLocalDepth: number | undefined\n\n/**\n * How many local calls deep a local call made now is nested (decision 20,\n * {@link MAX_LOCAL_DEPTH}). Inside a scope, the scope's. Outside any scope, the\n * deepest running local call's, so a self-recursion that awaits before each\n * call still reaches the engine at the limit. That value is taken once per\n * synchronous run: calls started together outside any scope (a fan-out, from\n * a loop or `Promise.all`) are siblings at one depth; only code after an\n * `await`, which runs later, sees them running and goes one level deeper.\n */\nexport function callLocalDepth(): number {\n if (current) return current.localDepth ?? 0\n if (unscopedLocalDepth === undefined) {\n let depth = 0\n for (const ctx of live()) if ((ctx.localDepth ?? 0) > depth) depth = ctx.localDepth ?? 0\n unscopedLocalDepth = depth\n queueMicrotask(() => {\n unscopedLocalDepth = undefined\n })\n }\n return unscopedLocalDepth\n}\n\n/**\n * `withInvocation`: runs `fn` inside `ctx`. When `fn` returns a promise, `ctx`\n * counts as running until it settles (at most `maxAgeMs`), so `fn`'s code after\n * its own `await`s falls back to it (see {@link callContext}, {@link callDepth}),\n * and the caller gets a promise that settles the same way: a rejection the\n * caller does not handle is still reported as unhandled.\n */\nexport function enterInvocation<T>(ctx: ActiveInvocation | undefined, fn: () => T, maxAgeMs: number): T {\n const result = runInContext(ctx, fn)\n if (!ctx || result === null || typeof (result as { then?: unknown })?.then !== 'function') return result\n const untrack = trackRunning(ctx, maxAgeMs)\n return (result as PromiseLike<unknown>).then(\n (value) => {\n untrack()\n return value\n },\n (error) => {\n untrack()\n throw error\n },\n ) as T\n}\n\n/** Runs `fn` synchronously inside `ctx` (`undefined`: outside any invocation). */\nexport function runInContext<T>(ctx: ActiveInvocation | undefined, fn: () => T): T {\n const previous = current\n current = ctx\n try {\n return fn()\n } finally {\n current = previous\n }\n}\n\n/** The public view of the current invocation (without the metadata sidecar). */\nexport function publicContext(ctx: ActiveInvocation | undefined): InvocationContext | undefined {\n if (!ctx) return undefined\n const view: InvocationContext = {\n function_id: ctx.function_id,\n invocation_id: ctx.invocation_id,\n observe_depth: ctx.observe_depth,\n }\n if (ctx.caller) view.caller = ctx.caller\n if (ctx.activation) view.activation = ctx.activation\n if (ctx.traceparent !== undefined) view.traceparent = ctx.traceparent\n if (ctx.baggage !== undefined) view.baggage = ctx.baggage\n views.set(view, ctx)\n return view\n}\n\n/**\n * The context `withInvocation` re-enters: the one a view of\n * `currentInvocation()` was taken from, or one built from a context the\n * caller assembled itself or copied (at the local depth of the code entering it).\n */\nexport function contextFromView(view: InvocationContext | undefined): ActiveInvocation | undefined {\n if (view === undefined || view === null) return undefined\n const known = views.get(view)\n if (known) {\n // Stored and entered again later, deeper in local calls: as deep as the\n // code entering it, as its own invocation entry, so a recursion through\n // one stored view still reaches the engine at MAX_LOCAL_DEPTH.\n const depth = callLocalDepth()\n return depth > (known.localDepth ?? 0) ? { ...known, localDepth: depth } : known\n }\n if (typeof view.function_id !== 'string' || typeof view.invocation_id !== 'string') {\n throw new Error('withInvocation: expected the value iii.currentInvocation() returned')\n }\n const ctx: ActiveInvocation = {\n function_id: view.function_id,\n invocation_id: view.invocation_id,\n observe_depth: typeof view.observe_depth === 'number' && view.observe_depth > 0 ? view.observe_depth : 0,\n // A copy (JSON, structuredClone) does not say how deep in local calls it\n // was taken: it is as deep as the code entering it, so a recursion through\n // copied views still reaches the engine at MAX_LOCAL_DEPTH.\n localDepth: callLocalDepth(),\n }\n if (view.caller) ctx.caller = view.caller\n if (view.activation) ctx.activation = view.activation\n if (typeof view.traceparent === 'string') ctx.traceparent = view.traceparent\n if (typeof view.baggage === 'string') ctx.baggage = view.baggage\n return ctx\n}\n","// Derived from sdk/packages/node/iii/src/observe-wire.ts by scripts/sync-browser-observe.py; edit those, not this file.\n/**\n * Builders and decoders for the observe messages (protocol.md §2,\n * `sdk/fixtures/protocol/observe`). Optional fields are left out, never sent\n * as `null`; decoders accept `null` for them, keep enum values they do not\n * know, and fill the documented defaults.\n */\nimport type {\n ActivationWire,\n CallerWire,\n CaptureWire,\n ErrorBody,\n FunctionRegisteredMessage,\n InvokeFunctionMessage,\n ObserveDescriptorWire,\n ObserveMessage,\n ObserveResultMessage,\n ObserverAckMessage,\n ObserverAddedMessage,\n ObserverInfoWire,\n ObserverRemovedMessage,\n ObserverStateChangedMessage,\n TriggerAction,\n WorkerRegisteredMessage,\n} from './iii-types'\nimport type { ObserveHooks, ObserverOptions, ObserveSource, Target } from './observe-types'\n\n/** CONTRACT D1: what an absent `capture` means. */\nexport const DEFAULT_CAPTURE: readonly CaptureWire[] = ['input', 'output', 'caller']\n\ntype Raw = Record<string, unknown>\n\nfunction isRecord(v: unknown): v is Raw {\n return v !== null && typeof v === 'object' && !Array.isArray(v)\n}\n\nfunction str(v: unknown): string | undefined {\n return typeof v === 'string' ? v : undefined\n}\n\nfunction num(v: unknown): number | undefined {\n return typeof v === 'number' ? v : undefined\n}\n\nfunction errorBody(v: unknown): ErrorBody | undefined {\n if (!isRecord(v)) return undefined\n const body: ErrorBody = { code: String(v.code ?? ''), message: String(v.message ?? '') }\n if (typeof v.stacktrace === 'string') body.stacktrace = v.stacktrace\n return body\n}\n\n/** Copies the wire caller, dropping `null`s and a `parent` inside `parent`. */\nexport function decodeCaller(v: unknown, depth = 0): CallerWire | undefined {\n if (!isRecord(v)) return undefined\n const caller: CallerWire = {}\n for (const key of ['worker_id', 'worker_name', 'function_id', 'invocation_id'] as const) {\n const value = str(v[key])\n if (value !== undefined) caller[key] = value\n }\n if (depth === 0) {\n const parent = decodeCaller(v.parent, 1)\n if (parent) caller.parent = parent\n }\n return caller\n}\n\nfunction decodeActivation(v: unknown): ActivationWire | undefined {\n if (!isRecord(v) || typeof v.observer_id !== 'string') return undefined\n const activation: ActivationWire = { observer_id: v.observer_id }\n if (typeof v.activation_id === 'string') activation.activation_id = v.activation_id\n return activation\n}\n\n/** An observer as the owner sees it (`observeradded.observer`, `functionregistered.observers[]`). */\nexport function decodeObserverInfo(v: unknown): ObserverInfoWire {\n const raw = isRecord(v) ? v : {}\n const info: ObserverInfoWire = {\n id: String(raw.id ?? ''),\n args: isRecord(raw.args) ? raw.args : {},\n // Absent is `{}`; anything else is compiled as sent, so a malformed one is\n // acked INVALID_FILTER rather than read as match-all.\n filters: (raw.filters === undefined ? {} : raw.filters) as Record<string, unknown>,\n target: String(raw.target ?? ''),\n capture: Array.isArray(raw.capture)\n ? raw.capture.filter((c): c is string => typeof c === 'string')\n : [...DEFAULT_CAPTURE],\n on: str(raw.on) ?? 'success',\n }\n if (isRecord(raw.legacy) && typeof raw.legacy.trigger_type === 'string') {\n info.legacy = { trigger_type: raw.legacy.trigger_type, config: raw.legacy.config ?? null }\n }\n return info\n}\n\nexport function decodeFunctionRegistered(v: Raw): Omit<FunctionRegisteredMessage, 'message_type'> {\n return {\n id: String(v.id ?? ''),\n namespace: String(v.namespace ?? ''),\n revision: num(v.revision) ?? 0,\n local_dispatch: v.local_dispatch === true,\n observers: Array.isArray(v.observers) ? v.observers.map(decodeObserverInfo) : [],\n }\n}\n\nexport function decodeObserverAdded(v: Raw): Omit<ObserverAddedMessage, 'message_type'> {\n return {\n function_id: String(v.function_id ?? ''),\n namespace: String(v.namespace ?? ''),\n revision: num(v.revision) ?? 0,\n observer: decodeObserverInfo(v.observer),\n }\n}\n\nexport function decodeObserverRemoved(v: Raw): Omit<ObserverRemovedMessage, 'message_type'> {\n return {\n function_id: String(v.function_id ?? ''),\n namespace: String(v.namespace ?? ''),\n revision: num(v.revision) ?? 0,\n id: String(v.id ?? ''),\n }\n}\n\nexport function decodeObserveResult(v: Raw): Omit<ObserveResultMessage, 'message_type'> {\n const msg: Omit<ObserveResultMessage, 'message_type'> = { id: String(v.id ?? ''), state: String(v.state ?? '') }\n const error = errorBody(v.error)\n if (error) msg.error = error\n if (Array.isArray(v.warnings)) msg.warnings = v.warnings.filter((w): w is string => typeof w === 'string')\n return msg\n}\n\nexport function decodeObserverStateChanged(v: Raw): Omit<ObserverStateChangedMessage, 'message_type'> {\n const msg: Omit<ObserverStateChangedMessage, 'message_type'> = {\n id: String(v.id ?? ''),\n state: String(v.state ?? ''),\n fires: num(v.fires) ?? 0,\n }\n const reason = errorBody(v.reason)\n if (reason) msg.reason = reason\n return msg\n}\n\nexport function decodeWorkerRegistered(v: Raw): Omit<WorkerRegisteredMessage, 'message_type'> {\n const msg: Omit<WorkerRegisteredMessage, 'message_type'> = { worker_id: String(v.worker_id ?? '') }\n if (typeof v.reattach_token === 'string') msg.reattach_token = v.reattach_token\n if (Array.isArray(v.features)) msg.features = v.features.filter((f): f is string => typeof f === 'string')\n return msg\n}\n\n/** The observe fields of an inbound `invokefunction` (`caller`, `observe_depth`, `activation`). */\nexport function decodeInvokeFunction(v: Raw): Omit<InvokeFunctionMessage, 'message_type'> {\n const msg: Omit<InvokeFunctionMessage, 'message_type'> = {\n function_id: String(v.function_id ?? ''),\n data: v.data,\n }\n if (typeof v.invocation_id === 'string') msg.invocation_id = v.invocation_id\n if (typeof v.traceparent === 'string') msg.traceparent = v.traceparent\n if (typeof v.baggage === 'string') msg.baggage = v.baggage\n if (isRecord(v.action)) msg.action = v.action as TriggerAction\n if (v.metadata !== undefined && v.metadata !== null) msg.metadata = v.metadata\n if (typeof v.namespace === 'string') msg.namespace = v.namespace\n const caller = decodeCaller(v.caller)\n if (caller) msg.caller = caller\n const depth = num(v.observe_depth)\n if (depth !== undefined && depth > 0) msg.observe_depth = depth\n const activation = decodeActivation(v.activation)\n if (activation) msg.activation = activation\n return msg\n}\n\n/** Drops `parent` (one level only). */\nexport function stripCaller(caller: CallerWire | undefined): Omit<CallerWire, 'parent'> | undefined {\n if (!caller) return undefined\n const { parent: _, ...rest } = caller\n return rest\n}\n\n/** JSON's view of a message: `undefined` fields left out, no caller-owned objects retained. */\nfunction snapshot<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T\n}\n\n/**\n * `observe { id, source, target, ... }` from the three arguments of\n * `iii.observe`. Only what the caller set is sent; the engine applies the\n * defaults. `resolveNamespace` gives the namespace of an unqualified id (this\n * worker's, `default` for `engine::*`).\n */\nexport function buildObserveMessage(\n id: string,\n source: ObserveSource,\n target: Target,\n options: ObserverOptions | undefined,\n resolveNamespace: (explicit: string | undefined, functionId: string, field: string) => string | undefined,\n): Omit<ObserveMessage, 'message_type'> {\n const targetRef = typeof target === 'string' ? { function_id: target } : target\n const sourceNamespace = resolveNamespace(source.namespace, source.function_id, 'ObserveSource.namespace')\n const targetNamespace = resolveNamespace(targetRef.namespace, targetRef.function_id, 'Target.namespace')\n return snapshot({\n id,\n source: {\n function_id: source.function_id,\n namespace: sourceNamespace,\n args: source.args,\n filters: source.filters,\n capture: source.capture,\n on: source.on,\n deliver: source.deliver,\n },\n target: { function_id: targetRef.function_id, namespace: targetNamespace },\n metadata: options?.metadata,\n max_fires: options?.max_fires,\n expires_in_ms: options?.expires_in_ms,\n max_in_flight: options?.max_in_flight,\n })\n}\n\n/** `registerfunction.observe`: the four fields that travel, or `undefined` when none is set. */\nexport function observeDescriptor(hooks: ObserveHooks | undefined): ObserveDescriptorWire | undefined {\n if (!hooks) return undefined\n const descriptor: ObserveDescriptorWire = snapshot({\n delivery: hooks.delivery,\n args_format: hooks.args_format,\n legacy_trigger_type: hooks.legacy_trigger_type,\n allow: hooks.allow,\n })\n return Object.keys(descriptor).length > 0 ? descriptor : undefined\n}\n\nexport function buildObserverAck(ack: {\n function_id: string\n namespace?: string\n id: string\n revision: number\n error?: { code: string; message: string }\n}): Omit<ObserverAckMessage, 'message_type'> {\n const msg: Omit<ObserverAckMessage, 'message_type'> = {\n function_id: ack.function_id,\n id: ack.id,\n revision: ack.revision,\n }\n if (ack.namespace !== undefined) msg.namespace = ack.namespace\n if (ack.error) msg.error = { code: ack.error.code, message: ack.error.message }\n return msg\n}\n\n/**\n * An outbound `invokefunction`. `observe_depth` is left out when 0, and every\n * optional field when unset.\n */\nexport function buildInvokeFunction(init: {\n invocation_id?: string\n function_id: string\n data: unknown\n traceparent?: string\n baggage?: string\n action?: TriggerAction\n metadata?: unknown\n namespace?: string\n caller?: CallerWire\n observe_depth?: number\n activation?: ActivationWire\n}): Record<string, unknown> {\n const msg: Record<string, unknown> = {}\n if (init.invocation_id !== undefined) msg.invocation_id = init.invocation_id\n msg.function_id = init.function_id\n msg.data = init.data\n if (init.traceparent !== undefined) msg.traceparent = init.traceparent\n if (init.baggage !== undefined) msg.baggage = init.baggage\n if (init.action !== undefined) msg.action = init.action\n if (init.metadata !== undefined) msg.metadata = init.metadata\n if (init.namespace !== undefined) msg.namespace = init.namespace\n if (init.caller !== undefined) msg.caller = init.caller\n if (init.observe_depth !== undefined && init.observe_depth > 0) msg.observe_depth = init.observe_depth\n if (init.activation !== undefined) msg.activation = init.activation\n return msg\n}\n\n/** The caller an outbound call asserts from inside a handler: that handler, and its own caller one level up. */\nexport function callerFor(ctx: { function_id: string; invocation_id: string; caller?: CallerWire }): CallerWire {\n const caller: CallerWire = { function_id: ctx.function_id, invocation_id: ctx.invocation_id }\n const parent = stripCaller(ctx.caller)\n if (parent && Object.keys(parent).length > 0) caller.parent = parent\n return caller\n}\n","// Derived from sdk/packages/node/iii/src/observable.ts by scripts/sync-browser-observe.py; edit those, not this file.\n/**\n * The owner side of observe (sdk.md §1, §4.1–§4.3): per-function observer\n * state, the observe hooks, the `Observer` object handed to them, and the\n * reports of local invocations and `obs.emit` events.\n */\nimport { InvocationError, ObserveRejection } from './errors'\nimport { type CompiledFilter, compileFilter } from './filter'\nimport type { CallerWire, ErrorBody, ObserverInfoWire } from './iii-types'\nimport { type ActiveInvocation, callContext, callDepth } from './invocation-context'\nimport type { Capture, Filter, ObserveDoc, ObserveHooks, Observer } from './observe-types'\nimport { stripCaller } from './observe-wire'\nimport type { Reporter } from './reporter'\nimport { randomUUID, unrefTimer } from './utils'\n\n/** CONTRACT D11: `onObserverAdded` (and `onObserverRemoved`) still running after this is `OWNER_TIMEOUT`. */\nexport const OBSERVE_HOOK_TIMEOUT_MS = 30_000\n\nexport interface ObserveHost {\n /** This worker, as the engine knows it. */\n identity(): { worker_id?: string; worker_name: string }\n sendAck(ack: {\n function_id: string\n namespace?: string\n id: string\n revision: number\n error?: { code: string; message: string }\n }): void\n readonly reporter: Reporter\n /** `obs.call`: a remote invocation of the target marked with the activation. */\n callTarget(target: string, observerId: string, payload: unknown, timeoutMs?: number): Promise<unknown>\n logError(message: string, error?: unknown): void\n hookTimeoutMs(): number\n /** The trace context an event emitted outside any handler carries (the active span, if any). */\n traceContext(): { traceparent?: string; baggage?: string }\n}\n\ntype HookOutcome =\n | { ok: true }\n | { ok: false; code: string; message: string; timedOut: boolean; late: Promise<unknown> }\n\nfunction sameJson(a: unknown, b: unknown): boolean {\n return JSON.stringify(a) === JSON.stringify(b)\n}\n\nfunction rejectionBody(error: unknown): { code: string; message: string } {\n if (error instanceof ObserveRejection) return { code: error.code, message: error.message }\n return { code: 'OBSERVE_REJECTED', message: error instanceof Error ? error.message : String(error) }\n}\n\nfunction onAccepts(on: string, ok: boolean): boolean {\n return on === 'complete' || (on === 'success' ? ok : on === 'error' ? !ok : false)\n}\n\n/** The `Observer` an owner receives. Its identity is stable while the observer lives. */\nexport class ObserverImpl implements Observer {\n readonly id: string\n readonly function_id: string\n args: Record<string, unknown>\n filters: Filter\n target: string\n capture: Capture[]\n on: 'success' | 'error' | 'complete'\n legacy?: { trigger_type: string; config: unknown }\n /** @internal */\n filter: CompiledFilter\n /** @internal The revision it was acked with (echoed by a late rejection). */\n revision: number\n /** @internal In the compiled set: `emit` / `call` deliver to it. */\n active = false\n /**\n * @internal The owner's late rejection (`obs.reject`). It survives a\n * reconnect: a replayed set that lists the observer is acked with it again,\n * and only a fresh `observeradded` reactivates the observer.\n */\n rejection?: { code: string; message: string }\n /** @internal Its `onObserverAdded` is running: a `reject()` now is applied by the add, not sent. */\n adding = false\n\n constructor(\n private readonly owner: FunctionObservers,\n info: ObserverInfoWire,\n filter: CompiledFilter,\n revision: number,\n ) {\n this.id = info.id\n this.function_id = owner.functionId\n this.args = info.args\n this.filters = info.filters\n this.target = info.target\n this.capture = info.capture as Capture[]\n this.on = info.on as Observer['on']\n if (info.legacy) this.legacy = info.legacy\n this.filter = filter\n this.revision = revision\n }\n\n /** @internal Takes the engine's current view of a kept observer. */\n update(info: ObserverInfoWire, filter: CompiledFilter): void {\n this.filters = info.filters\n this.filter = filter\n this.target = info.target\n this.capture = info.capture as Capture[]\n this.on = info.on as Observer['on']\n }\n\n matches(doc: ObserveDoc): boolean {\n return this.filter.matches(doc)\n }\n\n emit(event: unknown): boolean {\n return this.owner.emit(this, event)\n }\n\n call<R = unknown>(payload: unknown, opts?: { timeoutMs?: number; metadata?: never }): Promise<R> {\n return this.owner.call(this, payload, opts?.timeoutMs) as Promise<R>\n }\n\n reject(code: string, message: string): void {\n this.owner.reject(this, code, message)\n }\n\n toJSON(): Record<string, unknown> {\n return {\n id: this.id,\n function_id: this.function_id,\n args: this.args,\n filters: this.filters,\n target: this.target,\n capture: this.capture,\n on: this.on,\n ...(this.legacy ? { legacy: this.legacy } : {}),\n }\n }\n}\n\n/**\n * One registered function's observers, as the engine pushed them\n * (`functionregistered`, `observeradded`, `observerremoved`). Hooks run one\n * at a time, in revision order.\n */\nexport class FunctionObservers {\n readonly delivery: 'auto' | 'owner'\n /** `functionregistered` arrived (cleared by a namespace conflict). */\n confirmed = false\n /** The connection (`epoch`) whose `functionregistered` set was acked: its reports may go out. */\n confirmedEpoch = -1\n /** In-process dispatch: `functionregistered.local_dispatch` ∧ the `localDispatch` option. Survives a disconnect. */\n localDispatch = false\n /** The namespace the engine registered the function in. */\n namespace?: string\n /** The highest revision received on this connection. */\n revision = -1\n /** Every acked observer (until it is removed). */\n private readonly known = new Map<string, ObserverImpl>()\n /** The active observers: one reference, swapped on change; `isObserved()` reads its length. */\n compiled: readonly ObserverImpl[] = []\n private queue: Promise<void> = Promise.resolve()\n private disposed = false\n /** Bumped on every release (conflict, unregister): an add whose hook spans one is undone. */\n private releases = 0\n /**\n * The connection (`epoch`) on which the engine refused the function\n * (`FUNCTION_NAMESPACE_CONFLICT`). On that connection a flush treats its\n * reports as gone (INACTIVE), also those of a call that was already\n * running. On a later connection the replayed registration may be accepted,\n * so its reports wait for the answer; `functionregistered` clears it.\n * (An unregistered function is gone because it left the function map.)\n */\n releasedEpoch?: number\n\n constructor(\n readonly functionId: string,\n readonly hooks: ObserveHooks | undefined,\n private readonly localDispatchOption: boolean,\n private readonly hasHandler: boolean,\n private readonly host: ObserveHost,\n ) {\n this.delivery = hooks?.delivery === 'owner' ? 'owner' : 'auto'\n }\n\n /** Callbacks or owner delivery: what needs `observe.v1` on both sides. */\n get needsObserve(): boolean {\n return this.delivery === 'owner' || !!this.hooks?.onObserverAdded || !!this.hooks?.onObserverRemoved\n }\n\n isObserved(): boolean {\n return this.compiled.length > 0\n }\n\n observers(): readonly Observer[] {\n return [...this.compiled]\n }\n\n /** `functionregistered`: always accepted; replaces the set (§4.2). */\n onFunctionRegistered(\n msg: { namespace: string; revision: number; local_dispatch: boolean; observers: ObserverInfoWire[] },\n epoch: number,\n ): void {\n if (this.disposed) return\n this.confirmed = true\n this.releasedEpoch = undefined\n this.localDispatch = msg.local_dispatch && this.localDispatchOption && this.hasHandler\n this.namespace = msg.namespace\n this.revision = msg.revision\n this.enqueue(async () => {\n try {\n await this.applySet(msg.observers, msg.revision, msg.namespace)\n } finally {\n // Reports held across a reconnect go out only now, after the acks: the\n // engine drops an item whose observer is still pending (INACTIVE).\n // Also when the diff failed: the engine confirmed the function.\n this.confirmedEpoch = epoch\n this.host.reporter.flush()\n }\n })\n }\n\n onObserverAdded(msg: { namespace: string; revision: number; observer: ObserverInfoWire }): void {\n if (this.disposed || msg.revision <= this.revision) return\n this.revision = msg.revision\n this.enqueue(async () => {\n // A fresh add of an observer this owner rejected: it starts over (removed, then added).\n if (this.known.get(msg.observer.id)?.rejection) await this.remove(msg.observer.id)\n await this.add(msg.observer, msg.revision, msg.namespace)\n })\n }\n\n onObserverRemoved(msg: { revision: number; id: string }): void {\n if (this.disposed || msg.revision <= this.revision) return\n this.revision = msg.revision\n this.enqueue(() => this.remove(msg.id))\n }\n\n /**\n * `RegistrationRejected{FUNCTION_NAMESPACE_CONFLICT}`: no local dispatch, no\n * observers, and its held reports are discarded (they could never be\n * confirmed, and would starve other functions of buffer).\n */\n onRegistrationRejected(epoch: number): void {\n this.confirmed = false\n this.confirmedEpoch = -1\n this.localDispatch = false\n this.releasedEpoch = epoch\n this.releases++\n this.host.reporter.discard(this.functionId)\n this.dropAll()\n }\n\n /** The function was unregistered. */\n dispose(): void {\n this.disposed = true\n this.onRegistrationRejected(-1)\n }\n\n /**\n * Stops delivery at once, then removes every observer through the hook\n * queue, after the adds queued before it (which undo themselves: `add`).\n */\n private dropAll(): void {\n for (const obs of this.compiled) obs.active = false\n this.compiled = []\n this.enqueue(async () => {\n for (const id of [...this.known.keys()]) await this.remove(id)\n })\n }\n\n private enqueue(task: () => Promise<void>): void {\n this.queue = this.queue.then(task).catch((error) => {\n this.host.logError(`Observe hook failed for ${this.functionId}`, error)\n })\n }\n\n private activate(obs: ObserverImpl): void {\n if (obs.active) return\n obs.active = true\n this.compiled = [...this.compiled, obs]\n }\n\n private deactivate(obs: ObserverImpl): void {\n if (!obs.active) return\n obs.active = false\n this.compiled = this.compiled.filter((o) => o !== obs)\n }\n\n private ack(info: { id: string }, revision: number, namespace: string, error?: { code: string; message: string }) {\n this.host.sendAck({ function_id: this.functionId, namespace, id: info.id, revision, ...(error ? { error } : {}) })\n }\n\n /** Diffs the engine's full set against what this SDK holds. */\n private async applySet(list: ObserverInfoWire[], revision: number, namespace: string): Promise<void> {\n const incoming = new Set(list.map((o) => o.id))\n for (const id of [...this.known.keys()]) {\n if (!incoming.has(id)) await this.remove(id)\n }\n for (const info of list) {\n const existing = this.known.get(info.id)\n if (existing && sameJson(existing.args, info.args) && sameJson(existing.legacy, info.legacy)) {\n this.keep(existing, info, revision, namespace)\n } else {\n if (existing) await this.remove(info.id)\n await this.add(info, revision, namespace)\n }\n }\n }\n\n /**\n * A kept observer: the hook already ran for it; take the engine's filters\n * and ack it again, or repeat the owner's late rejection of it.\n */\n private keep(obs: ObserverImpl, info: ObserverInfoWire, revision: number, namespace: string): void {\n if (obs.rejection) {\n obs.revision = revision\n this.ack(info, revision, namespace, obs.rejection)\n return\n }\n let filter = obs.filter\n if (!sameJson(obs.filters, info.filters)) {\n try {\n filter = compileFilter(info.filters, { trusted: true })\n } catch (error) {\n obs.revision = revision\n this.deactivate(obs)\n this.ack(info, revision, namespace, { code: 'INVALID_FILTER', message: (error as Error).message })\n return\n }\n }\n obs.update(info, filter)\n obs.revision = revision\n this.activate(obs)\n this.ack(info, revision, namespace)\n }\n\n /** handleAdded (§4.2): hook, then the compiled set, then the ack. */\n private async add(info: ObserverInfoWire, revision: number, namespace: string): Promise<void> {\n // Refused or unregistered since this add was queued: nothing to add, nothing to ack.\n if (this.disposed || this.releasedEpoch !== undefined) return\n const releases = this.releases\n const existing = this.known.get(info.id)\n if (existing) {\n this.keep(existing, info, revision, namespace)\n return\n }\n let filter: CompiledFilter\n try {\n filter = compileFilter(info.filters, { trusted: true })\n } catch (error) {\n this.ack(info, revision, namespace, { code: 'INVALID_FILTER', message: (error as Error).message })\n return\n }\n const obs = new ObserverImpl(this, info, filter, revision)\n const onAdded = this.hooks?.onObserverAdded\n if (onAdded) {\n obs.adding = true\n const outcome = await this.runHook(() => onAdded.call(this.hooks, obs))\n obs.adding = false\n if (!outcome.ok) {\n this.ack(info, revision, namespace, { code: outcome.code, message: outcome.message })\n if (outcome.timedOut) {\n // It may still finish and index the observer: undo that once it does.\n outcome.late.then(\n () => this.enqueue(() => this.callRemoved(obs)),\n () => undefined, // it failed after all: nothing was indexed\n )\n }\n return\n }\n }\n // Released while the hook ran: undo what the hook did; no success ack, not active.\n if (this.disposed || this.releases !== releases) {\n await this.callRemoved(obs)\n return\n }\n this.known.set(obs.id, obs)\n // Rejected (`obs.reject`) while its hook was still running: the rejection wins.\n if (obs.rejection) {\n this.ack(info, revision, namespace, obs.rejection)\n return\n }\n // In the compiled set before the ack: the first event after `active` is evaluated.\n this.activate(obs)\n this.ack(info, revision, namespace)\n }\n\n private async remove(id: string): Promise<void> {\n const obs = this.known.get(id)\n if (!obs) return\n this.known.delete(id)\n this.deactivate(obs)\n await this.callRemoved(obs)\n }\n\n private async callRemoved(obs: ObserverImpl): Promise<void> {\n const onRemoved = this.hooks?.onObserverRemoved\n if (!onRemoved) return\n const outcome = await this.runHook(() => onRemoved.call(this.hooks, obs))\n if (!outcome.ok) {\n this.host.logError(`onObserverRemoved failed for observer ${obs.id} of ${this.functionId}: ${outcome.message}`)\n }\n }\n\n private async runHook(fn: () => void | Promise<void>): Promise<HookOutcome> {\n const run = Promise.resolve().then(fn)\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeoutMs = this.host.hookTimeoutMs()\n const timeout = new Promise<'timeout'>((resolve) => {\n timer = setTimeout(() => resolve('timeout'), timeoutMs)\n unrefTimer(timer)\n })\n try {\n const result = await Promise.race([run.then(() => 'done' as const), timeout])\n if (result === 'timeout') {\n return {\n ok: false,\n code: 'OWNER_TIMEOUT',\n message: `observe hook of ${this.functionId} still running after ${timeoutMs}ms`,\n timedOut: true,\n late: run,\n }\n }\n return { ok: true }\n } catch (error) {\n return { ok: false, ...rejectionBody(error), timedOut: false, late: run }\n } finally {\n if (timer) clearTimeout(timer)\n }\n }\n\n // ── owner delivery ────────────────────────────────────────────────────────\n\n private requireOwnerDelivery(what: string): void {\n if (this.delivery !== 'owner') {\n throw new InvocationError({\n code: 'NOT_OWNER_DELIVERED',\n message: `obs.${what}() needs an owner-delivered function; ${this.functionId} is auto-delivered (observe.delivery)`,\n function_id: this.functionId,\n })\n }\n }\n\n private isActive(obs: ObserverImpl): boolean {\n return obs.active && this.known.get(obs.id) === obs\n }\n\n /**\n * The caller an event carries (sdk.md §1): inside the function's own\n * handler, that invocation's caller; inside another handler, that handler;\n * outside any handler, this worker only.\n */\n private eventCaller(cur: ActiveInvocation | undefined): { caller?: CallerWire; own: boolean } {\n if (cur && cur.function_id === this.functionId) return { caller: cur.caller, own: true }\n const { worker_id, worker_name } = this.host.identity()\n const caller: CallerWire = worker_id !== undefined ? { worker_id, worker_name } : { worker_name }\n if (cur) {\n caller.function_id = cur.function_id\n caller.invocation_id = cur.invocation_id\n const parent = stripCaller(cur.caller)\n if (parent && Object.keys(parent).length > 0) caller.parent = parent\n }\n return { caller, own: false }\n }\n\n /**\n * Hands `event` to one observer. `false`, and nothing sent, when its\n * filters reject the event or it is no longer active (removed or rejected\n * meanwhile): an owner's fan-out loop must not stop for one observer.\n */\n emit(obs: ObserverImpl, event: unknown): boolean {\n this.requireOwnerDelivery('emit')\n if (!this.isActive(obs)) return false\n const cur = callContext()\n const { caller, own } = this.eventCaller(cur)\n const metadata = cur?.metadata\n if (!obs.filter.matches({ input: event, caller, metadata })) return false\n const values: { input: unknown; caller?: CallerWire; metadata?: unknown } = { input: event }\n if (caller !== undefined) values.caller = caller\n if (metadata !== undefined) values.metadata = metadata\n // The activation joins the trace the event was emitted in.\n const trace = cur ? { traceparent: cur.traceparent, baggage: cur.baggage } : this.host.traceContext()\n this.host.reporter.pushEmit({\n function_id: this.functionId,\n namespace: this.namespace,\n invocation_id: own && cur ? cur.invocation_id : randomUUID(),\n status: 'success',\n values,\n captures: obs.capture,\n started_at_ms: Date.now(),\n duration_ms: 0,\n observe_depth: cur ? cur.observe_depth : callDepth(),\n traceparent: trace.traceparent,\n baggage: trace.baggage,\n observer_id: obs.id,\n event,\n context: cur,\n })\n return true\n }\n\n async call(obs: ObserverImpl, payload: unknown, timeoutMs?: number): Promise<unknown> {\n this.requireOwnerDelivery('call')\n if (!this.isActive(obs)) {\n throw new InvocationError({\n code: 'OBSERVER_NOT_ACTIVE',\n message: `observer ${obs.id} of ${this.functionId} is not active`,\n function_id: this.functionId,\n })\n }\n const cur = callContext()\n const { caller } = this.eventCaller(cur)\n if (!obs.filter.matches({ input: payload, caller, metadata: cur?.metadata })) {\n throw new InvocationError({\n code: 'FILTERS_NOT_MATCHED',\n message: `the filters of observer ${obs.id} reject this payload`,\n function_id: this.functionId,\n })\n }\n return this.host.callTarget(obs.target, obs.id, payload, timeoutMs)\n }\n\n reject(obs: ObserverImpl, code: string, message: string): void {\n if (obs.adding) {\n // The add acks with it once the hook returns.\n obs.rejection = { code, message }\n return\n }\n if (this.known.get(obs.id) !== obs) return\n // Kept on the observer: if this ack is lost with the connection, the\n // replayed set gets it again (`keep`).\n obs.rejection = { code, message }\n this.deactivate(obs)\n this.host.sendAck({\n function_id: this.functionId,\n namespace: this.namespace,\n id: obs.id,\n revision: obs.revision,\n error: { code, message },\n })\n }\n\n // ── auto delivery: a local invocation ─────────────────────────────────────\n\n /**\n * Evaluates `set` (the compiled set captured when the call started) on a\n * finished local invocation of an auto function, and reports it when an\n * observer matches. Never throws.\n */\n reportLocal(\n set: readonly ObserverImpl[],\n init: {\n invocation_id: string\n ok: boolean\n input: unknown\n output?: unknown\n error?: ErrorBody\n caller?: CallerWire\n metadata?: unknown\n started_at_ms: number\n duration_ms: number\n observe_depth: number\n traceparent?: string\n baggage?: string\n },\n ): void {\n if (this.delivery !== 'auto' || set.length === 0) return\n const doc: ObserveDoc = { input: init.input, caller: init.caller, metadata: init.metadata }\n if (init.ok) doc.output = init.output\n else doc.error = init.error\n const matched: string[] = []\n const captures = new Set<string>()\n for (const obs of set) {\n if (!onAccepts(obs.on, init.ok)) continue\n if (!obs.filter.matches(doc)) continue\n matched.push(obs.id)\n for (const c of obs.capture) captures.add(c)\n }\n if (matched.length === 0) return\n // Pushed even if the function was released meanwhile: the flush decides\n // against the registration current then (`gone` → INACTIVE, re-confirmed → sent).\n const values: Record<string, unknown> = { input: init.input }\n // The error as the routed path reports it: the handler's error body.\n if (init.ok) values.output = init.output\n else values.error = init.error\n if (init.caller !== undefined) values.caller = init.caller\n if (init.metadata !== undefined) values.metadata = init.metadata\n this.host.reporter.push({\n function_id: this.functionId,\n namespace: this.namespace,\n invocation_id: init.invocation_id,\n matched,\n status: init.ok ? 'success' : 'error',\n values,\n captures,\n started_at_ms: init.started_at_ms,\n duration_ms: init.duration_ms,\n observe_depth: init.observe_depth,\n traceparent: init.traceparent,\n baggage: init.baggage,\n })\n }\n}\n","// Derived from sdk/packages/node/iii/src/observer-handle.ts by scripts/sync-browser-observe.py; edit those, not this file.\n/**\n * The observing side of observe (sdk.md §2): the handle `iii.observe`\n * returns, kept for replay until it is disposed.\n */\nimport { ObserveRejection } from './errors'\nimport type { ObserveMessage } from './iii-types'\nimport type { ObserveReason, ObserverHandle, ObserverState } from './observe-types'\n\ntype Listener = (state: ObserverState, reason?: ObserveReason) => void\n\n/** Active → resolved; error / disposed → rejected; otherwise still waiting. */\nfunction settlement(id: string, state: ObserverState, reason: ObserveReason | undefined): Promise<void> | undefined {\n if (state === 'active') return Promise.resolve()\n if (state === 'error' || state === 'disposed') {\n const why = reason ?? {\n code: state === 'error' ? 'OBSERVE_FAILED' : 'UNOBSERVED',\n message: `observer ${id} is ${state}`,\n }\n return Promise.reject(new ObserveRejection(why.code, why.message))\n }\n return undefined\n}\n\nexport class ObserverHandleImpl implements ObserverHandle {\n private currentState: ObserverState = 'pending'\n private currentReason?: ObserveReason\n private readonly listeners = new Set<Listener>()\n /** State changes not delivered to the listeners yet, in order. */\n private readonly undelivered: [ObserverState, ObserveReason | undefined][] = []\n private delivering = false\n /** @internal Sent on some connection: the engine may hold it, so disposing it needs an `unobserve`. */\n sent = false\n\n constructor(\n readonly id: string,\n /** @internal What `observe` sends, replayed on every connection. */\n readonly message: Omit<ObserveMessage, 'message_type'>,\n private readonly onDispose: (handle: ObserverHandleImpl) => void,\n private readonly logError: (message: string, error?: unknown) => void,\n ) {}\n\n get state(): ObserverState {\n return this.currentState\n }\n\n get reason(): ObserveReason | undefined {\n return this.currentReason\n }\n\n ready(): Promise<void> {\n const settled = settlement(this.id, this.currentState, this.currentReason)\n if (settled) return settled\n return new Promise<void>((resolve, reject) => {\n const off = this.onStateChange((state, reason) => {\n const result = settlement(this.id, state, reason)\n if (!result) return\n off()\n result.then(resolve, reject)\n })\n })\n }\n\n onStateChange(listener: Listener): () => void {\n this.listeners.add(listener)\n return () => {\n this.listeners.delete(listener)\n }\n }\n\n async dispose(): Promise<void> {\n if (this.currentState === 'disposed') return\n this.onDispose(this)\n this.setState('disposed', { code: 'UNOBSERVED', message: 'disposed by the observing worker' })\n }\n\n /** @internal A state from the engine (`observeresult`, `observerstatechanged`) or the SDK. */\n setState(state: ObserverState, reason?: ObserveReason): void {\n if (this.currentState === 'disposed') return\n const changed =\n state !== this.currentState ||\n reason?.code !== this.currentReason?.code ||\n reason?.message !== this.currentReason?.message\n this.currentState = state\n this.currentReason = reason\n if (!changed) return\n // Delivered later, in order: a listener never runs on the socket's read\n // path (or inside dispose()), so it may call the client freely.\n this.undelivered.push([state, reason])\n if (this.delivering) return\n this.delivering = true\n queueMicrotask(() => this.deliver())\n }\n\n private deliver(): void {\n for (let next = this.undelivered.shift(); next; next = this.undelivered.shift()) {\n const [state, reason] = next\n for (const listener of [...this.listeners]) {\n try {\n listener(state, reason)\n } catch (error) {\n this.logError(`Observer ${this.id} state listener threw`, error)\n }\n }\n }\n this.delivering = false\n }\n}\n\nconst STATES: ReadonlySet<string> = new Set(['pending', 'active', 'suspended', 'error', 'disposed'])\n\n/** A wire state this SDK does not know (a newer engine) reads as `pending`. */\nexport function toObserverState(state: string): ObserverState {\n return (STATES.has(state) ? state : 'pending') as ObserverState\n}\n","// Derived from sdk/packages/node/iii/src/reporter.ts by scripts/sync-browser-observe.py; edit those, not this file.\n/**\n * The reporter (sdk.md §4.4, CONTRACT D12): one bounded buffer for matched\n * local invocations of auto functions and `obs.emit` events of owner\n * functions, flushed as `invocationsobserved` batches; plus the periodic\n * `localinvocationstats`.\n *\n * It never blocks a call: when the buffer is full the newest item is dropped\n * and counted (`BUFFER_FULL`), and an item too large on its own is dropped and\n * counted (`TOO_LARGE`). The 8 MiB bound covers both the buffer and the bytes\n * already handed to the socket but not yet written (a peer that stops reading\n * does not grow memory). Items stay buffered while disconnected and are\n * flushed once the engine confirmed their function on the new connection.\n */\nimport type { CallerWire, LocalInvocationStatsMessage } from './iii-types'\nimport { MessageType } from './iii-types'\nimport { unrefTimer, utf8ByteLength } from './utils'\n\nexport type ReportPart = 'input' | 'output' | 'error' | 'caller' | 'metadata'\n\nconst PART_ORDER: readonly ReportPart[] = ['input', 'output', 'error', 'caller', 'metadata']\n\n/** The values an item may carry; a part is sent only when some matched observer captures it. */\nexport type ReportValues = {\n input?: unknown\n output?: unknown\n error?: unknown\n caller?: CallerWire\n metadata?: unknown\n}\n\nexport type ReportInit = {\n function_id: string\n namespace?: string\n invocation_id: string\n matched: string[]\n status: 'success' | 'error'\n values: ReportValues\n captures: Iterable<string>\n started_at_ms: number\n duration_ms: number\n observe_depth: number\n traceparent?: string\n baggage?: string\n}\n\nexport type ReporterLimits = {\n /** Flush at this many items (default 256). */\n batchItems: number\n /** Flush this long after the first buffered item (default 5 ms). */\n lingerMs: number\n /** Bounded buffer: items (default 10 000). */\n maxItems: number\n /** Bounded buffer: bytes (default 8 MiB); an item larger than this is `TOO_LARGE`. */\n maxBytes: number\n /** One frame's limit (default 16 MiB, the engine's). */\n maxFrameBytes: number\n /** `localinvocationstats` cadence (default 10 s). */\n statsIntervalMs: number\n}\n\nexport const DEFAULT_REPORTER_LIMITS: ReporterLimits = {\n batchItems: 256,\n lingerMs: 5,\n maxItems: 10_000,\n maxBytes: 8 * 1024 * 1024,\n maxFrameBytes: 16 * 1024 * 1024,\n statsIntervalMs: 10_000,\n}\n\nexport interface ReporterHost {\n /** Connected to an engine that advertised `observe.v1`. */\n online(): boolean\n /**\n * `ready`: the engine confirmed the function (`functionregistered`) on the\n * current connection; `wait`: not yet; `gone`: no longer registered here.\n */\n status(functionId: string): 'ready' | 'wait' | 'gone'\n /** Sends one JSON frame; false when the socket is not open. */\n sendFrame(data: string): boolean\n /** Bytes handed to the socket and not written yet (`ws.bufferedAmount`). */\n pendingBytes(): number\n logError(message: string, error?: unknown): void\n}\n\ntype ItemState = { matched: number; captured: string[]; parts: [ReportPart, string][]; json: string; bytes: number }\n\nclass ReportItem {\n readonly parts = new Map<ReportPart, string>()\n readonly captured = new Set<string>()\n json = ''\n bytes = 0\n\n constructor(\n readonly init: Omit<ReportInit, 'captures'>,\n /** An `obs.emit` item: later emits of the same event value (`coalesceKey`) from the same `context` merge into it. */\n readonly emit: boolean,\n readonly coalesceKey: unknown,\n readonly context: unknown,\n ) {}\n\n /** Adds the parts `captures` asks for that are not in the item yet. */\n capture(captures: Iterable<string>): void {\n for (const c of captures) {\n if (this.captured.has(c)) continue\n this.captured.add(c)\n if (!PART_ORDER.includes(c as ReportPart)) continue\n const part = c as ReportPart\n if (!(part in this.init.values)) continue\n const encoded = encodeJson(this.init.values[part])\n if (encoded !== undefined) this.parts.set(part, encoded)\n }\n }\n\n /** What a merge can change, to undo it. */\n save(): ItemState {\n return {\n matched: this.init.matched.length,\n captured: [...this.captured],\n parts: [...this.parts],\n json: this.json,\n bytes: this.bytes,\n }\n }\n\n restore(state: ItemState): void {\n this.init.matched.length = state.matched\n this.captured.clear()\n for (const c of state.captured) this.captured.add(c)\n this.parts.clear()\n for (const [part, encoded] of state.parts) this.parts.set(part, encoded)\n this.json = state.json\n this.bytes = state.bytes\n }\n\n /** Assembles the wire JSON from the pre-encoded parts. */\n render(): void {\n const i = this.init\n let s = `{\"function_id\":${JSON.stringify(i.function_id)}`\n if (i.namespace !== undefined) s += `,\"namespace\":${JSON.stringify(i.namespace)}`\n s += `,\"invocation_id\":${JSON.stringify(i.invocation_id)},\"matched\":${JSON.stringify(i.matched)}`\n s += `,\"status\":${JSON.stringify(i.status)}`\n for (const part of PART_ORDER) {\n const encoded = this.parts.get(part)\n if (encoded !== undefined) s += `,\"${part}\":${encoded}`\n }\n s += `,\"started_at_ms\":${finite(i.started_at_ms)},\"duration_ms\":${finite(i.duration_ms)}`\n s += `,\"observe_depth\":${finite(i.observe_depth)}`\n if (i.traceparent !== undefined) s += `,\"traceparent\":${JSON.stringify(i.traceparent)}`\n if (i.baggage !== undefined) s += `,\"baggage\":${JSON.stringify(i.baggage)}`\n this.json = wellFormed(`${s}}`)\n this.bytes = byteLength(this.json)\n }\n}\n\n/**\n * Replaces lone surrogates with U+FFFD (CONTRACT parity 32): `JSON.stringify`\n * writes one as `\\ud800`, which the engine's strict decoder refuses, and it\n * would take the whole batch down with it. `JSON.stringify` escapes nothing\n * else in that range (a valid pair is written as is), so every `\\udXXX`\n * escape it produced is a lone surrogate. Fast path: no `\\ud` at all.\n */\nexport function wellFormed(json: string): string {\n if (!json.includes('\\\\ud')) return json\n // An escape is a backslash preceded by an even run of backslashes (`\\\\ud800` is text).\n return json.replace(/(\\\\+)u(d[89a-f][0-9a-f]{2})/g, (match, slashes: string) =>\n slashes.length % 2 === 1 ? `${slashes.slice(0, -1)}\\\\ufffd` : match,\n )\n}\n\nfunction finite(n: number): number {\n return Number.isFinite(n) ? n : 0\n}\n\nfunction byteLength(s: string): number {\n return utf8ByteLength(s)\n}\n\n/** JSON text of a value as the remote path would send it; `BigInt` is written as its number. */\nfunction encodeJson(value: unknown): string | undefined {\n try {\n return JSON.stringify(value)\n } catch (error) {\n if (!(error instanceof TypeError)) throw error\n return JSON.stringify(value, (_k, v) => (typeof v === 'bigint' ? Number(v) : v))\n }\n}\n\nconst FRAME_HEAD = `{\"type\":\"${MessageType.InvocationsObserved}\",\"items\":[`\nconst FRAME_TAIL = ']}'\nconst FRAME_OVERHEAD = byteLength(FRAME_HEAD) + byteLength(FRAME_TAIL)\n\ntype FunctionStats = { count: number; errors: number; duration_ms_sum: number }\n\nexport class Reporter {\n private items: ReportItem[] = []\n private bytes = 0\n /** Buffered items per function: whether a flush has anything to send is one look per function. */\n private perFunction = new Map<string, number>()\n private lingerTimer?: ReturnType<typeof setTimeout>\n private statsTimer?: ReturnType<typeof setInterval>\n /** Emitted events still in the buffer, by event value: one event to N observers is one item. */\n private openEmits = new Map<unknown, ReportItem[]>()\n private stats = new Map<string, FunctionStats>()\n private drops = new Map<string, Map<string, number>>()\n private windowStart = Date.now()\n private unencodable = new Set<string>()\n readonly limits: ReporterLimits\n\n constructor(\n private readonly host: ReporterHost,\n limits?: Partial<ReporterLimits>,\n ) {\n this.limits = { ...DEFAULT_REPORTER_LIMITS, ...limits }\n }\n\n /** Starts the `localinvocationstats` timer. */\n start(): void {\n if (this.statsTimer) return\n this.windowStart = Date.now()\n this.statsTimer = setInterval(() => this.sendStats(), this.limits.statsIntervalMs)\n unrefTimer(this.statsTimer)\n }\n\n stop(): void {\n if (this.statsTimer) clearInterval(this.statsTimer)\n this.statsTimer = undefined\n if (this.lingerTimer) clearTimeout(this.lingerTimer)\n this.lingerTimer = undefined\n }\n\n /** Buffered items (for tests and diagnostics). */\n get size(): number {\n return this.items.length\n }\n\n /** A matched local invocation of an auto function. */\n push(init: ReportInit): boolean {\n const { captures, ...rest } = init\n const item = new ReportItem(rest, false, undefined, undefined)\n if (!this.build(item, captures)) return false\n return this.enqueue(item)\n }\n\n /**\n * An `obs.emit` event. The same event value emitted to several observers\n * from the same invocation context, before the buffer is flushed, becomes\n * one item whose `matched` lists them all.\n */\n pushEmit(init: Omit<ReportInit, 'matched'> & { observer_id: string; event: unknown; context: unknown }): boolean {\n const { observer_id, event, context, captures, ...rest } = init\n const open = this.openEmits.get(event)\n const merge = open?.find(\n (it) =>\n it.init.function_id === rest.function_id && it.context === context && !it.init.matched.includes(observer_id),\n )\n if (merge) return this.merge(merge, observer_id, captures)\n const item = new ReportItem({ ...rest, matched: [observer_id] }, true, event, context)\n if (!this.build(item, captures)) return false\n return this.enqueue(item)\n }\n\n /** Makes a buffered emit item a merge target. Only items in the buffer are: a flush re-indexes. */\n private index(item: ReportItem): void {\n if (!item.emit) return\n const list = this.openEmits.get(item.coalesceKey)\n if (list) list.push(item)\n else this.openEmits.set(item.coalesceKey, [item])\n }\n\n /** Adds an observer (and its captures) to a buffered emit item, within the same bounds as a new item. */\n private merge(item: ReportItem, observerId: string, captures: Iterable<string>): boolean {\n const fn = item.init.function_id\n const before = item.save()\n try {\n item.init.matched.push(observerId)\n item.capture(captures)\n item.render()\n } catch (error) {\n item.restore(before)\n this.logUnencodable(fn, error)\n return false\n }\n const growth = item.bytes - before.bytes\n const reason = this.tooLarge(item)\n ? 'TOO_LARGE'\n : growth > 0 && this.bytes + this.host.pendingBytes() + growth > this.limits.maxBytes\n ? 'BUFFER_FULL'\n : undefined\n if (reason) {\n item.restore(before)\n this.drop(fn, reason)\n return false\n }\n this.bytes += growth\n return true\n }\n\n private build(item: ReportItem, captures: Iterable<string>): boolean {\n try {\n item.capture(captures)\n item.render()\n return true\n } catch (error) {\n this.logUnencodable(item.init.function_id, error)\n return false\n }\n }\n\n private logUnencodable(functionId: string, error: unknown): void {\n if (this.unencodable.has(functionId)) return\n this.unencodable.add(functionId)\n this.host.logError(`Cannot encode an observed invocation of ${functionId} as JSON; it is not reported`, error)\n }\n\n /**\n * TOO_LARGE is measured against the buffer (8 MiB), the smaller of the two\n * limits: an item that can never be buffered. It also always fits a 16 MiB frame.\n */\n private tooLarge(item: ReportItem): boolean {\n return item.bytes > this.limits.maxBytes || item.bytes + FRAME_OVERHEAD > this.limits.maxFrameBytes\n }\n\n private enqueue(item: ReportItem): boolean {\n const fn = item.init.function_id\n if (this.tooLarge(item)) {\n this.drop(fn, 'TOO_LARGE')\n return false\n }\n if (\n this.items.length >= this.limits.maxItems ||\n this.bytes + this.host.pendingBytes() + item.bytes > this.limits.maxBytes\n ) {\n this.drop(fn, 'BUFFER_FULL')\n return false\n }\n this.items.push(item)\n this.bytes += item.bytes\n this.perFunction.set(fn, (this.perFunction.get(fn) ?? 0) + 1)\n // Indexed before a flush can send it: the flush then drops it from the index.\n this.index(item)\n if (this.items.length >= this.limits.batchItems) this.flush()\n else this.arm(this.limits.lingerMs)\n return true\n }\n\n private arm(ms: number): void {\n if (this.lingerTimer) return\n this.lingerTimer = setTimeout(() => {\n this.lingerTimer = undefined\n this.flush()\n }, ms)\n unrefTimer(this.lingerTimer)\n }\n\n /** Counts a report the SDK dropped (`BUFFER_FULL`, `TOO_LARGE`, `INACTIVE`). */\n drop(functionId: string, reason: string, count = 1): void {\n let byReason = this.drops.get(functionId)\n if (!byReason) {\n byReason = new Map()\n this.drops.set(functionId, byReason)\n }\n byReason.set(reason, (byReason.get(reason) ?? 0) + count)\n }\n\n /** Counts one local invocation (for `localinvocationstats`). */\n recordLocal(functionId: string, ok: boolean, durationMs: number): void {\n let s = this.stats.get(functionId)\n if (!s) {\n s = { count: 0, errors: 0, duration_ms_sum: 0 }\n this.stats.set(functionId, s)\n }\n s.count++\n if (!ok) s.errors++\n s.duration_ms_sum += durationMs\n }\n\n /**\n * Discards a function's buffered items, counted as `INACTIVE`: the\n * function is unregistered, or the engine refused it\n * (`FUNCTION_NAMESPACE_CONFLICT`), so they could never be confirmed.\n */\n discard(functionId: string): void {\n const count = this.perFunction.get(functionId)\n if (!count) return\n this.drop(functionId, 'INACTIVE', count)\n this.setItems(this.items.filter((it) => it.init.function_id !== functionId))\n }\n\n /**\n * Sends what can be sent: items whose function the engine confirmed on the\n * current connection, in frames under the frame limit, while the socket's\n * unwritten bytes stay within the buffer bound. The rest stays.\n */\n flush(): void {\n if (this.lingerTimer) {\n clearTimeout(this.lingerTimer)\n this.lingerTimer = undefined\n }\n if (this.items.length === 0 || !this.host.online()) return\n\n // One status per function, and nothing more to do while every one waits.\n const status = new Map<string, 'ready' | 'wait' | 'gone'>()\n for (const fn of this.perFunction.keys()) status.set(fn, this.host.status(fn))\n if (![...status.values()].some((s) => s !== 'wait')) return\n\n const ready: ReportItem[] = []\n const held: ReportItem[] = []\n for (const item of this.items) {\n const st = status.get(item.init.function_id)\n if (st === 'ready') ready.push(item)\n else if (st === 'wait') held.push(item)\n // The function was unregistered here: its observers are not ours to serve any more.\n else this.drop(item.init.function_id, 'INACTIVE')\n }\n this.setItems(held)\n\n let frame: ReportItem[] = []\n let frameBytes = FRAME_OVERHEAD\n let blocked = false\n const unsent: ReportItem[] = []\n const send = () => {\n if (frame.length === 0) return\n const data = `${FRAME_HEAD}${frame.map((it) => it.json).join(',')}${FRAME_TAIL}`\n // The socket is not draining (its unwritten bytes would pass the bound),\n // or it closed under us: the rest waits in the buffer, in order.\n const pending = blocked ? 0 : this.host.pendingBytes()\n if (blocked || (pending > 0 && pending + frameBytes > this.limits.maxBytes) || !this.host.sendFrame(data)) {\n blocked = true\n unsent.push(...frame)\n }\n frame = []\n frameBytes = FRAME_OVERHEAD\n }\n for (const item of ready) {\n // Cannot happen with the default limits (an item is at most the 8 MiB\n // buffer, `enqueue`), only with a frame limit set below the buffer's.\n if (item.bytes + FRAME_OVERHEAD > this.limits.maxFrameBytes) {\n this.drop(item.init.function_id, 'TOO_LARGE')\n continue\n }\n const separator = frame.length > 0 ? 1 : 0\n if (frameBytes + separator + item.bytes > this.limits.maxFrameBytes) send()\n frameBytes += (frame.length > 0 ? 1 : 0) + item.bytes\n frame.push(item)\n }\n send()\n if (unsent.length > 0) {\n this.requeue(unsent)\n // Try again once the socket had time to drain.\n if (this.host.online()) this.arm(this.limits.lingerMs * 20)\n }\n }\n\n /** Replaces the buffer, keeping the per-function counts and the emit coalescing index in step. */\n private setItems(items: ReportItem[]): void {\n this.items = items\n this.bytes = 0\n this.perFunction.clear()\n this.openEmits.clear()\n for (const item of items) {\n this.bytes += item.bytes\n const fn = item.init.function_id\n this.perFunction.set(fn, (this.perFunction.get(fn) ?? 0) + 1)\n this.index(item)\n }\n }\n\n /** Puts items back at the front of the buffer, within its bounds. */\n private requeue(items: ReportItem[]): void {\n const kept: ReportItem[] = []\n let bytes = this.bytes\n let count = this.items.length\n for (const item of items) {\n if (count >= this.limits.maxItems || bytes + item.bytes > this.limits.maxBytes) {\n this.drop(item.init.function_id, 'BUFFER_FULL')\n continue\n }\n kept.push(item)\n bytes += item.bytes\n count++\n }\n this.setItems([...kept, ...this.items])\n }\n\n /** Sends `localinvocationstats` when there is anything to report; keeps counting while offline. */\n sendStats(now = Date.now()): boolean {\n if (this.stats.size === 0 && this.drops.size === 0) {\n this.windowStart = now\n return false\n }\n if (!this.host.online()) return false\n const message = buildLocalInvocationStats(now - this.windowStart, this.stats, this.drops)\n if (!this.host.sendFrame(JSON.stringify({ type: MessageType.LocalInvocationStats, ...message }))) return false\n this.stats.clear()\n this.drops.clear()\n this.windowStart = now\n return true\n }\n\n /** Forgets everything buffered (the engine does not support observe). */\n clear(): void {\n this.setItems([])\n }\n}\n\n/** `localinvocationstats` from the counters, in insertion order. */\nexport function buildLocalInvocationStats(\n windowMs: number,\n stats: ReadonlyMap<string, FunctionStats>,\n drops: ReadonlyMap<string, ReadonlyMap<string, number>>,\n): Omit<LocalInvocationStatsMessage, 'message_type'> {\n return {\n window_ms: Math.max(0, Math.round(windowMs)),\n functions: [...stats].map(([function_id, s]) => ({\n function_id,\n count: s.count,\n errors: s.errors,\n duration_ms_sum: s.duration_ms_sum,\n })),\n dropped_reports: [...drops].flatMap(([function_id, byReason]) =>\n [...byReason].map(([reason, count]) => ({ function_id, reason, count })),\n ),\n }\n}\n\n/** One item's wire JSON (exported for the fixture tests). */\nexport function encodeReportItem(init: ReportInit): string {\n const { captures, ...rest } = init\n const item = new ReportItem(rest, false, undefined, undefined)\n item.capture(captures)\n item.render()\n return item.json\n}\n","import { ChannelReader, ChannelWriter } from './channels'\nimport {\n DEFAULT_BRIDGE_RECONNECTION_CONFIG,\n DEFAULT_INVOCATION_TIMEOUT_MS,\n EngineFunctions,\n type IIIConnectionState,\n type IIIReconnectionConfig,\n} from './iii-constants'\nimport { InvocationError, RegistrationRejectedError } from './errors'\nimport { compileFilter, FilterError } from './filter'\nimport {\n type ActivationWire,\n type CallerWire,\n type ErrorBody,\n FEATURE_OBSERVE_V1,\n type IIIMessage,\n type InvocationResultMessage,\n MessageType,\n type RegisterFunctionMessage,\n type RegisterTriggerMessage,\n type RegisterTriggerTypeMessage,\n SDK_FEATURES,\n type StreamChannelRef,\n type TriggerRegistrationResultMessage,\n type TriggerRequest,\n} from './iii-types'\nimport {\n type ActiveInvocation,\n callContext,\n callDepth,\n callLocalDepth,\n contextFromView,\n currentContext,\n enterInvocation,\n MAX_LOCAL_DEPTH,\n MAX_OFFLINE_LOCAL_DEPTH,\n MAX_RUNNING_INVOCATION_MS,\n publicContext,\n runInContext,\n trackRunning,\n} from './invocation-context'\nimport { FunctionObservers, OBSERVE_HOOK_TIMEOUT_MS, type ObserveHost } from './observable'\nimport type {\n InvocationContext,\n ObserveHooks,\n ObserverHandle,\n ObserverOptions,\n ObserveSource,\n Target,\n} from './observe-types'\nimport {\n buildInvokeFunction,\n buildObserveMessage,\n buildObserverAck,\n callerFor,\n decodeFunctionRegistered,\n decodeInvokeFunction,\n decodeObserveResult,\n decodeObserverAdded,\n decodeObserverRemoved,\n decodeObserverStateChanged,\n decodeWorkerRegistered,\n observeDescriptor,\n stripCaller,\n} from './observe-wire'\nimport { ObserverHandleImpl, toObserverState } from './observer-handle'\nimport { Reporter, type ReporterLimits } from './reporter'\nimport type { IStream } from './stream'\nimport type { TriggerHandler } from './triggers'\nimport type {\n FunctionRef,\n Invocation,\n ISdk,\n RegisterFunctionOptions,\n RemoteFunctionData,\n RemoteFunctionHandler,\n RemoteTriggerTypeData,\n Trigger,\n TriggerTypeRef,\n} from './types'\nimport { isChannelRef, randomUUID } from './utils'\n\n/** @internal */\nexport type TelemetryOptions = {\n language?: string\n project_name?: string\n framework?: string\n}\n\n// Browser WebSocket APIs expose no control over framing, so outbound JSON is limited to the 16 MiB single-frame size.\nconst MAX_JSON_FRAME_BYTES = 16 * 1024 * 1024\nconst JSON_ENCODER = new TextEncoder()\nconst PAYLOAD_SIZE_DOCS = 'https://iii.dev/docs/creating-workers/channels#payload-size'\n\nfunction payloadTooLargeMessage(size: number): string {\n return `Serialized JSON envelope is ${size} bytes; limit is ${MAX_JSON_FRAME_BYTES} bytes. Use channels for larger payloads: ${PAYLOAD_SIZE_DOCS}`\n}\n\nfunction createPayloadTooLargeError(\n size: number,\n functionId?: string,\n): InvocationError {\n return new InvocationError({\n code: 'payload_too_large',\n message: payloadTooLargeMessage(size),\n function_id: functionId,\n })\n}\n\nfunction isPayloadTooLargeError(error: unknown): error is Error & { code: string } {\n return error instanceof Error && 'code' in error && error.code === 'payload_too_large'\n}\n/**\n * Configuration options passed to {@link registerWorker}.\n *\n * @example\n * ```typescript\n * const worker = registerWorker('ws://localhost:49135', {\n * invocationTimeoutMs: 10000,\n * reconnectionConfig: { maxRetries: 5 },\n * })\n * ```\n */\nexport type InitOptions = {\n /**\n * Name this worker announces to the engine. Defaults to a unique\n * `browser:<random>` per client: a browser has no pid to disambiguate by, and\n * the engine allows only one live worker per name in a namespace, so two tabs\n * sharing a fixed name would evict each other.\n */\n workerName?: string\n /**\n * Namespace this worker registers under. When omitted the engine applies its\n * `default` namespace. Scopes worker and function registrations so\n * identically-named entries can coexist across namespaces. The browser has no\n * `process.env`, so there is no environment-variable fallback: pass the\n * option explicitly.\n */\n namespace?: string\n /** Default timeout for `worker.trigger()` invocations in milliseconds. Defaults to `30000`. */\n invocationTimeoutMs?: number\n /**\n * WebSocket reconnection behavior.\n *\n * @see {@link IIIReconnectionConfig} for available fields and defaults.\n */\n reconnectionConfig?: Partial<IIIReconnectionConfig>\n /** Browser WebSocket connections authenticate via query parameters or cookies; the `headers` option is ignored. */\n headers?: Record<string, string>\n /** @internal Test knobs for the observe hooks and the reporter. */\n observe?: { hookTimeoutMs?: number; reporter?: Partial<ReporterLimits> }\n}\n\n/** Short random suffix; `crypto.randomUUID` is unavailable on insecure origins. */\nfunction randomId(): string {\n const c = globalThis.crypto\n if (c?.randomUUID) {\n return c.randomUUID().slice(0, 8)\n }\n if (c?.getRandomValues) {\n return Array.from(c.getRandomValues(new Uint8Array(4)))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n }\n return Math.random().toString(16).slice(2, 10)\n}\n\n/**\n * The worker's namespace, refusing one that was named and left blank.\n *\n * Absent and blank mean opposite things. Absent asks for the engine's\n * `default`; blank names a namespace and gives nothing to name it with. Read as\n * absent, the worker registers in `default`, and since a worker's calls and\n * triggers follow its namespace, the whole project quietly serves from a place\n * its declaration never named -- the one thing an operator cannot see by\n * reading the declaration.\n *\n * The browser has no `III_NAMESPACE` to fall back to, so unlike the other SDKs\n * there is only the option here, and an option that was written and left empty\n * is never what someone meant.\n */\n/**\n * The namespace one call or one binding resolves in.\n *\n * `undefined` inherits the worker's. A blank one is refused: named and left\n * empty asks for the opposite of what absent asks for, and the two are only\n * ever confused by accident -- `??` forwards the empty string, Python's `or`\n * coerced it and Go dropped it, so one mistake produced three behaviours.\n */\nfunction callNamespace(\n explicit: string | undefined,\n worker: string | undefined,\n source: string,\n): string | undefined {\n if (explicit !== undefined && explicit.trim() === '') {\n throw new Error(\n `namespace is empty: ${source} was set to ${JSON.stringify(explicit)}. ` +\n \"Give it a name, or leave it unset to stay in this worker's namespace.\",\n )\n }\n return explicit ?? worker\n}\n\n/** Resolve one function invocation without leaking engine and configuration builtins into a worker namespace. */\nfunction invocationNamespace(\n explicit: string | undefined,\n worker: string | undefined,\n functionId: string,\n source = 'TriggerRequest.namespace',\n): string | undefined {\n const namespace = callNamespace(explicit, worker, source)\n return explicit === undefined && (functionId.startsWith('engine::') || functionId.startsWith('configuration::'))\n ? 'default'\n : namespace\n}\n\nconst MIGRATION_GUIDE = 'https://iii.dev/docs/upgrading/from-0-24-x'\n\n/** CONTRACT §5: one warning per page per deprecated API. */\nconst DEPRECATIONS = {\n registerTrigger: `registerTrigger is deprecated and will be removed in a future release. Use iii.observe(source, target) instead. Migration guide: ${MIGRATION_GUIDE}`,\n registerTriggerType: `registerTriggerType is deprecated and will be removed in a future release. Register a function with an observe descriptor (registerFunction(id, handler, { observe: { ... } })) instead. Migration guide: ${MIGRATION_GUIDE}`,\n} as const\n\nconst deprecationsWarned = new Set<keyof typeof DEPRECATIONS>()\n\n/**\n * Local dispatch hands the handler a copy of the caller's payload and the\n * caller a copy of the result (value semantics, as over the wire):\n * `structuredClone`, or JSON for what it cannot clone (functions, class\n * instances with methods the clone would drop).\n */\nfunction cloneValue<T>(value: T): T {\n if (value === null || typeof value !== 'object') {\n return (typeof value === 'function' || typeof value === 'symbol' ? undefined : value) as T\n }\n if (typeof structuredClone === 'function') {\n try {\n return structuredClone(value)\n } catch {\n // not cloneable: fall back to what the wire would carry\n }\n }\n const text = JSON.stringify(value)\n return (text === undefined ? undefined : JSON.parse(text)) as T\n}\n\nconst UNSUPPORTED_REASON = {\n code: 'UNSUPPORTED',\n message: 'the engine does not support observe (no observe.v1 in its features); upgrade it to 0.25 or later',\n}\n\n/** `args_format` needs `delivery: 'owner'`: an auto function's events are its invocations, offered to every observer. */\nfunction validateObserveHooks(functionId: string, hooks: ObserveHooks | undefined): void {\n if (!hooks) return\n const delivery = hooks.delivery\n if (delivery !== undefined && delivery !== 'auto' && delivery !== 'owner') {\n throw new InvocationError({\n code: 'INVALID_OBSERVE_DESCRIPTOR',\n message: `observe.delivery must be 'auto' or 'owner', got ${JSON.stringify(delivery)}`,\n function_id: functionId,\n })\n }\n if (hooks.args_format !== undefined && delivery !== 'owner') {\n throw new InvocationError({\n code: 'INVALID_OBSERVE_DESCRIPTOR',\n message: \"observe.args_format requires delivery: 'owner' (an auto function takes no args)\",\n function_id: functionId,\n })\n }\n}\n\n/**\n * The error a call that timed out rejects with, on the remote and the local\n * path: an `Error` (its message unchanged from earlier releases) that also\n * carries `code: 'TIMEOUT'` and the `function_id`, like the Node SDK's.\n */\nfunction timeoutError(ms: number, functionId: string): Error & { code: 'TIMEOUT'; function_id: string } {\n return Object.assign(new Error(`Invocation timeout after ${ms}ms: ${functionId}`), {\n code: 'TIMEOUT' as const,\n function_id: functionId,\n })\n}\n\n/** What an outgoing `invokefunction` carries from the invocation it is made in. */\ntype OutgoingFields = { caller?: CallerWire; observe_depth?: number; traceparent?: string; baggage?: string }\n\n/** What a handler failure reports when the thrown value cannot even be read (a getter or `toString` that throws). */\nconst UNREADABLE_FAILURE = 'the handler failed with a value that cannot be read'\n\nfunction safeString(value: unknown): string {\n try {\n return String(value)\n } catch {\n return UNREADABLE_FAILURE\n }\n}\n\n/**\n * An error body as the engine sends it, and as this SDK's own calls reject\n * with: a plain (JSON-parsed) object with a string `code`, a string `message`\n * and, optionally, a string `stacktrace`. A class instance or anything else\n * with such fields is not one: it is reported through `String()`.\n */\nfunction isEngineErrorBody(value: unknown): value is { code: string; message: string; stacktrace?: string } {\n if (value === null || typeof value !== 'object') return false\n const proto = Object.getPrototypeOf(value)\n if (proto !== Object.prototype && proto !== null) return false\n const body = value as Record<string, unknown>\n return (\n typeof body.code === 'string' &&\n typeof body.message === 'string' &&\n (body.stacktrace === undefined || typeof body.stacktrace === 'string')\n )\n}\n\n/**\n * The error a handler's failure becomes, the same on the local and the remote\n * path (code `invocation_failed`):\n * - an `Error`, from any realm (an iframe's too): its message and stack;\n * - an engine error body (a failed call's rejection, rethrown): its message and stacktrace;\n * - anything else: `String(value)`.\n * Never throws: when reading the value throws, a fixed message is reported, so\n * the caller always gets its answer.\n */\nfunction handlerErrorBody(error: unknown): ErrorBody {\n try {\n if (error instanceof Error || Object.prototype.toString.call(error) === '[object Error]') {\n const { message, stack } = error as Error\n return {\n code: 'invocation_failed',\n message: typeof message === 'string' ? message : safeString(message),\n stacktrace: typeof stack === 'string' ? stack : undefined,\n }\n }\n if (isEngineErrorBody(error)) {\n return { code: 'invocation_failed', message: error.message, stacktrace: error.stacktrace }\n }\n return { code: 'invocation_failed', message: String(error), stacktrace: undefined }\n } catch {\n return { code: 'invocation_failed', message: safeString(error), stacktrace: undefined }\n }\n}\n\nfunction resolveNamespace(optionNamespace?: string): string | undefined {\n if (optionNamespace !== undefined && optionNamespace.trim() === '') {\n throw new Error(\n `namespace is empty: options.namespace was set to ${JSON.stringify(optionNamespace)}. ` +\n 'Give it a name, or leave it unset to register in `default`.',\n )\n }\n return optionNamespace\n}\n\nclass Sdk implements ISdk {\n private ws?: WebSocket\n private functions = new Map<string, RemoteFunctionData>()\n private invocations = new Map<string, Invocation & { timeout?: ReturnType<typeof setTimeout> }>()\n private triggers = new Map<string, RegisterTriggerMessage>()\n private triggerTypes = new Map<string, RemoteTriggerTypeData>()\n private messagesToSend: Record<string, unknown>[] = []\n private reconnectTimeout?: ReturnType<typeof setTimeout>\n private invocationTimeoutMs: number\n private reconnectionConfig: IIIReconnectionConfig\n private reconnectAttempt = 0\n private connectionState: IIIConnectionState = 'disconnected'\n private connectionListeners = new Set<(state: IIIConnectionState) => void>()\n private isShuttingDown = false\n private readonly workerName: string\n private readonly namespace?: string\n private workerId?: string\n private reattachToken?: string\n private fatalError?: RegistrationRejectedError\n // Observers this worker created, replayed (same id) on every connection.\n private observers = new Map<string, ObserverHandleImpl>()\n // The engine's features (`WorkerRegistered.features`), kept across a\n // disconnect until the next `WorkerRegistered` replaces them.\n private engineFeatures: ReadonlySet<string> = new Set()\n // `WorkerRegistered` arrived on the current connection.\n private registeredOnConnection = false\n // Bumped on every connection: `functionregistered` confirms a function on one.\n private connectionEpoch = 0\n private hooksInactiveWarned = new Set<string>()\n // Observe-family frames waiting for the next `WorkerRegistered` (see sendObserveFamily).\n private observeQueue: Record<string, unknown>[] = []\n private readonly reporter: Reporter\n private readonly observeHost: ObserveHost\n\n constructor(\n private readonly address: string,\n private readonly options?: InitOptions,\n ) {\n this.workerName = options?.workerName ?? `browser:${randomId()}`\n // No env fallback: the browser has no `process.env`, so the option is the\n // only source -- and the only thing that can be wrong.\n this.namespace = resolveNamespace(options?.namespace)\n this.invocationTimeoutMs = options?.invocationTimeoutMs ?? DEFAULT_INVOCATION_TIMEOUT_MS\n this.reconnectionConfig = {\n ...DEFAULT_BRIDGE_RECONNECTION_CONFIG,\n ...options?.reconnectionConfig,\n }\n\n this.reporter = new Reporter(\n {\n online: () => this.observeOnline(),\n status: (functionId) => {\n const state = this.functions.get(functionId)?.observe\n if (!state || state.releasedEpoch === this.connectionEpoch) return 'gone'\n return state.confirmedEpoch === this.connectionEpoch ? 'ready' : 'wait'\n },\n sendFrame: (data) => {\n if (!this.isOpen()) return false\n this.sendMessageRaw(data)\n return true\n },\n // Handed to the socket and not written yet: counts against the reporter's bound.\n pendingBytes: () => this.ws?.bufferedAmount ?? 0,\n logError: (message, error) => this.logError(message, error),\n },\n options?.observe?.reporter,\n )\n this.observeHost = {\n identity: () =>\n this.workerId !== undefined\n ? { worker_id: this.workerId, worker_name: this.workerName }\n : { worker_name: this.workerName },\n sendAck: (ack) => this.sendMessage(MessageType.ObserverAck, buildObserverAck(ack), true),\n reporter: this.reporter,\n callTarget: (target, observerId, payload, timeoutMs) =>\n this.invokeRemote({ function_id: target, payload, timeoutMs }, undefined, {\n observer_id: observerId,\n }),\n logError: (message, error) => this.logError(message, error),\n hookTimeoutMs: () => options?.observe?.hookTimeoutMs ?? OBSERVE_HOOK_TIMEOUT_MS,\n // No OpenTelemetry here: an event emitted outside any handler starts no trace.\n traceContext: () => ({}),\n }\n\n this.reporter.start()\n this.connect()\n }\n\n private warnDeprecated(api: keyof typeof DEPRECATIONS): void {\n if (deprecationsWarned.has(api)) return\n deprecationsWarned.add(api)\n console.warn(`[iii] ${DEPRECATIONS[api]}`)\n }\n\n private logError(message: string, error?: unknown): void {\n if (error === undefined) console.error(`[iii] ${message}`)\n else console.error(`[iii] ${message}`, error)\n }\n\n /**\n * Registers a custom trigger type with the engine. A trigger type defines\n * how external events (HTTP, cron, queue, etc.) map to function invocations.\n *\n * @deprecated Register a function with an observe descriptor instead:\n * `registerFunction(id, handler, { observe: { delivery: 'owner', onObserverAdded, onObserverRemoved } })`.\n * Logs a warning once per page. Migration guide: https://iii.dev/docs/upgrading/from-0-24-x\n *\n * @param triggerType - Trigger type registration input.\n * @param triggerType.id - Unique trigger type identifier.\n * @param triggerType.description - Human-readable description.\n * @param handler - Handler with `registerTrigger` / `unregisterTrigger` callbacks.\n *\n * @example\n * ```typescript\n * worker.registerTriggerType(\n * { id: 'my-trigger', description: 'Custom trigger' },\n * {\n * async registerTrigger({ id, function_id, config }) { },\n * async unregisterTrigger({ id, function_id, config }) { },\n * },\n * )\n * ```\n */\n registerTriggerType = <TConfig>(\n triggerType: Omit<RegisterTriggerTypeMessage, 'message_type'>,\n handler: TriggerHandler<TConfig>,\n ): TriggerTypeRef<TConfig> => {\n this.warnDeprecated('registerTriggerType')\n const message = this.snapshotRegistration<RegisterTriggerTypeMessage>({\n ...triggerType,\n message_type: MessageType.RegisterTriggerType,\n })\n this.sendMessage(MessageType.RegisterTriggerType, message, true)\n this.triggerTypes.set(message.id, {\n message,\n handler,\n })\n\n return {\n id: message.id,\n // Pairs a function with its trigger, so it defaults the trigger's namespace\n // to this worker's — otherwise the function lands in the worker's namespace\n // and the trigger in `default`, never resolving it. The low-level\n // `registerTrigger` keeps the engine default (`default`).\n registerTrigger: (functionId: string, config: TConfig) => {\n return this.registerTrigger({\n type: message.id,\n function_id: functionId,\n config,\n namespace: this.namespace,\n })\n },\n registerFunction: (functionId, handler, config) => {\n const ref = this.registerFunction(functionId, handler)\n this.registerTrigger({\n type: message.id,\n function_id: functionId,\n config,\n namespace: this.namespace,\n })\n return ref\n },\n unregister: () => {\n this.unregisterTriggerType(message)\n },\n }\n }\n\n /**\n * Unregisters a previously registered trigger type.\n *\n * @deprecated Trigger types are replaced by functions with an observe\n * descriptor; unregister the function instead. Migration guide:\n * https://iii.dev/docs/upgrading/from-0-24-x\n *\n * @param triggerType - The trigger type to unregister (must match the `id` used during registration).\n */\n unregisterTriggerType = (triggerType: Omit<RegisterTriggerTypeMessage, 'message_type'>): void => {\n // The engine reads `{ id, namespace? }` (sdk/fixtures/protocol/observe/unregistertriggertype.json).\n const { id, namespace } = triggerType as { id: string; namespace?: string }\n this.sendMessage(MessageType.UnregisterTriggerType, namespace !== undefined ? { id, namespace } : { id }, true)\n this.triggerTypes.delete(id)\n }\n\n /**\n * Binds a trigger configuration to a registered function. When the trigger\n * fires, the engine invokes the target function.\n *\n * @deprecated Use `iii.observe(source, target)` instead. Logs a warning once\n * per page. Migration guide: https://iii.dev/docs/upgrading/from-0-24-x\n *\n * @param trigger - Trigger registration input.\n * @param trigger.type - Trigger type (e.g. `http`, `durable:subscriber`, `cron`).\n * @param trigger.function_id - ID of the function to invoke.\n * @param trigger.config - Trigger-specific configuration.\n * @returns A {@link Trigger} handle with an `unregister()` method.\n *\n * @example\n * ```typescript\n * const trigger = worker.registerTrigger({\n * type: 'http',\n * function_id: 'greet',\n * config: { api_path: '/greet', http_method: 'GET' },\n * })\n *\n * // Later...\n * trigger.unregister()\n * ```\n */\n registerTrigger = (trigger: Omit<RegisterTriggerMessage, 'message_type' | 'id'>): Trigger => {\n this.warnDeprecated('registerTrigger')\n const id = randomUUID()\n const fullTrigger = this.snapshotRegistration<RegisterTriggerMessage>({\n ...trigger,\n id,\n message_type: MessageType.RegisterTrigger,\n // Unset means this worker's namespace, not the engine's default. A\n // trigger names a function, and the function a worker registers lands in\n // the worker's namespace, so defaulting anywhere else registers a trigger\n // that fires and resolves nothing. Naming another namespace, `default`\n // included, stays a matter of saying so.\n ...(() => {\n const namespace = callNamespace(\n trigger.namespace,\n this.namespace,\n 'RegisterTriggerInput.namespace',\n )\n return namespace !== undefined ? { namespace } : {}\n })(),\n })\n this.sendMessage(MessageType.RegisterTrigger, fullTrigger, true)\n this.triggers.set(id, fullTrigger)\n\n return {\n unregister: () => {\n this.sendMessage(MessageType.UnregisterTrigger, {\n id,\n message_type: MessageType.UnregisterTrigger,\n type: fullTrigger.type,\n })\n this.triggers.delete(id)\n },\n }\n }\n\n /**\n * Registers a function with the engine. The `functionId` is the unique identifier\n * used by triggers and invocations.\n *\n * The handler runs locally in the browser session; HTTP invocation configs\n * are a Node.js SDK feature and are not accepted here. It receives the\n * payload and the invocation's metadata.\n *\n * Every function is observable. `options.observe` makes it observable on\n * its own terms (owner delivery, hooks when an observer is added or\n * removed), and calls this worker makes to it run in-process once the\n * engine confirmed it, unless `options.localDispatch` is `false`.\n *\n * @param functionId - Unique function identifier.\n * @param handlerOrInvocation - Async handler executed when the function is invoked.\n * @param options - Optional function registration options (description, request/response formats, metadata, observe hooks, localDispatch).\n * @returns A {@link FunctionRef} with `id`, `unregister()`, `isObserved()` and `observers()`.\n *\n * @example\n * ```typescript\n * const fn = worker.registerFunction(\n * 'greet',\n * async (input: { name: string }) => {\n * return { message: `Hello, ${input.name}!` }\n * },\n * { description: 'Greets a user' },\n * )\n * ```\n */\n registerFunction = (\n functionId: string,\n handlerOrInvocation: RemoteFunctionHandler,\n options?: RegisterFunctionOptions,\n ): FunctionRef => {\n if (!functionId || functionId.trim() === '') {\n throw new Error('id is required')\n }\n if (this.functions.has(functionId)) {\n throw new Error(`function id already registered: ${functionId}`)\n }\n\n // The hooks stay here; only the descriptor's four fields travel, and\n // `localDispatch` is this SDK's alone.\n const { observe: hooks, localDispatch, ...wireOptions } = options ?? {}\n validateObserveHooks(functionId, hooks)\n const descriptor = observeDescriptor(hooks)\n const fullMessage = this.snapshotRegistration<RegisterFunctionMessage>({\n ...wireOptions,\n ...(descriptor ? { observe: descriptor } : {}),\n id: functionId,\n message_type: MessageType.RegisterFunction,\n })\n\n this.sendMessage(MessageType.RegisterFunction, fullMessage, true)\n\n const observe = new FunctionObservers(functionId, hooks, localDispatch !== false, true, this.observeHost)\n if (observe.needsObserve && this.registeredOnConnection && !this.engineFeatures.has(FEATURE_OBSERVE_V1)) {\n this.warnHooksInactive(functionId)\n }\n\n const handler = handlerOrInvocation as RemoteFunctionHandler\n this.functions.set(functionId, {\n message: fullMessage,\n observe,\n handler: async (input, metadata?: unknown) => {\n return await handler(input, metadata)\n },\n })\n\n return {\n id: functionId,\n unregister: () => {\n // A stale ref (the id was unregistered and registered again) must not\n // touch the registration that replaced it: nothing to do.\n if (this.functions.get(functionId)?.observe !== observe) return\n this.sendMessage(MessageType.UnregisterFunction, { id: functionId }, true)\n this.functions.delete(functionId)\n observe.dispose()\n },\n isObserved: () => observe.isObserved(),\n observers: () => observe.observers(),\n }\n }\n\n /**\n * Observes a function: every event of `source` (an invocation of an auto\n * function, or what its owner hands over) that passes `source.filters`\n * invokes `target`, a registered function.\n *\n * Returns synchronously, also before the connection is up; the observer is\n * replayed with the same id on every reconnect. Errors (`INVALID_ARGS`,\n * `INVALID_FILTER`, `FORBIDDEN`, an owner's rejection, `UNSUPPORTED` against\n * an engine without observe) show up as state `error` and reject `ready()`.\n *\n * @param source - What is observed: `function_id`, `args` (owner-delivered\n * functions only), `filters`, and `on` / `capture` / `deliver`.\n * @param target - The function to invoke (registered first; until then the observer is `pending`).\n * @param options - Policy and metadata: `id`, `max_fires`, `expires_in_ms`, `max_in_flight`, `metadata`.\n *\n * @example\n * ```typescript\n * worker.registerFunction('ui::order-shipped', async ({ input }: Observed) => showToast(input))\n *\n * const shipped = worker.observe(\n * { function_id: 'orders::ship', filters: { 'input.customer_id': { $eq: customerId } }, capture: ['input'] },\n * 'ui::order-shipped',\n * )\n * await shipped.ready()\n * // later\n * await shipped.dispose()\n * ```\n */\n observe = (source: ObserveSource, target: Target, options?: ObserverOptions): ObserverHandle => {\n if (!source || typeof source.function_id !== 'string' || source.function_id.trim() === '') {\n throw new Error('observe: source.function_id is required')\n }\n const targetId = typeof target === 'string' ? target : target?.function_id\n if (typeof targetId !== 'string' || targetId.trim() === '') {\n throw new Error('observe: target is required (the id of a registered function)')\n }\n const id = options?.id ?? randomUUID()\n if (this.observers.has(id)) {\n throw new Error(`observe: observer id already in use: ${id}`)\n }\n const onDispose = (h: ObserverHandleImpl) => this.disposeObserver(h)\n const logError = (msg: string, error?: unknown) => this.logError(msg, error)\n // Nothing is sent for an observer that cannot be valid; its handle says why.\n const refused = (reason: { code: string; message: string }) => {\n const handle = new ObserverHandleImpl(\n id,\n { id, source: { function_id: source.function_id }, target: { function_id: targetId } },\n onDispose,\n logError,\n )\n handle.setState('error', reason)\n return handle\n }\n // Validated as written, before JSON could drop or rewrite a clause (an\n // `undefined` operand, `NaN`, a `Date`, a `Map`) and widen the filter.\n if (source.filters !== undefined) {\n try {\n compileFilter(source.filters)\n } catch (error) {\n if (!(error instanceof FilterError)) throw error\n return refused({ code: error.code, message: error.message })\n }\n }\n let message: ReturnType<typeof buildObserveMessage>\n try {\n message = buildObserveMessage(id, source, target, options, (explicit, functionId, field) =>\n invocationNamespace(explicit, this.namespace, functionId, field),\n )\n } catch (error) {\n if (!(error instanceof TypeError)) throw error\n // Not JSON (a BigInt, a cycle in the args or options)\n return refused({ code: 'INVALID_ARGS', message: `observe: the source or options are not JSON: ${error.message}` })\n }\n const handle = new ObserverHandleImpl(id, message, onDispose, logError)\n this.observers.set(id, handle)\n if (this.registeredOnConnection && this.isOpen()) {\n if (this.engineFeatures.has(FEATURE_OBSERVE_V1)) this.sendObserve(handle)\n else handle.setState('error', UNSUPPORTED_REASON)\n }\n return handle\n }\n\n /**\n * The invocation the calling code runs in (in every handler, remote or\n * local), or `undefined` outside any handler.\n *\n * Browsers have no `AsyncLocalStorage`: it is known while the handler runs\n * synchronously, up to its first `await`. Read it first and re-enter it with\n * {@link withInvocation} for what the handler does after an `await`. Calls\n * made after an `await` without it still carry the deepest running\n * invocation's `observe_depth`, so the loop guard holds (see `withInvocation`).\n *\n * @example\n * ```typescript\n * worker.registerFunction('ui::checkout', async (cart) => {\n * const inv = worker.currentInvocation() // { function_id, invocation_id, caller, observe_depth, ... }\n * const quote = await fetchQuote(cart)\n * return worker.withInvocation(inv, () => worker.trigger({ function_id: 'orders::create', payload: quote }))\n * })\n * ```\n */\n currentInvocation = (): InvocationContext | undefined => publicContext(currentContext())\n\n /**\n * Runs `fn` inside `invocation` (what {@link currentInvocation} returned) and\n * returns its result: the calls `fn` makes before its own first `await`\n * carry that invocation's caller, `observe_depth` and `traceparent`. When\n * `fn` returns a promise, the invocation counts as running until it settles.\n * `undefined` runs `fn` outside any invocation.\n *\n * Code after an `await`, outside `withInvocation`, runs outside any\n * invocation, but its calls are not treated as new chains: they carry the\n * `observe_depth` of the deepest invocation running on this page, so the\n * engine's loop guard (`max_observe_depth`) still stops an observer cycle\n * whose target awaits before calling back. With several invocations\n * running this over-counts, and a legitimate chain may stop early. They\n * carry a `caller` and `traceparent` only when that is unambiguous (one\n * invocation is running, and it is an observe activation); otherwise none.\n * They never get an invocation's metadata: `obs.emit` / `obs.call` filters\n * on `metadata.*` see it only inside a real scope. An invocation that never\n * settles stops counting as running after 10 minutes (a local call: at its\n * timeout). Local calls nest the same way: a self-recursion that awaits\n * before each call goes through the engine past 64 levels, while calls\n * started together count as one level. A limitation: local calls started in\n * separate ticks while earlier ones still run also look nested, so a long,\n * wide fan-out may send some through the engine (same results). While the\n * socket is closed none is: a function this worker hosts then runs here up\n * to 256 local calls deep, and past that the call fails at once with\n * `LOCAL_DEPTH_EXCEEDED` (a runaway recursion must not freeze the page).\n */\n withInvocation = <T>(invocation: InvocationContext | undefined, fn: () => T): T =>\n enterInvocation(contextFromView(invocation), fn, MAX_RUNNING_INVOCATION_MS)\n\n private sendObserve(handle: ObserverHandleImpl): void {\n this.sendMessage(MessageType.Observe, handle.message, true)\n handle.sent = true\n }\n\n private disposeObserver(handle: ObserverHandleImpl): void {\n if (this.observers.get(handle.id) === handle) this.observers.delete(handle.id)\n if (!handle.sent) return\n this.sendObserveFamily(MessageType.Unobserve, { id: handle.id })\n }\n\n /**\n * An observe-family frame that must not be lost to a disconnect (`unobserve`:\n * a reattach would otherwise keep the observer alive). Without a registered\n * connection it waits for the next `WorkerRegistered`, and goes out only if\n * that engine advertises `observe.v1`.\n */\n private sendObserveFamily(type: MessageType, message: Record<string, unknown>): void {\n if (!this.isOpen() || !this.registeredOnConnection) {\n this.observeQueue.push({ type, ...message })\n } else if (this.engineFeatures.has(FEATURE_OBSERVE_V1)) {\n this.sendMessage(type, message as Omit<IIIMessage, 'message_type'>, true)\n }\n }\n\n private warnHooksInactive(functionId: string): void {\n if (this.hooksInactiveWarned.has(functionId)) return\n this.hooksInactiveWarned.add(functionId)\n console.warn(\n `[iii] Function \"${functionId}\" declares observe hooks or owner delivery, but the engine does not support observe (observe.v1): it is registered as a plain function and its observe hooks are inactive.`,\n )\n }\n\n /** Connected to an engine that advertised `observe.v1`. */\n private observeOnline(): boolean {\n return this.isOpen() && this.registeredOnConnection && this.engineFeatures.has(FEATURE_OBSERVE_V1)\n }\n\n /**\n * @internal Implementation backing the `createChannel` helper in the\n * `iii-browser-sdk/helpers` submodule. Not part of the public `ISdk` surface.\n *\n * Creates a streaming channel pair for worker-to-worker data transfer.\n * Returns a {@link Channel} with a local writer/reader and serializable refs\n * that can be passed as fields in invocation data to other functions.\n */\n __helpers_create_channel = async (bufferSize?: number): Promise<import('./types').Channel> => {\n const result = await this.trigger<{ buffer_size?: number }, { writer: StreamChannelRef; reader: StreamChannelRef }>(\n { function_id: 'engine::channels::create', payload: { buffer_size: bufferSize } },\n )\n\n return {\n writer: new ChannelWriter(this.address, result.writer),\n reader: new ChannelReader(this.address, result.reader),\n writerRef: result.writer,\n readerRef: result.reader,\n }\n }\n\n /**\n * Invokes a remote function. The routing behavior and return type depend\n * on the `action` field of the request.\n *\n * | `action` | Behavior | Return type |\n * |-------------------------------|----------------------------------------------------|----------------------- |\n * | _(none)_ | Synchronous: waits for the function to return | `Promise<TOutput>` |\n * | `TriggerAction.Enqueue(...)` | Async via named queue; engine acknowledges enqueue | `Promise<EnqueueResult>` |\n * | `TriggerAction.Void()` | Fire-and-forget, no response | `Promise<undefined>` |\n *\n * @param request - The trigger request.\n * @param request.function_id - ID of the function to invoke.\n * @param request.payload - Payload to pass to the function.\n * @param request.action - Routing action. Omit for synchronous request/response.\n * @param request.timeoutMs - Override the default invocation timeout.\n * @param request.metadata - Per-invocation metadata, delivered to the handler beside the payload.\n * @param request.traceparent - W3C `traceparent` to continue; defaults to the current invocation's.\n * @param request.dispatch - `remote` forces the engine path for a function this worker hosts.\n * @returns The result of the function invocation.\n *\n * A call to a function this worker registered runs in-process once the\n * engine confirmed it for local dispatch (and puts nothing on the wire\n * unless someone observes the function); `enqueue` and `dispatch: 'remote'`\n * always go through the engine.\n *\n * @example\n * ```typescript\n * import { TriggerAction } from 'iii-browser-sdk'\n *\n * // Synchronous\n * const result = await worker.trigger({ function_id: 'get-order', payload: { id: '123' } })\n *\n * // Enqueue\n * const { messageReceiptId } = await worker.trigger({\n * function_id: 'payments::charge',\n * payload: { orderId: '123', amount: 49.99 },\n * action: TriggerAction.Enqueue({ queue: 'payment' }),\n * })\n *\n * // Fire-and-forget\n * worker.trigger({\n * function_id: 'notifications::send',\n * payload: { userId: '123' },\n * action: TriggerAction.Void(),\n * })\n * ```\n */\n // biome-ignore lint/suspicious/noExplicitAny: TOutput defaults to any so untyped calls type-check (the engine cannot express the return type statically)\n trigger = async <TInput = unknown, TOutput = any>(request: TriggerRequest<TInput>): Promise<TOutput> => {\n const { function_id, action } = request\n // Engine-owned builtins stay in `default`. Other implicit calls stay in\n // this worker's namespace. An explicit request namespace always wins.\n const namespace = invocationNamespace(request.namespace, this.namespace, function_id)\n\n // Local dispatch (sdk.md §3): a function this worker hosts, confirmed by\n // the engine for in-process calls, in the namespace it registered in.\n // `enqueue` expects a queue receipt, so it always goes to the engine, and\n // so does a call already MAX_LOCAL_DEPTH local calls deep. While the socket\n // is closed the engine cannot take it, so it runs here up to\n // MAX_OFFLINE_LOCAL_DEPTH, and past that it fails at once.\n if (request.dispatch !== 'remote' && action?.type !== 'enqueue') {\n const fn = this.functions.get(function_id)\n const observe = fn?.observe\n if (fn?.handler && observe?.localDispatch && (namespace === undefined || namespace === observe.namespace)) {\n const depth = callLocalDepth()\n if (depth < MAX_LOCAL_DEPTH) return this.invokeLocal<TOutput>(function_id, fn.handler, observe, request)\n if (!this.isOpen()) {\n if (depth < MAX_OFFLINE_LOCAL_DEPTH) {\n return this.invokeLocal<TOutput>(function_id, fn.handler, observe, request)\n }\n throw new InvocationError({\n code: 'LOCAL_DEPTH_EXCEEDED',\n message: `${function_id} is called ${depth} local calls deep: past ${MAX_LOCAL_DEPTH} the call needs the engine, and the socket is closed`,\n function_id,\n })\n }\n }\n }\n return this.invokeRemote<TOutput>(request, namespace)\n }\n\n /**\n * What an outgoing call carries from the invocation it is made in: `caller`\n * and `observe_depth` (engines with `observe.v1` only), and the trace\n * context. The browser has no OpenTelemetry, so `traceparent` / `baggage`\n * are the request's own, else the invocation's (see `callContext`), else\n * none. Outside any scope `observe_depth` is the deepest running\n * invocation's (`callDepth`), so the loop guard holds after an `await`.\n */\n private outgoingFields(request: TriggerRequest<unknown>): OutgoingFields {\n const cur = callContext()\n const fields: OutgoingFields = {\n traceparent: request.traceparent ?? cur?.traceparent,\n baggage: request.baggage ?? cur?.baggage,\n }\n if (this.engineFeatures.has(FEATURE_OBSERVE_V1)) {\n if (cur) fields.caller = callerFor(cur)\n fields.observe_depth = cur ? cur.observe_depth : callDepth()\n }\n return fields\n }\n\n /** The routed path: an `InvokeFunction` through the engine. */\n private invokeRemote<TOutput>(\n request: TriggerRequest<unknown>,\n namespace: string | undefined,\n activation?: ActivationWire,\n ): Promise<TOutput> {\n const { function_id, payload, action, timeoutMs, metadata } = request\n const effectiveTimeout = timeoutMs ?? this.invocationTimeoutMs\n const outgoing = this.outgoingFields(request)\n\n if (action?.type === 'void') {\n this.sendMessage(\n MessageType.InvokeFunction,\n buildInvokeFunction({\n function_id,\n data: payload,\n action,\n metadata,\n // Omitted only when this worker has no namespace either.\n namespace,\n ...outgoing,\n activation,\n }) as Omit<IIIMessage, 'message_type'>,\n )\n return Promise.resolve(undefined as TOutput)\n }\n\n const invocation_id = randomUUID()\n\n return new Promise<TOutput>((resolve, reject) => {\n const timeout = setTimeout(() => {\n const invocation = this.invocations.get(invocation_id)\n if (invocation) {\n this.invocations.delete(invocation_id)\n reject(timeoutError(effectiveTimeout, function_id))\n }\n }, effectiveTimeout)\n\n this.invocations.set(invocation_id, {\n resolve: (result: TOutput) => {\n clearTimeout(timeout)\n resolve(result)\n },\n reject: (error: unknown) => {\n clearTimeout(timeout)\n reject(error)\n },\n timeout,\n })\n\n this.sendMessage(\n MessageType.InvokeFunction,\n buildInvokeFunction({\n invocation_id,\n function_id,\n data: payload,\n action,\n metadata,\n // Omitted only when this worker has no namespace either.\n namespace,\n ...outgoing,\n activation,\n }) as Omit<IIIMessage, 'message_type'>,\n )\n })\n }\n\n /**\n * The local path (sdk.md §4.3): runs the handler in-process, with a copy of\n * the payload, inside a new invocation context; the same timeout and the\n * same rejection value as the remote path; reports the call when an\n * observer matches. Puts nothing on the wire when nobody observes the\n * function.\n */\n private invokeLocal<TOutput>(\n function_id: string,\n handler: NonNullable<RemoteFunctionData['handler']>,\n observe: FunctionObservers,\n request: TriggerRequest<unknown>,\n ): Promise<TOutput> {\n const parent = callContext()\n const caller: CallerWire =\n this.workerId !== undefined\n ? { worker_id: this.workerId, worker_name: this.workerName }\n : { worker_name: this.workerName }\n if (parent) {\n caller.function_id = parent.function_id\n caller.invocation_id = parent.invocation_id\n const grandparent = stripCaller(parent.caller)\n if (grandparent && Object.keys(grandparent).length > 0) caller.parent = grandparent\n }\n const ctx: ActiveInvocation = {\n function_id,\n invocation_id: randomUUID(),\n caller,\n observe_depth: parent ? parent.observe_depth : callDepth(),\n metadata: request.metadata,\n localDepth: callLocalDepth() + 1,\n }\n const traceparent = request.traceparent ?? parent?.traceparent\n const baggage = request.baggage ?? parent?.baggage\n if (traceparent !== undefined) ctx.traceparent = traceparent\n if (baggage !== undefined) ctx.baggage = baggage\n\n // The observers this call is evaluated against: those active when it\n // started. None → it is not reported, and its input is not copied for it.\n const set = observe.delivery === 'auto' ? observe.compiled : []\n let input: unknown\n let observedInput: unknown\n let observedMetadata: unknown\n let metadata: unknown\n try {\n // What observers see is the payload and metadata as the caller passed them\n // when the call started, not what the handler or the caller made of them since.\n if (set.length > 0) {\n observedInput = cloneValue(request.payload)\n observedMetadata = request.metadata === undefined ? undefined : cloneValue(request.metadata)\n }\n input = this.resolveChannelValue(cloneValue(request.payload))\n metadata = request.metadata === undefined ? undefined : cloneValue(request.metadata)\n } catch (error) {\n return Promise.reject(error)\n }\n\n const startedAt = Date.now()\n const t0 = performance.now()\n const finish = (ok: boolean, output: unknown, error: ErrorBody | undefined) => {\n try {\n const duration = performance.now() - t0\n this.reporter.recordLocal(function_id, ok, duration)\n observe.reportLocal(set, {\n invocation_id: ctx.invocation_id,\n ok,\n input: observedInput,\n output,\n error,\n caller: ctx.caller,\n metadata: observedMetadata,\n started_at_ms: startedAt,\n duration_ms: duration,\n observe_depth: ctx.observe_depth,\n traceparent,\n baggage,\n })\n } catch (reportError) {\n this.logError(`Failed to report a local invocation of ${function_id}`, reportError)\n }\n }\n\n const effectiveTimeout = request.timeoutMs ?? this.invocationTimeoutMs\n const untrack = trackRunning(ctx, effectiveTimeout)\n let started: Promise<unknown>\n try {\n started = runInContext(ctx, () => handler(input, metadata))\n } catch (error) {\n // Thrown before the handler's body ran (a stack too deep to enter it).\n started = Promise.reject(error)\n }\n const done = started.then(\n (output) => {\n untrack()\n finish(true, output, undefined)\n return output\n },\n (error) => {\n untrack()\n const body = handlerErrorBody(error)\n finish(false, undefined, body)\n // What the remote path rejects with: the handler's error body, as the engine forwards it.\n throw body\n },\n )\n\n if (request.action?.type === 'void') {\n done.catch((error) => this.logError(`Error invoking function ${function_id}`, error))\n return Promise.resolve(undefined as TOutput)\n }\n\n return new Promise<TOutput>((resolve, reject) => {\n // The handler's outcome is handled before anything else can fail here,\n // so it is never left as an unhandled rejection.\n let timeout: ReturnType<typeof setTimeout> | undefined\n done.then(\n (output) => {\n if (timeout !== undefined) clearTimeout(timeout)\n try {\n resolve(cloneValue(output) as TOutput)\n } catch (error) {\n reject(error)\n }\n },\n (error) => {\n if (timeout !== undefined) clearTimeout(timeout)\n reject(error)\n },\n )\n timeout = setTimeout(() => {\n reject(timeoutError(effectiveTimeout, function_id))\n }, effectiveTimeout)\n })\n }\n\n /**\n * @internal Implementation backing the `createStream` helper in the\n * `iii-browser-sdk/helpers` submodule. Not part of the public `ISdk` surface.\n *\n * Registers a custom stream implementation, overriding the engine default\n * for the given stream name.\n *\n * @deprecated __helpers_create_stream is deprecated (iii-stream) and will be removed in an upcoming release. Behavior is unchanged for now. Migration guide: https://iii.dev/docs/upgrading/migrate-from-streams\n */\n __helpers_create_stream = <TData>(streamName: string, stream: IStream<TData>): void => {\n this.registerFunction(`stream::get(${streamName})`, stream.get.bind(stream))\n this.registerFunction(`stream::set(${streamName})`, stream.set.bind(stream))\n this.registerFunction(`stream::delete(${streamName})`, stream.delete.bind(stream))\n this.registerFunction(`stream::list(${streamName})`, stream.list.bind(stream))\n this.registerFunction(`stream::list_groups(${streamName})`, stream.listGroups.bind(stream))\n }\n\n /**\n * The terminal rejection that closed this connection for good, if any. Set\n * only for a non-retryable registration rejection (e.g. a worker-name\n * collision). Mirrors the Node SDK.\n */\n getFatalError = (): RegistrationRejectedError | undefined => this.fatalError\n\n /**\n * Gracefully shutdown the SDK, cleaning up all resources.\n */\n shutdown = async (): Promise<void> => {\n this.isShuttingDown = true\n\n // Last chance for buffered reports and counters to reach the engine.\n try {\n this.reporter.flush()\n this.reporter.sendStats()\n } catch (error) {\n this.logError('Failed to flush observed invocations on shutdown', error)\n }\n this.reporter.stop()\n\n this.clearReconnectTimeout()\n\n for (const [_id, invocation] of this.invocations) {\n if (invocation.timeout) {\n clearTimeout(invocation.timeout)\n }\n invocation.reject(new Error('iii is shutting down'))\n }\n this.invocations.clear()\n\n if (this.ws) {\n this.ws.onopen = null\n this.ws.onclose = null\n // Closing a socket that is still connecting reports an error: ignore it,\n // this is a shutdown. (Without a handler, `ws`, which runs this SDK in\n // Node, throws it as an uncaught exception.)\n this.ws.onerror = () => undefined\n this.ws.onmessage = null\n try {\n this.ws.close()\n } catch {\n // shutting down anyway\n }\n this.ws = undefined\n }\n\n this.setConnectionState('disconnected')\n }\n\n /**\n * Subscribe to connection-state transitions. The handler is fired immediately\n * with the current state, then on every transition. Multiple listeners are\n * supported. Returns an unsubscribe function.\n */\n addConnectionStateListener = (handler: (state: IIIConnectionState) => void): (() => void) => {\n this.connectionListeners.add(handler)\n try {\n handler(this.connectionState)\n } catch (e) {\n console.error('[iii] connection listener threw on initial fire', e)\n }\n return () => {\n this.connectionListeners.delete(handler)\n }\n }\n\n // private methods\n\n private setConnectionState(state: IIIConnectionState): void {\n if (this.connectionState !== state) {\n this.connectionState = state\n for (const handler of this.connectionListeners) {\n try {\n handler(state)\n } catch (e) {\n console.error('[iii] connection listener threw', e)\n }\n }\n }\n }\n\n private connect(): void {\n if (this.isShuttingDown) {\n return\n }\n\n this.setConnectionState('connecting')\n this.ws = new WebSocket(this.address)\n this.ws.onopen = this.onSocketOpen.bind(this)\n this.ws.onclose = this.onSocketClose.bind(this)\n this.ws.onerror = this.onSocketError.bind(this)\n }\n\n private clearReconnectTimeout(): void {\n if (this.reconnectTimeout) {\n clearTimeout(this.reconnectTimeout)\n this.reconnectTimeout = undefined\n }\n }\n\n private scheduleReconnect(): void {\n if (this.isShuttingDown) {\n return\n }\n\n const { maxRetries, initialDelayMs, backoffMultiplier, maxDelayMs, jitterFactor } = this.reconnectionConfig\n\n if (maxRetries !== -1 && this.reconnectAttempt >= maxRetries) {\n this.setConnectionState('failed')\n console.error(`[iii] Max reconnection retries (${maxRetries}) reached, giving up`)\n return\n }\n\n if (this.reconnectTimeout) {\n return\n }\n\n const exponentialDelay = initialDelayMs * backoffMultiplier ** this.reconnectAttempt\n const cappedDelay = Math.min(exponentialDelay, maxDelayMs)\n const jitter = cappedDelay * jitterFactor * (2 * Math.random() - 1)\n const delay = Math.floor(cappedDelay + jitter)\n\n this.setConnectionState('reconnecting')\n console.debug(`[iii] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempt + 1})...`)\n\n this.reconnectTimeout = setTimeout(() => {\n this.reconnectTimeout = undefined\n this.reconnectAttempt++\n this.connect()\n }, delay)\n }\n\n private onSocketError(): void {\n console.error('[iii] WebSocket error')\n }\n\n private onSocketClose(): void {\n if (this.ws) {\n this.ws.onopen = null\n this.ws.onclose = null\n this.ws.onerror = null\n this.ws.onmessage = null\n }\n this.ws = undefined\n // Local dispatch and the compiled observer sets survive; what was sent on\n // this connection is replayed on the next one.\n this.registeredOnConnection = false\n\n // A fatal registration rejection (or shutdown) sets `isShuttingDown` and a\n // terminal state before closing the socket. Do not overwrite that state with\n // `disconnected`, and do not schedule a reconnect the engine would only\n // reject again. `scheduleReconnect` already no-ops while shutting down.\n if (this.isShuttingDown) {\n return\n }\n\n this.setConnectionState('disconnected')\n this.scheduleReconnect()\n }\n\n private onSocketOpen(): void {\n this.clearReconnectTimeout()\n this.reconnectAttempt = 0\n this.setConnectionState('connected')\n this.connectionEpoch++\n this.registeredOnConnection = false\n\n if (this.ws) {\n this.ws.onmessage = this.onMessage.bind(this)\n }\n\n // Reconnect: present the previous engine-assigned identity BEFORE the\n // metadata announce and registration replay so the engine retires the old\n // connection and the replay lands on a clean slate instead of racing its\n // cleanup. This must precede registerWorkerMetadata(): otherwise the old\n // connection still holds this (namespace, worker_name) and the announce\n // would trip WORKER_NAMESPACE_CONFLICT against ourselves. The token proves\n // we ARE that worker (ids alone are publicly listable).\n if (this.workerId) {\n try {\n this.sendMessageRaw(\n JSON.stringify({\n type: MessageType.Reattach,\n previous_worker_id: this.workerId,\n reattach_token: this.reattachToken,\n }),\n )\n } catch (error) {\n if (!isPayloadTooLargeError(error)) throw error\n console.error('[iii] Reattach JSON envelope rejected', error)\n }\n }\n\n // Announce before registering anything. The engine buffers a connection's\n // registrations until it knows the connection's namespace, which it takes\n // from this call — or, failing that, only after a grace period. Registering\n // first would stall every function behind that grace.\n this.registerWorkerMetadata()\n\n this.triggerTypes.forEach(({ message }) => {\n this.replayRegistration(MessageType.RegisterTriggerType, message)\n })\n this.functions.forEach(({ message }) => {\n this.replayRegistration(MessageType.RegisterFunction, message)\n })\n this.triggers.forEach((trigger) => {\n this.replayRegistration(MessageType.RegisterTrigger, trigger)\n })\n // Observers follow the functions (so local targets exist first), once\n // `WorkerRegistered` says whether this engine supports them.\n\n const pending = this.messagesToSend\n this.messagesToSend = []\n for (const message of pending) {\n if (\n message.type === MessageType.InvokeFunction &&\n typeof message.invocation_id === 'string' &&\n !this.invocations.has(message.invocation_id)\n ) {\n continue\n }\n try {\n this.sendMessageRaw(JSON.stringify(message))\n } catch (error) {\n if (!isPayloadTooLargeError(error)) throw error\n console.error('[iii] Queued JSON envelope rejected', error)\n }\n }\n }\n\n private isOpen(): boolean {\n return this.ws?.readyState === WebSocket.OPEN\n }\n\n private snapshotRegistration<T extends object>(message: T): T {\n return JSON.parse(JSON.stringify(message)) as T\n }\n\n private replayRegistration(type: MessageType, message: Omit<IIIMessage, 'message_type'>): void {\n try {\n this.sendMessage(type, message, true)\n } catch (error) {\n if (!isPayloadTooLargeError(error)) throw error\n console.error('[iii] Registration JSON envelope rejected', error)\n }\n }\n\n private prepareJson(message: Record<string, unknown>): string {\n const data = JSON.stringify(message)\n const size = JSON_ENCODER.encode(data).byteLength\n if (size <= MAX_JSON_FRAME_BYTES) return data\n\n const error = createPayloadTooLargeError(\n size,\n typeof message.function_id === 'string' ? message.function_id : undefined,\n )\n if (message.type === MessageType.InvocationResult) {\n // The wire body carries the bare message: `error.message` already has the `code: ` prefix.\n const fallback = JSON.stringify({\n type: MessageType.InvocationResult,\n invocation_id: message.invocation_id,\n function_id: message.function_id,\n error: { code: error.code, message: payloadTooLargeMessage(size) },\n })\n if (JSON_ENCODER.encode(fallback).byteLength <= MAX_JSON_FRAME_BYTES) return fallback\n }\n\n if (typeof message.invocation_id === 'string') {\n const pending = this.invocations.get(message.invocation_id)\n this.invocations.delete(message.invocation_id)\n pending?.reject(error)\n }\n throw error\n }\n\n private sendMessageRaw(data: string): void {\n if (JSON_ENCODER.encode(data).byteLength > MAX_JSON_FRAME_BYTES) {\n data = this.prepareJson(JSON.parse(data) as Record<string, unknown>)\n }\n if (this.ws && this.isOpen()) {\n try {\n this.ws.send(data)\n } catch (error) {\n console.error('[iii] Exception while sending message', error)\n }\n }\n }\n\n private toWireFormat(messageType: MessageType, message: Omit<IIIMessage, 'message_type'>): Record<string, unknown> {\n const { message_type: _, ...rest } = message as Record<string, unknown>\n if (messageType === MessageType.RegisterTrigger && 'type' in message) {\n const { type: triggerType, ...triggerRest } = message as RegisterTriggerMessage\n return { type: messageType, ...triggerRest, trigger_type: triggerType }\n }\n if (messageType === MessageType.UnregisterTrigger && 'type' in message) {\n const { type: triggerType, ...triggerRest } = message as RegisterTriggerMessage\n return { type: messageType, ...triggerRest, trigger_type: triggerType }\n }\n if (messageType === MessageType.TriggerRegistrationResult && 'type' in message) {\n const { type: triggerType, ...resultRest } = message as TriggerRegistrationResultMessage\n return { type: messageType, ...resultRest, trigger_type: triggerType }\n }\n return { type: messageType, ...rest } as Record<string, unknown>\n }\n\n /**\n * Tells the engine who this connection is. Sent on every open, before any\n * registration, so the engine can resolve this connection's namespace and\n * drain its buffered registrations immediately.\n */\n private registerWorkerMetadata(): void {\n this.sendMessage(MessageType.InvokeFunction, {\n function_id: EngineFunctions.REGISTER_WORKER,\n data: {\n runtime: 'browser',\n name: this.workerName,\n os: globalThis.navigator?.userAgent ?? 'browser',\n // Omit when absent so the engine falls back to its `default` namespace.\n ...(this.namespace !== undefined ? { namespace: this.namespace } : {}),\n // Opts this connection into the observe messages (CONTRACT D2).\n features: [...SDK_FEATURES],\n },\n action: { type: 'void' },\n } as unknown as Omit<IIIMessage, 'message_type'>)\n }\n\n private sendMessage(messageType: MessageType, message: Omit<IIIMessage, 'message_type'>, skipIfClosed = false): void {\n const wireMessage = this.toWireFormat(messageType, message)\n const data = this.prepareJson(wireMessage)\n if (this.isOpen()) {\n this.sendMessageRaw(data)\n } else if (!skipIfClosed) {\n this.messagesToSend.push(JSON.parse(data) as Record<string, unknown>)\n }\n }\n\n private onInvocationResult(invocation_id: string, result: unknown, error: unknown): void {\n const invocation = this.invocations.get(invocation_id)\n\n if (invocation) {\n if (invocation.timeout) {\n clearTimeout(invocation.timeout)\n }\n error ? invocation.reject(error) : invocation.resolve(result)\n }\n\n this.invocations.delete(invocation_id)\n }\n\n /**\n * Replaces channel refs with readers / writers. Copy-on-write: a value\n * without refs is returned as it is. Only arrays and plain objects are\n * walked, so a locally dispatched payload keeps its `Date`s, `Map`s and\n * class instances.\n */\n private resolveChannelValue(value: unknown): unknown {\n if (isChannelRef(value)) {\n return value.direction === 'read'\n ? new ChannelReader(this.address, value)\n : new ChannelWriter(this.address, value)\n }\n if (Array.isArray(value)) {\n let out: unknown[] | undefined\n for (let i = 0; i < value.length; i++) {\n const resolved = this.resolveChannelValue(value[i])\n if (resolved !== value[i]) {\n out ??= value.slice()\n out[i] = resolved\n }\n }\n return out ?? value\n }\n if (value !== null && typeof value === 'object') {\n const proto = Object.getPrototypeOf(value)\n if (proto !== Object.prototype && proto !== null) return value\n let out: Record<string, unknown> | undefined\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n const resolved = this.resolveChannelValue(v)\n if (resolved !== v) {\n out ??= { ...(value as Record<string, unknown>) }\n out[k] = resolved\n }\n }\n return out ?? value\n }\n return value\n }\n\n private async onInvokeFunction<TInput>(\n invocation_id: string | undefined,\n function_id: string,\n input: TInput,\n metadata?: unknown,\n traceparent?: string,\n baggage?: string,\n observeFields: {\n caller?: CallerWire\n observe_depth?: number\n activation?: ActivationWire\n } = {},\n ): Promise<unknown> {\n const fn = this.functions.get(function_id)\n\n const resolvedInput = this.resolveChannelValue(input) as TInput\n\n if (fn?.handler) {\n const handler = fn.handler\n // The invocation context every handler sees (`currentInvocation()`), and\n // what the calls it makes carry as their caller and trace context.\n const ctx: ActiveInvocation = {\n function_id,\n invocation_id: invocation_id ?? randomUUID(),\n observe_depth: observeFields.observe_depth ?? 0,\n metadata,\n }\n if (observeFields.caller) ctx.caller = observeFields.caller\n if (observeFields.activation) ctx.activation = observeFields.activation\n if (traceparent !== undefined) ctx.traceparent = traceparent\n if (baggage !== undefined) ctx.baggage = baggage\n // Running until it settles: what code after its `await`s falls back to (`callDepth`).\n const run = async () => {\n const untrack = trackRunning(ctx, MAX_RUNNING_INVOCATION_MS)\n try {\n return await runInContext(ctx, () => handler(resolvedInput, metadata))\n } finally {\n untrack()\n }\n }\n\n // Fire-and-forget (`void`, no invocation id): never answered. Activations\n // carry an id and are answered like any call (CONTRACT D16).\n if (!invocation_id) {\n try {\n await run()\n } catch (error) {\n console.error(`[iii] Error invoking function ${function_id}`, error)\n }\n return\n }\n\n try {\n const result = await run()\n this.sendMessage(MessageType.InvocationResult, {\n invocation_id,\n function_id,\n result,\n traceparent,\n baggage,\n })\n } catch (error) {\n this.sendMessage(MessageType.InvocationResult, {\n invocation_id,\n function_id,\n error: handlerErrorBody(error),\n traceparent,\n baggage,\n })\n }\n } else {\n const errorCode = fn ? 'function_not_invokable' : 'function_not_found'\n const errorMessage = fn ? 'Function is HTTP-invoked and cannot be invoked locally' : 'Function not found'\n if (invocation_id) {\n this.sendMessage(MessageType.InvocationResult, {\n invocation_id,\n function_id,\n error: { code: errorCode, message: errorMessage },\n traceparent,\n baggage,\n })\n }\n }\n }\n\n private async onRegisterTrigger(message: {\n trigger_type: string\n id: string\n function_id: string\n config: unknown\n namespace?: string\n }) {\n const { trigger_type, id, function_id, config, namespace } = message\n const triggerTypeData = this.triggerTypes.get(trigger_type)\n\n if (triggerTypeData) {\n try {\n await triggerTypeData.handler.registerTrigger({ id, function_id, config, namespace })\n this.sendMessage(MessageType.TriggerRegistrationResult, {\n id,\n message_type: MessageType.TriggerRegistrationResult,\n type: trigger_type,\n function_id,\n })\n } catch (error) {\n this.sendMessage(MessageType.TriggerRegistrationResult, {\n id,\n message_type: MessageType.TriggerRegistrationResult,\n type: trigger_type,\n function_id,\n error: { code: 'trigger_registration_failed', message: (error as Error).message },\n })\n }\n } else {\n this.sendMessage(MessageType.TriggerRegistrationResult, {\n id,\n message_type: MessageType.TriggerRegistrationResult,\n type: trigger_type,\n function_id,\n error: { code: 'trigger_type_not_found', message: 'Trigger type not found' },\n })\n }\n }\n\n private async onUnregisterTrigger(message: {\n trigger_type?: string\n id: string\n function_id?: string\n config?: unknown\n }) {\n const trigger_type = message.trigger_type\n if (!trigger_type) return\n\n const triggerTypeData = this.triggerTypes.get(trigger_type)\n if (!triggerTypeData) return\n\n const { id, function_id = '', config } = message\n try {\n await triggerTypeData.handler.unregisterTrigger({ id, function_id, config })\n } catch (error) {\n console.error(`[iii] Error unregistering trigger ${id}`, error)\n }\n }\n\n private onMessage(event: MessageEvent): void {\n let msgType: MessageType\n let message: Record<string, unknown>\n\n try {\n const parsed = JSON.parse(typeof event.data === 'string' ? event.data : '') as Record<string, unknown>\n msgType = parsed.type as MessageType\n const { type: _, ...rest } = parsed\n message = rest\n } catch (error) {\n console.error('[iii] Failed to parse incoming message', error)\n return\n }\n\n if (msgType === MessageType.InvocationResult) {\n const { invocation_id, result, error } = message as InvocationResultMessage\n this.onInvocationResult(invocation_id, result, error)\n } else if (msgType === MessageType.InvokeFunction) {\n const { invocation_id, function_id, data, metadata, traceparent, baggage, caller, observe_depth, activation } =\n decodeInvokeFunction(message)\n this.onInvokeFunction(invocation_id, function_id, data, metadata, traceparent, baggage, {\n caller,\n observe_depth,\n activation,\n })\n } else if (msgType === MessageType.FunctionRegistered) {\n const msg = decodeFunctionRegistered(message)\n // Its reports held across a reconnect are flushed once the set is acked.\n this.functions.get(msg.id)?.observe?.onFunctionRegistered(msg, this.connectionEpoch)\n } else if (msgType === MessageType.ObserverAdded) {\n const msg = decodeObserverAdded(message)\n this.functions.get(msg.function_id)?.observe?.onObserverAdded(msg)\n } else if (msgType === MessageType.ObserverRemoved) {\n const msg = decodeObserverRemoved(message)\n this.functions.get(msg.function_id)?.observe?.onObserverRemoved(msg)\n } else if (msgType === MessageType.ObserveResult) {\n const msg = decodeObserveResult(message)\n if (msg.warnings && msg.warnings.length > 0) {\n console.warn(`[iii] Observer ${msg.id}: ${msg.warnings.join('; ')}`)\n }\n this.onObserverState(msg.id, msg.state, msg.error)\n } else if (msgType === MessageType.ObserverStateChanged) {\n const msg = decodeObserverStateChanged(message)\n this.onObserverState(msg.id, msg.state, msg.reason)\n } else if (msgType === MessageType.RegisterTrigger) {\n this.onRegisterTrigger(message as { trigger_type: string; id: string; function_id: string; config: unknown })\n } else if (msgType === MessageType.UnregisterTrigger) {\n this.onUnregisterTrigger(\n message as { trigger_type?: string; id: string; function_id?: string; config?: unknown },\n )\n } else if (msgType === MessageType.RegistrationRejected) {\n this.onRegistrationRejected(\n message as { code: string; namespace: string; worker_name?: string; function_id?: string; owner_worker_id: string },\n )\n } else if (msgType === MessageType.WorkerRegistered) {\n const { worker_id, reattach_token, features } = decodeWorkerRegistered(message)\n this.workerId = worker_id\n this.reattachToken = reattach_token\n this.onEngineFeatures(features ?? [])\n }\n }\n\n /**\n * `WorkerRegistered` told this connection what the engine supports. With\n * `observe.v1` the observers are replayed (after the functions, sent on\n * open) and held reports flushed; without it `observe()` fails with\n * `UNSUPPORTED` and observe hooks are inactive.\n */\n private onEngineFeatures(features: string[]): void {\n this.engineFeatures = new Set(features)\n this.registeredOnConnection = true\n const queued = this.observeQueue\n this.observeQueue = []\n if (this.engineFeatures.has(FEATURE_OBSERVE_V1)) {\n // What was queued while disconnected (an `unobserve`), then the replay.\n for (const frame of queued) this.sendMessageRaw(JSON.stringify(frame))\n for (const handle of this.observers.values()) this.sendObserve(handle)\n this.reporter.flush()\n return\n }\n for (const handle of this.observers.values()) handle.setState('error', UNSUPPORTED_REASON)\n for (const [functionId, fn] of this.functions) {\n if (fn.observe?.needsObserve) this.warnHooksInactive(functionId)\n }\n this.reporter.clear()\n }\n\n private onObserverState(id: string, wireState: string, reason?: ErrorBody): void {\n const handle = this.observers.get(id)\n if (!handle) return\n const state = toObserverState(wireState)\n handle.setState(state, reason ? { code: reason.code, message: reason.message } : undefined)\n if (state === 'disposed') this.observers.delete(id)\n }\n\n /**\n * The engine rejected a registration. A `FUNCTION_NAMESPACE_CONFLICT` costs\n * one function and leaves the connection open, so log and keep serving. A\n * `WORKER_NAMESPACE_CONFLICT` means another live worker owns this name in the\n * namespace: it is terminal — stop and do not reconnect (otherwise the engine\n * would only reject the same name again, which with `maxRetries: -1` loops\n * forever).\n */\n private onRegistrationRejected(init: {\n code: string\n namespace: string\n worker_name?: string\n function_id?: string\n owner_worker_id: string\n }): void {\n if (init.code === 'FUNCTION_NAMESPACE_CONFLICT') {\n // The engine refused it: no local dispatch, no observers for it here.\n if (init.function_id !== undefined)\n this.functions.get(init.function_id)?.observe?.onRegistrationRejected(this.connectionEpoch)\n console.warn(\n `[iii] Function registration rejected: function \"${init.function_id ?? '<unknown>'}\" in namespace \"${init.namespace}\" is already exported by worker ${init.owner_worker_id}. Staying connected and serving the rest.`,\n )\n return\n }\n\n console.error(\n `[iii] Registration rejected (${init.code}): worker \"${init.worker_name}\" in namespace \"${init.namespace}\" is already owned by ${init.owner_worker_id}. Not reconnecting.`,\n )\n // Terminal: suppress reconnect so neither onSocketClose nor scheduleReconnect\n // revives a connection the engine would only reject again.\n this.isShuttingDown = true\n this.clearReconnectTimeout()\n\n // Reject every in-flight invocation now rather than leaving them to time out.\n const error = new RegistrationRejectedError(init)\n this.fatalError = error\n for (const [, invocation] of this.invocations) {\n if (invocation.timeout) {\n clearTimeout(invocation.timeout)\n }\n invocation.reject(error)\n }\n this.invocations.clear()\n\n // Drop the socket. onSocketClose sees `isShuttingDown` and leaves the\n // terminal `failed` state in place instead of overwriting it.\n this.setConnectionState('failed')\n this.ws?.close()\n }\n}\n\n/**\n * Factory object that constructs routing actions for {@link ISdk.trigger}.\n *\n * @example\n * ```typescript\n * import { TriggerAction } from 'iii-browser-sdk'\n *\n * // Enqueue to a named queue\n * worker.trigger({\n * function_id: 'process',\n * payload: { data: 'hello' },\n * action: TriggerAction.Enqueue({ queue: 'jobs' }),\n * })\n *\n * // Fire-and-forget\n * worker.trigger({\n * function_id: 'notify',\n * payload: {},\n * action: TriggerAction.Void(),\n * })\n * ```\n */\nexport const TriggerAction = {\n /**\n * Routes the invocation through a named queue. The engine enqueues the job,\n * acknowledges the caller with `{ messageReceiptId }`, and processes it\n * asynchronously.\n *\n * @param opts - Queue routing options.\n * @param opts.queue - Name of the target queue.\n */\n Enqueue: (opts: { queue: string }) => ({ type: 'enqueue' as const, ...opts }),\n /**\n * Fire-and-forget routing. The engine forwards the invocation without\n * waiting for a response or queuing the job.\n */\n Void: () => ({ type: 'void' as const }),\n} as const\n\n/**\n * Register the worker with a iii instance, returns a connected worker client.\n * The WebSocket connection is established automatically.\n *\n * @param address - WebSocket URL of the III engine (e.g. `ws://localhost:49135`).\n * @param options - Optional {@link InitOptions} for worker name, timeouts, and reconnection.\n * @returns A connected {@link ISdk} instance.\n *\n * @example\n * ```typescript\n * import { registerWorker } from 'iii-browser-sdk'\n *\n * const worker = registerWorker('ws://localhost:49135')\n * ```\n */\nexport const registerWorker = (address: string, options?: InitOptions): ISdk => new Sdk(address, options)\n"],"mappings":";;;;;;;;AAaA,IAAa,4BAAb,cAA+C,MAAM;CAOnD,YAAY,MAAgC;AAC1C,QACE,GAAG,KAAK,KAAK,8BAA8B,KAAK,gBAAgB,SAAY,aAAa,KAAK,YAAY,KAAK,WAAW,KAAK,eAAe,YAAY,GAAG,iBAAiB,KAAK,UAAU,6BAA6B,KAAK,gBAAgB,GAChP;AACD,OAAK,OAAO;AACZ,OAAK,OAAO,KAAK;AACjB,OAAK,YAAY,KAAK;AACtB,OAAK,cAAc,KAAK;AACxB,OAAK,cAAc,KAAK;AACxB,OAAK,kBAAkB,KAAK;;;;;;;;;;;;;;AAuBhC,IAAa,kBAAb,cAAqC,MAAM;CAKzC,YAAY,MAA2B;AACrC,QAAM,GAAG,KAAK,KAAK,IAAI,KAAK,UAAU;AACtC,OAAK,OAAO;AACZ,OAAK,OAAO,KAAK;AACjB,OAAK,cAAc,KAAK;AACxB,OAAK,aAAa,KAAK;;;;;;;;;;;;;;;;;;AAmB3B,IAAa,mBAAb,cAAsC,MAAM;CAG1C,YAAY,MAAc,SAAiB;AACzC,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,OAAK,OAAO;;;;;;;;;;;;;;;;;;AC1EhB,MAAa,kBAAkB;CAC7B,gBAAgB;CAChB,gBAAgB;CAChB,cAAc;CACd,cAAc;CACd,eAAe;CACf,eAAe;CACf,0BAA0B;CAC1B,0BAA0B;CAC1B,iBAAiB;CAClB;;AAGD,MAAa,iBAAiB,EAC5B,qBAAqB,+BACtB;;AAoBD,MAAa,qCAA4D;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