iii-browser-sdk 0.25.0 → 0.26.0-rc.2

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","../../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;CACvE,gBAAgB;CAChB,YAAY;CACZ,mBAAmB;CACnB,cAAc;CACd,YAAY;CACb;;AAGD,MAAa,gCAAgC;;;;ACp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js","names":["isPlainObject"],"sources":["../src/errors.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/filter-index.ts","../../iii/src/filter/index.ts","../src/iii-constants.ts","../src/iii-types.ts","../src/invocation-context.ts","../src/observable.ts","../src/observe-wire.ts","../src/observer-handle.ts","../src/reporter.ts","../src/iii.ts"],"sourcesContent":["import type { ErrorBody } from './iii-types'\n\nexport 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`: `LOCAL_DEPTH_EXCEEDED` (a local call nested too deep while the\n * socket is closed) and `payload_too_large`. Mirrors the Node SDK.\n *\n * A call the engine answers with an error rejects with the engine's error\n * body (`{ code, message, stacktrace? }`), and so does a locally dispatched\n * call whose handler or deliver hook throws: both paths reject with the same\n * 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 * 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 */\nexport class InvocationTimeoutError extends Error {\n public readonly code = 'TIMEOUT'\n public readonly function_id: string\n\n constructor(ms: number, functionId: string) {\n super(`Invocation timeout after ${ms}ms: ${functionId}`)\n this.function_id = functionId\n }\n}\n\n/** What a 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 */\nexport function 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\n/**\n * The error a deliver hook's failure becomes: an {@link ObserveRejection}, an\n * {@link InvocationError}, a call that timed out ({@link InvocationTimeoutError})\n * or an engine error body (a failed call's rejection, rethrown) keeps its code\n * and message; anything else is a handler failure ({@link handlerErrorBody}).\n * Never throws.\n */\nexport function deliverErrorBody(error: unknown): ErrorBody {\n try {\n if (error instanceof ObserveRejection) return { code: error.code, message: error.message }\n if (error instanceof InvocationError) {\n const prefix = `${error.code}: `\n return {\n code: error.code,\n message: error.message.startsWith(prefix) ? error.message.slice(prefix.length) : error.message,\n stacktrace: error.stacktrace,\n }\n }\n if (error instanceof InvocationTimeoutError) return { code: error.code, message: error.message }\n if (isEngineErrorBody(error)) return { code: error.code, message: error.message, stacktrace: error.stacktrace }\n } catch {\n // reading the value threw: reported as a handler failure\n }\n return handlerErrorBody(error)\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 * iii.onObserverAdded('cron::on-tick', (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","/** 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 * Many filters matched against one document by an index of their equality\n * conditions (decision 55), by the rule of the engine's\n * `iii_filter::FilterIndex`.\n *\n * A filter matches a document only if every clause of its top-level `$and`\n * does. A clause on a path with `$eq` of a scalar (or `$in` of scalars)\n * therefore names the values the document's value at that path must equal.\n * {@link FilterIndex} files each filter under one such condition, path to\n * value to entries, and keeps the filters without one in a list it scans.\n * Matching a document resolves each indexed path once, looks its value up,\n * and evaluates the whole filter of only the entries found there and of the\n * scanned ones: about one lookup per indexed path plus one evaluation per\n * candidate, however many filters the index holds.\n *\n * The index rules out only entries whose condition the document fails, and\n * evaluates every other entry's filter in full, so its matches are exactly\n * the entries that evaluating every filter would yield, in the order of their\n * keys.\n *\n * Values are compared by the filter language's equality, which a `Map`\n * already keys by: numbers by value (`1` and `1.0` are one number, `-0` is\n * `0`), strings by their characters, `null` and booleans as themselves, and a\n * value of one type never equals a value of another. An array or object\n * operand is never indexed: its clause is evaluated with the rest of the\n * filter.\n *\n * Pure TypeScript with no Node.js APIs: the browser SDK uses this file too.\n */\nimport type { CompiledFilter } from './index'\nimport { compilePath, type FilterDoc, parsePath } from './path'\nimport type { JsonView } from './value'\n\n/** A value an equality condition is indexed by. */\ntype Scalar = null | boolean | number | string\n\nfunction isScalar(value: unknown): value is Scalar {\n return value === null || typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string'\n}\n\n/** One `$eq` / `$in` condition of a filter's top-level `$and`: the path must equal one of `values`. */\ntype Condition = { path: string; raw: string; values: Scalar[] }\n\n/**\n * The equality conditions of `source`, a filter that compiled: for each\n * clause of its top-level `$and` (its keys and those of the filters its\n * `$and`s hold, never inside `$or`, `$not` or `$any`), its `$eq` operand or\n * its `$in` operands, when they are scalars. `path` is the parsed path,\n * spelled one way whatever escapes the filter used.\n */\nfunction conditionsOf(source: Record<string, unknown>): Condition[] {\n const out: Condition[] = []\n const pending: unknown[] = [source]\n while (pending.length > 0) {\n const current = pending.pop() as Record<string, unknown>\n for (const key of Object.keys(current)) {\n const value = current[key]\n if (key === '$and') {\n for (const item of value as unknown[]) pending.push(item)\n continue\n }\n if (key.startsWith('$')) continue\n const ops = value as Record<string, unknown>\n const eq = ops.$eq\n const inItems = ops.$in\n const hasEq = Object.prototype.hasOwnProperty.call(ops, '$eq')\n if (!hasEq && !Array.isArray(inItems)) continue\n const parsed = parsePath(key, false)\n const path = JSON.stringify([parsed.root, ...parsed.segments.map((s) => s.key)])\n if (hasEq && isScalar(eq)) out.push({ path, raw: key, values: [eq] })\n if (Array.isArray(inItems) && inItems.length > 0 && inItems.every(isScalar)) {\n out.push({ path, raw: key, values: [...new Set(inItems as Scalar[])] })\n }\n }\n }\n return out\n}\n\ntype Entry<T> = { value: T; filter: CompiledFilter; order: number }\n\n/** The entries filed under one path, by value. */\ntype PathIndex<T> = {\n resolve: (doc: FilterDoc, element: JsonView) => JsonView\n buckets: Map<Scalar, Set<Entry<T>>>\n /** Entries filed here. */\n entries: number\n}\n\n/** Where an entry is filed: under each of `values` of `path`, or (`undefined`) in the scanned list. */\ntype Filed<T> = { entry: Entry<T>; path?: string; values?: Scalar[] }\n\n/**\n * Filters, each with a value and an order, matched against a document by an\n * index of their equality conditions (see the module docs).\n * {@link FilterIndex.matches} returns exactly the values whose filter\n * matches the document (and that `accept` accepts), by ascending `order`.\n */\nexport class FilterIndex<T> {\n private readonly filed = new Map<T, Filed<T>>()\n /** Entries without a condition the index serves. */\n private readonly scanned = new Set<Entry<T>>()\n private readonly paths = new Map<string, PathIndex<T>>()\n /** Entries filed under an indexed path. */\n private indexed = 0\n\n /** Entries held. */\n get size(): number {\n return this.filed.size\n }\n\n /**\n * Whether {@link FilterIndex.matches} can evaluate fewer filters than\n * evaluating each entry's would. Looking a document's value up at an\n * indexed path costs about one evaluation, and rules out the entries filed\n * there under other values, so it can only when some indexed path files\n * more than one entry. Otherwise evaluating each filter in order costs less\n * and yields the same matches.\n */\n get narrows(): boolean {\n return this.indexed > this.paths.size\n }\n\n has(value: T): boolean {\n return this.filed.has(value)\n }\n\n /**\n * Files `value` with `filter`, in place of the entry `value` had. `order`\n * sorts the matches. The condition it is filed under is the one of the\n * filter's top-level `$and` that the fewest entries share now (an `$eq`\n * before an `$in` of several values).\n */\n insert(value: T, filter: CompiledFilter, order: number): void {\n this.remove(value)\n const entry: Entry<T> = { value, filter, order }\n const condition = this.conditionFor(filter)\n if (!condition) {\n this.scanned.add(entry)\n this.filed.set(value, { entry })\n return\n }\n let index = this.paths.get(condition.path)\n if (!index) {\n index = { resolve: compilePath(parsePath(condition.raw, false)), buckets: new Map(), entries: 0 }\n this.paths.set(condition.path, index)\n }\n for (const scalar of condition.values) {\n const bucket = index.buckets.get(scalar)\n if (bucket) bucket.add(entry)\n else index.buckets.set(scalar, new Set([entry]))\n }\n index.entries++\n this.indexed++\n this.filed.set(value, { entry, path: condition.path, values: condition.values })\n }\n\n /** Takes the entry of `value` out. */\n remove(value: T): void {\n const filed = this.filed.get(value)\n if (!filed) return\n this.filed.delete(value)\n if (filed.path === undefined || filed.values === undefined) {\n this.scanned.delete(filed.entry)\n return\n }\n const index = this.paths.get(filed.path)\n if (!index) return\n this.indexed--\n for (const scalar of filed.values) {\n const bucket = index.buckets.get(scalar)\n if (!bucket) continue\n bucket.delete(filed.entry)\n if (bucket.size === 0) index.buckets.delete(scalar)\n }\n if (--index.entries === 0) this.paths.delete(filed.path)\n }\n\n /**\n * The values whose filter matches `doc`, by ascending order. Resolves each\n * indexed path of `doc` once, and evaluates the filters of the entries\n * filed under the value found there and of the scanned entries\n * ({@link FilterIndex.candidates} counts them); every other entry has a\n * condition `doc` fails. `accept` is asked first, for each candidate.\n */\n matches(doc: FilterDoc, accept?: (value: T) => boolean): T[] {\n const found: Entry<T>[] = []\n // Sorted only when found out of order.\n let sorted = true\n let last = -Infinity\n if (this.paths.size > 0) {\n for (const index of this.paths.values()) {\n const bucket = this.bucket(index, doc)\n if (bucket === undefined) continue\n for (const entry of bucket) {\n if ((accept === undefined || accept(entry.value)) && entry.filter.matches(doc)) {\n if (entry.order < last) sorted = false\n last = entry.order\n found.push(entry)\n }\n }\n }\n }\n if (this.scanned.size > 0) {\n for (const entry of this.scanned) {\n if ((accept === undefined || accept(entry.value)) && entry.filter.matches(doc)) {\n if (entry.order < last) sorted = false\n last = entry.order\n found.push(entry)\n }\n }\n }\n if (!sorted) found.sort((a, b) => a.order - b.order)\n const values = new Array<T>(found.length)\n for (let i = 0; i < found.length; i++) values[i] = found[i].value\n return values\n }\n\n /** How many filters a match of `doc` evaluates: the entries filed under its values, and the scanned ones. */\n candidates(doc: FilterDoc): number {\n let n = this.scanned.size\n for (const index of this.paths.values()) n += this.bucket(index, doc)?.size ?? 0\n return n\n }\n\n /**\n * The entries filed under `doc`'s value at the path. A value an index\n * cannot hold (absent, an array, an object) matches no condition, and\n * neither does a path whose reading throws: each filter filed under it\n * holds a clause on that path, and a filter whose reading throws does not\n * match.\n */\n private bucket(index: PathIndex<T>, doc: FilterDoc): Set<Entry<T>> | undefined {\n let value: JsonView\n try {\n value = index.resolve(doc !== null && typeof doc === 'object' ? doc : {}, undefined)\n } catch {\n return undefined\n }\n return isScalar(value) ? index.buckets.get(value) : undefined\n }\n\n private conditionFor(filter: CompiledFilter): Condition | undefined {\n let best: { condition: Condition; score: [number, number, number] } | undefined\n for (const condition of conditionsOf(filter.source)) {\n const held = this.paths.get(condition.path)\n let sharing = 0\n if (held) for (const scalar of condition.values) sharing += held.buckets.get(scalar)?.size ?? 0\n const score: [number, number, number] = [condition.values.length > 1 ? 1 : 0, sharing, condition.values.length]\n if (best === undefined || lessThan(score, best.score)) best = { condition, score }\n }\n return best?.condition\n }\n}\n\nfunction lessThan(a: readonly number[], b: readonly number[]): boolean {\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return a[i] < b[i]\n }\n return false\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 { FilterIndex } from './filter-index'\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","/**\n * Constants for the III module.\n */\n\n/** Engine function paths for internal operations. */\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 REGISTER_WORKER: 'engine::workers::register',\n} as const\n\n/**\n * The event sources the engine hosts: private functions whose handler\n * returns the event, observed with `iii.observe(EngineSources.X, target)`.\n * None takes args; filter on the event (`input`) instead.\n */\nexport const EngineSources = {\n /** A function was registered or unregistered; each row carries `observer_count`. */\n FUNCTIONS_CHANGED: 'engine::on-functions-changed',\n /** A worker connected or left. */\n WORKERS_CHANGED: 'engine::on-workers-changed',\n /** An observer changed state: `{ observer_id, function_id, target, state, reason? }`. */\n OBSERVERS_CHANGED: 'engine::on-observers-changed',\n /** A log record. */\n LOG: 'observability::on-log',\n /** A finished span. */\n SPAN: 'observability::on-span',\n /** The engine's configuration was reloaded. */\n CONFIGURATION_UPDATED: 'configuration::on-updated',\n /** A stream item changed; filter on `input.stream_name`, `input.group_id`. */\n STREAM_CHANGED: 'stream::on-changed',\n /** A client joined a stream group. */\n STREAM_JOIN: 'stream::on-join',\n /** A client left a stream group. */\n STREAM_LEAVE: 'stream::on-leave',\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 type { Observer } from './observe-types'\n\nexport enum MessageType {\n RegisterFunction = 'registerfunction',\n UnregisterFunction = 'unregisterfunction',\n InvokeFunction = 'invokefunction',\n InvocationResult = 'invocationresult',\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 → host: the `registerfunction` ack, with the function's full observer set. */\n FunctionRegistered = 'functionregistered',\n /** Engine → host: one observer attached to a function this connection hosts. */\n ObserverAdded = 'observeradded',\n /** Engine → host: one observer detached. */\n ObserverRemoved = 'observerremoved',\n /** Host → engine: accept (or reject) an added observer. */\n ObserverAck = 'observerack',\n /** Host → engine: the calls of its functions that observers matched, batched. */\n InvocationsObserved = 'invocationsobserved',\n /** Host → 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'\n/**\n * The host delivers the calls of its functions (routed ones included), and\n * functions may set `args_format`, `private`, `observable: false` and\n * `onObserverDeliver`. Includes `observe.v1`.\n */\nexport const FEATURE_OBSERVE_V2 = 'observe.v2'\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_OBSERVE_V2, 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/** Which outcomes of a call reach the observer (`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/** `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 the host of its function sees it: never the observer's\n * metadata, 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 call. */\n filters: Record<string, unknown>\n target: string\n capture: CaptureWire[]\n on: ObserveOnWire\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 local call of a hosted function, with the observers its delivery selected. */\nexport type ObservedItemWire = {\n function_id: string\n namespace?: string\n invocation_id: string\n /** The observers delivered. */\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 /** Absent with `output_is_input`: the engine fills it from `input`. */\n output?: unknown\n /** The handler returned its input; left out when `false`. */\n output_is_input?: boolean\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` | `INACTIVE` (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`, `observe.v2`, `local-dispatch.v1`); absent on engines older than 0.25. */\n features?: string[]\n}\n\n/**\n * The engine refused a registration. `WORKER_NAMESPACE_CONFLICT` is terminal:\n * another live worker owns this name in the namespace. The others cost one\n * function and leave the connection open: `FUNCTION_NAMESPACE_CONFLICT`\n * (another worker hosts the id), `INVALID_ARGS_FORMAT` (its `args_format` is\n * not a valid JSON Schema) and `UNSUPPORTED`.\n */\nexport type RegistrationRejectedMessage = {\n message_type: MessageType.RegistrationRejected\n /** Machine-readable rejection code. */\n code: string\n /** Namespace of the refused registration. */\n namespace: string\n /** Contested worker name. Present only for `WORKER_NAMESPACE_CONFLICT`. */\n worker_name?: string\n /** The refused function. Present on every rejection of one function. */\n function_id?: string\n /** ID of the worker that already owns the contested identity; `\"\"` on a rejection that is not a conflict. */\n owner_worker_id: 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 * Human-readable summary of the function, listed by discovery\n * (`engine::functions::list`).\n */\n description?: string\n /**\n * JSON Schema of the call's input.\n */\n request_format?: RegisterFunctionFormat\n /**\n * JSON Schema of the handler's return value: what the function's observers\n * observe.\n */\n response_format?: RegisterFunctionFormat\n /**\n * Arbitrary metadata attached to the function, stored with it and listed by\n * discovery (`engine::functions::list`). It is distinct from the per-call\n * metadata a handler receives.\n */\n metadata?: Record<string, unknown>\n /**\n * JSON Schema of the `args` an observer of this function passes. The\n * engine validates every observer's args against it (`INVALID_ARGS`)\n * before the added hooks run, and refuses a schema that is not valid\n * (`INVALID_ARGS_FORMAT`). A function without it takes no args.\n */\n args_format?: RegisterFunctionFormat\n /**\n * Only this worker may call the function: the engine answers a call from\n * any other connection with `FORBIDDEN`, and refuses the function as an\n * observer's target. Any worker may observe it, and its observers receive\n * every call this worker makes. For event sources, whose calls from\n * anywhere else would be forged events. This worker's own calls pass the\n * input and the result by reference: the handler and hooks treat both as\n * read-only. Default `false`; sent only when `true`.\n */\n private?: boolean\n /**\n * `false`: nobody may observe the function (`NOT_OBSERVABLE`), for one\n * whose payloads carry credentials. Default `true`; sent only when `false`.\n */\n observable?: boolean\n}\n\n/**\n * Routing action for {@link CallRequest}. 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 CallAction = { type: 'enqueue'; queue: string } | { type: 'void' }\n\n/** @deprecated Use {@link CallAction}, the same type. */\nexport type TriggerAction = CallAction\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 /** 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?: CallAction\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_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 /** Only the registering worker may call the function; always sent. */\n private: boolean\n /** `false`: nobody may observe the function; always sent. */\n observable: boolean\n /** JSON Schema of the args its observers pass; sent when the registration sets it. */\n args_format?: Record<string, unknown>\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 /** Replaces the registration's `private`. */\n private?: boolean\n /** Replaces the registration's `observable`. */\n observable?: boolean\n /** Replaces the registration's `args_format`. */\n args_format?: Record<string, unknown>\n}\n\n/**\n * Result returned when a function is called with `CallAction.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.call}: a function by id, or the target\n * of an observer.\n *\n * @typeParam TInput - Type of the payload.\n */\nexport type CallRequest<TInput = unknown> =\n | {\n /** ID of the function to invoke. */\n function_id: string\n observer?: never\n /** Input data passed to the function. */\n payload: TInput\n /** Sets how the call is routed. Omit for a synchronous request/response. Specify for a specific routing scheme (e.g. `CallAction.Enqueue()`, `CallAction.Void()`). */\n action?: CallAction\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 value). Travels beside the payload: the\n * handler receives it as its second argument, and observer filters read it\n * as `metadata.*`. `null` is the same as no 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 | {\n /**\n * An observer of a function this worker hosts: the call runs the\n * observer's target, with the observer's policy, metadata and loop\n * guard. Only the host of the observed function may call through it\n * (`NOT_FUNCTION_OWNER`).\n */\n observer: Observer\n function_id?: never\n /** Input data passed to the target, as given (the observer's filters are not applied). */\n payload: TInput\n /** `CallAction.Void()` for fire-and-forget. Omit for a synchronous request/response. */\n action?: CallAction\n /** Override the default invocation timeout, in milliseconds. */\n timeoutMs?: number\n /**\n * A call through an observer takes no metadata: its target receives the\n * observer's registration metadata. `call` refuses one that names it.\n */\n metadata?: never\n }\n\n/** @deprecated Use {@link CallRequest}, the same type. */\nexport type TriggerRequest<TInput = unknown> = CallRequest<TInput>\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 * Call action for queue routing or fire-and-forget\n */\n action?: CallAction\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 `call` 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; outbound, marks a call through an observer. */\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 * Host → engine (`observe.v2`): the observers the function's match hook\n * (`onObserverMatch`) matched for this routed call, before their `on` and\n * filters, which the engine evaluates; `[]` when it matched none. Left out\n * by a function without a match hook: the engine then evaluates every\n * active observer of the function.\n */\n matched?: string[]\n /**\n * Host → engine (`observe.v2`): the function's deliver hook\n * (`onObserverDeliver`) delivered this routed call, and the engine\n * activates no observer for it. Sent only as `true`, and without\n * `matched`.\n */\n delivered?: boolean\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 | 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 and its\n * function's deliver hook, remote (`InvokeFunction`) and local (in-process\n * dispatch), and read by outgoing calls (`caller`, `observe_depth`,\n * `traceparent`).\n */\nexport type ActiveInvocation = {\n function_id: string\n invocation_id: string\n caller?: CallerWire\n activation?: ActivationWire\n observe_depth: number\n /** The trace context the invocation arrived with: what the calls 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 * `call()` is that call's caller.\n */\nlet current: ActiveInvocation | undefined\n\n/** The public views handed out, so `withInvocation(view, fn)` restores the invocation they were taken from. */\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/**\n * The invocations whose function's deliver hook is running: code after the\n * hook's `await`s falls back to them (see {@link callContext}).\n */\nconst delivering = new WeakSet<ActiveInvocation>()\n\n/**\n * Marks `ctx` as delivering (its function's deliver hook is running); call\n * the returned function when the hook settles.\n */\nexport function trackDelivering(ctx: ActiveInvocation): () => void {\n delivering.add(ctx)\n return () => {\n delivering.delete(ctx)\n }\n}\n\n/**\n * The invocation a call or a report made now belongs to. Inside a scope, the\n * scope's. Outside any scope (code after an `await`), the running invocation\n * when that is unambiguous: it is the only one running, and it is an observe\n * activation or its function's deliver hook is running (the calls the hook\n * makes after an `await`, through its observers or not). It lends its ids,\n * caller and trace context. Otherwise none, and the call carries no\n * `caller`: the SDK cannot tell which 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 || delivering.has(all[0])) ? all[0] : undefined\n}\n\n/**\n * The `observe_depth` a call 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. */\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/observable.ts by scripts/sync-browser-observe.py; edit those, not this file.\n/**\n * The host side of observe (v2 §4): per-function observer state, the\n * observer hooks of the worker and of the function, the `Observer` object\n * handed to them, matching (the key index, and the index of the filters'\n * equality conditions), and the delivery of each call of a hosted function.\n */\nimport { deliverErrorBody, ObserveRejection } from './errors'\nimport { type CompiledFilter, compileFilter, type FilterDoc, FilterIndex } from './filter'\nimport type { CallerWire, ErrorBody, ObserverInfoWire } from './iii-types'\nimport type {\n AddedHook,\n Call,\n Capture,\n DeliverHook,\n Filter,\n Key,\n MatchHook,\n MatchKeys,\n ObserveReason,\n Observer,\n RemovedHook,\n} from './observe-types'\nimport type { Reporter, ReportInit, ReportValues } from './reporter'\nimport { unrefTimer } from './utils'\n\n/** CONTRACT D11: an observer hook still running after this is `OWNER_TIMEOUT`. */\nexport const OBSERVE_HOOK_TIMEOUT_MS = 30_000\n\n/** The hooks that apply to one function: the worker's, and its own. */\nexport type FunctionHooks = {\n workerAdded?: AddedHook\n workerRemoved?: RemovedHook\n added?: AddedHook\n removed?: RemovedHook\n match?: MatchHook\n deliver?: DeliverHook\n}\n\nexport interface ObserveHost {\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 /** The hooks set for `functionId` now: they are read when they run, so a hook set later applies. */\n hooks(functionId: string): FunctionHooks\n logError(message: string, error?: unknown): void\n logWarn(message: string): void\n hookTimeoutMs(): number\n /** The engine advertised `observe.v2`: report items may carry `output_is_input`. */\n observeV2(): boolean\n}\n\n/** A hook level: the worker's hooks (every function it hosts) or the function's own. */\ntype Level = 'worker' | 'fn'\n\n/**\n * Where an observer stands at one level: `none` (not set up there, or torn\n * down), `bare` (set up while the level had no `onObserverAdded`), `hooked`\n * (its `onObserverAdded` resolved). A level that is set up is torn down\n * exactly once, by its `onObserverRemoved`; for an observer that is not\n * accepted, only its `hooked` levels are (`unwind`).\n */\ntype LevelState = 'none' | 'bare' | 'hooked'\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\n/** Whether `obs` is served with the view `info` announces: its filters, target, capture and `on`. */\nfunction sameView(obs: ObserverImpl, info: ObserverInfoWire): boolean {\n return (\n obs.target === info.target &&\n obs.on === info.on &&\n sameJson(obs.capture, info.capture) &&\n sameJson(obs.filters, info.filters)\n )\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/**\n * Whether two copies of a value hold the same JSON data: primitives, arrays\n * and plain objects, compared member by member in one walk. Any other object\n * (a `Date`, a class instance, a channel reader) is the same only as itself,\n * and so is an object the walk reaches twice (a shared member or a cycle).\n * A local call compares the handler's copy of its input with the copy the\n * delivery took when the call started.\n */\nexport function sameData(a: unknown, b: unknown): boolean {\n const left: unknown[] = [a]\n const right: unknown[] = [b]\n const seen = new Set<object>()\n while (left.length > 0) {\n const x = left.pop()\n const y = right.pop()\n if (x === y || (Number.isNaN(x) && Number.isNaN(y))) continue\n if (x === null || y === null || typeof x !== 'object' || typeof y !== 'object' || seen.has(x)) return false\n seen.add(x)\n if (Array.isArray(x)) {\n if (!Array.isArray(y) || x.length !== y.length) return false\n for (let i = 0; i < x.length; i++) {\n left.push(x[i])\n right.push(y[i])\n }\n continue\n }\n if (Array.isArray(y) || !isPlainObject(x) || !isPlainObject(y)) return false\n const keys = Object.keys(x)\n if (keys.length !== Object.keys(y).length) return false\n for (const key of keys) {\n if (!Object.prototype.hasOwnProperty.call(y, key)) return false\n left.push(x[key])\n right.push(y[key])\n }\n }\n return true\n}\n\nfunction isPlainObject(value: object): value is Record<string, unknown> {\n const proto = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\n/** What filters read from a call; a call without `status` reads as a successful one. */\nfunction filterDoc(call: Partial<Call>): FilterDoc {\n const doc: FilterDoc = { input: call.input, caller: call.caller, metadata: call.metadata }\n if (call.status === 'error') doc.error = call.error\n else doc.output = call.output\n return doc\n}\n\n/**\n * The caller a report item carries: the engine sets `worker_id` and\n * `worker_name` itself, so they are left out (a `parent` keeps its own).\n * Nothing for a call made outside any handler.\n */\nfunction reportCaller(caller: CallerWire | undefined): CallerWire | undefined {\n if (!caller) return undefined\n const { worker_id: _, worker_name: __, ...rest } = caller\n return Object.keys(rest).length > 0 ? rest : undefined\n}\n\n/** The key functions of a match hook given as keys, if it is one. */\nfunction matchKeysOf(hook: MatchHook | undefined): MatchKeys | undefined {\n return hook !== undefined && typeof hook !== 'function' ? hook : undefined\n}\n\nfunction keyList(keys: Key): readonly string[] {\n return typeof keys === 'string' ? [keys] : keys\n}\n\n/** The `Observer` a host 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 on: 'success' | 'error' | 'complete'\n capture: Capture[]\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 active set: delivery reaches it. */\n active = false\n /** @internal When it last joined the active set (`FunctionObservers.activations`). */\n activatedSeq = 0\n /**\n * @internal The host'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?: ObserveReason\n /** @internal Its `onObserverAdded` hooks are running: a `reject()` now is applied by the add, not sent. */\n adding = false\n /** @internal Where it stands at each hook level. */\n readonly levels: Record<Level, LevelState> = { worker: 'none', fn: 'none' }\n /** @internal The keys it is filed under (`onObserverMatch` by keys), computed once. */\n keys?: readonly string[]\n private acceptance: 'pending' | 'accepted' | ObserveReason = 'pending'\n private waiters?: { resolve: () => void; reject: (error: ObserveRejection) => void }[]\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.on = info.on as Observer['on']\n this.capture = info.capture as Capture[]\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.on = info.on as Observer['on']\n this.capture = info.capture as Capture[]\n }\n\n matches(call: Partial<Call>): boolean {\n return onAccepts(this.on, call.status !== 'error') && this.filter.matches(filterDoc(call))\n }\n\n accepted(): Promise<void> {\n const state = this.acceptance\n if (state === 'accepted') return Promise.resolve()\n if (state !== 'pending') return Promise.reject(new ObserveRejection(state.code, state.message))\n return new Promise<void>((resolve, reject) => {\n this.waiters ??= []\n this.waiters.push({ resolve, reject })\n })\n }\n\n reject(code: string, message: string): void {\n this.owner.reject(this, code, message)\n }\n\n /** @internal Acked (`accepted`) or never to be: settles `accepted()`, once. */\n settleAcceptance(outcome: 'accepted' | ObserveReason): void {\n if (this.acceptance !== 'pending') return\n this.acceptance = outcome\n const waiters = this.waiters ?? []\n this.waiters = undefined\n for (const waiter of waiters) {\n if (outcome === 'accepted') waiter.resolve()\n else waiter.reject(new ObserveRejection(outcome.code, outcome.message))\n }\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 on: this.on,\n capture: this.capture,\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 the order the engine announced the observers.\n */\nexport class FunctionObservers {\n /** `functionregistered` arrived (cleared by a refusal). */\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 observer the hooks set up, 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 /**\n * Bumped each time an observer joins the active set. A call reads it with\n * `compiled` when it starts, so matching by keys, which reads the live\n * index, skips the observers that joined after the call started.\n */\n activations = 0\n private queue: Promise<void> = Promise.resolve()\n private disposed = false\n /** Bumped on every release (conflict, unregister): an add whose hooks span 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 /** The key functions the index is built for: the function's match hook, when it is given as keys. */\n private matchKeys?: MatchKeys\n /** Matching by keys: the active observers by key. */\n private index?: Map<string, Set<ObserverImpl>>\n /**\n * The active observers by their filters' equality conditions, in the order\n * they joined the active set (decision 55). It changes with `compiled`, in\n * the same step, and with the filters of a held observer served a new view.\n */\n private readonly filterIndex = new FilterIndex<ObserverImpl>()\n /** A match hook threw: logged once per function. */\n private matchFailureLogged = false\n\n constructor(\n readonly functionId: string,\n private readonly localDispatchOption: boolean,\n private readonly hasHandler: boolean,\n private readonly host: ObserveHost,\n ) {\n this.matchChanged()\n }\n\n get reporter(): Reporter {\n return this.host.reporter\n }\n\n /** @internal */\n observeV2(): boolean {\n return this.host.observeV2()\n }\n\n /**\n * Whether a call would reach anyone. Without a call: any active observer\n * (one load). With a call, on a function matched by keys: an observer filed\n * under one of its keys (one lookup per key). Otherwise the call is not read.\n */\n isObserved(call?: Partial<Call>): boolean {\n if (this.compiled.length === 0) return false\n const keys = this.matchKeys\n const index = this.index\n if (call === undefined || !keys || !index) return true\n for (const key of this.callKeys(keys, call as Call)) {\n if (index.has(key)) return true\n }\n return false\n }\n\n /**\n * The observers of the call's snapshot that want `call` (`onObserverMatch`):\n * all of `snapshot` without a match hook, those of it the predicate accepts,\n * or those filed under one of the call's keys that joined the active set no\n * later than `activations` (the count when the call started), each once. A\n * match hook that throws matches nothing.\n */\n matching(call: Call, snapshot: readonly ObserverImpl[], activations: number): readonly ObserverImpl[] {\n const hook = this.host.hooks(this.functionId).match\n if (hook === undefined) return snapshot\n if (typeof hook === 'function') {\n return snapshot.filter((obs) => {\n try {\n return hook(obs, call) === true\n } catch (error) {\n this.matchFailed(error)\n return false\n }\n })\n }\n const index = this.index\n if (this.matchKeys !== hook || !index) return []\n const found = new Set<ObserverImpl>()\n for (const key of this.callKeys(hook, call)) {\n const filed = index.get(key)\n if (!filed) continue\n for (const obs of filed) if (obs.activatedSeq <= activations) found.add(obs)\n }\n return [...found]\n }\n\n /** The function has a match hook (`onObserverMatch`) now. */\n hasMatchHook(): boolean {\n return this.host.hooks(this.functionId).match !== undefined\n }\n\n /**\n * The active observers whose `on` accepts a call that succeeded (`ok`) or\n * failed and whose filters match `doc`, in the order of `compiled`. Matched\n * through the index of their filters' equality conditions when it narrows\n * them (`FilterIndex.narrows`): the call evaluates the filters of the\n * observers the index does not rule out. Otherwise each observer of\n * `compiled` is evaluated in order, which costs less and yields the same\n * observers in the same order.\n */\n selectActive(doc: FilterDoc, ok: boolean): ObserverImpl[] {\n const index = this.filterIndex\n if (!index.narrows) return this.compiled.filter((obs) => onAccepts(obs.on, ok) && obs.filter.matches(doc))\n return index.matches(doc, (obs) => onAccepts(obs.on, ok))\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 const releases = this.releases\n this.enqueue(async () => {\n try {\n // Released after it arrived: the function is not this worker's, and its set is not applied.\n if (this.releases === releases) 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 const releases = this.releases\n this.enqueue(async () => {\n // Released (refused, withdrawn, unregistered) since it arrived: the\n // function is not this worker's. No hook runs, no ack goes out.\n if (this.disposed || this.releases !== releases || this.releasedEpoch !== undefined) return\n const held = this.known.get(msg.observer.id)\n if (held && this.reack(held, msg.observer, msg.revision, msg.namespace, false)) return\n // New, with other args, or rejected late: a fresh observer (the one held is removed first).\n if (held) await this.remove(held.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 * The engine refused the function (`registrationrejected`), or it no\n * longer holds it here: no local dispatch, no observers, and its held\n * reports are discarded (they could never be confirmed, and would starve\n * 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 * An `onObserverAdded` was set at `level` (the worker's, or this\n * function's): the active observers that were set up without one there are\n * caught up. It runs for each of them, in the hook queue; a throw\n * late-rejects that observer. One warning names the function and how many\n * observers were active without the hook.\n */\n catchUp(level: Level): void {\n if (this.disposed) return\n this.enqueue(async () => {\n const behind = this.compiled.filter((obs) => obs.levels[level] === 'bare')\n if (behind.length === 0) return\n this.host.logWarn(\n `onObserverAdded was set for ${this.functionId} while ${behind.length} observer(s) were active without it; it runs for each of them now`,\n )\n for (const obs of behind) {\n const hook = this.addedHook(level)\n if (!hook) return\n if (!obs.active || obs.levels[level] !== 'bare') continue\n const outcome = await this.runHook(() => hook(obs))\n if (outcome.ok) {\n obs.levels[level] = 'hooked'\n continue\n }\n // Not set up at this level: its teardown is for the other one.\n obs.levels[level] = 'none'\n if (outcome.timedOut) this.undoLate(outcome.late, obs, level)\n this.reject(obs, outcome.code, outcome.message)\n }\n })\n }\n\n /**\n * The function's match hook was set or removed (decision 45). Matching by\n * keys rebuilds the index from the active observers; an observer whose keys\n * cannot be computed is late-rejected.\n */\n matchChanged(): void {\n const keys = matchKeysOf(this.host.hooks(this.functionId).match)\n if (keys === this.matchKeys) return\n this.matchKeys = keys\n this.index = keys ? new Map() : undefined\n for (const obs of this.known.values()) obs.keys = undefined\n for (const obs of this.compiled) {\n const failure = this.prepareKeys(obs)\n if (failure) this.reject(obs, failure.code, failure.message)\n else this.file(obs)\n }\n }\n\n /** The keys of a call; a key function that throws gives none. */\n private callKeys(keys: MatchKeys, call: Call): readonly string[] {\n try {\n return keyList(keys.call(call))\n } catch (error) {\n this.matchFailed(error)\n return []\n }\n }\n\n private matchFailed(error: unknown): void {\n if (this.matchFailureLogged) return\n this.matchFailureLogged = true\n this.host.logError(`onObserverMatch of ${this.functionId} threw; the call matches no observer`, error)\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) this.deactivate(obs)\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(`Observer hook failed for ${this.functionId}`, error)\n })\n }\n\n private addedHook(level: Level): AddedHook | undefined {\n const hooks = this.host.hooks(this.functionId)\n return level === 'worker' ? hooks.workerAdded : hooks.added\n }\n\n private removedHook(level: Level): RemovedHook | undefined {\n const hooks = this.host.hooks(this.functionId)\n return level === 'worker' ? hooks.workerRemoved : hooks.removed\n }\n\n private activate(obs: ObserverImpl): void {\n if (obs.active) return\n obs.active = true\n obs.activatedSeq = ++this.activations\n this.compiled = [...this.compiled, obs]\n this.filterIndex.insert(obs, obs.filter, obs.activatedSeq)\n this.file(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 this.filterIndex.remove(obs)\n this.unfile(obs)\n }\n\n /** Computes the keys `obs` is filed under, once, when the function is matched by keys. */\n private prepareKeys(obs: ObserverImpl): ObserveReason | undefined {\n const keys = this.matchKeys\n if (!keys || obs.keys) return undefined\n try {\n obs.keys = [...new Set(keyList(keys.observer(obs)))]\n return undefined\n } catch (error) {\n return {\n code: 'OBSERVE_REJECTED',\n message: `the keys of observer ${obs.id} of ${this.functionId} could not be computed: ${error instanceof Error ? error.message : String(error)}`,\n }\n }\n }\n\n private file(obs: ObserverImpl): void {\n const index = this.index\n if (!index || !obs.keys) return\n for (const key of obs.keys) {\n const filed = index.get(key)\n if (filed) filed.add(obs)\n else index.set(key, new Set([obs]))\n }\n }\n\n private unfile(obs: ObserverImpl): void {\n const index = this.index\n if (!index || !obs.keys) return\n for (const key of obs.keys) {\n const filed = index.get(key)\n if (!filed) continue\n filed.delete(obs)\n if (filed.size === 0) index.delete(key)\n }\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 /**\n * Diffs the engine's full set against what this SDK holds: the ones it no\n * longer lists are removed, the ones it holds are acked again\n * ({@link FunctionObservers.reack}), and the others are added.\n */\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 held = this.known.get(info.id)\n if (held && this.reack(held, info, revision, namespace, true)) continue\n // New, or with other args: removed, then added as a new observer.\n if (held) await this.remove(info.id)\n await this.add(info, revision, namespace)\n }\n }\n\n /**\n * Acks again, at `revision` and without running any hook, an observer this\n * SDK holds that the engine announced again (decision 44): one with the\n * same args, served from now on with the filters, target, capture and `on`\n * it was announced with (its keys computed again when they changed), or,\n * when `listed` by `functionregistered`, one rejected late, whose rejection\n * is sent again. `false` for an observer to add as a new one after removing\n * the one held: other args, a late rejection announced by `observeradded`,\n * or a view this SDK cannot serve (filters that do not compile, keys that\n * throw).\n */\n private reack(\n held: ObserverImpl,\n info: ObserverInfoWire,\n revision: number,\n namespace: string,\n listed: boolean,\n ): boolean {\n if (held.rejection) {\n if (!listed) return false\n held.revision = revision\n this.ack(info, revision, namespace, held.rejection)\n return true\n }\n if (!sameJson(held.args, info.args)) return false\n if (!sameView(held, info)) {\n let filter = held.filter\n if (!sameJson(held.filters, info.filters)) {\n try {\n filter = compileFilter(info.filters, { trusted: true })\n } catch {\n return false\n }\n }\n const keys = this.viewKeys(held, info, filter)\n if (keys === null) return false\n // Filed again under the keys and the filters of the view it is served with.\n if (held.active) this.unfile(held)\n held.update(info, filter)\n if (keys !== undefined) held.keys = keys\n if (held.active) {\n this.file(held)\n this.filterIndex.insert(held, held.filter, held.activatedSeq)\n }\n }\n held.revision = revision\n this.ack(info, revision, namespace)\n return true\n }\n\n /**\n * The keys `held` is filed under once it takes the view `info` (with\n * `filter`), on a function matched by keys: computed on a copy, so a key\n * function that throws (`null`) leaves `held` as it was. `undefined` when\n * the function is not matched by keys.\n */\n private viewKeys(\n held: ObserverImpl,\n info: ObserverInfoWire,\n filter: CompiledFilter,\n ): readonly string[] | null | undefined {\n const keys = this.matchKeys\n if (!keys) return undefined\n const view: ObserverImpl = Object.assign(Object.create(Object.getPrototypeOf(held)), held)\n view.update(info, filter)\n try {\n return [...new Set(keyList(keys.observer(view)))]\n } catch {\n return null\n }\n }\n\n /** handleAdded (§4.3): the hooks of both levels, then the active 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 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 obs.adding = true\n const failure = await this.setUp(obs)\n obs.adding = false\n if (failure) {\n this.ack(info, revision, namespace, failure)\n obs.settleAcceptance(failure)\n return\n }\n // Released while the hooks ran: undo what they did; no success ack, not active.\n if (this.disposed || this.releases !== releases) {\n await this.unwind(obs)\n obs.settleAcceptance({\n code: 'OBSERVER_NOT_ACTIVE',\n message: `${this.functionId} was released before observer ${obs.id} was accepted`,\n })\n return\n }\n this.known.set(obs.id, obs)\n // Rejected (`obs.reject`) while its hooks were still running: the rejection wins.\n const rejection = obs.rejection ?? this.prepareKeys(obs)\n if (rejection) {\n obs.rejection = rejection\n this.ack(info, revision, namespace, rejection)\n obs.settleAcceptance(rejection)\n await this.unwind(obs)\n return\n }\n // In the active set before the ack: the first call after `active` is delivered to it.\n this.activate(obs)\n this.ack(info, revision, namespace)\n obs.settleAcceptance('accepted')\n }\n\n /**\n * Runs `onObserverAdded` of the worker, then of the function. When one\n * fails, the levels whose `onObserverAdded` resolved are torn down, and the\n * rejection is returned.\n */\n private async setUp(obs: ObserverImpl): Promise<ObserveReason | undefined> {\n for (const level of ['worker', 'fn'] as const) {\n const hook = this.addedHook(level)\n if (!hook) {\n obs.levels[level] = 'bare'\n continue\n }\n const outcome = await this.runHook(() => hook(obs))\n if (!outcome.ok) {\n if (outcome.timedOut) this.undoLate(outcome.late, obs, level)\n await this.unwind(obs)\n return { code: outcome.code, message: outcome.message }\n }\n obs.levels[level] = 'hooked'\n }\n return undefined\n }\n\n /**\n * Undoes the setup of an observer that is not accepted: `onObserverRemoved`\n * runs only at the levels whose `onObserverAdded` resolved (§4.3), never at\n * a level set up without one.\n */\n private async unwind(obs: ObserverImpl): Promise<void> {\n for (const level of ['worker', 'fn'] as const) {\n if (obs.levels[level] === 'bare') obs.levels[level] = 'none'\n }\n await this.tearDown(obs)\n }\n\n /** Runs `onObserverRemoved` of the function, then of the worker, for each level set up, once. */\n private async tearDown(obs: ObserverImpl): Promise<void> {\n for (const level of ['fn', 'worker'] as const) {\n if (obs.levels[level] === 'none') continue\n obs.levels[level] = 'none'\n await this.runRemoved(obs, level)\n }\n }\n\n /** A timed-out `onObserverAdded` that resolves later is undone by its level's `onObserverRemoved`. */\n private undoLate(late: Promise<unknown>, obs: ObserverImpl, level: Level): void {\n late.then(\n () => this.enqueue(() => this.runRemoved(obs, level)),\n () => undefined, // it failed after all: nothing was set up\n )\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.tearDown(obs)\n }\n\n private async runRemoved(obs: ObserverImpl, level: Level): Promise<void> {\n const hook = this.removedHook(level)\n if (!hook) return\n const outcome = await this.runHook(() => hook(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: `observer 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 /** @internal Late rejection (`obs.reject`, a failed catch-up): inactive at once, then torn down. */\n reject(obs: ObserverImpl, code: string, message: string): void {\n if (obs.adding) {\n // The add acks with it once the hooks return.\n obs.rejection = { code, message }\n return\n }\n if (this.known.get(obs.id) !== obs || obs.rejection) 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 this.enqueue(() => this.tearDown(obs))\n }\n}\n\n/** What one call of a hosted function is delivered from (v2 §4.4). */\nexport type DeliveryInit = {\n /** The handler's call: its input and outcome. */\n call: Call\n /** What the handler threw, when `call.status` is `error`. */\n thrown?: unknown\n /** The function's active observers when the call started. */\n snapshot: readonly ObserverImpl[]\n /** The function's `activations` when the call started, read with `snapshot`. */\n activations: number\n started_at_ms: number\n /** How long the handler ran. */\n duration_ms: number\n observe_depth: number\n traceparent?: string\n baggage?: string\n /**\n * A routed call: the engine evaluates its observers' `on` and filters, and\n * its answer says how it is delivered (`matched`, `delivered`); a local\n * call is delivered here and reported.\n */\n routed: boolean\n}\n\n/**\n * The delivery of one call (v2 §4.4–§4.6, decisions 20, 36, 38, 45, 55): the\n * observers are matched (`onObserverMatch`), then the function's\n * `onObserverDeliver` delivers the call itself, or iii delivers it to the\n * matched observers whose `on` and filters accept it. For a local call the\n * host evaluates `on` and filters and reports the observers delivered in\n * one report item. For a routed call the engine evaluates them: the answer\n * carries the observers the match hook matched (`matched`), or says that\n * the deliver hook delivered the call (`delivered`), or neither for a\n * function with no match hook and no deliver hook.\n */\nexport class Delivery {\n /** A routed call's answer: the ids of the observers its match hook matched, before `on` and filters. */\n matched?: readonly string[]\n /** A routed call's answer: its deliver hook delivered it. */\n delivered = false\n\n constructor(\n private readonly owner: FunctionObservers,\n private readonly init: DeliveryInit,\n ) {}\n\n /** Resolves to what the caller gets back, or rejects with what it gets thrown. */\n async run(deliver: DeliverHook | undefined): Promise<unknown> {\n const { call, snapshot, activations, thrown, routed } = this.init\n const matched = this.owner.matching(call, snapshot, activations)\n if (deliver !== undefined) {\n // Its answer, whatever the hook returns or throws.\n if (routed) this.delivered = true\n return deliver(call, matched)\n }\n if (routed) {\n if (this.owner.hasMatchHook()) this.matched = matched.map((obs) => obs.id)\n } else {\n const selected = this.select(call, matched)\n if (selected.length > 0) this.owner.reporter.push(this.item(call, selected))\n }\n if (call.status === 'error') throw thrown\n return call.output\n }\n\n /**\n * The error body a call answers with for `error`: the handler's own, or\n * what the deliver hook threw ({@link deliverErrorBody}).\n */\n errorBody(error: unknown): ErrorBody {\n const { call, thrown } = this.init\n return error === thrown && call.error ? call.error : deliverErrorBody(error)\n }\n\n /**\n * The matched observers whose `on` and filters accept `call`, in the order\n * of `matched`. Without a match hook `matched` is the call's snapshot; while\n * it is also the active set (no observer joined or left since the call\n * started), {@link FunctionObservers.selectActive} selects them, through\n * the index of the filters' equality conditions when it narrows them.\n * Otherwise each matched observer's filters are evaluated.\n */\n private select(call: Call, matched: readonly ObserverImpl[]): ObserverImpl[] {\n const ok = call.status !== 'error'\n const doc = filterDoc(call)\n if (matched === this.init.snapshot && matched === this.owner.compiled) return this.owner.selectActive(doc, ok)\n return matched.filter((obs) => onAccepts(obs.on, ok) && obs.filter.matches(doc))\n }\n\n /** The report item of a local call delivered to `selected`. */\n private item(call: Call, selected: readonly ObserverImpl[]): ReportInit {\n const init = this.init\n const captures = new Set<string>()\n for (const obs of selected) for (const c of obs.capture) captures.add(c)\n const ok = call.status !== 'error'\n const values: ReportValues = { input: call.input }\n if (ok) values.output = call.output\n else values.error = call.error\n const caller = reportCaller(call.caller)\n if (caller !== undefined) values.caller = caller\n if (call.metadata !== undefined) values.metadata = call.metadata\n return {\n function_id: this.owner.functionId,\n namespace: this.owner.namespace,\n invocation_id: call.invocation_id,\n matched: selected.map((obs) => obs.id),\n status: ok ? 'success' : 'error',\n values,\n captures,\n output_is_input: ok && call.output === call.input && this.owner.observeV2(),\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/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 CallAction,\n CallerWire,\n CaptureWire,\n ErrorBody,\n FunctionRegisteredMessage,\n InvocationResultMessage,\n InvokeFunctionMessage,\n ObserveMessage,\n ObserveResultMessage,\n ObserverAckMessage,\n ObserverAddedMessage,\n ObserverInfoWire,\n ObserverRemovedMessage,\n ObserverStateChangedMessage,\n RegistrationRejectedMessage,\n WorkerRegisteredMessage,\n} from './iii-types'\nimport type { 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 its host 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 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 CallAction\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/**\n * An `invocationresult`. `result: null` is a value; an absent one is a\n * function that returned nothing. `matched` and `delivered` are read as the\n * engine reads them (decision 55): `matched: null` is absent, an array is its\n * string ids (`[]` included), and any other value is `[]`; `delivered` is\n * kept only when it is `true`.\n */\nexport function decodeInvocationResult(v: Raw): Omit<InvocationResultMessage, 'message_type'> {\n const msg: Omit<InvocationResultMessage, 'message_type'> = {\n invocation_id: String(v.invocation_id ?? ''),\n function_id: String(v.function_id ?? ''),\n }\n if (v.result !== undefined) msg.result = v.result\n const error = errorBody(v.error)\n if (error) msg.error = error\n if (typeof v.traceparent === 'string') msg.traceparent = v.traceparent\n if (typeof v.baggage === 'string') msg.baggage = v.baggage\n if (v.matched !== undefined && v.matched !== null) {\n msg.matched = Array.isArray(v.matched) ? v.matched.filter((id): id is string => typeof id === 'string') : []\n }\n if (v.delivered === true) msg.delivered = true\n return msg\n}\n\nexport function decodeRegistrationRejected(v: Raw): Omit<RegistrationRejectedMessage, 'message_type'> {\n const msg: Omit<RegistrationRejectedMessage, 'message_type'> = {\n code: String(v.code ?? ''),\n namespace: String(v.namespace ?? ''),\n owner_worker_id: String(v.owner_worker_id ?? ''),\n }\n if (typeof v.worker_name === 'string') msg.worker_name = v.worker_name\n if (typeof v.function_id === 'string') msg.function_id = v.function_id\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\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?: CallAction\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/**\n * An outbound `invocationresult`: `result` is left out when the function\n * returned nothing (`undefined`). A routed call's answer says how the call\n * is delivered (decision 55): `delivered: true` (its deliver hook delivered\n * it), or `matched` (the observers its match hook matched, `[]` when none),\n * or neither; `delivered` outweighs `matched`, and only one is sent.\n */\nexport function buildInvocationResult(init: {\n invocation_id: string\n function_id: string\n result?: unknown\n error?: ErrorBody\n traceparent?: string\n baggage?: string\n matched?: readonly string[]\n delivered?: boolean\n}): Record<string, unknown> {\n const msg: Record<string, unknown> = { invocation_id: init.invocation_id, function_id: init.function_id }\n if (init.result !== undefined) msg.result = init.result\n if (init.error !== undefined) msg.error = init.error\n if (init.traceparent !== undefined) msg.traceparent = init.traceparent\n if (init.baggage !== undefined) msg.baggage = init.baggage\n if (init.delivered === true) msg.delivered = true\n else if (init.matched !== undefined) msg.matched = [...init.matched]\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/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 /**\n * @internal Sent, and not refused since: the engine may hold it, so\n * disposing it needs an `unobserve`.\n */\n sent = false\n /** @internal The engine's `observeresult` for its `observe` on this connection arrived (decision 56). */\n answered = false\n /**\n * @internal The engine refused its `observe` (an `error` observeresult),\n * the handle's final answer: the engine holds no observer for it, it is\n * not sent again on a later connection, and it keeps its id until\n * disposed.\n */\n refused = 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 the local\n * calls of hosted functions that observers matched, flushed as\n * `invocationsobserved` batches; plus the periodic `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 /**\n * The handler returned its input (`values.output === values.input`): an\n * item that captures both carries `input` once and `\"output_is_input\": true`.\n */\n output_is_input?: boolean\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\nclass ReportItem {\n readonly parts = new Map<ReportPart, string>()\n /** `output` is left out and the engine fills it from `input`. */\n outputIsInput = false\n json = ''\n bytes = 0\n\n constructor(readonly init: Omit<ReportInit, 'captures'>) {}\n\n /** Encodes the parts `captures` asks for. */\n capture(captures: Iterable<string>): void {\n const wanted = new Set(captures)\n const values = this.init.values\n for (const part of PART_ORDER) {\n if (!wanted.has(part) || !(part in values)) continue\n if (part === 'output' && this.init.output_is_input && this.parts.has('input')) {\n this.outputIsInput = true\n continue\n }\n const encoded = encodeJson(values[part])\n if (encoded !== undefined) this.parts.set(part, encoded)\n }\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 if (part === 'input' && this.outputIsInput) s += ',\"output_is_input\":true'\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 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 local call that observers matched. */\n push(init: ReportInit): boolean {\n const { captures, ...rest } = init\n const item = new ReportItem(rest)\n if (!this.build(item, captures)) return false\n return this.enqueue(item)\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 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 in step. */\n private setItems(items: ReportItem[]): void {\n this.items = items\n this.bytes = 0\n this.perFunction.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 }\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)\n item.capture(captures)\n item.render()\n return item.json\n}\n","import { ChannelReader, ChannelWriter } from './channels'\nimport {\n handlerErrorBody,\n InvocationError,\n InvocationTimeoutError,\n ObserveRejection,\n RegistrationRejectedError,\n} from './errors'\nimport { compileFilter, FilterError } from './filter'\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 ActivationWire,\n type CallAction as CallActionType,\n type CallerWire,\n type CallRequest,\n type ErrorBody,\n FEATURE_OBSERVE_V1,\n FEATURE_OBSERVE_V2,\n type IIIMessage,\n type InvocationResultMessage,\n MessageType,\n type RegisterFunctionMessage,\n SDK_FEATURES,\n type StreamChannelRef,\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 trackDelivering,\n trackRunning,\n} from './invocation-context'\nimport {\n Delivery,\n type FunctionHooks,\n FunctionObservers,\n OBSERVE_HOOK_TIMEOUT_MS,\n type ObserveHost,\n type ObserverImpl,\n sameData,\n} from './observable'\nimport type {\n AddedHook,\n Call,\n DeliverHook,\n InvocationContext,\n MatchHook,\n Observer,\n ObserverHandle,\n ObserverOptions,\n ObserveSource,\n RemovedHook,\n Target,\n} from './observe-types'\nimport {\n buildInvocationResult,\n buildInvokeFunction,\n buildObserveMessage,\n buildObserverAck,\n callerFor,\n decodeFunctionRegistered,\n decodeInvokeFunction,\n decodeObserveResult,\n decodeObserverAdded,\n decodeObserverRemoved,\n decodeObserverStateChanged,\n decodeRegistrationRejected,\n decodeWorkerRegistered,\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 {\n FunctionRef,\n Invocation,\n ISdk,\n RegisterFunctionOptions,\n RemoteFunctionData,\n RemoteFunctionHandler,\n} from './types'\nimport { isChannelRef, randomUUID, unrefTimer } 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(size: number, functionId?: string): 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/**\n * `registrationrejected` code (engine `protocol.rs`): another live worker\n * already holds this `(namespace, worker_name)`. The engine closes the\n * connection -- fatal.\n */\nconst WORKER_NAMESPACE_CONFLICT = 'WORKER_NAMESPACE_CONFLICT'\n\n/**\n * `registrationrejected` code (engine `protocol.rs`): another live worker in\n * this namespace already exports this one function id. The connection stays\n * open -- non-fatal.\n */\nconst FUNCTION_NAMESPACE_CONFLICT = 'FUNCTION_NAMESPACE_CONFLICT'\n\n/**\n * `registrationrejected` codes that refuse one function only (decisions 1,\n * 11): its `args_format` is not a valid JSON Schema, or the engine does not\n * support what it declares. The connection stays open -- non-fatal.\n */\nconst FUNCTION_REJECTIONS: ReadonlySet<string> = new Set(['INVALID_ARGS_FORMAT', 'UNSUPPORTED'])\n\n/** A standby function retries its registration this often (decision 21), ±20 %. */\nconst STANDBY_RETRY_MS = 1000\n\n/** Why `call` refuses a call through an observer that names metadata (v2 §4.6, decision 53); the same in every SDK. */\nconst OBSERVER_CALL_METADATA =\n \"a call through an observer takes no metadata; its target receives the observer's metadata\"\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.call()` 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 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(explicit: string | undefined, worker: string | undefined, source: string): 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 = 'CallRequest.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\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/** 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/** A call the engine routes: by function id, or to the target of an observer (`activation`). */\ntype RemoteRequest = {\n function_id: string\n payload: unknown\n action?: CallActionType\n timeoutMs?: number\n metadata?: unknown\n traceparent?: string\n baggage?: string\n}\n\n/** How a handler finished: what it returned, or what it threw. */\ntype HandlerOutcome = { ok: true; value: unknown } | { ok: false; error: unknown }\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 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 // until the engine refuses one: the handle that holds each id (decision 56).\n private observerHandles = new Map<string, ObserverHandleImpl>()\n // Per id, the handles whose `observe` went out on this connection, oldest\n // first: the engine's answers name an id, and their order says which of\n // them each answer is about (decision 56). A disposed handle leaves once it\n // has its `observeresult`; the holder of the id is the last.\n private observesSent = 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 // Observer hooks of every function this worker hosts.\n private workerHooks: { added?: AddedHook; removed?: RemovedHook } = {}\n // Observer hooks by function id: they outlive a registration of the id.\n private functionHooks = new Map<\n string,\n { added?: AddedHook; removed?: RemovedHook; match?: MatchHook; deliver?: DeliverHook }\n >()\n private hooksInactiveWarned = new Set<string>()\n private unsupportedWarned = new Set<string>()\n private unregisteredHooksWarned = new Set<string>()\n // Standby functions waiting for their id to be free, by function id.\n private standbyTimers = new Map<string, ReturnType<typeof setTimeout>>()\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 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 sendAck: (ack) => this.sendMessage(MessageType.ObserverAck, buildObserverAck(ack), true),\n reporter: this.reporter,\n hooks: (functionId) => this.hooksOf(functionId),\n logError: (message, error) => this.logError(message, error),\n logWarn: (message) => this.logWarn(message),\n hookTimeoutMs: () => options?.observe?.hookTimeoutMs ?? OBSERVE_HOOK_TIMEOUT_MS,\n observeV2: () => this.engineFeatures.has(FEATURE_OBSERVE_V2),\n }\n\n this.reporter.start()\n this.connect()\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 private logWarn(message: string): void {\n console.warn(`[iii] ${message}`)\n }\n\n private logInfo(message: string): void {\n console.info(`[iii] ${message}`)\n }\n\n /**\n * Registers a function with the engine. The `functionId` is the unique\n * identifier callers and observers name. The handler's return value is what\n * the function's observers observe.\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. Calls this worker makes to it run\n * in-process once the engine confirmed it, unless `options.localDispatch`\n * is `false`.\n *\n * A function that sets `args_format`, `private: true`, `observable: false`,\n * an `onObserverMatch` hook or an `onObserverDeliver` hook needs an engine\n * with `observe.v2`: it is registered once the connection's engine\n * advertised it, and against an older engine it stays unregistered (logged\n * once, `UNSUPPORTED`).\n *\n * @param functionId - Unique function identifier.\n * @param handler - Handler executed when the function is invoked.\n * @param options - Optional {@link RegisterFunctionOptions}.\n * @returns A {@link FunctionRef}: the hook methods with the id filled in, 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 // biome-ignore lint/suspicious/noExplicitAny: the handler's types default to any so untyped handlers type-check\n registerFunction = <I = any, O = any>(\n functionId: string,\n handler: RemoteFunctionHandler<I, O>,\n options?: RegisterFunctionOptions,\n ): FunctionRef<I, O> => {\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 // `standby` and `localDispatch` are this SDK's alone; `private: false` and\n // `observable: true` are the defaults and are not sent.\n const { standby, localDispatch, private: isPrivate, observable, ...wireOptions } = options ?? {}\n const fullMessage = this.snapshotRegistration<RegisterFunctionMessage>({\n ...wireOptions,\n ...(isPrivate === true ? { private: true } : {}),\n ...(observable === false ? { observable: false } : {}),\n id: functionId,\n message_type: MessageType.RegisterFunction,\n })\n // Refused here when too large, before anything is retained.\n const frame = this.prepareJson(this.toWireFormat(MessageType.RegisterFunction, fullMessage))\n\n const observe = new FunctionObservers(functionId, localDispatch !== false, true, this.observeHost)\n const fn: RemoteFunctionData = {\n message: fullMessage,\n observe,\n standby: standby === true,\n handler: async (input, metadata?: unknown) => {\n return await handler(input, metadata)\n },\n }\n this.functions.set(functionId, fn)\n if (this.mayRegister(functionId, fn)) {\n this.sendMessageRaw(frame)\n fn.sentEpoch = this.connectionEpoch\n }\n if (\n this.registeredOnConnection &&\n !this.engineFeatures.has(FEATURE_OBSERVE_V1) &&\n this.hasObserverHooks(functionId)\n ) {\n this.warnHooksInactive(functionId)\n }\n\n const ref: FunctionRef<I, O> = {\n id: functionId,\n onObserverAdded: (hook) => {\n this.onObserverAdded(functionId, hook)\n return ref\n },\n onObserverRemoved: (hook) => {\n this.onObserverRemoved(functionId, hook)\n return ref\n },\n onObserverMatch: (hook: MatchHook<I, O> | null) => {\n this.onObserverMatch(functionId, hook)\n return ref\n },\n onObserverDeliver: (hook) => {\n this.onObserverDeliver(functionId, hook)\n return ref\n },\n // This registration's observers: one load, no lookup by id.\n observers: () => observe.observers(),\n isObserved: (call) => observe.isObserved(call as Partial<Call>),\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) !== fn) return\n this.sendMessage(MessageType.UnregisterFunction, { id: functionId }, true)\n this.functions.delete(functionId)\n this.stopStandby(functionId)\n observe.dispose()\n },\n }\n return ref\n }\n\n /**\n * What a function needs `observe.v2` for (decision 18): `args_format`,\n * `private`, `observable: false`, a match hook or a deliver hook.\n */\n private needsObserveV2(functionId: string, fn: RemoteFunctionData): boolean {\n const { message } = fn\n const hooks = this.functionHooks.get(functionId)\n return (\n message.args_format !== undefined ||\n message.private === true ||\n message.observable === false ||\n hooks?.match !== undefined ||\n hooks?.deliver !== undefined\n )\n }\n\n /**\n * Whether the function's `registerfunction` may go out on the current\n * connection now. One that needs `observe.v2` waits for this connection's\n * `WorkerRegistered`, and stays unregistered (`holdUnsupported`) when the\n * engine does not advertise it (decision 41).\n */\n private mayRegister(functionId: string, fn: RemoteFunctionData): boolean {\n if (!this.isOpen()) return false\n if (!this.needsObserveV2(functionId, fn)) return true\n if (!this.registeredOnConnection) return false\n if (this.engineFeatures.has(FEATURE_OBSERVE_V2)) return true\n this.holdUnsupported(functionId, fn)\n return false\n }\n\n /**\n * A function that needs `observe.v2` on a connection whose engine does not\n * advertise it: the engine does not hold it here, so what it kept from an\n * earlier connection is released once per connection (local dispatch, its\n * observers through `onObserverRemoved`, held reports), and `UNSUPPORTED`\n * is logged once per function.\n */\n private holdUnsupported(functionId: string, fn: RemoteFunctionData): void {\n if (fn.observe.releasedEpoch !== this.connectionEpoch) fn.observe.onRegistrationRejected(this.connectionEpoch)\n this.warnUnsupported(functionId)\n }\n\n /** Sends the registrations that may go out now and have not on this connection. */\n private sendRegistrations(): void {\n for (const [functionId, fn] of this.functions) {\n if (fn.sentEpoch === this.connectionEpoch || !this.mayRegister(functionId, fn)) continue\n this.replayRegistration(MessageType.RegisterFunction, fn.message)\n fn.sentEpoch = this.connectionEpoch\n }\n }\n\n /**\n * Decides the registration again once a match or deliver hook may have\n * changed whether the function needs `observe.v2` (set or removed, or set\n * before `WorkerRegistered`): against an engine without it, a registered\n * function is unregistered (and one held back is registered once it no\n * longer needs it).\n */\n private reconcileRegistration(functionId: string): void {\n const fn = this.functions.get(functionId)\n if (!fn || !this.isOpen() || !this.registeredOnConnection) return\n const sent = fn.sentEpoch === this.connectionEpoch\n const allowed = this.engineFeatures.has(FEATURE_OBSERVE_V2) || !this.needsObserveV2(functionId, fn)\n if (sent && !allowed) {\n this.sendMessage(MessageType.UnregisterFunction, { id: functionId }, true)\n fn.sentEpoch = undefined\n this.holdUnsupported(functionId, fn)\n } else if (!sent && allowed) {\n this.replayRegistration(MessageType.RegisterFunction, fn.message)\n fn.sentEpoch = this.connectionEpoch\n }\n }\n\n private warnUnsupported(functionId: string): void {\n if (this.unsupportedWarned.has(functionId)) return\n this.unsupportedWarned.add(functionId)\n this.logWarn(\n `UNSUPPORTED: function \"${functionId}\" needs observe.v2 (args_format, private, observable: false, onObserverMatch or onObserverDeliver), which this engine does not advertise; it stays unregistered until the worker connects to an engine with observe.v2.`,\n )\n }\n\n /** The hooks that apply to one function now: the worker's, and those set for its id. */\n private hooksOf(functionId: string): FunctionHooks {\n const own = this.functionHooks.get(functionId)\n return {\n workerAdded: this.workerHooks.added,\n workerRemoved: this.workerHooks.removed,\n added: own?.added,\n removed: own?.removed,\n match: own?.match,\n deliver: own?.deliver,\n }\n }\n\n private hasObserverHooks(functionId: string): boolean {\n const own = this.functionHooks.get(functionId)\n return !!(\n this.workerHooks.added ||\n this.workerHooks.removed ||\n own?.added ||\n own?.removed ||\n own?.match ||\n own?.deliver\n )\n }\n\n private setFunctionHook<K extends 'added' | 'removed' | 'match' | 'deliver'>(\n functionId: string,\n kind: K,\n hook: { added: AddedHook; removed: RemovedHook; match: MatchHook; deliver: DeliverHook }[K] | null,\n ): void {\n if (typeof functionId !== 'string' || functionId.trim() === '') {\n throw new TypeError('the function id of an observer hook is required')\n }\n const keys =\n kind === 'match' &&\n hook !== null &&\n typeof hook === 'object' &&\n typeof (hook as { observer?: unknown }).observer === 'function' &&\n typeof (hook as { call?: unknown }).call === 'function'\n if (hook !== null && typeof hook !== 'function' && !keys) {\n throw new TypeError(\n kind === 'match'\n ? `the match hook of ${functionId} must be a predicate, { observer, call } key functions, or null to remove it`\n : `the ${kind} hook of ${functionId} must be a function, or null to remove it`,\n )\n }\n const hooks = { ...this.functionHooks.get(functionId), [kind]: hook ?? undefined }\n if (hooks.added || hooks.removed || hooks.match || hooks.deliver) this.functionHooks.set(functionId, hooks)\n else this.functionHooks.delete(functionId)\n const fn = this.functions.get(functionId)\n if (!fn) return\n if (kind === 'added' && hook) fn.observe.catchUp('fn')\n if (kind === 'match') fn.observe.matchChanged()\n // A match or deliver hook decides whether the function needs observe.v2.\n if (kind === 'match' || kind === 'deliver') this.reconcileRegistration(functionId)\n }\n\n private setWorkerHook<K extends 'added' | 'removed'>(\n kind: K,\n hook: { added: AddedHook; removed: RemovedHook }[K] | null,\n ): void {\n if (hook !== null && typeof hook !== 'function') {\n throw new TypeError(`the worker's ${kind} hook must be a function, or null to remove it`)\n }\n this.workerHooks = { ...this.workerHooks, [kind]: hook ?? undefined }\n if (kind === 'added' && hook) {\n for (const fn of this.functions.values()) fn.observe.catchUp('worker')\n }\n }\n\n /**\n * Runs `hook` when an observer of any function this worker hosts is added,\n * before the SDK acks it; with a function id, for that function only. When\n * both are set, the worker's runs first. Throw to reject the observer (an\n * {@link ObserveRejection} sets the code). `null` removes the hook.\n */\n onObserverAdded: ISdk['onObserverAdded'] = (a: string | AddedHook | null, b?: AddedHook | null) => {\n if (typeof a === 'string') this.setFunctionHook(a, 'added', b as AddedHook | null)\n else this.setWorkerHook('added', a)\n return this\n }\n\n /**\n * Runs `hook` once for every accepted observer when it is removed; with a\n * function id, for that function only. When both are set, the function's\n * runs first. `null` removes the hook.\n */\n onObserverRemoved: ISdk['onObserverRemoved'] = (a: string | RemovedHook | null, b?: RemovedHook | null) => {\n if (typeof a === 'string') this.setFunctionHook(a, 'removed', b as RemovedHook | null)\n else this.setWorkerHook('removed', a)\n return this\n }\n\n /**\n * Says which observers want each call of `functionId`: a predicate\n * `(obs, call) => boolean`, or `{ observer, call }` key functions the SDK\n * indexes. iii's delivery (or the function's deliver hook) gets only the\n * observers that want the call. `null` removes the hook.\n */\n onObserverMatch: ISdk['onObserverMatch'] = (functionId: string, hook: MatchHook | null): ISdk => {\n this.setFunctionHook(functionId, 'match', hook)\n return this\n }\n\n /**\n * Delivers each call of `functionId` itself: the hook receives the call and\n * the observers that matched it, and what it returns (or throws) is what the\n * caller gets back. iii delivers nothing for that function. `null` removes\n * the hook.\n */\n // biome-ignore lint/suspicious/noExplicitAny: the call's types default to any so untyped hooks read their input\n onObserverDeliver = <I = any, O = any, R = O>(functionId: string, hook: DeliverHook<I, O, R> | null): ISdk => {\n this.setFunctionHook(functionId, 'deliver', hook as DeliverHook | null)\n return this\n }\n\n /** The active observers of a function this worker hosts (empty for any other). */\n observers = (functionId: string): readonly Observer[] => this.functions.get(functionId)?.observe.observers() ?? []\n\n /**\n * Whether a call of a function this worker hosts would reach anyone (see\n * {@link ISdk.isObserved}).\n */\n isObserved = (functionId: string, call?: Partial<Call>): boolean =>\n this.functions.get(functionId)?.observe.isObserved(call) ?? false\n\n /**\n * Observes a function: every call of `source` that passes `source.filters`\n * runs `target`, a registered function. `source` is a function id, or an\n * {@link ObserveSource} with `args` for the worker that hosts the 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`, `NOT_OBSERVABLE`, the host's rejection,\n * `UNSUPPORTED` against an engine without observe) show up as state `error`\n * and reject `ready()`. An `error` answer to the `observe` is the engine's\n * refusal, the handle's final answer: the engine holds no observer for it,\n * it is not replayed, and its `dispose()` sends nothing. The handle holds\n * its id until it is disposed: an `observe` of an id a handle of this\n * client holds throws an {@link ObserveRejection} (`OBSERVER_ID_CONFLICT`)\n * and sends nothing.\n *\n * @param source - What is observed: a function id, or `function_id`,\n * `args`, `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 = (sourceOrId: string | ObserveSource, target: Target, options?: ObserverOptions): ObserverHandle => {\n const source: ObserveSource = typeof sourceOrId === 'string' ? { function_id: sourceOrId } : sourceOrId\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 // Held by a handle of this client: refused here, nothing sent, the holder untouched.\n if (this.observerHandles.has(id)) {\n throw new ObserveRejection('OBSERVER_ID_CONFLICT', `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.observerHandles.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, and in its function's deliver hook), or `undefined` outside any\n * 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.call({ 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 or its function's\n * deliver hook is running); otherwise none. 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 handle.answered = false\n const sent = this.observesSent.get(handle.id)\n if (sent) sent.push(handle)\n else this.observesSent.set(handle.id, [handle])\n }\n\n private disposeObserver(handle: ObserverHandleImpl): void {\n if (this.observerHandles.get(handle.id) === handle) this.observerHandles.delete(handle.id)\n // Answered, it leaves the list: what the engine says about it later\n // reaches no other handle (a newer one hears nothing before its answer).\n if (handle.answered) this.unlistObserve(handle)\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 this.logWarn(\n `Function \"${functionId}\" has observer hooks, but the engine does not support observe (observe.v1): it is registered as a plain function and its observer hooks are inactive.`,\n )\n }\n\n /** Once the connection is registered: a hook set for an id this worker has not registered (a mistyped id?). */\n private warnUnregisteredHookIds(): void {\n for (const functionId of this.functionHooks.keys()) {\n if (this.functions.has(functionId) || this.unregisteredHooksWarned.has(functionId)) continue\n this.unregisteredHooksWarned.add(functionId)\n this.logWarn(\n `Observer hooks are set for \"${functionId}\", which this worker has not registered; check the function id.`,\n )\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.call<{ buffer_size?: number }, { writer: StreamChannelRef; reader: StreamChannelRef }>({\n function_id: 'engine::channels::create',\n 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 function. The routing behavior and return type depend on the\n * `action` field of the request.\n *\n * | `action` | Behavior | Return type |\n * |----------------------------|----------------------------------------------------|--------------------------|\n * | _(none)_ | Synchronous: waits for the function to return | `Promise<TOutput>` |\n * | `CallAction.Enqueue(...)` | Async via named queue; engine acknowledges enqueue | `Promise<EnqueueResult>` |\n * | `CallAction.Void()` | Fire-and-forget, no response | `Promise<undefined>` |\n *\n * With `observer` instead of `function_id`, the call runs that observer's\n * target, with the observer's policy (`max_fires`, expiry,\n * `max_in_flight`), metadata and loop guard. Only the worker that hosts the\n * observed function may call through it (`NOT_FUNCTION_OWNER`); the\n * payload goes as given. It is routed by the observer alone, so it reaches\n * the observer's target from anywhere, after an `await` included. It takes\n * no metadata: the target's metadata argument is the observer's\n * registration metadata, and a request that names metadata is refused\n * before anything is sent.\n *\n * @param request - The call request.\n * @param request.function_id - ID of the function to invoke.\n * @param request.observer - An observer of a function this worker hosts: its target is invoked.\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 (any JSON value), delivered to the handler\n * beside the payload. `null` is the same as no metadata: the handler receives `undefined`.\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 { CallAction } from 'iii-browser-sdk'\n *\n * // Synchronous\n * const result = await worker.call({ function_id: 'get-order', payload: { id: '123' } })\n *\n * // Enqueue\n * const { messageReceiptId } = await worker.call({\n * function_id: 'payments::charge',\n * payload: { orderId: '123', amount: 49.99 },\n * action: CallAction.Enqueue({ queue: 'payment' }),\n * })\n *\n * // Fire-and-forget\n * worker.call({\n * function_id: 'notifications::send',\n * payload: { userId: '123' },\n * action: CallAction.Void(),\n * })\n *\n * // Through an observer, from the function's deliver hook\n * worker.onObserverDeliver('ui::on-command', async (call) => {\n * const handler = commands.match(call.input)\n * return handler ? worker.call({ observer: handler.obs, payload: call.input }) : { handled: false }\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 call = async <TInput = unknown, TOutput = any>(request: CallRequest<TInput>): Promise<TOutput> => {\n if (request.observer !== undefined) {\n const { observer, payload, action, timeoutMs } = request\n // Its target's metadata is the observer's: refused before anything is\n // sent, so no metadata is lost on the way (decision 53). `null` is none.\n if ((request as { metadata?: unknown }).metadata != null) throw new Error(OBSERVER_CALL_METADATA)\n // The engine routes to the observer's stored target and is the one that\n // checks it (decision 13); no namespace travels.\n return this.invokeRemote<TOutput>({ function_id: observer.target, payload, action, timeoutMs }, undefined, {\n observer_id: observer.id,\n })\n }\n // `metadata: null` is no metadata, local or routed (decision 54).\n const req = request.metadata === null ? { ...request, metadata: undefined } : request\n const { function_id, action } = req\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(req.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 (req.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, req)\n if (!this.isOpen()) {\n if (depth < MAX_OFFLINE_LOCAL_DEPTH) return this.invokeLocal<TOutput>(function_id, fn, req)\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>(req, namespace)\n }\n\n /**\n * Invokes a function using a request object.\n *\n * @deprecated Use {@link Sdk.call}, the same function.\n */\n trigger = this.call\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: { traceparent?: string; baggage?: string }): 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: RemoteRequest,\n namespace: string | undefined,\n activation?: ActivationWire,\n ): Promise<TOutput> {\n // The engine refused this worker for good: nothing reaches it.\n if (this.fatalError) return Promise.reject(this.fatalError)\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(new InvocationTimeoutError(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 * Runs a call's delivery inside `ctx`: the function's deliver hook, or\n * iii's delivery to its observers. The hook sees the invocation up to its\n * first `await`, and counts as delivering until it settles, so the calls it\n * makes after an `await` fall back to the invocation while it is the only\n * one running (`callContext`).\n */\n private deliverIn(ctx: ActiveInvocation, delivery: Delivery, hook: DeliverHook | undefined): Promise<unknown> {\n if (hook === undefined) return delivery.run(undefined)\n const untrack = trackDelivering(ctx)\n return runInContext(ctx, () => delivery.run(hook)).finally(untrack)\n }\n\n /**\n * The local path (sdk.md §4.3): runs the handler in-process inside a new\n * invocation context, then delivers the call (the function's deliver hook,\n * or iii's delivery to its observers); the same timeout and the same\n * rejection value as the remote path. A call of a function nobody observes\n * and without a deliver hook puts nothing on the wire.\n *\n * The handler gets a copy of the payload and the caller a copy of the\n * result; a private function's input and result pass by reference.\n */\n private invokeLocal<TOutput>(\n function_id: string,\n fn: RemoteFunctionData,\n request: {\n payload: unknown\n action?: CallActionType\n timeoutMs?: number\n metadata?: unknown\n traceparent?: string\n baggage?: string\n },\n ): Promise<TOutput> {\n const { observe } = fn\n const handler = fn.handler as NonNullable<RemoteFunctionData['handler']>\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 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 the call is delivered from: those active when it started.\n const snapshot = observe.compiled\n const activations = observe.activations\n const hook = this.functionHooks.get(function_id)?.deliver\n const delivering = hook !== undefined || snapshot.length > 0\n const byReference = fn.message.private === true\n let input: unknown\n let metadata: unknown\n let callInput: unknown\n let callMetadata: unknown\n try {\n if (byReference) {\n // Nobody else sees either value: neither is copied, and both are read-only.\n callInput = request.payload\n callMetadata = request.metadata\n input = this.resolveChannelValue(request.payload)\n metadata = request.metadata\n } else {\n // What the delivery sees is the payload and metadata as the caller passed\n // them when the call started, not what the handler or the caller made of\n // them since. Not copied when nothing is delivered.\n if (delivering) {\n callInput = cloneValue(request.payload)\n callMetadata = 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 }\n } catch (error) {\n return Promise.reject(error)\n }\n\n const startedAt = Date.now()\n const t0 = performance.now()\n let delivery: Delivery | undefined\n const settle = (handled: HandlerOutcome): unknown => {\n const duration = performance.now() - t0\n this.reporter.recordLocal(function_id, handled.ok, duration)\n if (!delivering) {\n if (handled.ok) return handled.value\n throw handled.error\n }\n const outcome = byReference ? handled : this.deliveredOutcome(handled, input, callInput)\n delivery = new Delivery(observe, {\n call: this.callOf(function_id, ctx.invocation_id, outcome, callInput, ctx.caller, callMetadata),\n thrown: outcome.ok ? undefined : outcome.error,\n snapshot,\n activations,\n started_at_ms: startedAt,\n duration_ms: duration,\n observe_depth: ctx.observe_depth,\n traceparent,\n baggage,\n routed: false,\n })\n return this.deliverIn(ctx, delivery, hook)\n }\n\n const effectiveTimeout = request.timeoutMs ?? this.invocationTimeoutMs\n // Running until the call is delivered: what code after its `await`s falls back to.\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\n .then(\n (value) => settle({ ok: true, value }),\n (error) => settle({ ok: false, error }),\n )\n .then(\n (output) => {\n untrack()\n return output\n },\n (error) => {\n untrack()\n // What the remote path rejects with: the error body, as the engine forwards it.\n throw delivery ? delivery.errorBody(error) : handlerErrorBody(error)\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((byReference ? output : 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(new InvocationTimeoutError(effectiveTimeout, function_id))\n }, effectiveTimeout)\n })\n }\n\n /**\n * The outcome a local call of a function that is not private is delivered\n * with: a handler that returns its own input unchanged is delivered with\n * the input the call started with as its output, so the report carries the\n * value once (`output_is_input`, decision 4).\n */\n private deliveredOutcome(outcome: HandlerOutcome, input: unknown, callInput: unknown): HandlerOutcome {\n if (!outcome.ok) return outcome\n const ownInput = outcome.value === input && input !== null && typeof input === 'object'\n return ownInput && sameData(callInput, input) ? { ok: true, value: callInput } : outcome\n }\n\n /** The {@link Call} a finished handler made: what it was called with, and what it returned or threw. */\n private callOf(\n function_id: string,\n invocation_id: string,\n outcome: HandlerOutcome,\n input: unknown,\n caller: CallerWire | undefined,\n metadata: unknown,\n ): Call {\n const call: Call = { function_id, invocation_id, status: outcome.ok ? 'success' : 'error', input }\n if (outcome.ok) call.output = outcome.value\n else call.error = handlerErrorBody(outcome.error)\n if (caller !== undefined) call.caller = caller\n if (metadata !== undefined) call.metadata = metadata as Record<string, unknown>\n return call\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 for (const functionId of [...this.standbyTimers.keys()]) this.stopStandby(functionId)\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 (standby functions too).\n this.registeredOnConnection = false\n this.observesSent.clear()\n for (const functionId of [...this.standbyTimers.keys()]) this.stopStandby(functionId)\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 this.observesSent.clear()\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 // Functions that need observe.v2 wait for `WorkerRegistered`, and so do\n // the observers, which follow the functions (so local targets exist first).\n this.sendRegistrations()\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 /**\n * The `payload_too_large` error that replaces an answer too large to send\n * is not the handler's outcome, so it activates no observer: to an engine\n * with `observe.v2` it says `delivered` when the deliver hook delivered the\n * call (`answer.delivered`), and `matched: []` otherwise, whatever the\n * function's hooks. An engine without `observe.v2` gets the bare error.\n */\n private oversizedAnswer(answer: Record<string, unknown>, fallback: Record<string, unknown>): Record<string, unknown> {\n if (!this.engineFeatures.has(FEATURE_OBSERVE_V2)) return fallback\n if (answer.delivered === true) return { ...fallback, delivered: true }\n return { ...fallback, matched: [] }\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 this.oversizedAnswer(message, {\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 )\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 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(\n invocation_id: string | undefined,\n function_id: string,\n input: unknown,\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 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 }\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\n // The engine evaluates the `on` and filters of the calls it routes\n // (decision 55). An observe.v2 host runs the function's match and\n // deliver hooks for them, which see the input as it arrived (channel\n // refs unresolved), and its answer says how the call is delivered:\n // `delivered`, `matched`, or neither for a function with no hook.\n const snapshot: readonly ObserverImpl[] = fn.observe.compiled\n const activations = fn.observe.activations\n const hook = this.functionHooks.get(function_id)?.deliver\n const answering = this.engineFeatures.has(FEATURE_OBSERVE_V2)\n const startedAt = Date.now()\n const t0 = performance.now()\n let delivery: Delivery | undefined\n // The answer's `matched` when the call needs no delivery.\n let matched: readonly string[] | undefined\n const resolvedInput = this.resolveChannelValue(input)\n // Running until the call is delivered: what code after its `await`s falls back to (`callDepth`).\n const run = async (): Promise<unknown> => {\n const untrack = trackRunning(ctx, MAX_RUNNING_INVOCATION_MS)\n try {\n let outcome: HandlerOutcome\n try {\n outcome = { ok: true, value: await runInContext(ctx, () => handler(resolvedInput, metadata)) }\n } catch (error) {\n outcome = { ok: false, error }\n }\n // No delivery runs without a deliver hook when the function has no\n // match hook (the answer carries neither field: the engine\n // evaluates every active observer), or when no observer was active\n // as the call started (`matched: []`: the match hook has none to\n // match and does not run, as a local call with an empty snapshot\n // skips delivery).\n const narrowed = answering && hook === undefined && fn.observe.hasMatchHook()\n if (!answering || (hook === undefined && (!narrowed || snapshot.length === 0))) {\n if (narrowed) matched = []\n if (outcome.ok) return outcome.value\n throw outcome.error\n }\n delivery = new Delivery(fn.observe, {\n call: this.callOf(function_id, ctx.invocation_id, outcome, input, ctx.caller, metadata),\n thrown: outcome.ok ? undefined : outcome.error,\n snapshot,\n activations,\n started_at_ms: startedAt,\n duration_ms: performance.now() - t0,\n observe_depth: ctx.observe_depth,\n traceparent,\n baggage,\n routed: true,\n })\n return await this.deliverIn(ctx, delivery, hook)\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(\n MessageType.InvocationResult,\n buildInvocationResult({\n invocation_id,\n function_id,\n result,\n traceparent,\n baggage,\n matched: delivery ? delivery.matched : matched,\n delivered: delivery?.delivered,\n }) as Omit<IIIMessage, 'message_type'>,\n )\n } catch (error) {\n this.sendMessage(\n MessageType.InvocationResult,\n buildInvocationResult({\n invocation_id,\n function_id,\n error: delivery ? delivery.errorBody(error) : handlerErrorBody(error),\n traceparent,\n baggage,\n matched: delivery ? delivery.matched : matched,\n delivered: delivery?.delivered,\n }) as Omit<IIIMessage, 'message_type'>,\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(\n MessageType.InvocationResult,\n buildInvocationResult({\n invocation_id,\n function_id,\n error: { code: errorCode, message: errorMessage },\n traceparent,\n baggage,\n }) as Omit<IIIMessage, 'message_type'>,\n )\n }\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 const fn = this.functions.get(msg.id)\n // Only a registration sent on this connection is confirmed: not one\n // unregistered since (a match or deliver hook against an engine without observe.v2).\n if (fn && fn.sentEpoch === this.connectionEpoch) {\n // A standby function took over the id: its hooks run for every observer in the set.\n this.stopStandby(msg.id)\n fn.standingBy = false\n // Its reports held across a reconnect are flushed once the set is acked.\n fn.observe.onFunctionRegistered(msg, this.connectionEpoch)\n }\n } else if (msgType === MessageType.ObserverAdded) {\n const msg = decodeObserverAdded(message)\n const fn = this.functions.get(msg.function_id)\n // An observer of a registration this connection withdrew (or never\n // sent) is ignored, as its functionregistered is: no hook, no ack.\n if (fn && fn.sentEpoch === this.connectionEpoch) fn.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 this.logWarn(`Observer ${msg.id}: ${msg.warnings.join('; ')}`)\n }\n this.onObserveResult(msg.id, msg.state, msg.error)\n } else if (msgType === MessageType.ObserverStateChanged) {\n const msg = decodeObserverStateChanged(message)\n this.onObserverStateChanged(msg.id, msg.state, msg.reason)\n } else if (msgType === MessageType.RegistrationRejected) {\n this.onRegistrationRejected(decodeRegistrationRejected(message))\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. The\n * functions that need `observe.v2` go out now, or stay unregistered without\n * it; without it, one sent earlier on this connection that has gained a\n * match or deliver hook since is unregistered. With `observe.v1` the observers the\n * engine has not refused are replayed (after the functions) and held reports flushed; without it\n * `observe()` fails with `UNSUPPORTED` and observer hooks are inactive.\n */\n private onEngineFeatures(features: string[]): void {\n this.engineFeatures = new Set(features)\n this.registeredOnConnection = true\n this.sendRegistrations()\n for (const [functionId, fn] of this.functions) {\n if (fn.sentEpoch === this.connectionEpoch) this.reconcileRegistration(functionId)\n }\n this.warnUnregisteredHookIds()\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 // A refused handle is not sent again: its refusal is its final answer.\n for (const handle of this.observerHandles.values()) {\n if (!handle.refused) this.sendObserve(handle)\n }\n this.reporter.flush()\n return\n }\n for (const handle of this.observerHandles.values()) {\n if (!handle.refused) handle.setState('error', UNSUPPORTED_REASON)\n }\n for (const functionId of this.functions.keys()) {\n if (this.hasObserverHooks(functionId)) this.warnHooksInactive(functionId)\n }\n this.reporter.clear()\n }\n\n /**\n * An `observeresult`: the answer to the oldest `observe` of the id sent on\n * this connection that has none yet. The engine answers every `observe`\n * once, in the order it read them (decision 56).\n */\n private onObserveResult(id: string, wireState: string, reason?: ErrorBody): void {\n const handle = this.observesSent.get(id)?.find((h) => !h.answered)\n if (!handle) return\n handle.answered = true\n if (toObserverState(wireState) === 'error') {\n // A refusal, the handle's final answer: the engine holds no observer\n // for it (it stores nothing for a refused `observe`, and disposes an\n // observer in `error` as it answers its replay), so dispose() sends\n // no `unobserve`.\n handle.sent = false\n handle.refused = true\n this.unlistObserve(handle)\n handle.setState('error', reason ? { code: reason.code, message: reason.message } : undefined)\n return\n }\n // Disposed before its answer: its `unobserve` follows, and nothing\n // the engine says about it later reaches another handle.\n if (handle.state === 'disposed') this.unlistObserve(handle)\n else this.applyObserverState(handle, wireState, reason)\n }\n\n /**\n * An `observerstatechanged`: about the newest observer of the id whose\n * `observeresult` arrived on this connection. One that arrives before any\n * did is dropped: a reattached connection hears its observers resume\n * before its replayed `observe`s are answered, and each answer carries the\n * current state (decision 56).\n */\n private onObserverStateChanged(id: string, wireState: string, reason?: ErrorBody): void {\n const sent = this.observesSent.get(id)\n if (!sent) return\n for (let at = sent.length - 1; at >= 0; at--) {\n if (sent[at].answered) {\n this.applyObserverState(sent[at], wireState, reason)\n return\n }\n }\n }\n\n /** A state from the engine for `handle`; `disposed` frees its id. */\n private applyObserverState(handle: ObserverHandleImpl, wireState: string, reason?: ErrorBody): void {\n const state = toObserverState(wireState)\n handle.setState(state, reason ? { code: reason.code, message: reason.message } : undefined)\n if (state !== 'disposed') return\n this.unlistObserve(handle)\n if (this.observerHandles.get(handle.id) === handle) this.observerHandles.delete(handle.id)\n }\n\n private unlistObserve(handle: ObserverHandleImpl): void {\n const sent = this.observesSent.get(handle.id)\n const at = sent ? sent.indexOf(handle) : -1\n if (!sent || at < 0) return\n sent.splice(at, 1)\n if (sent.length === 0) this.observesSent.delete(handle.id)\n }\n\n /**\n * The engine rejected a registration. The `code` decides the severity:\n *\n * - {@link FUNCTION_NAMESPACE_CONFLICT}: another live worker in this\n * namespace already exports this one function id. Only that registration\n * is refused; the connection stays open and the worker keeps serving its\n * other functions. A `standby` function retries its registration until\n * the id is free.\n * - {@link FUNCTION_REJECTIONS} on one function: only that function is\n * refused. Logged; the worker keeps serving.\n * - {@link WORKER_NAMESPACE_CONFLICT}, or any other code: terminal — stop and\n * do not reconnect (otherwise the engine would only reject the same name\n * again, which with `maxRetries: -1` loops 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 const fn = init.function_id !== undefined ? this.functions.get(init.function_id) : undefined\n // The engine refused it: no local dispatch, no observers for it here.\n fn?.observe.onRegistrationRejected(this.connectionEpoch)\n if (fn?.standby && init.function_id !== undefined) {\n this.standBy(init.function_id, fn, init.owner_worker_id)\n return\n }\n this.logWarn(\n `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 if (FUNCTION_REJECTIONS.has(init.code) && init.function_id !== undefined) {\n this.functions.get(init.function_id)?.observe.onRegistrationRejected(this.connectionEpoch)\n this.logError(\n `Function registration rejected with ${init.code}: function \"${init.function_id}\" in namespace \"${init.namespace}\" is not registered. Staying connected and serving the rest.`,\n )\n return\n }\n\n if (init.code === WORKER_NAMESPACE_CONFLICT) {\n this.logError(\n `Registration rejected (${init.code}): worker \"${init.worker_name}\" in namespace \"${init.namespace}\" is already owned by ${init.owner_worker_id}. Not reconnecting.`,\n )\n } else {\n this.logError(\n `Registration rejected by engine with unknown code \"${init.code}\"; treating as fatal. Not reconnecting.`,\n )\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 * A `standby` function whose id another connection hosts (decision 21): its\n * registration is retried every second (±20 %) until the engine accepts it\n * (`functionregistered`, whose observers then run their hooks here) or the\n * function is unregistered.\n */\n private standBy(functionId: string, fn: RemoteFunctionData, owner: string): void {\n if (this.standbyTimers.has(functionId)) return\n if (!fn.standingBy) {\n this.logInfo(`Function \"${functionId}\" is hosted by worker ${owner}; standing by to take it over when it leaves.`)\n }\n fn.standingBy = true\n const delay = Math.floor(STANDBY_RETRY_MS * (0.8 + 0.4 * Math.random()))\n const timer = setTimeout(() => {\n this.standbyTimers.delete(functionId)\n if (this.functions.get(functionId) !== fn || !this.mayRegister(functionId, fn)) return\n this.replayRegistration(MessageType.RegisterFunction, fn.message)\n fn.sentEpoch = this.connectionEpoch\n }, delay)\n unrefTimer(timer)\n this.standbyTimers.set(functionId, timer)\n }\n\n private stopStandby(functionId: string): void {\n const timer = this.standbyTimers.get(functionId)\n if (!timer) return\n clearTimeout(timer)\n this.standbyTimers.delete(functionId)\n }\n}\n\n/**\n * Factory object that constructs routing actions for {@link ISdk.call}.\n *\n * @example\n * ```typescript\n * import { CallAction } from 'iii-browser-sdk'\n *\n * // Enqueue to a named queue\n * worker.call({\n * function_id: 'process',\n * payload: { data: 'hello' },\n * action: CallAction.Enqueue({ queue: 'jobs' }),\n * })\n *\n * // Fire-and-forget\n * worker.call({\n * function_id: 'notify',\n * payload: {},\n * action: CallAction.Void(),\n * })\n * ```\n */\nexport const CallAction = {\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/** @deprecated Use {@link CallAction}, the same object. */\nexport const TriggerAction = CallAction\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":";;;;;;;;AAeA,IAAa,4BAAb,cAA+C,MAAM;CAOnD,YAAY,MAAgC;AAC1C,QACE,GAAG,KAAK,KAAK,8BAA8B,KAAK,gBAAgB,SAAY,aAAa,KAAK,YAAY,KAAK,WAAW,KAA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