@vscode/component-explorer 0.2.1-18 → 0.2.1-180
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +198 -27
- package/dist/browserDaemonClient-AB8d4x2O.js +3465 -0
- package/dist/browserDaemonClient-AB8d4x2O.js.map +1 -0
- package/dist/components/BottomDebugPanel.d.ts +8 -0
- package/dist/components/BottomDebugPanel.d.ts.map +1 -0
- package/dist/components/DebugPanelPlacement.d.ts +3 -0
- package/dist/components/DebugPanelPlacement.d.ts.map +1 -0
- package/dist/components/DebugWorkbench.d.ts +42 -0
- package/dist/components/DebugWorkbench.d.ts.map +1 -0
- package/dist/components/DebugWorkbenchLayout.d.ts +30 -0
- package/dist/components/DebugWorkbenchLayout.d.ts.map +1 -0
- package/dist/components/DebugWorkbenchState.d.ts +31 -0
- package/dist/components/DebugWorkbenchState.d.ts.map +1 -0
- package/dist/components/ExplorerModel.d.ts +28 -5
- package/dist/components/ExplorerModel.d.ts.map +1 -1
- package/dist/components/FixtureDebugStore.d.ts +20 -0
- package/dist/components/FixtureDebugStore.d.ts.map +1 -0
- package/dist/components/FixturePreviewItem.d.ts +11 -0
- package/dist/components/FixturePreviewItem.d.ts.map +1 -1
- package/dist/components/LeftSidebar.d.ts.map +1 -1
- package/dist/components/PageViewportState.d.ts +34 -0
- package/dist/components/PageViewportState.d.ts.map +1 -0
- package/dist/components/PreviewArea.d.ts.map +1 -1
- package/dist/components/RightSidebar.d.ts +8 -2
- package/dist/components/RightSidebar.d.ts.map +1 -1
- package/dist/components/TitleBar.d.ts.map +1 -1
- package/dist/components/TreeView.d.ts +3 -1
- package/dist/components/TreeView.d.ts.map +1 -1
- package/dist/components/favoriteFixtures.d.ts +4 -0
- package/dist/components/favoriteFixtures.d.ts.map +1 -0
- package/dist/components/icons.d.ts +12 -8
- package/dist/components/icons.d.ts.map +1 -1
- package/dist/components/types.d.ts +2 -0
- package/dist/components/types.d.ts.map +1 -1
- package/dist/core/ComponentRenderer.d.ts +26 -3
- package/dist/core/ComponentRenderer.d.ts.map +1 -1
- package/dist/core/ErrorInfo.d.ts +21 -1
- package/dist/core/ErrorInfo.d.ts.map +1 -1
- package/dist/core/FixtureInputStore.d.ts +32 -0
- package/dist/core/FixtureInputStore.d.ts.map +1 -0
- package/dist/core/FixtureInteractionRuntime.d.ts +30 -0
- package/dist/core/FixtureInteractionRuntime.d.ts.map +1 -0
- package/dist/core/FixtureNode.d.ts.map +1 -1
- package/dist/core/FixtureRegistry.d.ts +2 -0
- package/dist/core/FixtureRegistry.d.ts.map +1 -1
- package/dist/core/RenderTimeout.d.ts +39 -0
- package/dist/core/RenderTimeout.d.ts.map +1 -0
- package/dist/core/fixtureApi.d.ts +234 -32
- package/dist/core/fixtureApi.d.ts.map +1 -1
- package/dist/core/fixtureApiConsumer.d.ts +22 -2
- package/dist/core/fixtureApiConsumer.d.ts.map +1 -1
- package/dist/core/index.d.ts +7 -3
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/inputAggregation.d.ts +31 -0
- package/dist/core/inputAggregation.d.ts.map +1 -0
- package/dist/daemon/DaemonConfig.d.ts +0 -2
- package/dist/daemon/DaemonConfig.d.ts.map +1 -1
- package/dist/daemon/DaemonModel.d.ts +12 -6
- package/dist/daemon/DaemonModel.d.ts.map +1 -1
- package/dist/daemon/browserDaemonClient.d.ts +3 -0
- package/dist/daemon/browserDaemonClient.d.ts.map +1 -0
- package/dist/fixtureApi.d-DjVuiRlO.d.ts +533 -0
- package/dist/index.d.ts +53 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11 -9
- package/dist/lib/explorerQueryParams.d.ts +2 -2
- package/dist/lib/explorerQueryParams.d.ts.map +1 -1
- package/dist/lib/fixtureSizeCache.d.ts +2 -0
- package/dist/lib/fixtureSizeCache.d.ts.map +1 -1
- package/dist/modes/EmbeddedMode.d.ts +7 -0
- package/dist/modes/EmbeddedMode.d.ts.map +1 -1
- package/dist/modes/ExplorerUIMode.d.ts +1 -1
- package/dist/modes/ExplorerUIMode.d.ts.map +1 -1
- package/dist/modes/HeadlessMode.d.ts +12 -3
- package/dist/modes/HeadlessMode.d.ts.map +1 -1
- package/dist/{runtimeVersion-DLeDvOjy.js → runtimeVersion-D9F0L_-O.js} +80 -39
- package/dist/runtimeVersion-D9F0L_-O.js.map +1 -0
- package/dist/viewer.d.ts +2900 -24
- package/dist/viewer.d.ts.map +1 -1
- package/dist/viewer.js +5596 -2332
- package/dist/viewer.js.map +1 -1
- package/package.json +10 -6
- package/dist/core/PropertySchema.d.ts +0 -40
- package/dist/core/PropertySchema.d.ts.map +0 -1
- package/dist/runtimeVersion-DLeDvOjy.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browserDaemonClient-AB8d4x2O.js","sources":["../../../../external/linkrpc/typescript/packages/linkrpc/dist/chunks/inspectionHost-BA6ZmC_P.js","../../../../external/linkrpc/typescript/packages/linkrpc/dist/chunks/src-DYVSK_tz.js","../../common/dist/daemonRpc.js","../src/daemon/browserDaemonClient.ts"],"sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Microsoft Corporation. All rights reserved.\n* Licensed under the MIT License. See License.txt in the project root for license information.\n*--------------------------------------------------------------------------------------------*/\nimport { any, array, boolean, enum as enum$1, int, literal, nonnegative, number, object, optional, record, strictObject, string, union, unknown, void as void$1 } from \"zod/mini\";\nimport { safeParse, toJSONSchema } from \"zod/v4/core\";\nimport { z } from \"zod\";\n//#region src/schema/normalize.ts\n/**\n* Keys that describe structural shape and are part of the decidable subset.\n* Everything else gets stripped during normalization.\n*\n* Note: `not` is intentionally NOT in this list. The special case `{\"not\":{}}`\n* (i.e. matches-nothing) is mapped to the literal `false` bottom; any other\n* `not` is dropped.\n*/\nconst KEPT_KEYS = /* @__PURE__ */ new Set([\n\t\"type\",\n\t\"format\",\n\t\"properties\",\n\t\"required\",\n\t\"additionalProperties\",\n\t\"items\",\n\t\"prefixItems\",\n\t\"const\",\n\t\"enum\",\n\t\"anyOf\",\n\t\"oneOf\",\n\t\"discriminator\",\n\t\"$ref\",\n\t\"title\",\n\t\"description\"\n]);\n/**\n* Normalize raw JSON Schema output (e.g. from `z.toJSONSchema`) into the\n* SvcJsonSchema subset:\n*\n* - drop annotation keys (`examples`, `default`, `$comment`, `readOnly`, ...)\n* - drop out-of-subset refinements (`pattern`, `minimum`, `multipleOf`,\n* `allOf`, `oneOf`, `if/then/else`, `patternProperties`, ...)\n* - empty schema `{}` ⇒ `true` (top)\n* - `{\"not\":{}}` ⇒ `false` (bottom); any other `not` is stripped\n* - `type:\"object\"` without `additionalProperties` ⇒ closed (`false`),\n* matching linkrpc's stricter contract\n* - producer `type` arrays ⇒ `anyOf` branches, preserving their order\n*\n* The output is canonical: structurally equal inputs produce structurally\n* equal outputs, which is what `computeInterfaceHash` relies on.\n*/\nfunction normalizeJsonSchema(raw) {\n\tif (raw === true || raw === false) return raw;\n\tif (raw === null || typeof raw !== \"object\") throw new Error(`normalizeJsonSchema: expected object, got ${typeof raw}`);\n\tif (Array.isArray(raw)) throw new Error(\"normalizeJsonSchema: expected object, got array\");\n\tconst r = raw;\n\tif (\"not\" in r && isEmptyObject(r[\"not\"])) return false;\n\tif (Array.isArray(r[\"type\"])) {\n\t\tconst types = r[\"type\"];\n\t\tif (types.length === 0 || new Set(types).size !== types.length || types.some((type) => ![\n\t\t\t\"null\",\n\t\t\t\"boolean\",\n\t\t\t\"number\",\n\t\t\t\"integer\",\n\t\t\t\"string\",\n\t\t\t\"array\",\n\t\t\t\"object\"\n\t\t].includes(type))) throw new Error(\"normalizeJsonSchema: type array must contain distinct JSON Schema type names\");\n\t\tconst { title, description, ...branch } = r;\n\t\treturn normalizeJsonSchema({\n\t\t\ttitle,\n\t\t\tdescription,\n\t\t\tanyOf: types.map((type) => {\n\t\t\t\tconst schema = {\n\t\t\t\t\t...branch,\n\t\t\t\t\ttype\n\t\t\t\t};\n\t\t\t\tif (type !== \"object\") {\n\t\t\t\t\tdelete schema.properties;\n\t\t\t\t\tdelete schema.required;\n\t\t\t\t\tdelete schema.additionalProperties;\n\t\t\t\t}\n\t\t\t\tif (type !== \"array\") {\n\t\t\t\t\tdelete schema.items;\n\t\t\t\t\tdelete schema.prefixItems;\n\t\t\t\t}\n\t\t\t\tif (type !== \"string\" && type !== \"number\" && type !== \"integer\") delete schema.format;\n\t\t\t\treturn schema;\n\t\t\t})\n\t\t});\n\t}\n\tconst out = {};\n\tfor (const [k, v] of Object.entries(r)) {\n\t\tif (!KEPT_KEYS.has(k)) continue;\n\t\tconst normalized = normalizeChild(k, v);\n\t\tif (normalized === void 0) continue;\n\t\tout[k] = normalized;\n\t}\n\tif (out[\"type\"] === \"object\" && !(\"additionalProperties\" in out)) out[\"additionalProperties\"] = false;\n\tif (Array.isArray(out[\"oneOf\"]) && !(\"discriminator\" in out)) {\n\t\tconst detected = _detectDiscriminator(out[\"oneOf\"]);\n\t\tif (detected !== void 0) out[\"discriminator\"] = detected;\n\t}\n\tif (\"discriminator\" in out && !Array.isArray(out[\"oneOf\"])) delete out[\"discriminator\"];\n\tif (Object.keys(out).length === 0) return true;\n\treturn out;\n}\nfunction normalizeChild(key, v) {\n\tswitch (key) {\n\t\tcase \"properties\": {\n\t\t\tif (!isPlainObject(v)) return {};\n\t\t\tconst out = {};\n\t\t\tfor (const [pk, pv] of Object.entries(v)) out[pk] = normalizeJsonSchema(pv);\n\t\t\treturn out;\n\t\t}\n\t\tcase \"items\":\n\t\tcase \"additionalProperties\":\n\t\t\tif (v === false) return false;\n\t\t\treturn normalizeJsonSchema(v);\n\t\tcase \"prefixItems\":\n\t\tcase \"anyOf\":\n\t\tcase \"oneOf\":\n\t\t\tif (!Array.isArray(v)) return [];\n\t\t\treturn v.map((s) => normalizeJsonSchema(s));\n\t\tcase \"discriminator\": {\n\t\t\tif (!isPlainObject(v)) return void 0;\n\t\t\tconst name = v[\"propertyName\"];\n\t\t\tif (typeof name !== \"string\" || name.length === 0) return void 0;\n\t\t\treturn { propertyName: name };\n\t\t}\n\t\tcase \"enum\":\n\t\t\tif (!Array.isArray(v)) return [];\n\t\t\treturn v.slice();\n\t\tcase \"required\":\n\t\t\tif (!Array.isArray(v)) return [];\n\t\t\treturn v.slice().sort();\n\t\tdefault: return v;\n\t}\n}\nfunction isEmptyObject(v) {\n\treturn isPlainObject(v) && Object.keys(v).length === 0;\n}\nfunction isPlainObject(v) {\n\treturn v !== null && typeof v === \"object\" && !Array.isArray(v);\n}\n/**\n* Inspect a `oneOf` branch list and return a `discriminator` hint when\n* every branch is an object schema and there is exactly one property name\n* that appears in every branch with a distinct `const`-valued schema.\n*\n* This is the canonical JSON-Schema-only encoding of a tagged union, and\n* the shape `z.toJSONSchema(z.discriminatedUnion(...))` emits.\n*/\nfunction _detectDiscriminator(branches) {\n\tif (branches.length < 2) return void 0;\n\tconst branchPropsList = [];\n\tfor (const b of branches) {\n\t\tif (b === true || b === false) return void 0;\n\t\tif (b.type !== \"object\") return void 0;\n\t\tconst props = b.properties;\n\t\tif (!props) return void 0;\n\t\tbranchPropsList.push(props);\n\t}\n\tlet candidates = _constPropNames(branchPropsList[0]);\n\tfor (let i = 1; i < branchPropsList.length; i++) {\n\t\tcandidates = candidates.filter((n) => _constPropNames(branchPropsList[i]).includes(n));\n\t\tif (candidates.length === 0) return void 0;\n\t}\n\tfor (const name of candidates) {\n\t\tconst seen = /* @__PURE__ */ new Set();\n\t\tlet allDistinct = true;\n\t\tfor (const props of branchPropsList) {\n\t\t\tconst s = props[name];\n\t\t\tconst key = JSON.stringify(s.const);\n\t\t\tif (seen.has(key)) {\n\t\t\t\tallDistinct = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tseen.add(key);\n\t\t}\n\t\tif (allDistinct) return { propertyName: name };\n\t}\n}\nfunction _constPropNames(props) {\n\tconst out = [];\n\tfor (const [k, v] of Object.entries(props)) {\n\t\tif (v === true || v === false) continue;\n\t\tif (\"const\" in v) out.push(k);\n\t}\n\treturn out;\n}\n//#endregion\n//#region src/connection/rpcFailure.ts\nconst rpcFailureBrand = Symbol(\"linkrpc.rpcFailure\");\n/** A nominal failure wrapper: successful application objects can never collide with it. */\nvar RpcFailure = class {\n\terror;\n\t[rpcFailureBrand] = true;\n\tconstructor(error) {\n\t\tthis.error = error;\n\t\tObject.freeze(this);\n\t}\n};\nfunction isRpcFailure(value) {\n\treturn typeof value === \"object\" && value !== null && value[rpcFailureBrand] === true;\n}\n//#endregion\n//#region src/protocol/jsonRpc.ts\nconst ErrorCode = {\n\t/** Default code for named LinkRPC application errors. */\n\tapplicationError: 1,\n\tparseError: -32700,\n\tinvalidRequest: -32600,\n\tmethodNotFound: -32601,\n\tinvalidParams: -32602,\n\tinternalError: -32603,\n\t/** Caller is authenticated but lacks a capability covering the call. */\n\tpermissionRequired: -32401,\n\t/** The peer a request was routed to detached before it could respond. */\n\tpeerDisconnected: -32402,\n\t/** The request exceeded the hub's idle timeout with no stream activity. */\n\trequestTimeout: -32403,\n\t/** The request was cancelled (by the caller, or by the hub on disconnect). */\n\tcancelled: -32800\n};\nfunction isRequest(m) {\n\treturn typeof m.method === \"string\" && m.id !== void 0;\n}\nfunction isNotification(m) {\n\treturn typeof m.method === \"string\" && m.id === void 0;\n}\nfunction isResponse(m) {\n\treturn typeof m.method !== \"string\";\n}\n//#endregion\n//#region src/schema/applicationErrorBrand.ts\nconst applicationErrorBrand = Symbol(\"linkrpc.applicationError\");\nfunction brandApplicationError(value) {\n\treturn Object.freeze(Object.defineProperty(value, applicationErrorBrand, { value: true }));\n}\n//#endregion\n//#region src/schema/schemaSource.ts\nconst schemaSources = /* @__PURE__ */ new WeakMap();\n//#endregion\n//#region src/schema/validationIssue.ts\nfunction jsonPointerSegment(key) {\n\treturn `/${String(key).replace(/~/g, \"~0\").replace(/\\//g, \"~1\")}`;\n}\n//#endregion\n//#region src/schema/errorValidation.ts\nconst bodySchemas = /* @__PURE__ */ new WeakMap();\nfunction parseDeclaredErrorBody(descriptor, body) {\n\treturn parseErrorBody(descriptor.bodySchema ?? errorBodySchema(descriptor), body);\n}\nfunction errorBodySchema(descriptor) {\n\tlet schema = bodySchemas.get(descriptor);\n\tif (schema === void 0) {\n\t\tconst payload = descriptor.dataSchema === void 0 ? {} : { data: descriptor.dataSchema };\n\t\tschema = descriptor.type === void 0 ? strictObject({\n\t\t\tmessage: literal(descriptor.message),\n\t\t\t...payload\n\t\t}) : strictObject({\n\t\t\tmessage: string(),\n\t\t\tdata: strictObject({\n\t\t\t\ttype: literal(descriptor.type),\n\t\t\t\t...payload\n\t\t\t})\n\t\t});\n\t\tbodySchemas.set(descriptor, schema);\n\t}\n\treturn schema;\n}\nfunction parseErrorBody(schema, body) {\n\tconst parsed = safeParse(schema, body);\n\tif (!parsed.success) return {\n\t\tsuccess: false,\n\t\tissues: validationIssues(parsed.error.issues)\n\t};\n\tif (typeof parsed.data !== \"object\" || parsed.data === null || !(\"message\" in parsed.data) || typeof parsed.data.message !== \"string\") return {\n\t\tsuccess: false,\n\t\tissues: [{\n\t\t\tpath: \"/message\",\n\t\t\tmessage: \"Expected a string message\"\n\t\t}]\n\t};\n\treturn {\n\t\tsuccess: true,\n\t\tdata: {\n\t\t\t...parsed.data,\n\t\t\tmessage: parsed.data.message\n\t\t}\n\t};\n}\nfunction validationIssues(issues, prefix = []) {\n\treturn issues.flatMap((issue) => {\n\t\tconst path = [...prefix, ...issue.path];\n\t\tif (issue.code === \"invalid_union\") return issue.errors.flatMap((branch) => validationIssues(branch, path));\n\t\tif (issue.code === \"unrecognized_keys\") return issue.keys.map((key) => ({\n\t\t\tpath: pointer([...path, key]),\n\t\t\tmessage: \"Unexpected property\"\n\t\t}));\n\t\treturn [{\n\t\t\tpath: pointer(path),\n\t\t\tmessage: issue.message\n\t\t}];\n\t});\n}\nfunction pointer(path) {\n\treturn path.map(jsonPointerSegment).join(\"\");\n}\nfunction jsonIssues(value, path = [], ancestors = /* @__PURE__ */ new Set()) {\n\tif (value === null || typeof value === \"string\" || typeof value === \"boolean\" || typeof value === \"number\" && Number.isFinite(value)) return [];\n\tif (typeof value !== \"object\" || ancestors.has(value) || !Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return [{\n\t\tpath: pointer(path),\n\t\tmessage: \"Expected a JSON value\"\n\t}];\n\tancestors.add(value);\n\tconst issues = (Array.isArray(value) ? Array.from(value.entries()) : Object.entries(value)).flatMap(([key, child]) => jsonIssues(child, [...path, key], ancestors));\n\tancestors.delete(value);\n\treturn issues;\n}\n//#endregion\n//#region src/schema/memberTypes.ts\nfunction rpcError(code, schemaOrShape) {\n\tassertErrorCode(code);\n\tconst bodySchema = \"_zod\" in schemaOrShape ? schemaOrShape : object({\n\t\tmessage: schemaOrShape.message ?? string(),\n\t\t...schemaOrShape.data === void 0 ? {} : { data: schemaOrShape.data }\n\t});\n\treturn Object.freeze({\n\t\tcode,\n\t\tbodySchema,\n\t\tcreate(body) {\n\t\t\treturn brandApplicationError({\n\t\t\t\tkind: \"application\",\n\t\t\t\tcode,\n\t\t\t\tmessage: body.message,\n\t\t\t\t...Object.hasOwn(body, \"data\") ? { data: body.data } : {}\n\t\t\t});\n\t\t},\n\t\tis(value) {\n\t\t\tconst payload = isRpcFailure(value) ? value.error : value;\n\t\t\tif (!isApplicationErrorValue(payload) || payload.code !== code || payload.type !== void 0) return false;\n\t\t\treturn parseErrorBody(bodySchema, {\n\t\t\t\tmessage: payload.message,\n\t\t\t\t...Object.hasOwn(payload, \"data\") ? { data: payload.data } : {}\n\t\t\t}).success;\n\t\t}\n\t});\n}\nfunction applicationError(codeOrType, messageOrOptions, dataSchema) {\n\tconst type = typeof codeOrType === \"string\" ? codeOrType : void 0;\n\tif (type === \"\") throw new Error(\"Application error type must be a nonempty string.\");\n\tconst options = typeof messageOrOptions === \"object\" ? messageOrOptions : void 0;\n\tconst code = typeof codeOrType === \"number\" ? codeOrType : options?.code ?? ErrorCode.applicationError;\n\tconst message = type === void 0 ? messageOrOptions : options?.message ?? type;\n\tif (type !== void 0) dataSchema = options?.data;\n\tassertApplicationErrorCode(code);\n\tif (typeof message !== \"string\") throw new Error(\"Application error message must be a string.\");\n\tconst create = dataSchema === void 0 ? function() {\n\t\tif (arguments.length !== 0) throw new Error(`Application error ${code} does not accept data.`);\n\t\treturn Object.freeze({\n\t\t\tkind: \"application\",\n\t\t\tcode,\n\t\t\tmessage,\n\t\t\t...type === void 0 ? {} : { type },\n\t\t\t[applicationErrorBrand]: true\n\t\t});\n\t} : function(data) {\n\t\tif (arguments.length !== 1) throw new Error(`Application error ${code} requires exactly one data value.`);\n\t\treturn Object.freeze({\n\t\t\tkind: \"application\",\n\t\t\tcode,\n\t\t\tmessage,\n\t\t\t...type === void 0 ? {} : { type },\n\t\t\t[applicationErrorBrand]: true,\n\t\t\tdata\n\t\t});\n\t};\n\tconst descriptor = Object.freeze({\n\t\ttype,\n\t\tcode,\n\t\tmessage,\n\t\t...dataSchema === void 0 ? {} : { dataSchema },\n\t\tcreate,\n\t\tis(value) {\n\t\t\tconst payload = isRpcFailure(value) ? value.error : value;\n\t\t\tif (!isApplicationErrorValue(payload)) return false;\n\t\t\tif (payload.kind !== \"application\" || payload.code !== code || payload.type !== type) return false;\n\t\t\tconst data = Object.hasOwn(payload, \"data\") ? { data: payload.data } : {};\n\t\t\treturn parseDeclaredErrorBody(descriptor, {\n\t\t\t\tmessage: payload.message,\n\t\t\t\t...type === void 0 ? data : { data: {\n\t\t\t\t\ttype,\n\t\t\t\t\t...data\n\t\t\t\t} }\n\t\t\t}).success;\n\t\t}\n\t});\n\treturn descriptor;\n}\n/** Runtime nominal check for values produced by an application-error descriptor. */\nfunction isApplicationErrorValue(value) {\n\treturn typeof value === \"object\" && value !== null && value[applicationErrorBrand] === true;\n}\nfunction assertApplicationErrorCode(code) {\n\tassertErrorCode(code);\n\tif (code >= -32768 && code <= -32e3 || code === -32800) throw new Error(`Application error code ${code} is reserved by JSON-RPC or LinkRPC.`);\n}\nfunction assertErrorCode(code) {\n\tif (!Number.isInteger(code) || code < -2147483648 || code > 2147483647) throw new Error(`Application error code ${code} must be a signed 32-bit integer.`);\n}\nvar RequestType = class RequestType {\n\tparamsSchema;\n\tresultSchema;\n\terrorSchema;\n\tdocs;\n\tclientStreamSchema;\n\tserverStreamSchema;\n\tapplicationErrors;\n\tkind = \"request\";\n\tconstructor(paramsSchema, resultSchema, errorSchema, docs = {}, clientStreamSchema, serverStreamSchema, applicationErrors = []) {\n\t\tthis.paramsSchema = paramsSchema;\n\t\tthis.resultSchema = resultSchema;\n\t\tthis.errorSchema = errorSchema;\n\t\tthis.docs = docs;\n\t\tthis.clientStreamSchema = clientStreamSchema;\n\t\tthis.serverStreamSchema = serverStreamSchema;\n\t\tthis.applicationErrors = applicationErrors;\n\t\tconst seen = /* @__PURE__ */ new Set();\n\t\tfor (const error of applicationErrors) {\n\t\t\tif (applicationErrors.some((other) => other !== error && other.code === error.code && (other.bodySchema !== void 0 || error.bodySchema !== void 0))) throw new Error(`Raw error code ${error.code} cannot be shared.`);\n\t\t\tif (error.bodySchema !== void 0) {\n\t\t\t\tassertErrorCode(error.code);\n\t\t\t\tconst key = `code:${error.code}`;\n\t\t\t\tif (seen.has(key)) throw new Error(`Duplicate application error ${key}.`);\n\t\t\t\tseen.add(key);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tassertApplicationErrorCode(error.code);\n\t\t\tif (typeof error.message !== \"string\") throw new Error(\"Application error message must be a string.\");\n\t\t\tif (error.type !== void 0 && (typeof error.type !== \"string\" || error.type.length === 0)) throw new Error(\"Application error type must be a nonempty string.\");\n\t\t\tconst key = error.type === void 0 ? `code:${error.code}` : `type:${error.type}`;\n\t\t\tif (seen.has(key)) throw new Error(`Duplicate application error ${key}.`);\n\t\t\tseen.add(key);\n\t\t}\n\t\tthis.applicationErrors = Object.freeze([...applicationErrors]);\n\t\tthis.errors = this.applicationErrors;\n\t}\n\t/** Declared checked errors, retained as a tuple for generated-contract consumers. */\n\terrors;\n\t/**\n\t* Return a copy of this request type with stream payload schemas\n\t* attached. Pass `undefined` for either direction to leave it\n\t* closed.\n\t* `NoInfer` keeps a contextual MemberMap's `any` stream slots from\n\t* widening undeclared directions; only the supplied schemas infer payloads.\n\t*/\n\twithStream(opts) {\n\t\treturn new RequestType(this.paramsSchema, this.resultSchema, this.errorSchema, this.docs, opts.client, opts.server, this.applicationErrors);\n\t}\n\t/**\n\t* Return a copy with an explicit, typed set of checked application errors.\n\t* The legacy third `requestType` schema remains accepted for compatibility,\n\t* but does not opt a method into checked errors.\n\t*/\n\twithErrors(errors) {\n\t\treturn new RequestType(this.paramsSchema, this.resultSchema, this.errorSchema, this.docs, this.clientStreamSchema, this.serverStreamSchema, errors);\n\t}\n};\nvar NotificationType = class {\n\tparamsSchema;\n\tdocs;\n\tkind = \"notification\";\n\tconstructor(paramsSchema, docs = {}) {\n\t\tthis.paramsSchema = paramsSchema;\n\t\tthis.docs = docs;\n\t}\n};\n/**\n* Define a request method.\n*\n* @example\n* bar: requestType(z.object({ to: z.string() }), z.string(), {\n* description: \"MUST resolve before the next call from the same caller.\",\n* })\n*/\nfunction requestType(params, result, docsOrError, maybeDocs) {\n\tconst isErrorSchema = (v) => typeof v === \"object\" && v !== null && \"_zod\" in v;\n\tconst error = isErrorSchema(docsOrError) ? docsOrError : void 0;\n\tconst docs = (!isErrorSchema(docsOrError) ? docsOrError : maybeDocs) ?? {};\n\treturn new RequestType(params, result ?? void$1(), error ?? void$1(), docs);\n}\n/**\n* Define a notification method.\n*\n* @example\n* foo: notificationType(z.object({ message: z.string() }))\n*/\nfunction notificationType(params, docs = {}) {\n\treturn new NotificationType(params, docs);\n}\n/** Convert a zod schema to our restricted SvcJsonSchema subset. */\nfunction zodToSvcJsonSchema(schema, options) {\n\tconst source = schemaSources.get(schema);\n\tif (source !== void 0) {\n\t\tfor (const [name, component] of Object.entries(source.components)) {\n\t\t\tif (options === void 0) throw new Error(\"Imported schema references require a component destination\");\n\t\t\taddComponent(options.components, name, normalizeJsonSchema(component));\n\t\t}\n\t\treturn normalizeJsonSchema(source.schema);\n\t}\n\tconst type = schema._zod?.def?.type;\n\tif (type === \"void\" || type === \"undefined\") return true;\n\treturn normalizeZodJsonSchema(toJSONSchema(schema, { override: (context) => {\n\t\tconst name = options?.parameterNames?.get(context.zodSchema);\n\t\tif (name !== void 0) {\n\t\t\tfor (const key of Object.keys(context.jsonSchema)) delete context.jsonSchema[key];\n\t\t\tcontext.jsonSchema.$ref = `linkrpc-parameter:${encodeURIComponent(name)}`;\n\t\t} else if (options?.parameterNames !== void 0) {\n\t\t\tfor (const key of [\n\t\t\t\t\"allOf\",\n\t\t\t\t\"patternProperties\",\n\t\t\t\t\"unevaluatedProperties\",\n\t\t\t\t\"if\",\n\t\t\t\t\"then\",\n\t\t\t\t\"else\",\n\t\t\t\t\"contains\"\n\t\t\t]) if (key in context.jsonSchema) throw new Error(`Unsupported template JSON Schema keyword \"${key}\"`);\n\t\t}\n\t} }), options);\n}\nfunction normalizeZodJsonSchema(raw, options) {\n\tif (!isRecord(raw)) return normalizeJsonSchema(raw);\n\tconst definitions = isRecord(raw.$defs) ? raw.$defs : {};\n\tconst localRefs = collectLocalRefs(raw);\n\tif (Object.keys(definitions).length === 0 && localRefs.size === 0) return normalizeJsonSchema(raw);\n\tif (options === void 0) throw new Error(\"zodToSvcJsonSchema: local references require a component destination\");\n\tconst componentNamePrefix = `method=${encodeComponentNamePart(options.methodName)}&schema=${encodeComponentNamePart(options.schemaPosition)}`;\n\tconst definitionComponents = /* @__PURE__ */ new Map();\n\tfor (const definitionName of Object.keys(definitions)) definitionComponents.set(definitionName, `${componentNamePrefix}&def=${encodeComponentNamePart(definitionName)}`);\n\tconst rootComponent = localRefs.has(\"#\") ? `${componentNamePrefix}&root` : void 0;\n\tconst rewrite = (value) => rewriteLocalRefs(value, definitionComponents, rootComponent);\n\tfor (const [definitionName, definition] of Object.entries(definitions)) {\n\t\tconst componentName = definitionComponents.get(definitionName);\n\t\tif (componentName === void 0) throw new Error(`zodToSvcJsonSchema: missing component for \"${definitionName}\"`);\n\t\taddComponent(options.components, componentName, normalizeJsonSchema(rewrite(definition)));\n\t}\n\tconst root = rewrite(raw);\n\tif (rootComponent !== void 0) {\n\t\taddComponent(options.components, rootComponent, normalizeJsonSchema(root));\n\t\treturn { $ref: componentRef(rootComponent) };\n\t}\n\treturn normalizeJsonSchema(root);\n}\nfunction collectLocalRefs(value, refs = /* @__PURE__ */ new Set()) {\n\tif (Array.isArray(value)) {\n\t\tfor (const child of value) collectLocalRefs(child, refs);\n\t\treturn refs;\n\t}\n\tif (!isRecord(value)) return refs;\n\tif (typeof value.$ref === \"string\" && value.$ref.startsWith(\"#\")) refs.add(value.$ref);\n\tfor (const child of Object.values(value)) collectLocalRefs(child, refs);\n\treturn refs;\n}\nfunction rewriteLocalRefs(value, definitionComponents, rootComponent) {\n\tif (Array.isArray(value)) return value.map((child) => rewriteLocalRefs(child, definitionComponents, rootComponent));\n\tif (!isRecord(value)) return value;\n\tconst result = {};\n\tfor (const [key, child] of Object.entries(value)) {\n\t\tif (key === \"$defs\") continue;\n\t\tif (key === \"$ref\" && typeof child === \"string\") result[key] = rewriteLocalRef(child, definitionComponents, rootComponent);\n\t\telse result[key] = rewriteLocalRefs(child, definitionComponents, rootComponent);\n\t}\n\treturn result;\n}\nfunction rewriteLocalRef(ref, definitionComponents, rootComponent) {\n\tif (ref === \"#\") {\n\t\tif (rootComponent === void 0) throw new Error(\"zodToSvcJsonSchema: root reference has no component destination\");\n\t\treturn componentRef(rootComponent);\n\t}\n\tif (ref.startsWith(\"#/$defs/\")) {\n\t\tconst encodedName = ref.slice(8);\n\t\tconst definitionName = [...definitionComponents.keys()].find((name) => encodeJsonPointerSegment(name) === encodedName);\n\t\tconst componentName = definitionName === void 0 ? void 0 : definitionComponents.get(definitionName);\n\t\tif (componentName === void 0) throw new Error(`zodToSvcJsonSchema: dangling local reference \"${ref}\"`);\n\t\treturn componentRef(componentName);\n\t}\n\tif (ref.startsWith(\"#\") && !ref.startsWith(\"#/components/schemas/\")) throw new Error(`zodToSvcJsonSchema: unsupported local reference \"${ref}\"`);\n\treturn ref;\n}\nfunction addComponent(components, name, schema) {\n\tif (Object.hasOwn(components, name)) throw new Error(`zodToSvcJsonSchema: duplicate component name \"${name}\"`);\n\tcomponents[name] = schema;\n}\nfunction componentRef(name) {\n\treturn `#/components/schemas/${encodeJsonPointerSegment(name)}`;\n}\nfunction encodeJsonPointerSegment(value) {\n\treturn value.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\nfunction encodeComponentNamePart(value) {\n\treturn encodeURIComponent(value).replace(/~/g, \"%7E\");\n}\nfunction isRecord(value) {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n//#endregion\n//#region src/schema/schemaValidationError.ts\n/** Invalid reflected schema data, as distinct from an unexpected implementation failure. */\nvar SchemaValidationError = class extends Error {\n\tname = \"SchemaValidationError\";\n};\n//#endregion\n//#region src/schema/assertSchemaReferences.ts\nconst componentPrefix = \"#/components/schemas/\";\nfunction componentSchemaRef(name) {\n\treturn componentPrefix + name.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\nfunction componentSchemaName(ref) {\n\tif (!ref.startsWith(componentPrefix)) throw new SchemaValidationError(`Invalid component reference: ${ref}`);\n\tconst token = ref.slice(21);\n\tif (token.includes(\"/\") || /~(?:[^01]|$)/.test(token)) throw new SchemaValidationError(`Invalid component reference token: ${ref}`);\n\treturn token.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n}\n/**\n* Check the finite schema graph without interpreting JSON literal payloads.\n* A reference/union-only cycle is invalid; descending into an object member\n* or an array item guards a cycle, but does not imply the schema is nonempty.\n*/\nfunction assertSchemaReferences(roots, components = {}) {\n\tconst nodes = /* @__PURE__ */ new Set();\n\tconst pending = [...roots, ...Object.values(components)];\n\tconst unguarded = /* @__PURE__ */ new Map();\n\twhile (pending.length > 0) {\n\t\tconst node = pending.pop();\n\t\tif (typeof node === \"boolean\" || nodes.has(node)) continue;\n\t\tnodes.add(node);\n\t\tconst edges = [];\n\t\tif (\"$ref\" in node) {\n\t\t\tconst name = componentSchemaName(node.$ref);\n\t\t\tif (!Object.hasOwn(components, name)) throw new Error(`Unresolved component reference: ${node.$ref}`);\n\t\t\tedges.push(components[name]);\n\t\t}\n\t\tif (\"anyOf\" in node) edges.push(...node.anyOf);\n\t\tif (\"oneOf\" in node) edges.push(...node.oneOf);\n\t\tunguarded.set(node, edges);\n\t\tpending.push(...edges);\n\t\tif (\"type\" in node && node.type === \"object\") pending.push(...Object.values(node.properties ?? {}), node.additionalProperties);\n\t\tif (\"type\" in node && node.type === \"array\") {\n\t\t\tif (\"prefixItems\" in node) pending.push(...node.prefixItems);\n\t\t\tif (node.items !== void 0) pending.push(node.items);\n\t\t}\n\t}\n\tconst visiting = /* @__PURE__ */ new Set();\n\tconst checked = /* @__PURE__ */ new Set();\n\tconst visit = (node) => {\n\t\tif (typeof node === \"boolean\" || checked.has(node)) return;\n\t\tif (visiting.has(node)) throw new Error(\"Unguarded recursive schema: cycle does not descend into a child value\");\n\t\tvisiting.add(node);\n\t\tfor (const child of unguarded.get(node) ?? []) visit(child);\n\t\tvisiting.delete(node);\n\t\tchecked.add(node);\n\t};\n\tfor (const node of nodes) visit(node);\n}\n//#endregion\n//#region src/protocol/jcs.ts\n/**\n* RFC 8785 JSON Canonicalization Scheme (JCS).\n*\n* Used as the byte-deterministic encoding under every linkrpc signature\n* (RPC calls, capabilities, hub-signed previews). Both signer and verifier\n* canonicalize the same value object and obtain byte-identical UTF-8 bytes.\n*\n* Implementation inlined from the `canonicalize` npm package (Apache-2.0,\n* https://github.com/erdtman/canonicalize) so this module stays\n* zero-dependency for browser bundlers that don't resolve transitive\n* npm specifiers (e.g. the in-house app-bundler).\n*/\n/** RFC 8785 canonical JSON string for `value`. */\nfunction jcsCanonicalize(value) {\n\tconst out = _canonicalize(value);\n\tif (out === void 0) throw new Error(\"jcsCanonicalize: value is not JSON-representable\");\n\treturn out;\n}\nconst _encoder = new TextEncoder();\n/** UTF-8 bytes of the RFC 8785 canonical JSON for `value`. The thing actually signed / hashed. */\nfunction jcsCanonicalizeBytes(value) {\n\treturn _encoder.encode(jcsCanonicalize(value));\n}\nfunction _canonicalize(object, seen = /* @__PURE__ */ new Set()) {\n\tif (typeof object === \"number\" && Number.isNaN(object)) throw new Error(\"NaN is not allowed\");\n\tif (typeof object === \"number\" && !Number.isFinite(object)) throw new Error(\"Infinity is not allowed\");\n\tif (object === null || typeof object !== \"object\") return JSON.stringify(object);\n\tconst obj = object;\n\tif (typeof obj.toJSON === \"function\") {\n\t\tif (seen.has(obj)) throw new Error(\"Circular reference detected\");\n\t\tseen.add(obj);\n\t\tconst result = _canonicalize(obj.toJSON(), seen);\n\t\tseen.delete(obj);\n\t\treturn result;\n\t}\n\tif (seen.has(obj)) throw new Error(\"Circular reference detected\");\n\tseen.add(obj);\n\tlet result;\n\tif (Array.isArray(obj)) result = `[${obj.map((cv) => {\n\t\treturn _canonicalize(cv === void 0 || typeof cv === \"symbol\" ? null : cv, seen);\n\t}).join(\",\")}]`;\n\telse {\n\t\tconst parts = [];\n\t\tfor (const key of Object.keys(obj).sort()) {\n\t\t\tconst v = obj[key];\n\t\t\tif (v === void 0 || typeof v === \"symbol\") continue;\n\t\t\tparts.push(`${JSON.stringify(key)}:${_canonicalize(v, seen)}`);\n\t\t}\n\t\tresult = `{${parts.join(\",\")}}`;\n\t}\n\tseen.delete(obj);\n\treturn result;\n}\n//#endregion\n//#region src/crypto/sha256.ts\n/**\n* Pure-JS SHA-256 (RFC 6234 / FIPS 180-4). Synchronous, dependency-free,\n* isomorphic. Used internally by linkrpc for content-hashing interface\n* schemas and deriving identity slot names; also surfaced through the\n* `crypto` API as `crypto.sha256`. For signature work we go through the\n* `crypto` module (`./identity/crypto`).\n*\n* Replaces the previous `@noble/hashes/sha2` import so the bundle has\n* no runtime npm dependencies. Trades the well-vetted dep for ~80 lines\n* of straight-line code that has no branching on input contents and is\n* exercised by the existing test vectors plus `sha256.test.ts`.\n*/\nconst K = new Uint32Array([\n\t1116352408,\n\t1899447441,\n\t3049323471,\n\t3921009573,\n\t961987163,\n\t1508970993,\n\t2453635748,\n\t2870763221,\n\t3624381080,\n\t310598401,\n\t607225278,\n\t1426881987,\n\t1925078388,\n\t2162078206,\n\t2614888103,\n\t3248222580,\n\t3835390401,\n\t4022224774,\n\t264347078,\n\t604807628,\n\t770255983,\n\t1249150122,\n\t1555081692,\n\t1996064986,\n\t2554220882,\n\t2821834349,\n\t2952996808,\n\t3210313671,\n\t3336571891,\n\t3584528711,\n\t113926993,\n\t338241895,\n\t666307205,\n\t773529912,\n\t1294757372,\n\t1396182291,\n\t1695183700,\n\t1986661051,\n\t2177026350,\n\t2456956037,\n\t2730485921,\n\t2820302411,\n\t3259730800,\n\t3345764771,\n\t3516065817,\n\t3600352804,\n\t4094571909,\n\t275423344,\n\t430227734,\n\t506948616,\n\t659060556,\n\t883997877,\n\t958139571,\n\t1322822218,\n\t1537002063,\n\t1747873779,\n\t1955562222,\n\t2024104815,\n\t2227730452,\n\t2361852424,\n\t2428436474,\n\t2756734187,\n\t3204031479,\n\t3329325298\n]);\nfunction _rotr(x, n) {\n\treturn x >>> n | x << 32 - n;\n}\nfunction sha256(data) {\n\tconst inputLen = data.length;\n\tconst bitLen = inputLen * 8;\n\tconst paddedLen = inputLen + 9 + 63 & -64;\n\tconst padded = new Uint8Array(paddedLen);\n\tpadded.set(data);\n\tpadded[inputLen] = 128;\n\tconst view = new DataView(padded.buffer);\n\tview.setUint32(paddedLen - 8, Math.floor(bitLen / 4294967296), false);\n\tview.setUint32(paddedLen - 4, bitLen >>> 0, false);\n\tconst H = new Uint32Array([\n\t\t1779033703,\n\t\t3144134277,\n\t\t1013904242,\n\t\t2773480762,\n\t\t1359893119,\n\t\t2600822924,\n\t\t528734635,\n\t\t1541459225\n\t]);\n\tconst W = /* @__PURE__ */ new Uint32Array(64);\n\tfor (let block = 0; block < paddedLen; block += 64) {\n\t\tfor (let t = 0; t < 16; t++) W[t] = view.getUint32(block + t * 4, false);\n\t\tfor (let t = 16; t < 64; t++) {\n\t\t\tconst w15 = W[t - 15];\n\t\t\tconst w2 = W[t - 2];\n\t\t\tconst s0 = _rotr(w15, 7) ^ _rotr(w15, 18) ^ w15 >>> 3;\n\t\t\tconst s1 = _rotr(w2, 17) ^ _rotr(w2, 19) ^ w2 >>> 10;\n\t\t\tW[t] = W[t - 16] + s0 + W[t - 7] + s1 >>> 0;\n\t\t}\n\t\tlet a = H[0], b = H[1], c = H[2], d = H[3];\n\t\tlet e = H[4], f = H[5], g = H[6], h = H[7];\n\t\tfor (let t = 0; t < 64; t++) {\n\t\t\tconst S1 = _rotr(e, 6) ^ _rotr(e, 11) ^ _rotr(e, 25);\n\t\t\tconst ch = e & f ^ ~e & g;\n\t\t\tconst temp1 = h + S1 + ch + K[t] + W[t] >>> 0;\n\t\t\tconst temp2 = (_rotr(a, 2) ^ _rotr(a, 13) ^ _rotr(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;\n\t\t\th = g;\n\t\t\tg = f;\n\t\t\tf = e;\n\t\t\te = d + temp1 >>> 0;\n\t\t\td = c;\n\t\t\tc = b;\n\t\t\tb = a;\n\t\t\ta = temp1 + temp2 >>> 0;\n\t\t}\n\t\tH[0] = H[0] + a >>> 0;\n\t\tH[1] = H[1] + b >>> 0;\n\t\tH[2] = H[2] + c >>> 0;\n\t\tH[3] = H[3] + d >>> 0;\n\t\tH[4] = H[4] + e >>> 0;\n\t\tH[5] = H[5] + f >>> 0;\n\t\tH[6] = H[6] + g >>> 0;\n\t\tH[7] = H[7] + h >>> 0;\n\t}\n\tconst out = /* @__PURE__ */ new Uint8Array(32);\n\tconst outView = new DataView(out.buffer);\n\tfor (let i = 0; i < 8; i++) outView.setUint32(i * 4, H[i], false);\n\treturn out;\n}\n//#endregion\n//#region src/schema/hash.ts\nconst methodSchemaFields = [\n\t\"params\",\n\t\"result\",\n\t\"clientStream\",\n\t\"serverStream\"\n];\n/**\n* Compute the interface hash: SHA-256 of the canonicalized schema, truncated\n* to 16 hex chars (64 bits of collision budget per id).\n*\n* Canonicalization strips the schema down to its **normative wire-contract\n* projection** before hashing, so a single interface document can carry richer\n* non-normative material (codegen hints, safety expressions, notes) without\n* changing identity:\n*\n* 1. Normalize every JSON-Schema position (`params`, `result`, streams, and\n* `components.schemas`) onto the decidable linkrpc subset.\n* 2. Strip every `comment` field (non-normative — must not affect identity).\n* `description` is NORMATIVE and kept in the hash.\n* 3. Strip every **specification-extension** field — any object key whose name\n* begins with `x-` — at every level of the document (see\n* {@link EXTENSION_PREFIX}). This is the minimal, explicit \"one document,\n* two views\" mechanism: the stored document keeps the rich `x-…`\n* expressions; identity hashes only the simple contract. It mirrors\n* OpenRPC/OpenAPI specification extensions (this schema format is a subset\n* of OpenRPC 1.x). Editing an `x-…` value never changes the hash; changing\n* a wire field (`params`, `result`, member names, `type`, `required`,\n* `description`, `annotations`, …) does.\n* 4. Omit the top-level `hash` field itself.\n* 5. RFC 8785 JCS encode (recursive key sort, no whitespace) via {@link jcsCanonicalize}.\n*\n* Because no interface schema uses `x-…` keys today, this preserves every\n* existing hash: stripping a set of keys that are always absent is a no-op.\n*\n* > Reservation. `x-…` is reserved for non-normative extensions at every level.\n* > Member names cannot collide (they are alphanumeric per chapter 01 §2), and\n* > object property names in the JSON Schema subset MUST NOT begin with `x-`.\n*/\nfunction computeInterfaceHash(schema) {\n\tconst json = jcsCanonicalize(stripNonNormative(normalizeSchemaPositions(schema), true));\n\tconst digest = sha256(new TextEncoder().encode(json));\n\treturn Array.from(digest.subarray(0, 8), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\nfunction normalizeSchemaPositions(schema) {\n\tconst methods = Object.fromEntries(Object.entries(schema.methods).map(([name, method]) => {\n\t\tconst normalized = { ...method };\n\t\tfor (const field of methodSchemaFields) {\n\t\t\tconst value = normalized[field];\n\t\t\tif (value !== void 0) normalized[field] = normalizeJsonSchema(value);\n\t\t}\n\t\tif (method.errors !== void 0) normalized.errors = method.errors.map((error) => error.schema !== void 0 ? {\n\t\t\t...error,\n\t\t\tschema: normalizeJsonSchema(error.schema)\n\t\t} : {\n\t\t\t...error,\n\t\t\t...error.data === void 0 ? {} : { data: normalizeJsonSchema(error.data) }\n\t\t});\n\t\treturn [name, normalized];\n\t}));\n\tconst componentSchemas = schema.components?.schemas;\n\tconst components = componentSchemas === void 0 ? schema.components : {\n\t\t...schema.components,\n\t\tschemas: Object.fromEntries(Object.entries(componentSchemas).map(([name, value]) => [name, normalizeJsonSchema(value)]))\n\t};\n\treturn {\n\t\t...schema,\n\t\tmethods,\n\t\t...components === void 0 ? {} : { components }\n\t};\n}\n/**\n* Prefix marking a non-normative **specification-extension** key. Any object\n* key beginning with this prefix is stripped before hashing (at every level),\n* exactly like `comment`. Reserved for rich, identity-neutral material such as\n* codegen directives, richer validation/safety expressions, or tooling hints.\n*/\nconst EXTENSION_PREFIX = \"x-\";\n/** True for a key that must not contribute to the interface hash. */\nfunction isNonNormativeKey(key, isRoot) {\n\treturn key === \"comment\" || key.startsWith(\"x-\") || isRoot && (key === \"hash\" || key === \"tags\");\n}\nfunction stripNonNormative(value, isRoot = false) {\n\tif (value === null || typeof value !== \"object\") return value;\n\tif (Array.isArray(value)) return value.map((v) => stripNonNormative(v));\n\tconst out = {};\n\tfor (const k of Object.keys(value)) {\n\t\tif (isNonNormativeKey(k, isRoot)) continue;\n\t\tconst v = value[k];\n\t\tif (v === void 0) continue;\n\t\tout[k] = stripNonNormative(v);\n\t}\n\treturn out;\n}\n//#endregion\n//#region src/schema/interfaceTemplates.ts\nconst INTERFACE_TEMPLATES_EXTENSION = \"x-interface-templates\";\n/** Reflect concrete schema arguments without importing interface constructors. */\nfunction bindTemplateArguments(template, parameters) {\n\tvalidateInterfaceTemplate(template);\n\tconst expectedParameters = new Set(template.parameters);\n\tconst suppliedParameters = Object.keys(parameters);\n\tfor (const name of suppliedParameters) if (!expectedParameters.has(name)) throw new Error(`Interface template \"${template.id}\" supplies unknown parameter \"${name}\"`);\n\tfor (const name of expectedParameters) if (!Object.hasOwn(parameters, name)) throw new Error(`Interface template \"${template.id}\" is missing parameter \"${name}\"`);\n\tconst arguments_ = {};\n\tfor (const name of template.parameters) {\n\t\tconst components = {};\n\t\tconst parameterSchema = parameters[name];\n\t\tif (parameterSchema === void 0) throw new Error(`Interface template \"${template.id}\" is missing parameter \"${name}\"`);\n\t\targuments_[name] = {\n\t\t\tschema: zodToSvcJsonSchema(parameterSchema, {\n\t\t\t\tmethodName: `template=${template.id}`,\n\t\t\t\tschemaPosition: `parameter=${name}`,\n\t\t\t\tcomponents\n\t\t\t}),\n\t\t\t...Object.keys(components).length === 0 ? {} : { components: { schemas: components } }\n\t\t};\n\t}\n\treturn arguments_;\n}\n/** Attach structural metadata to an already lowered schema, without rebuilding a definition. */\nfunction attachInterfaceTemplates(schema, mapped) {\n\tconst templates = Object.create(null);\n\tconst instances = [];\n\tfor (const [name, instance] of Object.entries(mapped)) {\n\t\tconst priorTemplate = templates[instance.template.id];\n\t\tif (priorTemplate !== void 0 && !interfaceTemplatesEqual(priorTemplate, instance.template)) throw new Error(`Conflicting definitions for interface template \"${instance.template.id}\"`);\n\t\ttemplates[instance.template.id] = priorTemplate === void 0 ? instance.template : {\n\t\t\t...priorTemplate,\n\t\t\ttags: normalizeInterfaceTags([...priorTemplate.tags ?? [], ...instance.template.tags ?? []])\n\t\t};\n\t\tinstances.push({\n\t\t\t...instance.schema,\n\t\t\tname\n\t\t});\n\t}\n\tconst tags = normalizeInterfaceTags([...schema.tags ?? [], ...instances.flatMap((instance) => templates[instance.template].tags ?? [])]);\n\treturn {\n\t\t...schema,\n\t\t...schema.tags !== void 0 || tags.length > 0 ? { tags } : {},\n\t\t[INTERFACE_TEMPLATES_EXTENSION]: {\n\t\t\ttemplates,\n\t\t\tinstances\n\t\t}\n\t};\n}\n/** Stable, deduplicated discovery labels for a schema and its instantiated templates. */\nfunction getInterfaceTags(schema) {\n\tvalidateInterfaceTemplates(schema);\n\tconst metadata = schema[INTERFACE_TEMPLATES_EXTENSION];\n\treturn normalizeInterfaceTags([...schema.tags ?? [], ...(metadata?.instances ?? []).flatMap((instance) => metadata?.templates[instance.template]?.tags ?? [])]);\n}\nfunction normalizeInterfaceTags(tags) {\n\treturn [...new Set(tags)].sort();\n}\nfunction validateInterfaceTemplates(schema) {\n\tvalidateTags(schema.tags, `Interface \"${schema.id}\"`);\n\tconst raw = schema[INTERFACE_TEMPLATES_EXTENSION];\n\tif (raw === void 0) return;\n\tif (!_isRecord(raw) || !_isRecord(raw.templates) || !Array.isArray(raw.instances)) throw new SchemaValidationError(`${INTERFACE_TEMPLATES_EXTENSION} must contain templates and instances`);\n\tconst templates = raw.templates;\n\tfor (const [id, template] of Object.entries(templates)) {\n\t\tif (!_isRecord(template) || template.id !== id) throw new SchemaValidationError(`Interface template key \"${id}\" must match its id`);\n\t\tvalidateInterfaceTemplate(template);\n\t}\n\tconst occupied = /* @__PURE__ */ new Map();\n\tconst names = /* @__PURE__ */ new Set();\n\tfor (const value of raw.instances) {\n\t\tif (!_isRecord(value)) throw new SchemaValidationError(\"Interface template instance must be an object\");\n\t\tif (typeof value.name !== \"string\") throw new SchemaValidationError(\"Interface template instance name must be a string\");\n\t\tif (typeof value.template !== \"string\") throw new SchemaValidationError(\"Interface template reference must be a string\");\n\t\tif (value.prefix !== void 0) throw new SchemaValidationError(\"Interface template instances require explicit member mappings, not prefixes\");\n\t\tif (!_isRecord(value.members)) throw new SchemaValidationError(\"Interface template members must be an object\");\n\t\tif (!_isRecord(value.arguments)) throw new SchemaValidationError(\"Interface template arguments must be an object\");\n\t\tconst instance = {\n\t\t\tname: value.name,\n\t\t\ttemplate: value.template,\n\t\t\tmembers: value.members,\n\t\t\targuments: value.arguments\n\t\t};\n\t\t_assertSegment(instance.name, \"interface template instance name\");\n\t\tif (names.has(instance.name)) throw new SchemaValidationError(`Interface template instance name collision at \"${instance.name}\"`);\n\t\tnames.add(instance.name);\n\t\tconst template = templates[instance.template];\n\t\tif (!Object.hasOwn(templates, instance.template)) throw new SchemaValidationError(`Interface template instance \"${instance.name}\" references unknown template \"${instance.template}\"`);\n\t\t_validateArguments(instance, template);\n\t\tif (instance.members !== void 0) {\n\t\t\tfor (const name of Object.keys(instance.members)) if (!Object.hasOwn(template.methods, name)) throw new SchemaValidationError(`Unknown mapped member \"${name}\"`);\n\t\t\tfor (const name of Object.keys(template.methods)) {\n\t\t\t\tconst target = instance.members[name];\n\t\t\t\tif (!Object.hasOwn(instance.members, name) || typeof target !== \"string\") throw new SchemaValidationError(`Missing mapped member \"${name}\"`);\n\t\t\t}\n\t\t}\n\t\t_validateInstanceMethods(schema, instance, template, occupied);\n\t}\n}\n/**\n* Best-effort reflection selection, not template consumption or RPC validation.\n* Keep a whole document; incompatible explanations and ties retain the first.\n* Malformed optional metadata is unranked, while template-aware consumers still\n* use validateInterfaceTemplates and report its errors normally.\n*/\nfunction preferRicherInterfaceSchema(existing, candidate) {\n\tif (existing.id !== candidate.id || existing.hash !== candidate.hash) return existing;\n\tif (computeInterfaceHash(existing) !== existing.hash || computeInterfaceHash(candidate) !== candidate.hash) return existing;\n\tvalidateTags(existing.tags, `Interface \"${existing.id}\"`);\n\tvalidateTags(candidate.tags, `Interface \"${candidate.id}\"`);\n\tconst next = _rankingMetadata(candidate);\n\tconst prior = _rankingMetadata(existing);\n\tif (candidate[\"x-interface-templates\"] !== void 0 && next === void 0) return existing;\n\tif (existing[\"x-interface-templates\"] !== void 0 && prior === void 0) return candidate;\n\tif (prior !== void 0 && next === void 0) return existing;\n\tif (next !== void 0 && prior !== void 0) {\n\t\tfor (const [id, template] of Object.entries(prior.templates)) if (!Object.hasOwn(next.templates, id) || !interfaceTemplatesEqual(template, next.templates[id])) return existing;\n\t\tfor (const instance of prior.instances) if (!next.instances.some((value) => _jsonEqual(instance, value))) return existing;\n\t\tfor (const [key, value] of Object.entries(prior)) if (key !== \"templates\" && key !== \"instances\" && !_jsonEqual(value, next[key])) return existing;\n\t}\n\tconst existingTags = getInterfaceTags(existing);\n\tconst candidateTags = getInterfaceTags(candidate);\n\tif (existingTags.some((tag) => !candidateTags.includes(tag))) return existing;\n\treturn prior === void 0 && next !== void 0 || prior !== void 0 && next !== void 0 && (Object.keys(next.templates).length > Object.keys(prior.templates).length || next.instances.length > prior.instances.length) || candidateTags.length > existingTags.length ? candidate : existing;\n}\nfunction _rankingMetadata(schema) {\n\tif (schema[\"x-interface-templates\"] === void 0) return void 0;\n\ttry {\n\t\tvalidateInterfaceTemplates(schema);\n\t} catch (error) {\n\t\tif (!(error instanceof SchemaValidationError)) throw error;\n\t\treturn;\n\t}\n\treturn schema[INTERFACE_TEMPLATES_EXTENSION];\n}\nfunction validateInterfaceTemplate(template) {\n\tif (!_isRecord(template) || typeof template.id !== \"string\" || template.id.length === 0) throw new SchemaValidationError(\"Interface template id must be a non-empty string\");\n\tif (!Array.isArray(template.parameters) || !_isRecord(template.methods)) throw new SchemaValidationError(`Interface template \"${template.id}\" must contain parameters and methods`);\n\tvalidateTags(template.tags, `Interface template \"${template.id}\"`);\n\tconst parameters = /* @__PURE__ */ new Set();\n\tfor (const parameter of template.parameters) {\n\t\tif (typeof parameter !== \"string\" || parameter.length === 0) throw new SchemaValidationError(`Interface template \"${template.id}\" has an invalid parameter name`);\n\t\tif (parameters.has(parameter)) throw new SchemaValidationError(`Interface template \"${template.id}\" repeats parameter \"${parameter}\"`);\n\t\tparameters.add(parameter);\n\t}\n\tconst components = _componentSchemas(template.components);\n\tfor (const [name, method] of Object.entries(template.methods)) {\n\t\t_assertSegment(name, `member of interface template \"${template.id}\"`);\n\t\tif (!_isRecord(method) || !Object.hasOwn(method, \"params\")) throw new SchemaValidationError(`Interface template \"${template.id}\" member \"${name}\" has no params`);\n\t\tfor (const field of _methodSchemaFields) {\n\t\t\tconst value = method[field];\n\t\t\tif (field === \"params\" || value !== void 0) _validateTemplateSchema(value, parameters, components, /* @__PURE__ */ new Set());\n\t\t}\n\t\tif (method.errors !== void 0 && !Array.isArray(method.errors)) throw new SchemaValidationError(\"Interface template method errors must be an array\");\n\t\tfor (const error of method.errors ?? []) {\n\t\t\tif (!_isRecord(error)) throw new SchemaValidationError(\"Interface template method error must be an object\");\n\t\t\tif (error.schema !== void 0) _validateTemplateSchema(error.schema, parameters, components, /* @__PURE__ */ new Set());\n\t\t\tif (error.data !== void 0) _validateTemplateSchema(error.data, parameters, components, /* @__PURE__ */ new Set());\n\t\t}\n\t}\n\tfor (const component of Object.values(components)) _validateTemplateSchema(component, parameters, components, /* @__PURE__ */ new Set());\n}\nfunction _validateTemplateSchema(schema, parameters, components, seen) {\n\tif (typeof schema === \"boolean\") return;\n\tif (!_isRecord(schema)) throw new SchemaValidationError(\"Interface template schema must be an object or boolean\");\n\tif (seen.has(schema)) return;\n\tseen.add(schema);\n\tif (\"$parameter\" in schema) {\n\t\tif (Object.keys(schema).length !== 1 || typeof schema.$parameter !== \"string\") throw new SchemaValidationError(\"A schema parameter reference must contain only $parameter\");\n\t\tif (!parameters.has(schema.$parameter)) throw new SchemaValidationError(`Unknown schema parameter \"${schema.$parameter}\"`);\n\t\treturn;\n\t}\n\tif (\"$ref\" in schema) {\n\t\tif (typeof schema.$ref !== \"string\") throw new SchemaValidationError(\"Component reference must be a string\");\n\t\tconst name = componentSchemaName(schema.$ref);\n\t\tif (!Object.hasOwn(components, name)) throw new SchemaValidationError(`Unknown interface template component \"${name}\"`);\n\t}\n\tfor (const child of _schemaChildren(schema)) _validateTemplateSchema(child, parameters, components, seen);\n}\nfunction _validateArguments(instance, template) {\n\tconst expected = new Set(template.parameters);\n\tfor (const name of Object.keys(instance.arguments)) if (!expected.has(name)) throw new SchemaValidationError(`Interface template instance \"${instance.name}\" supplies unknown parameter \"${name}\"`);\n\tfor (const name of expected) {\n\t\tconst argument = instance.arguments[name];\n\t\tif (!_isRecord(argument) || !Object.hasOwn(argument, \"schema\")) throw new SchemaValidationError(`Interface template instance \"${instance.name}\" is missing parameter \"${name}\"`);\n\t\tconst components = _componentSchemas(argument.components);\n\t\t_validateConcreteSchema(argument.schema, components, /* @__PURE__ */ new Set());\n\t\tfor (const component of Object.values(components)) _validateConcreteSchema(component, components, /* @__PURE__ */ new Set());\n\t}\n}\nfunction _validateConcreteSchema(schema, components, seen) {\n\tif (typeof schema === \"boolean\") return;\n\tif (!_isRecord(schema)) throw new SchemaValidationError(\"Concrete schema argument must be an object or boolean\");\n\tif (seen.has(schema)) return;\n\tseen.add(schema);\n\tif (\"$parameter\" in schema) throw new SchemaValidationError(\"Concrete schema arguments cannot contain $parameter\");\n\tif (\"$ref\" in schema) {\n\t\tif (typeof schema.$ref !== \"string\") throw new SchemaValidationError(\"Component reference must be a string\");\n\t\tconst name = componentSchemaName(schema.$ref);\n\t\tif (!Object.hasOwn(components, name)) throw new SchemaValidationError(`Unknown schema argument component \"${name}\"`);\n\t}\n\tfor (const child of _schemaChildren(schema)) _validateConcreteSchema(child, components, seen);\n}\nfunction _validateInstanceMethods(schema, instance, template, occupied) {\n\tconst expectedComponents = {};\n\tconst instantiatedMethods = Object.fromEntries(Object.entries(template.methods).map(([name, method]) => [name, _instantiateMethod(method, template, instance, expectedComponents)]));\n\tconst actualComponents = schema.components?.schemas ?? {};\n\tfor (const [name, expected] of Object.entries(instantiatedMethods)) {\n\t\tconst flattenedName = interfaceTemplateMemberName(instance, name);\n\t\t_assertSegment(flattenedName, `mapped member of interface template instance \"${instance.name}\"`);\n\t\tconst prior = occupied.get(flattenedName);\n\t\tif (prior !== void 0) throw new SchemaValidationError(`Interface template member collision at \"${flattenedName}\" between \"${prior}\" and \"${instance.name}\"`);\n\t\toccupied.set(flattenedName, instance.name);\n\t\tconst actual = schema.methods[flattenedName];\n\t\tif (actual === void 0) throw new SchemaValidationError(`Interface template instance \"${instance.name}\" is missing mapped member \"${flattenedName}\"`);\n\t\tif (!_methodsEquivalent(expected, actual, expectedComponents, actualComponents)) throw new SchemaValidationError(`Interface template instance \"${instance.name}\" member \"${flattenedName}\" does not match its instantiated template`);\n\t}\n}\nfunction interfaceTemplateMemberName(instance, member) {\n\tconst mapped = instance.members[member];\n\tif (mapped !== void 0) return mapped;\n\tthrow new Error(`Missing mapped member \"${member}\"`);\n}\nfunction _instantiateMethod(method, template, instance, components) {\n\tconst instantiate = (value) => _instantiateSchema(value, template, instance, components, /* @__PURE__ */ new Map());\n\tconst result = {\n\t\t...method,\n\t\tparams: instantiate(method.params)\n\t};\n\tfor (const field of _methodSchemaFields.slice(1)) {\n\t\tconst value = method[field];\n\t\tif (value !== void 0) result[field] = instantiate(value);\n\t}\n\tif (method.errors !== void 0) result.errors = method.errors.map((error) => error.schema !== void 0 ? {\n\t\tcode: error.code,\n\t\tschema: instantiate(error.schema)\n\t} : {\n\t\tcode: error.code,\n\t\tmessage: error.message,\n\t\t...error.type === void 0 ? {} : { type: error.type },\n\t\t...error.data === void 0 ? {} : { data: instantiate(error.data) }\n\t});\n\treturn result;\n}\nfunction _instantiateSchema(schema, template, instance, destination, copied) {\n\tif (typeof schema === \"boolean\") return schema;\n\tif (\"$parameter\" in schema) return _copyArgumentSchema(schema.$parameter, instance, destination, copied);\n\treturn _rewriteSchema(schema, (name) => {\n\t\tconst key = `template:${template.id}:${name}`;\n\t\tif (!Object.hasOwn(destination, key)) {\n\t\t\tconst component = template.components?.schemas?.[name];\n\t\t\tif (component === void 0) throw new Error(`Unknown interface template component \"${name}\"`);\n\t\t\tdestination[key] = false;\n\t\t\tdestination[key] = _instantiateSchema(component, template, instance, destination, copied);\n\t\t}\n\t\treturn key;\n\t}, (child) => _instantiateSchema(child, template, instance, destination, copied));\n}\nfunction _copyArgumentSchema(parameter, instance, destination, copied) {\n\tconst argument = instance.arguments[parameter];\n\tif (argument === void 0) throw new Error(`Missing schema argument \"${parameter}\"`);\n\tconst rewrite = (schema) => _rewriteSchema(schema, (name) => {\n\t\tconst sourceKey = `${parameter}:${name}`;\n\t\tconst existing = copied.get(sourceKey);\n\t\tif (existing !== void 0) return existing;\n\t\tconst target = `argument:${instance.name}:${parameter}:${name}`;\n\t\tcopied.set(sourceKey, target);\n\t\tconst component = argument.components?.schemas?.[name];\n\t\tif (component === void 0) throw new Error(`Unknown schema argument component \"${name}\"`);\n\t\tdestination[target] = false;\n\t\tdestination[target] = rewrite(component);\n\t\treturn target;\n\t}, (child) => rewrite(child));\n\treturn rewrite(argument.schema);\n}\nfunction _rewriteSchema(schema, rewriteRef, rewriteChild) {\n\tif (typeof schema === \"boolean\") return schema;\n\tconst result = {};\n\tfor (const [key, value] of Object.entries(schema)) if (key === \"$ref\" && typeof value === \"string\") result.$ref = componentSchemaRef(rewriteRef(componentSchemaName(value)));\n\telse if (key === \"properties\" && _isRecord(value)) result.properties = Object.fromEntries(Object.entries(value).map(([name, child]) => [name, rewriteChild(child)]));\n\telse if (key === \"additionalProperties\" || key === \"items\") result[key] = typeof value === \"boolean\" ? value : rewriteChild(value);\n\telse if (key === \"prefixItems\" || key === \"anyOf\" || key === \"oneOf\") result[key] = value.map(rewriteChild);\n\telse result[key] = value;\n\treturn result;\n}\nfunction _methodsEquivalent(expected, actual, expectedComponents, actualComponents) {\n\tconst expectedRest = { ...expected };\n\tconst actualRest = { ...actual };\n\tfor (const field of _methodSchemaFields) {\n\t\tconst expectedSchema = expected[field];\n\t\tconst actualSchema = actual[field];\n\t\tdelete expectedRest[field];\n\t\tdelete actualRest[field];\n\t\tif (expectedSchema === void 0 || actualSchema === void 0) {\n\t\t\tif (expectedSchema !== actualSchema) return false;\n\t\t} else if (!_schemasEquivalent(expectedSchema, actualSchema, expectedComponents, actualComponents)) return false;\n\t}\n\tconst expectedErrors = expectedRest.errors;\n\tconst actualErrors = actualRest.errors;\n\tdelete expectedRest.errors;\n\tdelete actualRest.errors;\n\tif (!_jsonEqual(expectedRest, actualRest)) return false;\n\tif (expectedErrors === void 0 || actualErrors === void 0) return expectedErrors === actualErrors;\n\tif (expectedErrors.length !== actualErrors.length) return false;\n\treturn expectedErrors.every((error, index) => {\n\t\tconst candidate = actualErrors[index];\n\t\tif (error.schema !== void 0 || candidate.schema !== void 0) return error.schema !== void 0 && candidate.schema !== void 0 && error.code === candidate.code && _schemasEquivalent(error.schema, candidate.schema, expectedComponents, actualComponents);\n\t\treturn error.code === candidate.code && error.type === candidate.type && error.message === candidate.message && (error.data === void 0 || candidate.data === void 0 ? error.data === candidate.data : _schemasEquivalent(error.data, candidate.data, expectedComponents, actualComponents));\n\t});\n}\nfunction interfaceTemplateArgumentsEquivalent(left, right) {\n\treturn _schemasEquivalent(left.schema, right.schema, left.components?.schemas ?? {}, right.components?.schemas ?? {});\n}\nfunction interfaceTemplatesEqual(left, right) {\n\tconst { tags: _leftTags, ...leftStructure } = left;\n\tconst { tags: _rightTags, ...rightStructure } = right;\n\treturn _jsonEqual(leftStructure, rightStructure);\n}\nfunction validateTags(tags, context) {\n\tif (tags === void 0) return;\n\tif (!Array.isArray(tags) || tags.some((tag) => typeof tag !== \"string\")) throw new SchemaValidationError(`${context} tags must be an array of strings`);\n}\nfunction _schemasEquivalent(left, right, leftComponents, rightComponents, seen = /* @__PURE__ */ new WeakMap()) {\n\tif (typeof left === \"boolean\" || typeof right === \"boolean\") return left === right;\n\tlet rights = seen.get(left);\n\tif (rights?.has(right)) return true;\n\tif (rights === void 0) {\n\t\trights = /* @__PURE__ */ new WeakSet();\n\t\tseen.set(left, rights);\n\t}\n\trights.add(right);\n\tconst leftRef = \"$ref\" in left ? left.$ref : void 0;\n\tconst rightRef = \"$ref\" in right ? right.$ref : void 0;\n\tconst leftOwn = leftRef === void 0 ? _toRecord(left) : _withoutRef(left);\n\tconst rightOwn = rightRef === void 0 ? _toRecord(right) : _withoutRef(right);\n\tif (leftRef !== void 0 && Object.keys(leftOwn).length === 0) {\n\t\tconst resolved = leftComponents[componentSchemaName(leftRef)];\n\t\treturn resolved !== void 0 && _schemasEquivalent(resolved, right, leftComponents, rightComponents, seen);\n\t}\n\tif (rightRef !== void 0 && Object.keys(rightOwn).length === 0) {\n\t\tconst resolved = rightComponents[componentSchemaName(rightRef)];\n\t\treturn resolved !== void 0 && _schemasEquivalent(left, resolved, leftComponents, rightComponents, seen);\n\t}\n\tif (!_schemaObjectsEquivalent(leftOwn, rightOwn, leftComponents, rightComponents, seen)) return false;\n\tif (leftRef === void 0 || rightRef === void 0) {\n\t\tif (leftRef === rightRef) return true;\n\t\tconst ref = leftRef ?? rightRef;\n\t\tconst components = leftRef === void 0 ? rightComponents : leftComponents;\n\t\tconst resolved = components[componentSchemaName(ref)];\n\t\tif (resolved === void 0) return false;\n\t\treturn leftRef === void 0 ? _schemasEquivalent(left, resolved, leftComponents, components, seen) : _schemasEquivalent(resolved, right, components, rightComponents, seen);\n\t}\n\tconst leftResolved = leftComponents[componentSchemaName(leftRef)];\n\tconst rightResolved = rightComponents[componentSchemaName(rightRef)];\n\treturn leftResolved !== void 0 && rightResolved !== void 0 && _schemasEquivalent(leftResolved, rightResolved, leftComponents, rightComponents, seen);\n}\nfunction _schemaObjectsEquivalent(left, right, leftComponents, rightComponents, seen) {\n\tconst leftKeys = Object.keys(left).sort();\n\tif (!_jsonEqual(leftKeys, Object.keys(right).sort())) return false;\n\tfor (const key of leftKeys) {\n\t\tconst l = left[key];\n\t\tconst r = right[key];\n\t\tif (key === \"properties\" && _isRecord(l) && _isRecord(r)) {\n\t\t\tconst names = Object.keys(l).sort();\n\t\t\tif (!_jsonEqual(names, Object.keys(r).sort())) return false;\n\t\t\tif (!names.every((name) => _schemasEquivalent(l[name], r[name], leftComponents, rightComponents, seen))) return false;\n\t\t} else if ((key === \"items\" || key === \"additionalProperties\") && _isSchema(l) && _isSchema(r)) {\n\t\t\tif (!_schemasEquivalent(l, r, leftComponents, rightComponents, seen)) return false;\n\t\t} else if ((key === \"prefixItems\" || key === \"anyOf\" || key === \"oneOf\") && Array.isArray(l) && Array.isArray(r)) {\n\t\t\tif (l.length !== r.length || !l.every((value, index) => _schemasEquivalent(value, r[index], leftComponents, rightComponents, seen))) return false;\n\t\t} else if (!_jsonEqual(l, r)) return false;\n\t}\n\treturn true;\n}\nfunction _componentSchemas(components) {\n\tif (components === void 0) return {};\n\tif (!_isRecord(components) || components.schemas !== void 0 && !_isRecord(components.schemas)) throw new SchemaValidationError(\"Schema components and component schemas must be objects\");\n\treturn components.schemas ?? {};\n}\nfunction _schemaChildren(schema) {\n\tconst result = [];\n\tif (schema.properties !== void 0) {\n\t\tif (!_isRecord(schema.properties)) throw new SchemaValidationError(\"Schema properties must be an object\");\n\t\tresult.push(...Object.values(schema.properties));\n\t}\n\tfor (const key of [\"items\", \"additionalProperties\"]) {\n\t\tconst child = schema[key];\n\t\tif (child !== void 0) {\n\t\t\tif (!_isSchema(child)) throw new SchemaValidationError(`Schema ${key} must be an object or boolean`);\n\t\t\tresult.push(child);\n\t\t}\n\t}\n\tfor (const key of [\n\t\t\"prefixItems\",\n\t\t\"anyOf\",\n\t\t\"oneOf\"\n\t]) {\n\t\tconst children = schema[key];\n\t\tif (children !== void 0) {\n\t\t\tif (!Array.isArray(children)) throw new SchemaValidationError(`Schema ${key} must be an array`);\n\t\t\tresult.push(...children);\n\t\t}\n\t}\n\treturn result;\n}\nconst _methodSchemaFields = [\n\t\"params\",\n\t\"result\",\n\t\"clientStream\",\n\t\"serverStream\"\n];\nconst _segmentPattern = /^[A-Za-z0-9!#$%&'()*+,\\-;=?@\\[\\]^_`{|}~]+$/;\nfunction _assertSegment(value, label) {\n\tif (!_segmentPattern.test(value)) throw new SchemaValidationError(`Invalid ${label} \"${value}\"`);\n}\nfunction _withoutRef(schema) {\n\tconst result = _toRecord(schema);\n\tdelete result.$ref;\n\treturn result;\n}\nfunction _toRecord(value) {\n\treturn Object.fromEntries(Object.entries(value));\n}\nfunction _isSchema(value) {\n\treturn typeof value === \"boolean\" || _isRecord(value);\n}\nfunction _isRecord(value) {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction _jsonEqual(left, right) {\n\tif (left === right) return true;\n\tif (Array.isArray(left) || Array.isArray(right)) return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((value, index) => _jsonEqual(value, right[index]));\n\tif (!_isRecord(left) || !_isRecord(right)) return false;\n\tconst leftKeys = Object.keys(left).sort();\n\tconst rightKeys = Object.keys(right).sort();\n\treturn leftKeys.length === rightKeys.length && leftKeys.every((key, index) => key === rightKeys[index] && _jsonEqual(left[key], right[key]));\n}\n//#endregion\n//#region src/schema/schemaToZod.ts\n/**\n* Create a recursive LinkRPC-schema validator materializer. Component\n* references are lazy, so self and mutual recursion remain guarded.\n*/\nfunction createSchemaToZod(components = {}) {\n\tassertSchemaReferences([], components);\n\tconst refs = /* @__PURE__ */ new Map();\n\tconst component = (name) => {\n\t\tconst existing = refs.get(name);\n\t\tif (existing !== void 0) return existing;\n\t\tconst source = components[name];\n\t\tif (source === void 0) throw new Error(`schemaToZod: dangling component reference \"${name}\"`);\n\t\tconst lazy = z.lazy(() => compile(source));\n\t\trefs.set(name, lazy);\n\t\treturn lazy;\n\t};\n\tconst compile = (schema) => {\n\t\tif (schema === true) return z.unknown();\n\t\tif (schema === false) return z.never();\n\t\tconst raw = schema;\n\t\tlet base;\n\t\tif (\"$ref\" in schema) base = component(componentSchemaName(schema.$ref));\n\t\telse if (\"const\" in schema) base = valueSchema(schema.const);\n\t\telse if (\"enum\" in schema) base = union$1(schema.enum.map(valueSchema));\n\t\telse if (\"anyOf\" in schema) base = union$1(schema.anyOf.map(compile));\n\t\telse if (\"oneOf\" in schema) base = union$1(schema.oneOf.map(compile));\n\t\telse if (isAnnotationOnlySchema(raw)) base = z.unknown();\n\t\telse switch (schema.type) {\n\t\t\tcase \"null\":\n\t\t\t\tbase = z.null();\n\t\t\t\tbreak;\n\t\t\tcase \"boolean\":\n\t\t\t\tbase = z.boolean();\n\t\t\t\tbreak;\n\t\t\tcase \"string\":\n\t\t\t\tbase = stringSchema(schema.format);\n\t\t\t\tbreak;\n\t\t\tcase \"integer\":\n\t\t\t\tbase = z.number().int();\n\t\t\t\tbreak;\n\t\t\tcase \"number\":\n\t\t\t\tbase = z.number();\n\t\t\t\tbreak;\n\t\t\tcase \"array\":\n\t\t\t\tif (\"prefixItems\" in schema) {\n\t\t\t\t\tconst tuple = z.tuple(schema.prefixItems.map(compile));\n\t\t\t\t\tbase = schema.items !== void 0 && schema.items !== false ? tuple.rest(compile(schema.items)) : tuple;\n\t\t\t\t} else base = z.array(compile(schema.items));\n\t\t\t\tbreak;\n\t\t\tcase \"object\": {\n\t\t\t\tconst required = new Set(schema.required ?? []);\n\t\t\t\tconst shape = {};\n\t\t\t\tfor (const [name, property] of Object.entries(schema.properties ?? {})) {\n\t\t\t\t\tconst validator = compile(property);\n\t\t\t\t\tshape[name] = required.has(name) ? validator : validator.optional();\n\t\t\t\t}\n\t\t\t\tconst object = z.object(shape);\n\t\t\t\tif (schema.additionalProperties === false) base = object.strict();\n\t\t\t\telse if (schema.additionalProperties === true) base = object.loose();\n\t\t\t\telse base = object.catchall(compile(schema.additionalProperties));\n\t\t\t\tbase = base.superRefine((value, context) => {\n\t\t\t\t\tfor (const name of required) if (typeof value === \"object\" && value !== null && !Object.hasOwn(value, name)) context.addIssue({\n\t\t\t\t\t\tcode: \"custom\",\n\t\t\t\t\t\tpath: [name],\n\t\t\t\t\t\tmessage: \"Required property is missing\"\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault: throw new Error(\"schemaToZod: unsupported schema type; normalize producer schemas before use\");\n\t\t}\n\t\treturn base;\n\t};\n\treturn { toZod(schema) {\n\t\tassertSchemaReferences([schema], components);\n\t\tconst result = compile(schema);\n\t\tschemaSources.set(result, {\n\t\t\tschema,\n\t\t\tcomponents\n\t\t});\n\t\treturn result;\n\t} };\n}\nfunction isAnnotationOnlySchema(schema) {\n\treturn ![\n\t\t\"$ref\",\n\t\t\"const\",\n\t\t\"enum\",\n\t\t\"anyOf\",\n\t\t\"oneOf\",\n\t\t\"type\",\n\t\t\"properties\",\n\t\t\"items\",\n\t\t\"prefixItems\",\n\t\t\"additionalProperties\"\n\t].some((key) => Object.hasOwn(schema, key));\n}\nfunction schemaToZod(schema, components = {}) {\n\treturn createSchemaToZod(components).toZod(schema);\n}\nfunction union$1(items) {\n\tif (items.length === 0) return z.never();\n\tif (items.length === 1) return items[0];\n\treturn z.union(items);\n}\nfunction valueSchema(expected) {\n\treturn z.unknown().refine((actual) => jsonValueEqual(actual, expected), { message: `Expected ${JSON.stringify(expected)}` });\n}\nfunction jsonValueEqual(actual, expected) {\n\tif (Object.is(actual, expected)) return true;\n\tif (Array.isArray(actual) && Array.isArray(expected)) return actual.length === expected.length && actual.every((value, index) => jsonValueEqual(value, expected[index]));\n\tif (actual !== null && expected !== null && typeof actual === \"object\" && typeof expected === \"object\" && !Array.isArray(actual) && !Array.isArray(expected)) {\n\t\tconst actualRecord = actual;\n\t\tconst expectedRecord = expected;\n\t\tconst keys = Object.keys(actualRecord);\n\t\treturn keys.length === Object.keys(expectedRecord).length && keys.every((key) => Object.hasOwn(expectedRecord, key) && jsonValueEqual(actualRecord[key], expectedRecord[key]));\n\t}\n\treturn false;\n}\nfunction stringSchema(format) {\n\tswitch (format) {\n\t\tcase \"email\": return z.email();\n\t\tcase \"uri\":\n\t\tcase \"url\": return z.url();\n\t\tcase \"uuid\": return z.uuid();\n\t\tcase \"date-time\": return z.iso.datetime();\n\t\tdefault: return z.string();\n\t}\n}\n//#endregion\n//#region src/schema/validateInterfaceErrors.ts\nfunction validateInterfaceErrors(schema) {\n\tif (schema === void 0) return;\n\tfor (const [methodName, method] of Object.entries(schema.methods)) {\n\t\tif (method.result === void 0 && method.errors !== void 0) throw new Error(`Notification \"${methodName}\" cannot declare application errors.`);\n\t\tconst seen = /* @__PURE__ */ new Set();\n\t\tconst errors = method.errors ?? [];\n\t\tfor (const error of errors) {\n\t\t\tif (!Number.isInteger(error.code) || error.code < -2147483648 || error.code > 2147483647) throw new Error(`Application error code ${error.code} on \"${methodName}\" must be a signed 32-bit integer.`);\n\t\t\tif (errors.some((other) => other !== error && other.code === error.code && (other.schema !== void 0 || error.schema !== void 0))) throw new Error(`Raw error code ${error.code} on \"${methodName}\" cannot be shared.`);\n\t\t\tif (error.schema !== void 0) {\n\t\t\t\tif ([\n\t\t\t\t\t\"message\",\n\t\t\t\t\t\"type\",\n\t\t\t\t\t\"data\"\n\t\t\t\t].some((key) => Object.hasOwn(error, key))) throw new Error(`Raw error ${error.code} on \"${methodName}\" must contain only code and schema.`);\n\t\t\t} else {\n\t\t\t\tif (typeof error.message !== \"string\") throw new Error(`Application error message on \"${methodName}\" must be a string.`);\n\t\t\t\tif (error.code >= -32768 && error.code <= -32e3 || error.code === -32800) throw new Error(`Application error code ${error.code} on \"${methodName}\" is reserved by JSON-RPC or LinkRPC.`);\n\t\t\t\tif (error.type !== void 0 && (typeof error.type !== \"string\" || error.type.length === 0)) throw new Error(`Application error type on \"${methodName}\" must be a nonempty string.`);\n\t\t\t}\n\t\t\tconst key = error.type === void 0 ? `code:${error.code}` : `type:${error.type}`;\n\t\t\tif (seen.has(key)) throw new Error(`Duplicate application error ${key} on \"${methodName}\".`);\n\t\t\tseen.add(key);\n\t\t}\n\t}\n}\n//#endregion\n//#region src/schema/interfaceTemplateGroup.ts\n/** Local authoring marker. Never serialized into the wire contract. */\nconst interfaceTemplateGroup = Symbol.for(\"@hediet/linkrpc.interfaceTemplateGroup\");\n//#endregion\n//#region src/connection/interfaceDefinition.ts\nconst interfaceDefinitionState = /* @__PURE__ */ new WeakMap();\nvar InterfaceDefinition = class {\n\tinfo;\n\tmembers;\n\t/** Typed wire references for capability and access-request construction. */\n\tref;\n\tconstructor(info, members, opts = {}) {\n\t\tthis.info = info;\n\t\tthis.members = members;\n\t\tif (opts.frozenSchema !== void 0 && opts.templates !== void 0) throw new Error(\"Cannot combine frozenSchema with authored templates\");\n\t\tconst frozenSchema = opts.templates === void 0 ? opts.frozenSchema : attachInterfaceTemplates(buildSchema(info, members, \"\"), opts.templates);\n\t\tvalidateInterfaceErrors(frozenSchema);\n\t\tif (frozenSchema !== void 0) validateInterfaceTemplates(frozenSchema);\n\t\tconst effectiveTags = frozenSchema === void 0 ? normalizeInterfaceTags(info.tags ?? []) : getInterfaceTags(frozenSchema);\n\t\tif (info.tags !== void 0 || effectiveTags.length > 0) this.info = {\n\t\t\t...info,\n\t\t\ttags: effectiveTags\n\t\t};\n\t\tinterfaceDefinitionState.set(this, {\n\t\t\tfrozenSchema,\n\t\t\tschemaCache: void 0,\n\t\t\thashCache: void 0,\n\t\t\tdeclarationGroups: void 0\n\t\t});\n\t\tthis.ref = Object.fromEntries(Object.keys(members).map((member) => [member, {\n\t\t\tinterfaceId: this.info.id,\n\t\t\tinterfaceHash: this.schemaHash,\n\t\t\tmember\n\t\t}]));\n\t\tif (info.hash !== void 0 && this.schemaHash !== info.hash) throw new Error(`Interface hash mismatch for \"${info.id}\": expected \"${info.hash}\", got \"${this.schemaHash}\". The interface's wire contract changed — update the pinned hash to \"${this.schemaHash}\" after reviewing the change.`);\n\t}\n\t/** @internal Materialize authored groups using the existing wire call functions verbatim. */\n\tnestClient(client) {\n\t\tconst groups = interfaceDefinitionState.get(this).declarationGroups;\n\t\tif (groups === void 0) return client;\n\t\tconst groupedWireNames = new Set(Object.values(groups).flatMap((group) => Object.values(group)));\n\t\tconst result = Object.create(null);\n\t\tfor (const [name, call] of Object.entries(client)) if (!groupedWireNames.has(name)) result[name] = call;\n\t\tfor (const [name, mapping] of Object.entries(groups)) {\n\t\t\tconst group = Object.create(null);\n\t\t\tfor (const [member, wireName] of Object.entries(mapping)) group[member] = client[wireName];\n\t\t\tresult[name] = group;\n\t\t}\n\t\treturn result;\n\t}\n\t/** Validate grouped implementations atomically, then lower them to wire handlers. */\n\tflattenHandlers(handlers) {\n\t\tconst groups = interfaceDefinitionState.get(this).declarationGroups;\n\t\tif (groups === void 0) return handlers;\n\t\tconst requireObject = (value, where) => {\n\t\t\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new Error(`Expected handler group object at \"${where}\"`);\n\t\t\treturn value;\n\t\t};\n\t\tconst implementation = requireObject(handlers, this.info.id);\n\t\tconst groupedWireNames = new Set(Object.values(groups).flatMap((group) => Object.values(group)));\n\t\tconst flatNames = Object.keys(this.members).filter((name) => !groupedWireNames.has(name));\n\t\tconst expected = /* @__PURE__ */ new Set([...Object.keys(groups), ...flatNames]);\n\t\tfor (const key of Reflect.ownKeys(implementation)) if (typeof key !== \"string\" || !expected.has(key)) throw new Error(`Unexpected handler \"${String(key)}\"; grouped members require grouped handlers`);\n\t\tconst result = Object.create(null);\n\t\tconst requireHandler = (object, key, where) => {\n\t\t\tif (!Object.hasOwn(object, key) || typeof object[key] !== \"function\") throw new Error(`Missing or invalid handler \"${where}\"`);\n\t\t\treturn object[key];\n\t\t};\n\t\tfor (const name of flatNames) result[name] = requireHandler(implementation, name, name);\n\t\tfor (const [name, mapping] of Object.entries(groups)) {\n\t\t\tif (!Object.hasOwn(implementation, name)) throw new Error(`Missing handler group \"${name}\"`);\n\t\t\tconst group = requireObject(implementation[name], name);\n\t\t\tfor (const member of Reflect.ownKeys(group)) if (typeof member !== \"string\" || !Object.hasOwn(mapping, member)) throw new Error(`Unexpected handler \"${name}.${String(member)}\"`);\n\t\t\tfor (const [member, wireName] of Object.entries(mapping)) result[wireName] = requireHandler(group, member, `${name}.${member}`);\n\t\t}\n\t\treturn result;\n\t}\n\t/** Content hash of this interface (see `computeInterfaceHash`). */\n\tget schemaHash() {\n\t\tconst state = interfaceDefinitionState.get(this);\n\t\tif (state.hashCache === void 0) state.hashCache = computeInterfaceHash(state.frozenSchema ?? buildSchema(this.info, this.members, \"\"));\n\t\treturn state.hashCache;\n\t}\n\t/** Lower the definition to a wire-format `LinkRpcInterfaceSchema`, hash filled in. */\n\ttoSchema() {\n\t\tconst state = interfaceDefinitionState.get(this);\n\t\tif (state.schemaCache === void 0) state.schemaCache = state.frozenSchema !== void 0 ? {\n\t\t\t...state.frozenSchema,\n\t\t\thash: this.schemaHash,\n\t\t\t...this.info.tags !== void 0 ? { tags: [...this.info.tags] } : {}\n\t\t} : buildSchema(this.info, this.members, this.schemaHash);\n\t\treturn state.schemaCache;\n\t}\n};\nfunction buildSchema(info, members, hash) {\n\tconst methods = Object.create(null);\n\tconst components = {};\n\tfor (const [name, member] of Object.entries(members)) methods[name] = toMethodSchema(name, member, components);\n\tconst schema = {\n\t\tid: info.id,\n\t\thash,\n\t\tmethods\n\t};\n\tif (Object.keys(components).length > 0) schema.components = { schemas: components };\n\tif (info.description !== void 0) schema.description = info.description;\n\tif (info.comment !== void 0) schema.comment = info.comment;\n\tif (info.tags !== void 0) schema.tags = [...new Set(info.tags)];\n\treturn schema;\n}\nfunction toMethodSchema(name, member, components, convert = (schema, position) => convertMemberSchema(name, position, schema, components)) {\n\tconst docs = member.docs;\n\tif (member.kind === \"request\") {\n\t\tconst m = {\n\t\t\tparams: convert(member.paramsSchema, \"params\"),\n\t\t\tresult: convert(member.resultSchema, \"result\")\n\t\t};\n\t\tif (member.clientStreamSchema !== void 0) m.clientStream = convert(member.clientStreamSchema, \"clientStream\");\n\t\tif (member.serverStreamSchema !== void 0) m.serverStream = convert(member.serverStreamSchema, \"serverStream\");\n\t\tif (member.applicationErrors.length > 0) m.errors = member.applicationErrors.map((error) => {\n\t\t\tif (error.bodySchema !== void 0) return {\n\t\t\t\tcode: error.code,\n\t\t\t\tschema: convert(error.bodySchema, `error=${error.code}`)\n\t\t\t};\n\t\t\tconst result = {\n\t\t\t\tcode: error.code,\n\t\t\t\tmessage: error.message,\n\t\t\t\t...error.type === void 0 ? {} : { type: error.type }\n\t\t\t};\n\t\t\tif (error.dataSchema !== void 0) result.data = convert(error.dataSchema, `error=${error.code}`);\n\t\t\treturn result;\n\t\t});\n\t\tif (docs.description !== void 0) m.description = docs.description;\n\t\tif (docs.comment !== void 0) m.comment = docs.comment;\n\t\tif (docs.annotations !== void 0) m.annotations = docs.annotations;\n\t\treturn m;\n\t}\n\tconst m = { params: convert(member.paramsSchema, \"params\") };\n\tif (docs.description !== void 0) m.description = docs.description;\n\tif (docs.comment !== void 0) m.comment = docs.comment;\n\tif (docs.annotations !== void 0) m.annotations = docs.annotations;\n\treturn m;\n}\nfunction convertMemberSchema(methodName, position, schema, components) {\n\treturn zodToSvcJsonSchema(schema, {\n\t\tmethodName,\n\t\tschemaPosition: position,\n\t\tcomponents\n\t});\n}\n/**\n* Convenient builder for an interface definition. Tracks TypeScript types\n* through `requestType` / `notificationType` so client and server code can\n* derive their shapes from the definition.\n*\n* @example\n* const myInterface = defineInterface(\n* { id: \"de.hediet.notification-target\" },\n* {\n* send: requestType(z.object({ to: z.string() }), z.string()),\n* notify: notificationType(z.object({ message: z.string() })),\n* },\n* );\n*/\nfunction defineInterface(info, declarations, options = {}) {\n\tconst entries = Object.entries(declarations);\n\tconst isGroup = (value) => value !== null && typeof value === \"object\" && interfaceTemplateGroup in value && value[interfaceTemplateGroup] === true;\n\tif (!entries.some(([, value]) => isGroup(value))) return new InterfaceDefinition(info, declarations, options);\n\tconst members = Object.create(null);\n\tconst groups = Object.create(null);\n\tconst templates = Object.assign(Object.create(null), options.templates);\n\tconst groupNames = new Set(entries.filter(([, value]) => isGroup(value)).map(([name]) => name));\n\tconst addMember = (name, member) => {\n\t\tif (Object.hasOwn(members, name) || groupNames.has(name)) throw new Error(`Interface member collision at \"${name}\"`);\n\t\tmembers[name] = member;\n\t};\n\tfor (const [name, declaration] of entries) {\n\t\tif (!isGroup(declaration)) {\n\t\t\taddMember(name, declaration);\n\t\t\tcontinue;\n\t\t}\n\t\tif (Object.hasOwn(templates, name)) throw new Error(`Interface template instance collision at \"${name}\"`);\n\t\tconst mapping = Object.create(null);\n\t\tif (declaration.mapping !== void 0) {\n\t\t\tfor (const member of Object.keys(declaration.mapping)) if (!Object.hasOwn(declaration.members, member)) throw new Error(`Unknown mapped member \"${member}\"`);\n\t\t}\n\t\tfor (const [member, type] of Object.entries(declaration.members)) {\n\t\t\tif (declaration.mapping !== void 0 && !Object.hasOwn(declaration.mapping, member)) throw new Error(`Missing mapped member \"${member}\"`);\n\t\t\tconst wireName = declaration.mapping === void 0 ? `${name}$${member}` : declaration.mapping[member];\n\t\t\tif (typeof wireName !== \"string\" || wireName.length === 0) throw new Error(`Missing mapped member \"${member}\"`);\n\t\t\taddMember(wireName, type);\n\t\t\tmapping[member] = wireName;\n\t\t}\n\t\tgroups[name] = Object.freeze(mapping);\n\t\ttemplates[name] = {\n\t\t\ttemplate: declaration.template,\n\t\t\tschema: {\n\t\t\t\ttemplate: declaration.template.id,\n\t\t\t\targuments: declaration.arguments,\n\t\t\t\tmembers: mapping\n\t\t\t}\n\t\t};\n\t}\n\tconst definition = new InterfaceDefinition(info, members, {\n\t\t...options,\n\t\ttemplates\n\t});\n\tinterfaceDefinitionState.get(definition).declarationGroups = Object.freeze(groups);\n\treturn definition;\n}\n/**\n* Build a runtime {@link InterfaceDefinition} from a previously-published\n* {@link LinkRpcInterfaceSchema} — typically one received over the wire (e.g.\n* from `hubrpc.schemas::get`) or generated at runtime by tooling that does\n* not have the original zod sources at hand (codegen, faker / mock\n* services, dynamic gateways).\n*\n* The original schema is kept verbatim: `toSchema()` returns it (with\n* `hash` overlaid) and `schemaHash` is computed from it, so reflection\n* consumers see the real wire contract. Member-level params / results /\n* streams use `z.any()` because no zod source is available — call-site\n* validation is therefore a no-op and the caller is responsible for\n* shape-checking inputs and outputs. Declared application-error payloads\n* are materialized and validated after code selection. A known code whose\n* body fails all declared branches is a noncompliant-server failure.\n*\n* Methods with no `result` descriptor become notifications; methods with\n* `clientStream` / `serverStream` get pass-through stream payload\n* schemas attached.\n*/\nfunction interfaceFromSchema(schema) {\n\tvalidateInterfaceErrors(schema);\n\tvalidateInterfaceTemplates(schema);\n\tconst members = Object.create(null);\n\tfor (const [name, method] of Object.entries(schema.methods)) {\n\t\tif (method.result === void 0) {\n\t\t\tmembers[name] = new NotificationType(any());\n\t\t\tcontinue;\n\t\t}\n\t\tconst base = new RequestType(any(), any(), void$1()).withErrors((method.errors ?? []).map((error) => error.schema !== void 0 ? rpcError(error.code, schemaToZod(error.schema, schema.components?.schemas)) : error.type !== void 0 ? error.data === void 0 ? applicationError(error.type, {\n\t\t\tcode: error.code,\n\t\t\tmessage: error.message\n\t\t}) : applicationError(error.type, {\n\t\t\tcode: error.code,\n\t\t\tmessage: error.message,\n\t\t\tdata: schemaToZod(error.data, schema.components?.schemas)\n\t\t}) : error.data === void 0 ? applicationError(error.code, error.message) : applicationError(error.code, error.message, schemaToZod(error.data, schema.components?.schemas))));\n\t\tmembers[name] = method.clientStream !== void 0 || method.serverStream !== void 0 ? base.withStream({\n\t\t\tclient: method.clientStream !== void 0 ? any() : void 0,\n\t\t\tserver: method.serverStream !== void 0 ? any() : void 0\n\t\t}) : base;\n\t}\n\tconst info = { id: schema.id };\n\tif (schema.description !== void 0) info.description = schema.description;\n\tif (schema.comment !== void 0) info.comment = schema.comment;\n\tif (schema.tags !== void 0) info.tags = schema.tags;\n\treturn new InterfaceDefinition(info, members, { frozenSchema: schema });\n}\n//#endregion\n//#region src/crypto/cryptoProvider.ts\nconst _b64UrlAlphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\nconst _b64UrlReverse = (() => {\n\tconst m = {};\n\tfor (let i = 0; i < 64; i++) m[_b64UrlAlphabet[i]] = i;\n\treturn m;\n})();\nfunction bytesToBase64Url(bytes) {\n\tlet out = \"\";\n\tlet i = 0;\n\tfor (; i + 3 <= bytes.length; i += 3) {\n\t\tconst n = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];\n\t\tout += _b64UrlAlphabet[n >> 18 & 63] + _b64UrlAlphabet[n >> 12 & 63] + _b64UrlAlphabet[n >> 6 & 63] + _b64UrlAlphabet[n & 63];\n\t}\n\tconst rem = bytes.length - i;\n\tif (rem === 1) {\n\t\tconst n = bytes[i] << 16;\n\t\tout += _b64UrlAlphabet[n >> 18 & 63] + _b64UrlAlphabet[n >> 12 & 63];\n\t} else if (rem === 2) {\n\t\tconst n = bytes[i] << 16 | bytes[i + 1] << 8;\n\t\tout += _b64UrlAlphabet[n >> 18 & 63] + _b64UrlAlphabet[n >> 12 & 63] + _b64UrlAlphabet[n >> 6 & 63];\n\t}\n\treturn out;\n}\nfunction base64UrlToBytes(s) {\n\tconst len = s.length;\n\tconst fullGroups = Math.floor(len / 4);\n\tconst rem = len % 4;\n\tif (rem === 1) throw new Error(\"base64UrlToBytes: invalid length\");\n\tconst outLen = fullGroups * 3 + (rem === 0 ? 0 : rem - 1);\n\tconst out = new Uint8Array(outLen);\n\tlet oi = 0;\n\tlet i = 0;\n\tfor (let g = 0; g < fullGroups; g++, i += 4) {\n\t\tconst n = _lookup(s, i) << 18 | _lookup(s, i + 1) << 12 | _lookup(s, i + 2) << 6 | _lookup(s, i + 3);\n\t\tout[oi++] = n >> 16 & 255;\n\t\tout[oi++] = n >> 8 & 255;\n\t\tout[oi++] = n & 255;\n\t}\n\tif (rem === 2) {\n\t\tconst n = _lookup(s, i) << 18 | _lookup(s, i + 1) << 12;\n\t\tout[oi++] = n >> 16 & 255;\n\t} else if (rem === 3) {\n\t\tconst n = _lookup(s, i) << 18 | _lookup(s, i + 1) << 12 | _lookup(s, i + 2) << 6;\n\t\tout[oi++] = n >> 16 & 255;\n\t\tout[oi++] = n >> 8 & 255;\n\t}\n\treturn out;\n}\nfunction _lookup(s, i) {\n\tconst v = _b64UrlReverse[s[i]];\n\tif (v === void 0) throw new Error(`base64UrlToBytes: invalid char at ${i}`);\n\treturn v;\n}\n/** Role-tag prefix on a {@link KeyId}'s inline-key form. */\nconst KEY_ID_PREFIX = \"key:\";\n/** Role-tag prefix that wraps a genesis {@link KeyId} into a {@link PrincipalId}. */\nconst PRINCIPAL_PREFIX = \"id:\";\n/** The inline {@link KeyId} for a raw public key: `\"key:\" + b64url(pk)`. */\nfunction keyIdForPublicKey(pk) {\n\treturn KEY_ID_PREFIX + bytesToBase64Url(pk);\n}\n/** The perpetual {@link PrincipalId} for a raw public key: `\"id:key:\" + b64url(pk)`. */\nfunction principalForPublicKey(pk) {\n\treturn \"id:\" + keyIdForPublicKey(pk);\n}\n/**\n* The genesis {@link KeyId} embedded in a perpetual {@link PrincipalId}\n* (`\"id:\" + keyId`). Throws if `principal` is not a well-formed `id:` name.\n*/\nfunction keyIdForPrincipal(principal) {\n\tif (!principal.startsWith(\"id:\")) throw new Error(`malformed principal (missing \"id:\" prefix): ${principal}`);\n\treturn principal.slice(3);\n}\n/**\n* The raw public key carried inline by a `\"key:\"` {@link KeyId}. Throws on a\n* missing prefix or malformed base64url.\n*/\nfunction publicKeyForKeyId(keyId) {\n\tif (!keyId.startsWith(\"key:\")) throw new Error(`unsupported keyId (expected \"${KEY_ID_PREFIX}\" prefix): ${keyId}`);\n\treturn base64UrlToBytes(keyId.slice(4));\n}\n/**\n* Resolve the verifying public key for `(principal, keyId)`, or `undefined`\n* to **reject** (fail closed). This is the single seam every verifier goes\n* through, replacing the old \"the id *is* the key\" decode.\n*\n* Phase 1 supports only inline genesis keys: the `keyId` must be a `\"key:\"`\n* form and the principal must be exactly `\"id:\" + keyId` (genesis\n* self-certification by string equality). `keydoc:`/rotation forms resolve\n* through `bindings`/`timeMs` later and are intentionally not handled here.\n*/\nfunction resolveSigningKey(args) {\n\tconst { principal, keyId } = args;\n\tif (!keyId.startsWith(\"key:\")) return;\n\tif (\"id:\" + keyId !== principal) return;\n\ttry {\n\t\treturn { publicKey: base64UrlToBytes(keyId.slice(4)) };\n\t} catch {\n\t\treturn;\n\t}\n}\n//#endregion\n//#region src/inspection/inspection.interfaces.ts\nconst zTopologyPort = object({\n\tportId: string(),\n\tlabel: optional(string())\n});\nconst zParticipantDescriptor = object({\n\ttype: optional(string()),\n\tlabel: optional(string()),\n\tprocessId: optional(number()),\n\tprocessType: optional(string()),\n\tnodeStatusServiceId: optional(string()),\n\tmetadata: optional(record(string(), union([\n\t\tstring(),\n\t\tnumber(),\n\t\tboolean()\n\t])))\n});\nconst zParticipantDescriptorSource = object({\n\tsource: enum$1([\"self\", \"attacher\"]),\n\tdescriptor: zParticipantDescriptor\n});\nconst zTopologyNode = object({\n\tnodeId: string(),\n\tkind: optional(enum$1([\"endpoint\", \"hub\"])),\n\tlabel: optional(string()),\n\tdescriptors: optional(array(zParticipantDescriptorSource)),\n\tports: array(zTopologyPort)\n});\nconst zTopologyLinkEndpoint = object({\n\tnodeId: string(),\n\tportId: string()\n});\nconst zTopologyTransportEndpoint = object({\n\taddress: optional(string()),\n\tport: optional(number().check(int(), nonnegative()))\n});\n/**\n* Transport details as observed at a topology link. `local` corresponds to the\n* link's `from` endpoint and `remote` to its `to` endpoint.\n*/\nconst zTopologyTransportInfo = object({\n\ttype: string(),\n\tlocal: optional(zTopologyTransportEndpoint),\n\tremote: optional(zTopologyTransportEndpoint),\n\tpath: optional(string()),\n\tmetadata: optional(record(string(), union([\n\t\tstring(),\n\t\tnumber(),\n\t\tboolean()\n\t])))\n});\nconst zTopologyLink = object({\n\tfrom: zTopologyLinkEndpoint,\n\tto: zTopologyLinkEndpoint,\n\tlabel: optional(string()),\n\tpeerState: optional(enum$1([\n\t\t\"identified\",\n\t\t\"pending\",\n\t\t\"unsupported\",\n\t\t\"error\"\n\t])),\n\ttransport: optional(zTopologyTransportInfo)\n});\nconst zRouteClaim = object({\n\tserviceId: string(),\n\tnodeId: string(),\n\tportId: string(),\n\tmatch: enum$1([\"exact\", \"prefix\"])\n});\nconst zTopologyGraph = object({\n\tobserverServiceId: string(),\n\tentryNodeId: string(),\n\tnodes: array(zTopologyNode),\n\tlinks: array(zTopologyLink),\n\troutes: array(zRouteClaim)\n});\nconst topologyInterface = defineInterface({\n\tid: \"hubrpc.topology\",\n\tdescription: \"Inspect the transport graph visible from a service. A watch emits invalidation ticks; consumers re-fetch getGraph after each tick.\"\n}, {\n\tgetGraph: requestType(object({}), zTopologyGraph).withStream({ client: object({}) }),\n\twatchGraph: requestType(object({}), object({})).withStream({ server: object({}) })\n});\nconst zTrafficTransitEndpoint = object({\n\tedgeId: string(),\n\tportId: string(),\n\trequestId: optional(union([number(), string()]))\n});\nconst zTrafficTransitEvent = object({\n\ttype: literal(\"transit\"),\n\ttimeMs: number(),\n\tnodeId: string(),\n\tin: optional(zTrafficTransitEndpoint),\n\tout: optional(zTrafficTransitEndpoint),\n\tdisposition: enum$1([\n\t\t\"forwarded\",\n\t\t\"consumed\",\n\t\t\"dropped\",\n\t\t\"unroutable\"\n\t]),\n\tkind: enum$1([\n\t\t\"request\",\n\t\t\"notification\",\n\t\t\"response\",\n\t\t\"stream\"\n\t]),\n\tmethod: optional(string()),\n\tparams: optional(unknown()),\n\tresult: optional(unknown()),\n\terror: optional(object({\n\t\tcode: number(),\n\t\tmessage: string(),\n\t\tdata: optional(unknown())\n\t}))\n});\nconst zTrafficOverflowEvent = object({\n\ttype: literal(\"overflow\"),\n\tdropped: number().check(int(), nonnegative())\n});\nconst zTrafficEvent = union([zTrafficTransitEvent, zTrafficOverflowEvent]);\nconst zTrafficWatchResult = object({\n\tdelivered: number().check(int(), nonnegative()),\n\tdropped: number().check(int(), nonnegative())\n});\nconst zTrafficWatchParams = object({\n\tmethodPrefix: optional(string()),\n\ttrafficIgnoreKey: optional(string()),\n\tfocusRequest: optional(object({\n\t\tportId: string(),\n\t\trequestId: union([number(), string()])\n\t}))\n});\nconst zTrafficWatchWithPayloadsParams = object({\n\tmethodPrefix: optional(string()),\n\ttrafficIgnoreKey: optional(string()),\n\tfocusRequest: optional(object({\n\t\tportId: string(),\n\t\trequestId: union([number(), string()])\n\t})),\n\tmaxPayloadBytes: number().check(int(), nonnegative())\n});\n/**\n* Observe raw message transits at the node hosting the addressed service.\n* Consumers may correlate adjacent transits by shared `(portId, requestId)`.\n*/\nconst trafficInterface = defineInterface({\n\tid: \"hubrpc.traffic\",\n\tdescription: \"Stream raw message transits for the entire node hosting the addressed service. Payload-free and explicitly payload-bearing variants keep disclosure opt-in.\"\n}, {\n\twatch: requestType(zTrafficWatchParams, zTrafficWatchResult).withStream({ server: zTrafficEvent }),\n\twatchWithPayloads: requestType(zTrafficWatchWithPayloadsParams, zTrafficWatchResult).withStream({ server: zTrafficEvent })\n});\n//#endregion\n//#region src/inspection/node.interfaces.ts\nconst zNodeInfo = object({\n\t/**\n\t* Random identity of this connection's node. It is a topology-correlation\n\t* label only and must not be used for authentication or authorization.\n\t*/\n\tnodeId: string(),\n\t/** Random identity of this connection's port on its node. */\n\tportId: string(),\n\t/** Optional diagnostic descriptors; never used for authorization. */\n\tdescriptors: optional(array(zParticipantDescriptorSource))\n});\n/**\n* Minimal root service for aligning the independently observed topologies at\n* both ends of a connection.\n*/\nconst nodeInterface = defineInterface({\n\tid: \"hubrpc.node\",\n\tdescription: \"Topology bootstrap: identify the node and port at this end of the direct connection.\"\n}, { getNodeId: requestType(object({}), zNodeInfo) });\n//#endregion\n//#region src/connection/streaming.ts\n/**\n* Direction a {@link STREAM_METHOD} message travels, relative to the\n* request it is correlated with. Made explicit on the wire so that a\n* middlebox (the hub) can *author* a stream message — e.g. inject a\n* cancel when a caller disconnects — without an inbound message whose\n* arrival link it could infer the direction from.\n*/\nconst StreamDir = {\n\t/** callee → caller: progress, partial results. Routes like a response. */\n\ttoCaller: \"toCaller\",\n\t/** caller → callee: input, cancellation, keepalive ping. */\n\ttoCallee: \"toCallee\"\n};\n/**\n* Reserved control verbs. A control message carries no app `payload`; it\n* is interpreted by the runtime / hub itself, independently of the\n* originating method's stream schemas, so *any* request is cancellable\n* and keep-alive-able even when it declares no app stream.\n*/\nconst StreamControlType = {\n\t/**\n\t* Ask the callee to abort the in-flight request. Always {@link\n\t* StreamDir.toCallee}. The callee surfaces this as an `AbortSignal`\n\t* and is expected to settle the request (typically with a\n\t* `cancelled` error response).\n\t*/\n\tcancel: \"cancel\",\n\t/**\n\t* Keepalive / liveness probe. Resets the hub's per-request idle timer\n\t* so a long-running call is not reaped, and lets either side actively\n\t* probe the peer. Carries a `nonce` the peer echoes in its {@link\n\t* StreamControlType.pong}. May travel in either direction. Emitted\n\t* automatically (without awaiting a pong) by the channel for streaming\n\t* calls; see {@link STREAM_METHOD}.\n\t*/\n\tping: \"ping\",\n\t/**\n\t* Reply to a {@link StreamControlType.ping}, echoing the ping's\n\t* `nonce` so the prober can correlate it. Travels opposite the ping.\n\t* Carries no app effect — purely a liveness acknowledgement.\n\t*/\n\tpong: \"pong\"\n};\n/**\n* Well-known `control.reason` strings. The set is **open** — any string\n* is valid on the wire; these are the reasons linkrpc itself emits.\n*/\nconst StreamControlReason = {\n\t/**\n\t* The caller's transport dropped while the request was in flight; the\n\t* hub cancels the callee's now-orphaned work.\n\t*/\n\tclientDisconnected: \"clientDisconnected\",\n\t/**\n\t* The request exceeded the hub's idle timeout with no stream activity\n\t* (no ping, no stream message). See {@link STREAM_METHOD} docs.\n\t*/\n\tidleTimeout: \"idleTimeout\"\n};\n/**\n* Streaming sub-protocol. Long-running requests can emit additional\n* notifications correlated with the original call in either direction\n* (callee → caller progress, caller → callee input / cancellation /\n* keepalive).\n*\n* Wire form: a JSON-RPC notification whose method is\n* `${streamInterface.info.id}::send` and whose params match\n* `streamInterface.members.send.paramsSchema`. The hub routes purely on\n* `requestId` (following the originating request's established path, like\n* a response); the originating request's capability authorization covers\n* its full stream lifetime, so stream notifications carry no method /\n* interface namespace of their own. App `payload` contents are typed per\n* request via the originating method's\n* `RequestType.clientStreamSchema` / `serverStreamSchema`; reserved\n* `control` messages are schema-independent.\n*\n* Idle timeout: a request that never streams (no `control` ping, no\n* stream message) is subject to the hub's per-request idle timeout\n* (default 30 minutes) — at which point it is cancelled and its caller\n* gets a `requestTimeout` error. This bounds the hub's pending-request\n* table, which is also what protects it from a slow-loris / DDoS that\n* opens requests and never completes them. Streaming-enabled calls keep\n* themselves alive by emitting a periodic {@link StreamControlType.ping}.\n*\n* The interface is declarative: nobody calls\n* `LinkRpcConnection.register(streamInterface, ...)`. The channel and the\n* hub intercept `$stream::send` directly. The definition exists so\n* reflection / consent UIs can describe the wire shape and so all wire\n* constants derive from one source.\n*/\nconst streamInterface = defineInterface({\n\tid: \"$stream\",\n\tdescription: \"Reserved sub-protocol for in-flight stream messages correlated to a request by `requestId`.\"\n}, { send: notificationType(object({\n\t/**\n\t* Id of the in-flight request the message belongs to.\n\t* The hub rewrites this across the forwarding boundary\n\t* in the same way it rewrites response ids.\n\t*/\n\trequestId: union([number(), string()]),\n\t/**\n\t* Which way this message travels relative to the request.\n\t* Explicit so the hub can author messages (e.g. cancel on\n\t* disconnect) without inferring direction from arrival.\n\t*/\n\tdir: enum$1([\"toCaller\", \"toCallee\"]),\n\t/**\n\t* Reserved control verb (cancel / ping / pong). Mutually\n\t* exclusive with `payload` in practice: a control message\n\t* is interpreted by the runtime, not the application.\n\t*/\n\tcontrol: optional(object({\n\t\ttype: enum$1([\n\t\t\t\"cancel\",\n\t\t\t\"ping\",\n\t\t\t\"pong\"\n\t\t]),\n\t\t/** Open-set human/diagnostic reason; see {@link StreamControlReason}. */\n\t\treason: optional(string()),\n\t\t/**\n\t\t* Correlation token. A `ping` carries a fresh nonce;\n\t\t* the matching `pong` echoes it back so the prober\n\t\t* can resolve the right outstanding probe.\n\t\t*/\n\t\tnonce: optional(string())\n\t})),\n\t/** Opaque app payload — typed per call by the request's stream schema. */\n\tpayload: optional(unknown())\n}), { description: \"Emit a stream message tied to the request `requestId`.\" }) });\n/**\n* Full wire method name for stream notifications. Pulled from the\n* interface object so we have a single source of truth.\n*/\nconst STREAM_METHOD = `${streamInterface.info.id}::send`;\n//#endregion\n//#region src/inspection/trafficFlowFilter.ts\nvar TrafficFlowFilter = class {\n\t_focused;\n\tconstructor(options) {\n\t\tthis._focused = options.focus !== void 0 ? new CorrelatedFlow([options.focus]) : void 0;\n\t}\n\tshouldInclude(transit) {\n\t\treturn this._focused?.accept(transit).matches ?? true;\n\t}\n};\nvar TrafficWatchFlowTracker = class {\n\t_active = /* @__PURE__ */ new Set();\n\t_unclaimed = /* @__PURE__ */ new Map();\n\taccept(transit) {\n\t\tif (transit.kind === \"request\" && isTrafficWatchMethod(transit.method)) {\n\t\t\tconst trafficIgnoreKey = readTrafficIgnoreKey(transit.params);\n\t\t\tlet flow = this._findFlow(transit);\n\t\t\tif (flow === void 0) {\n\t\t\t\tflow = new CorrelatedFlow(requestRefsOf(transit), completionRefOf(transit));\n\t\t\t\tif (!isTerminal(transit)) this._active.add(flow);\n\t\t\t} else flow.accept(transit);\n\t\t\tif (isTerminal(transit)) {\n\t\t\t\tthis._removeFlow(flow);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (trafficIgnoreKey !== void 0) this._unclaimed.set(trafficIgnoreKey, flow);\n\t\t\treturn true;\n\t\t}\n\t\tfor (const flow of this._active) {\n\t\t\tconst match = flow.accept(transit);\n\t\t\tif (!match.matches) continue;\n\t\t\tif (match.completed) this._removeFlow(flow);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t_findFlow(transit) {\n\t\tfor (const flow of this._active) if (flow.matches(transit)) return flow;\n\t}\n\t_removeFlow(flow) {\n\t\tthis._active.delete(flow);\n\t\tfor (const [key, pending] of this._unclaimed) if (pending === flow) this._unclaimed.delete(key);\n\t}\n\tclaim(trafficIgnoreKey) {\n\t\treturn this._unclaimed.delete(trafficIgnoreKey);\n\t}\n\tclear() {\n\t\tthis._active.clear();\n\t\tthis._unclaimed.clear();\n\t}\n\tforgetPort(portId) {\n\t\tfor (const flow of this._active) if (flow.hasPort(portId)) this._removeFlow(flow);\n\t}\n};\nvar CorrelatedFlow = class {\n\t_endpoints = /* @__PURE__ */ new Set();\n\t_ports = /* @__PURE__ */ new Set();\n\t_completionEndpoint;\n\tconstructor(endpoints, completionEndpoint = endpoints[0]) {\n\t\tfor (const endpoint of endpoints) {\n\t\t\tthis._endpoints.add(endpointKey(endpoint));\n\t\t\tthis._ports.add(endpoint.portId);\n\t\t}\n\t\tthis._completionEndpoint = completionEndpoint === void 0 ? void 0 : endpointKey(completionEndpoint);\n\t}\n\tmatches(transit) {\n\t\treturn requestRefsOf(transit).some((endpoint) => this._endpoints.has(endpointKey(endpoint)));\n\t}\n\thasPort(portId) {\n\t\treturn this._ports.has(portId);\n\t}\n\taccept(transit) {\n\t\tconst endpoints = requestRefsOf(transit);\n\t\tif (!this.matches(transit)) return {\n\t\t\tmatches: false,\n\t\t\tcompleted: false\n\t\t};\n\t\tfor (const endpoint of endpoints) {\n\t\t\tthis._endpoints.add(endpointKey(endpoint));\n\t\t\tthis._ports.add(endpoint.portId);\n\t\t}\n\t\tconst completed = transit.kind === \"response\" && (isTerminal(transit) || this._completionEndpoint !== void 0 && endpoints.some((endpoint) => endpointKey(endpoint) === this._completionEndpoint));\n\t\tif (completed) this._endpoints.clear();\n\t\treturn {\n\t\t\tmatches: true,\n\t\t\tcompleted\n\t\t};\n\t}\n};\nfunction isTerminal(transit) {\n\treturn transit.disposition === \"dropped\" || transit.disposition === \"unroutable\";\n}\nfunction requestRefsOf(transit) {\n\tconst result = [];\n\tif (transit.in?.requestId !== void 0) result.push(requestRef(transit.in));\n\tif (transit.out?.requestId !== void 0) result.push(requestRef(transit.out));\n\treturn result;\n}\nfunction requestRef(endpoint) {\n\treturn {\n\t\tportId: endpoint.portId,\n\t\trequestId: endpoint.requestId\n\t};\n}\nfunction completionRefOf(transit) {\n\tif (transit.in?.requestId !== void 0) return requestRef(transit.in);\n\tif (transit.out?.requestId !== void 0) return requestRef(transit.out);\n}\nfunction endpointKey(endpoint) {\n\treturn JSON.stringify([\n\t\tendpoint.portId,\n\t\ttypeof endpoint.requestId,\n\t\tendpoint.requestId\n\t]);\n}\nfunction isTrafficWatchMethod(method) {\n\treturn method?.endsWith(\"::hubrpc.traffic::watch\") === true || method?.endsWith(\"::hubrpc.traffic::watchWithPayloads\") === true || method === \"hubrpc.traffic::watch\" || method === \"hubrpc.traffic::watchWithPayloads\";\n}\nfunction readTrafficIgnoreKey(params) {\n\tif (params === null || Array.isArray(params) || typeof params !== \"object\" || !(\"trafficIgnoreKey\" in params)) return;\n\tconst value = params.trafficIgnoreKey;\n\treturn typeof value === \"string\" ? value : void 0;\n}\n//#endregion\n//#region src/inspection/boundedTrafficSubscription.ts\nconst DEFAULT_QUEUE_LIMIT = 256;\n/**\n* Applies per-subscriber filtering and payload policy while isolating traffic\n* producers from slow or failed stream consumers.\n*/\nvar BoundedTrafficSubscription = class {\n\t_options;\n\t_send;\n\t_onDispose;\n\t_queueLimit;\n\t_queue = [];\n\t_active = true;\n\t_pumping = false;\n\t_overflowPending = 0;\n\t_delivered = 0;\n\t_dropped = 0;\n\t_resolveClosed;\n\t_filter;\n\tclosed;\n\tconstructor(_options, _send, _onDispose, _queueLimit = DEFAULT_QUEUE_LIMIT) {\n\t\tthis._options = _options;\n\t\tthis._send = _send;\n\t\tthis._onDispose = _onDispose;\n\t\tthis._queueLimit = _queueLimit;\n\t\tlet resolve;\n\t\tthis.closed = new Promise((r) => resolve = r);\n\t\tthis._resolveClosed = resolve;\n\t\tthis._filter = new TrafficFlowFilter({ focus: _options.focusRequest });\n\t}\n\tenqueue(transit) {\n\t\tif (!this._active) return;\n\t\tif (!this._filter.shouldInclude(transit)) return;\n\t\tif (this._options.methodPrefix !== void 0 && !transit.method?.startsWith(this._options.methodPrefix)) return;\n\t\tconst event = this._options.maxPayloadBytes === void 0 ? withoutPayloads(transit) : withCappedPayloads(transit, this._options.maxPayloadBytes);\n\t\tif (this._queue.length >= this._queueLimit) {\n\t\t\tthis._queue.shift();\n\t\t\tthis._dropped++;\n\t\t\tthis._overflowPending++;\n\t\t}\n\t\tthis._queue.push(event);\n\t\tif (!this._pumping) {\n\t\t\tthis._pumping = true;\n\t\t\tqueueMicrotask(() => void this._pump());\n\t\t}\n\t}\n\tdispose() {\n\t\tif (!this._active) return;\n\t\tthis._active = false;\n\t\tthis._dropped += this._queue.length;\n\t\tthis._queue.length = 0;\n\t\tthis._overflowPending = 0;\n\t\tthis._onDispose();\n\t\tif (!this._pumping) this._complete();\n\t}\n\tasync _pump() {\n\t\ttry {\n\t\t\twhile (this._active) {\n\t\t\t\tif (this._overflowPending > 0) {\n\t\t\t\t\tconst dropped = this._overflowPending;\n\t\t\t\t\tthis._overflowPending = 0;\n\t\t\t\t\tawait this._send({\n\t\t\t\t\t\ttype: \"overflow\",\n\t\t\t\t\t\tdropped\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst event = this._queue.shift();\n\t\t\t\tif (event === void 0) break;\n\t\t\t\tawait this._send(event);\n\t\t\t\tthis._delivered++;\n\t\t\t}\n\t\t} catch {\n\t\t\tthis.dispose();\n\t\t} finally {\n\t\t\tthis._pumping = false;\n\t\t\tif (!this._active) this._complete();\n\t\t\telse if (this._queue.length > 0 || this._overflowPending > 0) {\n\t\t\t\tthis._pumping = true;\n\t\t\t\tqueueMicrotask(() => void this._pump());\n\t\t\t}\n\t\t}\n\t}\n\t_complete() {\n\t\tthis._resolveClosed({\n\t\t\tdelivered: this._delivered,\n\t\t\tdropped: this._dropped\n\t\t});\n\t}\n};\nfunction withoutPayloads(transit) {\n\tconst { params: _params, result: _result, error, ...rest } = transit;\n\tif (error === void 0) return rest;\n\treturn {\n\t\t...rest,\n\t\terror: {\n\t\t\tcode: error.code,\n\t\t\tmessage: error.message\n\t\t}\n\t};\n}\nfunction withCappedPayloads(transit, maxPayloadBytes) {\n\treturn {\n\t\t...transit,\n\t\tparams: capPayload(transit.params, maxPayloadBytes),\n\t\tresult: capPayload(transit.result, maxPayloadBytes),\n\t\terror: transit.error === void 0 ? void 0 : {\n\t\t\t...transit.error,\n\t\t\tdata: capPayload(transit.error.data, maxPayloadBytes)\n\t\t}\n\t};\n}\nfunction capPayload(value, maxBytes) {\n\tif (value === void 0) return void 0;\n\tif (maxBytes === Number.POSITIVE_INFINITY) return value;\n\tconst json = JSON.stringify(value);\n\tif (json === void 0) return void 0;\n\tconst encoded = new TextEncoder().encode(json);\n\tif (encoded.byteLength <= maxBytes) return value;\n\tconst encoder = new TextEncoder();\n\tlet preview = new TextDecoder().decode(encoded.slice(0, maxBytes));\n\twhile (encoder.encode(preview).byteLength > maxBytes) preview = preview.slice(0, -1);\n\treturn preview;\n}\n//#endregion\n//#region src/inspection/endpointTrafficInspector.ts\nconst REQUEST_CORRELATION_RETENTION_MS = 18e5;\nconst MAX_REQUEST_CORRELATIONS = 4096;\nvar EndpointTrafficInspector = class {\n\t_nodeId;\n\t_portId;\n\t_emit;\n\t_isObserved;\n\t_outboundRequests = /* @__PURE__ */ new Map();\n\t_inboundRequests = /* @__PURE__ */ new Map();\n\tobserve = (direction, message) => {\n\t\tthis._onMessage(direction, message);\n\t};\n\tconstructor(_nodeId, _portId, _emit, _isObserved) {\n\t\tthis._nodeId = _nodeId;\n\t\tthis._portId = _portId;\n\t\tthis._emit = _emit;\n\t\tthis._isObserved = _isObserved;\n\t}\n\tdispose() {\n\t\tthis._outboundRequests.clear();\n\t\tthis._inboundRequests.clear();\n\t}\n\t_onMessage(direction, message) {\n\t\tconst now = Date.now();\n\t\tthis._pruneRequestCorrelations(now);\n\t\tconst publiclyObserved = this._isObserved();\n\t\tif (!publiclyObserved) this.dispose();\n\t\tlet transit;\n\t\tconst endpoint = this._endpoint(\"id\" in message ? message.id ?? void 0 : void 0);\n\t\tconst base = {\n\t\t\ttype: \"transit\",\n\t\t\ttimeMs: now,\n\t\t\tnodeId: this._nodeId,\n\t\t\t...direction === \"inbound\" ? { in: endpoint } : { out: endpoint },\n\t\t\tdisposition: direction === \"inbound\" ? \"consumed\" : \"forwarded\"\n\t\t};\n\t\tif (isRequest(message)) {\n\t\t\tconst correlation = {\n\t\t\t\tmethod: message.method,\n\t\t\t\ttimeMs: now\n\t\t\t};\n\t\t\tif (publiclyObserved) {\n\t\t\t\tconst map = this._requestMap(direction);\n\t\t\t\tconst key = requestKey(message.id);\n\t\t\t\tmap.delete(key);\n\t\t\t\tmap.set(key, correlation);\n\t\t\t}\n\t\t\ttransit = {\n\t\t\t\t...base,\n\t\t\t\tkind: \"request\",\n\t\t\t\tmethod: message.method,\n\t\t\t\tparams: message.params\n\t\t\t};\n\t\t} else if (isResponse(message)) {\n\t\t\tconst responseMap = direction === \"inbound\" ? this._outboundRequests : this._inboundRequests;\n\t\t\tconst key = requestKey(message.id);\n\t\t\tconst correlation = responseMap.get(key);\n\t\t\tresponseMap.delete(key);\n\t\t\ttransit = {\n\t\t\t\t...base,\n\t\t\t\tkind: \"response\",\n\t\t\t\tmethod: correlation?.method,\n\t\t\t\tresult: \"result\" in message ? message.result : void 0,\n\t\t\t\terror: \"error\" in message ? message.error : void 0\n\t\t\t};\n\t\t} else if (isNotification(message) && message.method === STREAM_METHOD) {\n\t\t\tconst params = message.params;\n\t\t\tconst streamEndpoint = this._endpoint(params?.requestId);\n\t\t\ttransit = {\n\t\t\t\t...base,\n\t\t\t\t...direction === \"inbound\" ? { in: streamEndpoint } : { out: streamEndpoint },\n\t\t\t\tkind: \"stream\",\n\t\t\t\tmethod: STREAM_METHOD,\n\t\t\t\tparams: message.params\n\t\t\t};\n\t\t} else transit = {\n\t\t\t...base,\n\t\t\tkind: \"notification\",\n\t\t\tmethod: message.method,\n\t\t\tparams: message.params\n\t\t};\n\t\tfunction requestKey(requestId) {\n\t\t\treturn JSON.stringify([typeof requestId, requestId]);\n\t\t}\n\t\tthis._emit(transit);\n\t}\n\t_requestMap(direction) {\n\t\treturn direction === \"outbound\" ? this._outboundRequests : this._inboundRequests;\n\t}\n\t_endpoint(requestId) {\n\t\treturn {\n\t\t\tedgeId: this._portId,\n\t\t\tportId: this._portId,\n\t\t\t...requestId !== void 0 ? { requestId } : {}\n\t\t};\n\t}\n\t_pruneRequestCorrelations(timeMs) {\n\t\tthis._pruneRequestMap(this._outboundRequests, timeMs);\n\t\tthis._pruneRequestMap(this._inboundRequests, timeMs);\n\t}\n\t_pruneRequestMap(map, timeMs) {\n\t\twhile (map.size !== 0) {\n\t\t\tconst first = map.entries().next().value;\n\t\t\tif (first === void 0 || map.size <= MAX_REQUEST_CORRELATIONS && timeMs - first[1].timeMs <= REQUEST_CORRELATION_RETENTION_MS) return;\n\t\t\tmap.delete(first[0]);\n\t\t}\n\t}\n};\n//#endregion\n//#region src/inspection/connectionInspectionSource.ts\nvar ConnectionInspectionSource = class {\n\t_connection;\n\t_nodeId;\n\t_options;\n\t_isObserved;\n\tconstructor(_connection, _nodeId, _options, _isObserved) {\n\t\tthis._connection = _connection;\n\t\tthis._nodeId = _nodeId;\n\t\tthis._options = _options;\n\t\tthis._isObserved = _isObserved;\n\t}\n\tsnapshotTopology() {\n\t\tconst { portId, label, peer, transport } = this._options;\n\t\tconst nodes = [{\n\t\t\tnodeId: this._nodeId,\n\t\t\tports: [{\n\t\t\t\tportId,\n\t\t\t\t...label === void 0 ? {} : { label }\n\t\t\t}]\n\t\t}];\n\t\tconst links = [];\n\t\tif (peer !== void 0) {\n\t\t\tnodes.push({\n\t\t\t\tnodeId: peer.nodeId,\n\t\t\t\tkind: \"endpoint\",\n\t\t\t\t...peer.label === void 0 ? {} : { label: peer.label },\n\t\t\t\tports: [{ portId: peer.portId }]\n\t\t\t});\n\t\t\tlinks.push({\n\t\t\t\tfrom: {\n\t\t\t\t\tnodeId: this._nodeId,\n\t\t\t\t\tportId\n\t\t\t\t},\n\t\t\t\tto: {\n\t\t\t\t\tnodeId: peer.nodeId,\n\t\t\t\t\tportId: peer.portId\n\t\t\t\t},\n\t\t\t\tpeerState: \"identified\",\n\t\t\t\t...transport === void 0 ? {} : { transport }\n\t\t\t});\n\t\t}\n\t\treturn {\n\t\t\tnodes,\n\t\t\tlinks,\n\t\t\troutes: []\n\t\t};\n\t}\n\tonTopologyChanged(_listener) {\n\t\treturn { dispose: () => {} };\n\t}\n\tobserveTraffic(listener) {\n\t\tconst inspector = new EndpointTrafficInspector(this._nodeId, this._options.portId, listener, this._isObserved);\n\t\tconst observation = this._connection.observeWireMessages(inspector.observe);\n\t\treturn { dispose: () => {\n\t\t\tobservation.dispose();\n\t\t\tinspector.dispose();\n\t\t} };\n\t}\n};\n//#endregion\n//#region src/inspection/inspectionHost.ts\n/** A shared inspection scope, independent of both routing and its RPC connections. */\nvar InspectionHost = class {\n\t_options;\n\t_sources = /* @__PURE__ */ new Map();\n\t_trackedConnections = /* @__PURE__ */ new Set();\n\t_bindings = /* @__PURE__ */ new Set();\n\t_subscribers = /* @__PURE__ */ new Set();\n\t_observers = /* @__PURE__ */ new Set();\n\t_topologyListeners = /* @__PURE__ */ new Set();\n\t_trafficSources = /* @__PURE__ */ new Set();\n\t_trafficWatches = new TrafficWatchFlowTracker();\n\t_disposed = false;\n\tnodeId;\n\tconstructor(_options) {\n\t\tthis._options = _options;\n\t\tthis.nodeId = _options.nodeId;\n\t}\n\tget observerCount() {\n\t\treturn this._subscribers.size + this._observers.size;\n\t}\n\taddSource(source) {\n\t\tthis._assertActive();\n\t\tif (this._sources.has(source)) throw new Error(\"Inspection source is already registered\");\n\t\tconst readPorts = () => new Set(source.snapshotTopology().nodes.flatMap((node) => node.ports.map((port) => port.portId)));\n\t\tlet ports = readPorts();\n\t\tconst topology = source.onTopologyChanged(() => {\n\t\t\tconst nextPorts = readPorts();\n\t\t\tconst removed = [...ports].filter((port) => !nextPorts.has(port));\n\t\t\tports = nextPorts;\n\t\t\tthis._forgetUnusedPorts(removed);\n\t\t\tthis._invalidateTopology();\n\t\t});\n\t\tlet traffic;\n\t\ttry {\n\t\t\ttraffic = source.observeTraffic((event) => this.publishTransit(event));\n\t\t} catch (error) {\n\t\t\ttopology.dispose();\n\t\t\tthrow error;\n\t\t}\n\t\tconst registration = { dispose: () => {\n\t\t\tif (this._sources.get(source) !== registration) return;\n\t\t\tthis._sources.delete(source);\n\t\t\ttopology.dispose();\n\t\t\ttraffic.dispose();\n\t\t\tthis._forgetUnusedPorts([...ports]);\n\t\t\tthis._invalidateTopology();\n\t\t} };\n\t\tthis._sources.set(source, registration);\n\t\tthis._invalidateTopology();\n\t\treturn registration;\n\t}\n\ttrackConnection(connection, options) {\n\t\tthis._assertActive();\n\t\tif (this.getGraph(\"\").nodes.some((node) => node.ports.some((port) => port.portId === options.portId))) throw new Error(`Inspection port \"${options.portId}\" is already registered`);\n\t\tconst source = new ConnectionInspectionSource(connection, this.nodeId, options, () => this.observerCount !== 0);\n\t\tconst registration = this.addSource(source);\n\t\tlet close;\n\t\ttry {\n\t\t\tclose = connection.onDidClose(() => result.dispose());\n\t\t} catch (error) {\n\t\t\tregistration.dispose();\n\t\t\tthrow error;\n\t\t}\n\t\tconst result = { dispose: () => {\n\t\t\tthis._trackedConnections.delete(result);\n\t\t\tclose.dispose();\n\t\t\tregistration.dispose();\n\t\t} };\n\t\tthis._trackedConnections.add(result);\n\t\treturn result;\n\t}\n\texpose(connection, options) {\n\t\tthis._assertActive();\n\t\tconst portId = options.portId ?? createPortId();\n\t\tconst binding = new InspectionBinding(portId);\n\t\tconst registrations = [];\n\t\tthis._bindings.add(binding);\n\t\tconst registerOptions = { serviceId: options.serviceId };\n\t\ttry {\n\t\t\tconst controls = new EndpointTrafficInspector(this.nodeId, portId, (event) => this._trafficWatches.accept(event), () => false);\n\t\t\tregistrations.push(connection.observeWireMessages(controls.observe));\n\t\t\tregistrations.push({ dispose: () => controls.dispose() });\n\t\t\tregistrations.push(connection.registerInspection(nodeInterface, { getNodeId: () => ({\n\t\t\t\tnodeId: this.nodeId,\n\t\t\t\tportId,\n\t\t\t\t...(options.descriptors ?? this._options.descriptors) === void 0 ? {} : { descriptors: [...options.descriptors ?? this._options.descriptors ?? []] }\n\t\t\t}) }, registerOptions));\n\t\t\tregistrations.push(connection.registerInspection(topologyInterface, {\n\t\t\t\tgetGraph: () => this.getGraph(options.serviceId, options.includeRoute === false ? void 0 : portId),\n\t\t\t\twatchGraph: (_params, _ctx, stream) => this._watchGraph(binding, stream)\n\t\t\t}, registerOptions));\n\t\t\tregistrations.push(connection.registerInspection(trafficInterface, {\n\t\t\t\twatch: (params, _ctx, stream) => this._watchTraffic(binding, params, stream),\n\t\t\t\twatchWithPayloads: (params, _ctx, stream) => this._watchTraffic(binding, params, stream)\n\t\t\t}, registerOptions));\n\t\t} catch (error) {\n\t\t\tfor (const registration of registrations.reverse()) registration.dispose();\n\t\t\tthis._bindings.delete(binding);\n\t\t\tthrow error;\n\t\t}\n\t\tbinding.onDispose = () => {\n\t\t\tthis._bindings.delete(binding);\n\t\t\tfor (const registration of registrations.reverse()) registration.dispose();\n\t\t\tthis._forgetUnusedPorts([portId]);\n\t\t\tthis._invalidateTopology();\n\t\t};\n\t\tregistrations.push(connection.onDidClose(() => binding.dispose()));\n\t\tthis._invalidateTopology();\n\t\treturn binding;\n\t}\n\tgetGraph(observerServiceId, routePortId) {\n\t\tthis._assertActive();\n\t\tconst nodes = /* @__PURE__ */ new Map();\n\t\tconst mergeNode = (node) => {\n\t\t\tconst previous = nodes.get(node.nodeId);\n\t\t\tconst ports = new Map(previous?.ports.map((port) => [port.portId, port]));\n\t\t\tfor (const port of node.ports) ports.set(port.portId, {\n\t\t\t\t...ports.get(port.portId),\n\t\t\t\t...port\n\t\t\t});\n\t\t\tnodes.set(node.nodeId, {\n\t\t\t\t...previous,\n\t\t\t\t...node,\n\t\t\t\tports: [...ports.values()]\n\t\t\t});\n\t\t};\n\t\tmergeNode({\n\t\t\tnodeId: this.nodeId,\n\t\t\tkind: this._options.kind ?? \"endpoint\",\n\t\t\t...this._options.label === void 0 ? {} : { label: this._options.label },\n\t\t\t...this._options.descriptors === void 0 ? {} : { descriptors: [...this._options.descriptors] },\n\t\t\tports: []\n\t\t});\n\t\tconst links = [];\n\t\tconst routes = [];\n\t\tfor (const source of this._sources.keys()) {\n\t\t\tconst fragment = source.snapshotTopology();\n\t\t\tfor (const node of fragment.nodes) mergeNode(node);\n\t\t\tlinks.push(...fragment.links);\n\t\t\troutes.push(...fragment.routes);\n\t\t}\n\t\tfor (const binding of this._bindings) mergeNode({\n\t\t\tnodeId: this.nodeId,\n\t\t\tports: [{ portId: binding.portId }]\n\t\t});\n\t\tif (routePortId !== void 0) routes.push({\n\t\t\tserviceId: observerServiceId,\n\t\t\tnodeId: this.nodeId,\n\t\t\tportId: routePortId,\n\t\t\tmatch: \"exact\"\n\t\t});\n\t\treturn {\n\t\t\tobserverServiceId,\n\t\t\tentryNodeId: this.nodeId,\n\t\t\tnodes: [...nodes.values()],\n\t\t\tlinks,\n\t\t\troutes\n\t\t};\n\t}\n\tpublishTransit(event) {\n\t\tif (this._disposed || this._trafficWatches.accept(event)) return;\n\t\tfor (const observer of [...this._observers]) try {\n\t\t\tobserver(event);\n\t\t} catch {}\n\t\tfor (const subscriber of this._subscribers) subscriber.enqueue(event);\n\t}\n\tsubscribe(options, send) {\n\t\tthis._assertActive();\n\t\tif (options.trafficIgnoreKey !== void 0 && !this._trafficWatches.claim(options.trafficIgnoreKey)) throw new Error(\"Traffic watch request was not observed before subscription\");\n\t\tconst subscriber = new BoundedTrafficSubscription(options, send, () => {\n\t\t\tthis._subscribers.delete(subscriber);\n\t\t\tthis._stopUnusedTrafficSources();\n\t\t});\n\t\tthis._subscribers.add(subscriber);\n\t\ttry {\n\t\t\tthis._startTrafficSources();\n\t\t} catch (error) {\n\t\t\tsubscriber.dispose();\n\t\t\tthrow error;\n\t\t}\n\t\treturn subscriber;\n\t}\n\tobserveTraffic(observer) {\n\t\tthis._assertActive();\n\t\tthis._observers.add(observer);\n\t\tconst registration = { dispose: () => {\n\t\t\tthis._observers.delete(observer);\n\t\t\tthis._stopUnusedTrafficSources();\n\t\t} };\n\t\ttry {\n\t\t\tthis._startTrafficSources();\n\t\t} catch (error) {\n\t\t\tregistration.dispose();\n\t\t\tthrow error;\n\t\t}\n\t\treturn registration;\n\t}\n\taddTrafficSource(source) {\n\t\tthis._assertActive();\n\t\tconst entry = { source };\n\t\tthis._trafficSources.add(entry);\n\t\ttry {\n\t\t\tthis._startTrafficSources();\n\t\t} catch (error) {\n\t\t\tthis._trafficSources.delete(entry);\n\t\t\tthrow error;\n\t\t}\n\t\treturn { dispose: () => {\n\t\t\tthis._trafficSources.delete(entry);\n\t\t\tentry.observation?.dispose();\n\t\t\tentry.observation = void 0;\n\t\t} };\n\t}\n\tdispose() {\n\t\tif (this._disposed) return;\n\t\tthis._disposed = true;\n\t\tfor (const binding of [...this._bindings]) binding.dispose();\n\t\tfor (const subscriber of [...this._subscribers]) subscriber.dispose();\n\t\tthis._observers.clear();\n\t\tthis._stopUnusedTrafficSources();\n\t\tthis._trafficSources.clear();\n\t\tfor (const connection of [...this._trackedConnections]) connection.dispose();\n\t\tfor (const source of [...this._sources.values()]) source.dispose();\n\t\tthis._topologyListeners.clear();\n\t\tthis._trafficWatches.clear();\n\t}\n\t_startTrafficSources() {\n\t\tif (this.observerCount === 0) return;\n\t\tfor (const entry of this._trafficSources) entry.observation ??= entry.source.observe((event) => this.publishTransit(event));\n\t}\n\t_stopUnusedTrafficSources() {\n\t\tif (this.observerCount !== 0) return;\n\t\tfor (const entry of this._trafficSources) {\n\t\t\tentry.observation?.dispose();\n\t\t\tentry.observation = void 0;\n\t\t}\n\t}\n\t_invalidateTopology() {\n\t\tif (this._disposed) return;\n\t\tfor (const listener of this._topologyListeners) listener();\n\t}\n\t_forgetUnusedPorts(portIds) {\n\t\tif (this._disposed) return;\n\t\tconst remaining = new Set(this.getGraph(\"\").nodes.flatMap((node) => node.ports.map((port) => port.portId)));\n\t\tfor (const portId of portIds) if (!remaining.has(portId)) this._trafficWatches.forgetPort(portId);\n\t}\n\t_watchGraph(binding, stream) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tlet pending = false;\n\t\t\tlet active = true;\n\t\t\tconst finish = () => {\n\t\t\t\tactive = false;\n\t\t\t\tthis._topologyListeners.delete(invalidate);\n\t\t\t\tstream.signal.removeEventListener(\"abort\", finish);\n\t\t\t\tbinding.abort.signal.removeEventListener(\"abort\", finish);\n\t\t\t\tresolve({});\n\t\t\t};\n\t\t\tconst invalidate = () => {\n\t\t\t\tif (pending || !active) return;\n\t\t\t\tpending = true;\n\t\t\t\tqueueMicrotask(() => {\n\t\t\t\t\tpending = false;\n\t\t\t\t\tif (!active) return;\n\t\t\t\t\tstream.send({}).catch((error) => {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t\tfinish();\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t};\n\t\t\tthis._topologyListeners.add(invalidate);\n\t\t\tstream.signal.addEventListener(\"abort\", finish, { once: true });\n\t\t\tbinding.abort.signal.addEventListener(\"abort\", finish, { once: true });\n\t\t\tif (stream.signal.aborted || binding.abort.signal.aborted) finish();\n\t\t});\n\t}\n\tasync _watchTraffic(binding, options, stream) {\n\t\tconst subscription = this.subscribe(options, (event) => stream.send(event));\n\t\tconst dispose = () => subscription.dispose();\n\t\tstream.signal.addEventListener(\"abort\", dispose, { once: true });\n\t\tbinding.abort.signal.addEventListener(\"abort\", dispose, { once: true });\n\t\tif (stream.signal.aborted || binding.abort.signal.aborted) dispose();\n\t\ttry {\n\t\t\treturn await subscription.closed;\n\t\t} finally {\n\t\t\tstream.signal.removeEventListener(\"abort\", dispose);\n\t\t\tbinding.abort.signal.removeEventListener(\"abort\", dispose);\n\t\t\tsubscription.dispose();\n\t\t}\n\t}\n\t_assertActive() {\n\t\tif (this._disposed) throw new Error(\"Inspection host is disposed\");\n\t}\n};\nvar InspectionBinding = class {\n\tportId;\n\tabort = new AbortController();\n\tonDispose = () => {};\n\tconstructor(portId) {\n\t\tthis.portId = portId;\n\t}\n\tdispose() {\n\t\tif (this.abort.signal.aborted) return;\n\t\tthis.abort.abort();\n\t\tthis.onDispose();\n\t}\n};\nfunction createPortId() {\n\tconst bytes = /* @__PURE__ */ new Uint8Array(16);\n\tglobalThis.crypto.getRandomValues(bytes);\n\treturn `port:${bytesToBase64Url(bytes)}`;\n}\n//#endregion\nexport { validateInterfaceTemplate as $, PRINCIPAL_PREFIX as A, interfaceFromSchema as B, zTopologyTransportInfo as C, isRequest as Ct, zTrafficTransitEvent as D, normalizeJsonSchema as Dt, zTrafficTransitEndpoint as E, isRpcFailure as Et, principalForPublicKey as F, schemaToZod as G, interfaceTemplateGroup as H, publicKeyForKeyId as I, getInterfaceTags as J, INTERFACE_TEMPLATES_EXTENSION as K, resolveSigningKey as L, bytesToBase64Url as M, keyIdForPrincipal as N, zTrafficWatchResult as O, keyIdForPublicKey as P, preferRicherInterfaceSchema as Q, InterfaceDefinition as R, zTopologyTransportEndpoint as S, isNotification as St, zTrafficOverflowEvent as T, RpcFailure as Tt, validateInterfaceErrors as U, toMethodSchema as V, createSchemaToZod as W, interfaceTemplateMemberName as X, interfaceTemplateArgumentsEquivalent as Y, interfaceTemplatesEqual as Z, zTopologyGraph as _, jsonIssues as _t, TrafficWatchFlowTracker as a, jcsCanonicalizeBytes as at, zTopologyNode as b, brandApplicationError as bt, StreamControlType as c, componentSchemaRef as ct, nodeInterface as d, applicationError as dt, validateInterfaceTemplates as et, topologyInterface as f, isApplicationErrorValue as ft, zRouteClaim as g, zodToSvcJsonSchema as gt, zParticipantDescriptorSource as h, rpcError as ht, TrafficFlowFilter as i, jcsCanonicalize as it, base64UrlToBytes as j, KEY_ID_PREFIX as k, StreamDir as l, NotificationType as lt, zParticipantDescriptor as m, requestType as mt, ConnectionInspectionSource as n, computeInterfaceHash as nt, STREAM_METHOD as o, assertSchemaReferences as ot, trafficInterface as p, notificationType as pt, bindTemplateArguments as q, BoundedTrafficSubscription as r, sha256 as rt, StreamControlReason as s, componentSchemaName as st, InspectionHost as t, EXTENSION_PREFIX as tt, streamInterface as u, RequestType as ut, zTopologyLink as v, parseDeclaredErrorBody as vt, zTrafficEvent as w, isResponse as wt, zTopologyPort as x, ErrorCode as xt, zTopologyLinkEndpoint as y, jsonPointerSegment as yt, defineInterface as z };\n\n//# sourceMappingURL=inspectionHost-BA6ZmC_P.js.map","/*---------------------------------------------------------------------------------------------\n* Copyright (c) Microsoft Corporation. All rights reserved.\n* Licensed under the MIT License. See License.txt in the project root for license information.\n*--------------------------------------------------------------------------------------------*/\nimport { t as __exportAll } from \"./rolldown-runtime-4LSo1kEK.js\";\nimport { $ as validateInterfaceTemplate, Ct as isRequest, F as principalForPublicKey, H as interfaceTemplateGroup, I as publicKeyForKeyId, L as resolveSigningKey, M as bytesToBase64Url, N as keyIdForPrincipal, Q as preferRicherInterfaceSchema, St as isNotification, Tt as RpcFailure, U as validateInterfaceErrors, V as toMethodSchema, _t as jsonIssues, at as jcsCanonicalizeBytes, bt as brandApplicationError, c as StreamControlType, d as nodeInterface, et as validateInterfaceTemplates, ft as isApplicationErrorValue, gt as zodToSvcJsonSchema, it as jcsCanonicalize, j as base64UrlToBytes$1, l as StreamDir, mt as requestType, nt as computeInterfaceHash, o as STREAM_METHOD, q as bindTemplateArguments, rt as sha256$1, st as componentSchemaName, t as InspectionHost, vt as parseDeclaredErrorBody, wt as isResponse, xt as ErrorCode, yt as jsonPointerSegment, z as defineInterface } from \"./inspectionHost-BA6ZmC_P.js\";\nimport { array, boolean, int, never, nonnegative, number, object, optional, positive, string, union, unknown } from \"zod/mini\";\nimport { safeParse } from \"zod/v4/core\";\n//#region src/schema/defineInterfaceTemplate.ts\n/**\n* Wrap an explicitly generic, declarative, side-effect-free schema factory.\n* It runs once with symbolic schemas for reflection, then once per call with\n* the original concrete schemas. Never branch on the schema arguments.\n* The bare callable return preserves TypeScript's higher-order generic inference.\n*/\nfunction defineInterfaceTemplate(info, factory) {\n\tconst snapshot = {\n\t\tid: info.id,\n\t\tparameters: [...info.parameters],\n\t\t...info.tags === void 0 ? {} : { tags: [...info.tags] }\n\t};\n\tconst markers = /* @__PURE__ */ new WeakMap();\n\tconst members = factory(Object.fromEntries(snapshot.parameters.map((name) => {\n\t\tconst schema = never();\n\t\tmarkers.set(schema, name);\n\t\treturn [name, schema];\n\t})));\n\tconst components = {};\n\tconst methods = Object.fromEntries(Object.entries(members).map(([name, member]) => [name, toMethodSchema(name, member, components, (schema, position) => zodToSvcJsonSchema(schema, {\n\t\tmethodName: name,\n\t\tschemaPosition: position,\n\t\tcomponents,\n\t\tparameterNames: markers\n\t}))]));\n\tconst replace = (value) => {\n\t\tif (Array.isArray(value)) return value.map(replace);\n\t\tif (value !== null && typeof value === \"object\") {\n\t\t\tconst record = value;\n\t\t\tif (typeof record.$ref === \"string\" && record.$ref.startsWith(\"linkrpc-parameter:\")) return { $parameter: decodeURIComponent(record.$ref.slice(18)) };\n\t\t\treturn Object.fromEntries(Object.entries(record).map(([key, child]) => [key, replace(child)]));\n\t\t}\n\t\treturn value;\n\t};\n\tconst template = replace({\n\t\t...snapshot,\n\t\tmethods,\n\t\t...Object.keys(components).length === 0 ? {} : { components: { schemas: components } }\n\t});\n\tvalidateInterfaceTemplate(template);\n\tfreezeMetadata(template);\n\treturn (args) => {\n\t\tif (args === null || typeof args !== \"object\" || Array.isArray(args)) throw new Error(\"Interface template arguments must be a schema argument object\");\n\t\tfor (const key of Reflect.ownKeys(args)) if (typeof key !== \"string\" || !snapshot.parameters.includes(key)) throw new Error(`Interface template \"${snapshot.id}\" supplies unknown parameter \"${String(key)}\"`);\n\t\tfor (const name of snapshot.parameters) {\n\t\t\tif (!Object.hasOwn(args, name)) throw new Error(`Interface template \"${snapshot.id}\" is missing parameter \"${name}\"`);\n\t\t\tconst schema = args[name];\n\t\t\tif (schema === null || typeof schema !== \"object\" || !(\"_zod\" in schema)) throw new Error(`Interface template parameter \"${name}\" must be a Zod schema`);\n\t\t\tif (schema._zod.optout === \"optional\") throw new Error(\"Generic schema arguments must not be optional; wrap the parameter with optional() in the template\");\n\t\t}\n\t\tconst arguments_ = structuredClone(bindTemplateArguments(template, args));\n\t\tfreezeMetadata(arguments_);\n\t\tconst concrete = factory(args);\n\t\tconst bound = {\n\t\t\t[interfaceTemplateGroup]: true,\n\t\t\ttemplate,\n\t\t\targuments: arguments_,\n\t\t\tmapping: void 0,\n\t\t\tmembers: concrete,\n\t\t\tmapMembers(mapping) {\n\t\t\t\tconst targets = /* @__PURE__ */ new Set();\n\t\t\t\tfor (const key of Object.keys(mapping)) if (!Object.hasOwn(concrete, key)) throw new Error(`Unknown mapped member \"${key}\"`);\n\t\t\t\tfor (const key of Object.keys(concrete)) {\n\t\t\t\t\tconst target = mapping[key];\n\t\t\t\t\tif (!Object.hasOwn(mapping, key) || typeof target !== \"string\") throw new Error(`Missing mapped member \"${key}\"`);\n\t\t\t\t\tif (targets.has(target)) throw new Error(`Interface template member collision at \"${target}\"`);\n\t\t\t\t\ttargets.add(target);\n\t\t\t\t}\n\t\t\t\tconst frozenMapping = Object.freeze({ ...mapping });\n\t\t\t\treturn {\n\t\t\t\t\t[interfaceTemplateGroup]: true,\n\t\t\t\t\ttemplate,\n\t\t\t\t\targuments: arguments_,\n\t\t\t\t\tmembers: concrete,\n\t\t\t\t\tmapping: frozenMapping,\n\t\t\t\t\tschema: Object.freeze({\n\t\t\t\t\t\ttemplate: template.id,\n\t\t\t\t\t\targuments: arguments_,\n\t\t\t\t\t\tmembers: frozenMapping\n\t\t\t\t\t})\n\t\t\t\t};\n\t\t\t}\n\t\t};\n\t\tdefineInterface({ id: snapshot.id }, { instance: bound });\n\t\treturn bound;\n\t};\n}\nfunction freezeMetadata(value) {\n\tif (value === null || typeof value !== \"object\" || Object.isFrozen(value)) return;\n\tfor (const child of Object.values(value)) freezeMetadata(child);\n\tObject.freeze(value);\n}\n//#endregion\n//#region src/connection/nonCompliantServerError.ts\nvar NonCompliantServerError = class extends Error {\n\toriginal;\n\tissues;\n\tkind = \"nonCompliantServer\";\n\tconstructor(original, issues) {\n\t\tsuper(`Server error ${original.code} does not match its declared schema: ${issues.map((issue) => `${issue.path || \"/\"}: ${issue.message}`).join(\"; \")}`);\n\t\tthis.original = original;\n\t\tthis.issues = issues;\n\t\tthis.name = \"NonCompliantServerError\";\n\t}\n};\n//#endregion\n//#region src/schema/assignability.ts\n/**\n* Structural subtype check: returns `true` iff every JSON value matching\n* `sub` also matches `sup`, over the SvcJsonSchema subset.\n*\n* Cycles introduced by `$ref` are broken by assuming the recursive case\n* holds (standard coinductive subtyping). This is sound for productive\n* (non-degenerate) schemas; pathological inputs are out of scope.\n*/\nfunction isAssignable(sub, sup, components = {}) {\n\treturn _check(sub, sup, components, /* @__PURE__ */ new Set());\n}\n/** Match one JSON value against the structural LinkRPC subset without transforming it. */\nfunction matchesJsonSchema(value, schema, components = {}) {\n\treturn _matches(value, schema, components, /* @__PURE__ */ new Set());\n}\nfunction validateJsonSchema(value, schema, components = {}) {\n\tconst issues = [];\n\t_matches(value, schema, components, /* @__PURE__ */ new Set(), issues);\n\treturn issues;\n}\nfunction _check(sub, sup, c, seen) {\n\tif (sup === true) return true;\n\tif (sub === false) return true;\n\tif (sup === false) return _isBottom(sub, c, seen);\n\tif (sub === true) return false;\n\tif (_isRef(sub)) {\n\t\tconst k = `S:${sub.$ref}|${_keyOf(sup)}`;\n\t\tif (seen.has(k)) return true;\n\t\tconst resolved = _resolveRef(sub, c);\n\t\tif (!resolved) return false;\n\t\treturn _check(resolved, sup, c, new Set(seen).add(k));\n\t}\n\tif (_isRef(sup)) {\n\t\tconst k = `${_keyOf(sub)}|T:${sup.$ref}`;\n\t\tif (seen.has(k)) return true;\n\t\tconst resolved = _resolveRef(sup, c);\n\t\tif (!resolved) return false;\n\t\treturn _check(sub, resolved, c, new Set(seen).add(k));\n\t}\n\tif (_isUnion(sub)) return _branches(sub).every((branch) => _check(branch, sup, c, seen));\n\tif (_isUnion(sup)) return _branches(sup).some((branch) => _check(sub, branch, c, seen));\n\tif (_isConst(sub)) return _matches(sub.const, sup, c, seen);\n\tif (_isEnum(sub)) return sub.enum.every((v) => _matches(v, sup, c, seen));\n\tif (_isConst(sup)) {\n\t\tif (_isConst(sub)) return _jsonEq(sub.const, sup.const);\n\t\treturn false;\n\t}\n\tif (_isEnum(sup)) {\n\t\tif (_isConst(sub)) return sup.enum.some((v) => _jsonEq(sub.const, v));\n\t\treturn false;\n\t}\n\tconst subType = sub.type;\n\tconst supType = sup.type;\n\tif (subType !== supType) {\n\t\tif (subType === \"integer\" && supType === \"number\") return true;\n\t\treturn false;\n\t}\n\tswitch (subType) {\n\t\tcase \"null\":\n\t\tcase \"boolean\": return true;\n\t\tcase \"number\":\n\t\tcase \"integer\": return _formatCompatible(sub.format, sup.format);\n\t\tcase \"string\": return _formatCompatible(sub.format, sup.format);\n\t\tcase \"array\": return _checkArrayLike(sub, sup, c, seen);\n\t\tcase \"object\": return _checkObject(sub, sup, c, seen);\n\t\tdefault: return false;\n\t}\n}\nfunction _checkObject(sub, sup, c, seen) {\n\tconst subReq = new Set(sub.required ?? []);\n\tconst supReq = new Set(sup.required ?? []);\n\tfor (const k of supReq) if (!subReq.has(k)) return false;\n\tfor (const [k, supProp] of Object.entries(sup.properties)) {\n\t\tconst subProp = sub.properties[k] ?? sub.additionalProperties;\n\t\tif (subProp === false) {\n\t\t\tif (supReq.has(k)) return false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!_check(subProp, supProp, c, seen)) return false;\n\t}\n\tfor (const [k, subProp] of Object.entries(sub.properties)) {\n\t\tif (k in sup.properties) continue;\n\t\tif (sup.additionalProperties === false) return false;\n\t\tif (!_check(subProp, sup.additionalProperties, c, seen)) return false;\n\t}\n\tif (sub.additionalProperties === false) {} else if (sup.additionalProperties === false) return false;\n\telse if (!_check(sub.additionalProperties, sup.additionalProperties, c, seen)) return false;\n\treturn true;\n}\nfunction _checkArrayLike(sub, sup, c, seen) {\n\tconst subPrefix = sub.prefixItems ?? [];\n\tconst supPrefix = sup.prefixItems ?? [];\n\tconst subRest = _restOf(sub);\n\tconst supRest = _restOf(sup);\n\tconst n = Math.max(subPrefix.length, supPrefix.length);\n\tfor (let i = 0; i < n; i++) {\n\t\tconst a = subPrefix[i] ?? subRest;\n\t\tconst b = supPrefix[i] ?? supRest;\n\t\tif (a === false) {\n\t\t\tif (b !== false && b !== true) return false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (b === false) return false;\n\t\tif (!_check(a, b, c, seen)) return false;\n\t}\n\tif (subRest === false) {} else if (supRest === false) return false;\n\telse if (!_check(subRest, supRest, c, seen)) return false;\n\treturn true;\n}\nfunction _restOf(s) {\n\tif (\"items\" in s) {\n\t\tif (s.items === void 0) return false;\n\t\treturn s.items;\n\t}\n\treturn true;\n}\nfunction _matches(v, sup, c, seen, issues, path = \"\") {\n\tconst mismatch = (message) => {\n\t\tissues?.push({\n\t\t\tpath,\n\t\t\tmessage\n\t\t});\n\t\treturn false;\n\t};\n\tif (sup === true) return true;\n\tif (sup === false) return mismatch(\"No value is allowed\");\n\tif (_isRef(sup)) {\n\t\tif (seen.has(sup.$ref)) return mismatch(`Unguarded recursive reference ${sup.$ref}`);\n\t\tconst r = _resolveRef(sup, c);\n\t\treturn r === void 0 ? mismatch(`Unresolved reference ${sup.$ref}`) : _matches(v, r, c, new Set(seen).add(sup.$ref), issues, path);\n\t}\n\tif (_isUnion(sup)) {\n\t\tconst failures = issues === void 0 ? void 0 : [];\n\t\tif (_branches(sup).some((branch) => _matches(v, branch, c, seen, failures, path))) return true;\n\t\tif (failures?.length) issues?.push(...failures);\n\t\telse mismatch(\"No union branch accepts this value\");\n\t\treturn false;\n\t}\n\tif (_isConst(sup)) return _jsonEq(v, sup.const) || mismatch(`Expected ${JSON.stringify(sup.const)}`);\n\tif (_isEnum(sup)) return sup.enum.some((e) => _jsonEq(v, e)) || mismatch(`Expected one of ${JSON.stringify(sup.enum)}`);\n\tswitch (sup.type) {\n\t\tcase \"null\": return v === null || mismatch(\"Expected null\");\n\t\tcase \"boolean\": return typeof v === \"boolean\" || mismatch(\"Expected boolean\");\n\t\tcase \"number\": return typeof v === \"number\" || mismatch(\"Expected number\");\n\t\tcase \"integer\": return typeof v === \"number\" && Number.isInteger(v) || mismatch(\"Expected integer\");\n\t\tcase \"string\": return typeof v === \"string\" || mismatch(\"Expected string\");\n\t\tcase \"array\": return Array.isArray(v) ? _matchesArray(v, sup, c, issues, path) : mismatch(\"Expected array\");\n\t\tcase \"object\": return v !== null && typeof v === \"object\" && !Array.isArray(v) ? _matchesObject(v, sup, c, issues, path) : mismatch(\"Expected object\");\n\t\tdefault: return Object.keys(sup).every((key) => key === \"title\" || key === \"description\" || key.startsWith(\"x-\")) || mismatch(\"Unsupported schema shape\");\n\t}\n}\nfunction _matchesArray(v, sup, c, issues, path = \"\") {\n\tconst prefix = sup.prefixItems ?? [];\n\tconst rest = _restOf(sup);\n\tif (v.length < prefix.length || rest === false && v.length > prefix.length) {\n\t\tissues?.push({\n\t\t\tpath,\n\t\t\tmessage: rest === false ? `Expected ${prefix.length} items` : `Expected at least ${prefix.length} items`\n\t\t});\n\t\treturn false;\n\t}\n\tlet valid = true;\n\tfor (let i = 0; i < v.length; i++) {\n\t\tconst s = prefix[i] ?? (rest === false ? false : rest);\n\t\tif (!_matches(v[i], s, c, /* @__PURE__ */ new Set(), issues, `${path}/${i}`)) valid = false;\n\t}\n\treturn valid;\n}\nfunction _matchesObject(v, sup, c, issues, path = \"\") {\n\tlet valid = true;\n\tfor (const k of sup.required ?? []) if (!Object.hasOwn(v, k)) {\n\t\tissues?.push({\n\t\t\tpath: path + jsonPointerSegment(k),\n\t\t\tmessage: \"Required property is missing\"\n\t\t});\n\t\tvalid = false;\n\t}\n\tfor (const [k, val] of Object.entries(v)) if (!_matches(val, Object.hasOwn(sup.properties, k) ? sup.properties[k] : sup.additionalProperties, c, /* @__PURE__ */ new Set(), issues, path + jsonPointerSegment(k))) valid = false;\n\treturn valid;\n}\nfunction _isBottom(s, c, seen) {\n\tif (s === false) return true;\n\tif (s === true) return false;\n\tif (_isRef(s)) {\n\t\tconst k = `B:${s.$ref}`;\n\t\tif (seen.has(k)) return false;\n\t\tconst r = _resolveRef(s, c);\n\t\treturn r ? _isBottom(r, c, new Set(seen).add(k)) : false;\n\t}\n\tif (_isUnion(s)) return _branches(s).every((b) => _isBottom(b, c, seen));\n\treturn false;\n}\nfunction _formatCompatible(subFmt, supFmt) {\n\tif (supFmt === void 0) return true;\n\treturn subFmt === supFmt;\n}\nfunction _isRef(s) {\n\treturn s !== true && s !== false && \"$ref\" in s;\n}\nfunction _isUnion(s) {\n\treturn s !== true && s !== false && (\"anyOf\" in s || \"oneOf\" in s);\n}\nfunction _branches(s) {\n\treturn \"anyOf\" in s ? s.anyOf : s.oneOf;\n}\nfunction _isConst(s) {\n\treturn s !== true && s !== false && \"const\" in s;\n}\nfunction _isEnum(s) {\n\treturn s !== true && s !== false && \"enum\" in s;\n}\nfunction _resolveRef(r, c) {\n\tif (!r.$ref.startsWith(\"#/components/schemas/\")) return void 0;\n\tconst name = componentSchemaName(r.$ref);\n\treturn c.schemas?.[name];\n}\nfunction _keyOf(s) {\n\tif (s === true || s === false) return String(s);\n\tif (\"$ref\" in s) return `R:${s.$ref}`;\n\treturn JSON.stringify(s);\n}\nfunction _jsonEq(a, b) {\n\tif (a === b) return true;\n\tif (a === null || b === null) return false;\n\tif (typeof a !== typeof b) return false;\n\tif (Array.isArray(a)) {\n\t\tif (!Array.isArray(b) || a.length !== b.length) return false;\n\t\treturn a.every((v, i) => _jsonEq(v, b[i]));\n\t}\n\tif (typeof a === \"object\") {\n\t\tconst ao = a;\n\t\tconst bo = b;\n\t\tconst ak = Object.keys(ao).sort();\n\t\tconst bk = Object.keys(bo).sort();\n\t\tif (ak.length !== bk.length) return false;\n\t\treturn ak.every((k, i) => k === bk[i] && _jsonEq(ao[k], bo[k]));\n\t}\n\treturn false;\n}\n//#endregion\n//#region src/schema/materializeJsonSchema.ts\n/**\n* Export a LinkRPC schema and its components as standalone JSON Schema\n* draft 2020-12. Node-local `x-json-schema` constraints are conjoined via\n* `allOf`, so a refinement cannot accidentally override the wire contract.\n*\n* References are rewritten rather than dereferenced. Consequently recursive\n* and mutually-recursive component graphs are materialized in finite time.\n*/\nfunction materializeJsonSchema(root, components = {}) {\n\tconst materialized = materializeNode(root);\n\treturn {\n\t\t$schema: \"https://json-schema.org/draft/2020-12/schema\",\n\t\t...typeof materialized === \"boolean\" ? { allOf: [materialized] } : materialized,\n\t\t...Object.keys(components).length === 0 ? {} : { $defs: Object.fromEntries(Object.entries(components).map(([name, schema]) => [name, materializeNode(schema)])) }\n\t};\n}\nfunction materializeNode(value) {\n\tif (typeof value === \"boolean\") return value;\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"materializeJsonSchema: expected a JSON Schema node\");\n\tconst input = value;\n\tconst refinement = input[\"x-json-schema\"];\n\tconst base = {};\n\tfor (const [key, child] of Object.entries(input)) {\n\t\tif (key === \"x-json-schema\") continue;\n\t\tif (key === \"$ref\" && typeof child === \"string\") base.$ref = rewriteRef(child);\n\t\telse if (key === \"properties\" && isRecord(child)) base.properties = Object.fromEntries(Object.entries(child).map(([name, schema]) => [name, materializeNode(schema)]));\n\t\telse if (key === \"items\" || key === \"additionalProperties\") base[key] = typeof child === \"boolean\" ? child : materializeNode(child);\n\t\telse if (key === \"prefixItems\" || key === \"anyOf\" || key === \"oneOf\") {\n\t\t\tconst outputKey = key === \"oneOf\" ? \"anyOf\" : key;\n\t\t\tbase[outputKey] = Array.isArray(child) ? child.map(materializeNode) : child;\n\t\t} else base[key] = child;\n\t}\n\tif (input.type === \"array\" && Array.isArray(input.prefixItems)) {\n\t\tbase.minItems = input.prefixItems.length;\n\t\tif (input.items === void 0 || input.items === false) base.maxItems = input.prefixItems.length;\n\t}\n\tif (refinement === void 0) return base;\n\tif (typeof refinement !== \"boolean\" && !isRecord(refinement)) throw new Error(\"materializeJsonSchema: x-json-schema must be a boolean or object\");\n\treturn { allOf: [base, materializeGeneralSchema(refinement)] };\n}\nfunction materializeGeneralSchema(value) {\n\tif (value === null || typeof value !== \"object\") return value;\n\tif (Array.isArray(value)) return value;\n\tconst result = {};\n\tfor (const [key, child] of Object.entries(value)) if (key === \"$ref\" && typeof child === \"string\") result[key] = rewriteRef(child);\n\telse if (key === \"x-json-schema\") result[key] = materializeGeneralSchema(child);\n\telse if (schemaMapKeywords.has(key) && isRecord(child)) result[key] = Object.fromEntries(Object.entries(child).map(([name, schema]) => [name, materializeGeneralSchema(schema)]));\n\telse if (schemaArrayKeywords.has(key) && Array.isArray(child)) result[key] = child.map(materializeGeneralSchema);\n\telse if (schemaKeywords.has(key)) result[key] = materializeGeneralSchema(child);\n\telse result[key] = child;\n\treturn result;\n}\nconst schemaMapKeywords = /* @__PURE__ */ new Set([\n\t\"$defs\",\n\t\"definitions\",\n\t\"properties\",\n\t\"patternProperties\",\n\t\"dependentSchemas\"\n]);\nconst schemaArrayKeywords = /* @__PURE__ */ new Set([\n\t\"allOf\",\n\t\"anyOf\",\n\t\"oneOf\",\n\t\"prefixItems\"\n]);\nconst schemaKeywords = /* @__PURE__ */ new Set([\n\t\"additionalProperties\",\n\t\"contains\",\n\t\"contentSchema\",\n\t\"else\",\n\t\"if\",\n\t\"items\",\n\t\"not\",\n\t\"propertyNames\",\n\t\"then\",\n\t\"unevaluatedItems\",\n\t\"unevaluatedProperties\"\n]);\nfunction rewriteRef(ref) {\n\treturn ref.startsWith(\"#/components/schemas/\") ? `#/$defs/${ref.slice(21)}` : ref;\n}\nfunction isRecord(value) {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n//#endregion\n//#region src/connection/bareInterfaceTarget.ts\n/**\n* Bundle an interface definition with metadata-free foreign-protocol\n* addressing for use with `connection.get(target)` or\n* `connection.register(target, handlers)`.\n*/\nfunction bareInterfaceTarget(iface, options = {}) {\n\tconst prefix = options.prefix ?? \"\";\n\tvalidateBarePrefix(prefix);\n\treturn Object.freeze({\n\t\tmode: \"bare\",\n\t\tinterface: iface,\n\t\tprefix\n\t});\n}\nfunction validateBarePrefix(prefix) {\n\tif (prefix.includes(\"::\") || !/^[\\x20-\\x7e]*$/.test(prefix)) throw new Error(\"Bare interface prefix must contain only printable ASCII and must not contain \\\"::\\\".\");\n}\n//#endregion\n//#region src/schema/codegen/utils/codeWriter.ts\n/**\n* Minimal indentation-aware text builder for code generation.\n*\n* Usage pattern:\n* - {@link append} extends the *current* (unfinished) line. Indentation\n* is inserted lazily the first time content lands on a fresh line, so\n* blank lines stay blank.\n* - {@link newline} ends the current line.\n* - {@link writeLine} is `append` + `newline`.\n* - {@link indent} / {@link dedent} change the indent level used for\n* *future* fresh lines; they do not retroactively reformat the\n* in-progress line.\n*\n* Indentation is fixed at four spaces, matching the surrounding codebase.\n*/\nvar CodeWriter = class {\n\t_lines = [];\n\t_current = \"\";\n\t_indent = 0;\n\t_onFreshLine = true;\n\tindent() {\n\t\tthis._indent++;\n\t\treturn this;\n\t}\n\tdedent() {\n\t\tif (this._indent === 0) throw new Error(\"CodeWriter: dedent below 0\");\n\t\tthis._indent--;\n\t\treturn this;\n\t}\n\tappend(text) {\n\t\tif (text.length === 0) return this;\n\t\tif (this._onFreshLine) {\n\t\t\tthis._current = \" \".repeat(this._indent);\n\t\t\tthis._onFreshLine = false;\n\t\t}\n\t\tthis._current += text;\n\t\treturn this;\n\t}\n\tnewline() {\n\t\tthis._lines.push(this._current);\n\t\tthis._current = \"\";\n\t\tthis._onFreshLine = true;\n\t\treturn this;\n\t}\n\twriteLine(text = \"\") {\n\t\treturn this.append(text).newline();\n\t}\n\ttoString() {\n\t\tconst lines = [...this._lines];\n\t\tif (!this._onFreshLine) lines.push(this._current);\n\t\treturn lines.join(\"\\n\") + \"\\n\";\n\t}\n};\n//#endregion\n//#region src/schema/codegen/generateTsInterface.ts\n/**\n* Render a {@link LinkRpcInterfaceSchema} as a stand-alone TypeScript source\n* file that, when evaluated, reproduces the same canonical schema (and\n* therefore the same `schemaHash`).\n*\n* Components in `components.schemas` are emitted as named `const`\n* declarations referenced from the bodies via `$ref`. Only recursive\n* components receive explicit payload types; other types remain Zod-inferred.\n*/\nfunction generateTsInterface(schema, options = {}) {\n\tvalidateInterfaceErrors(schema);\n\tvalidateInterfaceTemplates(schema);\n\tconst linkRpcImport = options.linkRpcImport ?? \"@hediet/linkrpc\";\n\tconst exportName = options.exportName ?? _deriveExportName(schema.id);\n\tconst preserveWireSchema = options.preserveWireSchema ?? (schema[\"x-interface-templates\"] !== void 0 || Object.values(schema.methods).some((method) => Object.hasOwn(method, \"tags\")));\n\tif (options.bareTarget !== void 0) validateBarePrefix(options.bareTarget.prefix);\n\tconst w = new CodeWriter();\n\tconst bareTargetImport = options.bareTarget === void 0 ? \"\" : \"bareInterfaceTarget, \";\n\tconst errorImport = Object.values(schema.methods).some((method) => (method.errors?.length ?? 0) > 0) ? \"applicationError, \" : \"\";\n\tconst rawErrorImport = Object.values(schema.methods).some((method) => method.errors?.some((error) => error.schema !== void 0)) ? \"rpcError, \" : \"\";\n\tconst definitionImport = preserveWireSchema ? `${errorImport}${bareTargetImport}InterfaceDefinition, notificationType, requestType, type LinkRpcInterfaceSchema` : `${errorImport}${bareTargetImport}defineInterface, notificationType, requestType`;\n\tif (!options.omitImports) {\n\t\tw.writeLine(`import { ${rawErrorImport}${definitionImport} } from \"${linkRpcImport}\";`);\n\t\tw.writeLine(`import { z } from \"zod\";`);\n\t\tw.writeLine();\n\t}\n\tconst componentSchemas = schema.components?.schemas ?? {};\n\tconst cyclicComponents = _findCyclicComponents(componentSchemas);\n\tconst componentNames = _allocateComponentNames(componentSchemas);\n\tconst payloadNames = _allocatePayloadNames(componentSchemas, cyclicComponents);\n\tfor (const [name, sub] of _sortComponents(componentSchemas)) {\n\t\tif (!cyclicComponents.has(name)) continue;\n\t\tw.writeLine(`type ${payloadNames.get(name)} = ${_schemaType(sub, componentNames, payloadNames)};`);\n\t}\n\tif (cyclicComponents.size > 0) w.writeLine();\n\tfor (const [name, sub] of _sortComponents(componentSchemas)) {\n\t\tconst varName = componentNames.get(name);\n\t\t_writeJsDoc(w, _schemaDescription(sub));\n\t\tif (cyclicComponents.has(name)) w.append(`const ${varName}: z.ZodType<${payloadNames.get(name)}> = z.lazy(() => `);\n\t\telse w.append(`const ${varName} = `);\n\t\t_writeSchema(w, sub, componentNames, preserveWireSchema, name);\n\t\tif (cyclicComponents.has(name)) w.append(\")\");\n\t\tw.append(\";\");\n\t\tw.newline();\n\t\tw.writeLine();\n\t}\n\tif (preserveWireSchema) {\n\t\tw.writeLine(`const wireSchema: LinkRpcInterfaceSchema = JSON.parse(${JSON.stringify(JSON.stringify(schema))});`);\n\t\tw.writeLine();\n\t}\n\t_writeJsDoc(w, schema.description);\n\tw.append(`export const ${exportName} = ${preserveWireSchema ? \"new InterfaceDefinition\" : \"defineInterface\"}(`);\n\tw.newline();\n\tw.indent();\n\t_writeInterfaceInfo(w, schema, preserveWireSchema);\n\tw.append(\",\");\n\tw.newline();\n\t_writeMembers(w, schema.methods, componentNames, componentSchemas, preserveWireSchema);\n\tw.append(\",\");\n\tw.newline();\n\tif (preserveWireSchema) w.writeLine(\"{ frozenSchema: wireSchema },\");\n\tw.dedent();\n\tw.writeLine(\");\");\n\tif (options.bareTarget !== void 0) {\n\t\tw.writeLine();\n\t\tw.writeLine(`export const ${options.bareTarget.exportName} = bareInterfaceTarget(${exportName}, { prefix: ${JSON.stringify(options.bareTarget.prefix)} });`);\n\t}\n\treturn w.toString();\n}\nfunction _schemaType(schema, components, payloads) {\n\tif (schema === true) return \"unknown\";\n\tif (schema === false) return \"never\";\n\tconst s = schema;\n\tif (typeof s[\"$ref\"] === \"string\") {\n\t\tconst name = _parseRef(s[\"$ref\"]);\n\t\tconst payload = payloads.get(name);\n\t\tif (payload !== void 0) return payload;\n\t\tconst component = components.get(name);\n\t\tif (component === void 0) throw new Error(`generateInterface: dangling $ref \"${s[\"$ref\"]}\"`);\n\t\treturn `z.infer<typeof ${component}>`;\n\t}\n\tif (\"const\" in s) return _jsonLiteral(s[\"const\"]);\n\tif (Array.isArray(s[\"enum\"])) return s[\"enum\"].map(_jsonLiteral).join(\" | \") || \"never\";\n\tconst union = s[\"oneOf\"] ?? s[\"anyOf\"];\n\tif (Array.isArray(union)) return union.map((item) => _schemaType(item, components, payloads)).join(\" | \") || \"never\";\n\tif (s[\"type\"] === \"object\") {\n\t\tconst properties = s[\"properties\"] ?? {};\n\t\tconst required = new Set(s[\"required\"] ?? []);\n\t\tconst objectType = `{ ${Object.entries(properties).map(([name, property]) => `${_propKey(name)}${required.has(name) ? \"\" : \"?\"}: ${_schemaType(property, components, payloads)}${required.has(name) ? \"\" : \" | undefined\"};`).join(\" \")} }`;\n\t\tconst additional = s[\"additionalProperties\"];\n\t\tif (additional === true) return `${objectType} & { [key: string]: unknown }`;\n\t\tif (additional !== void 0 && additional !== false) return `${objectType} & { [key: string]: ${_schemaType(additional, components, payloads)} }`;\n\t\treturn objectType;\n\t}\n\tif (s[\"type\"] === \"array\" && Array.isArray(s[\"prefixItems\"])) {\n\t\tconst prefix = s[\"prefixItems\"].map((item) => _schemaType(item, components, payloads));\n\t\tconst rest = s[\"items\"];\n\t\tif (rest !== void 0 && rest !== false) prefix.push(`...Array<${_schemaType(rest, components, payloads)}>`);\n\t\treturn `[${prefix.join(\", \")}]`;\n\t}\n\tif (s[\"type\"] === \"array\") return `Array<${_schemaType(s[\"items\"] ?? true, components, payloads)}>`;\n\tif (_isAnnotationOnlySchema(s)) return \"unknown\";\n\tswitch (s[\"type\"]) {\n\t\tcase \"null\": return \"null\";\n\t\tcase \"boolean\": return \"boolean\";\n\t\tcase \"string\": return \"string\";\n\t\tcase \"integer\": return \"number\";\n\t\tcase \"number\": return \"number\";\n\t\tdefault: throw new Error(`generateInterface: unsupported schema: ${JSON.stringify(schema)}`);\n\t}\n}\nfunction _writeInterfaceInfo(w, schema, includeHash) {\n\tw.append(\"{\").newline();\n\tw.indent();\n\tw.append(`id: ${JSON.stringify(schema.id)},`).newline();\n\tif (schema.description !== void 0) w.append(`description: ${JSON.stringify(schema.description)},`).newline();\n\tif (schema.comment !== void 0) w.append(`comment: ${JSON.stringify(schema.comment)},`).newline();\n\tif (schema.tags !== void 0) w.append(`tags: ${JSON.stringify(schema.tags)},`).newline();\n\tif (includeHash) w.append(`hash: ${JSON.stringify(schema.hash)},`).newline();\n\tw.dedent();\n\tw.append(\"}\");\n}\nfunction _writeMembers(w, methods, components, componentSchemas, preserveWireSchema) {\n\tw.append(\"{\").newline();\n\tw.indent();\n\tfor (const [name, method] of Object.entries(methods)) {\n\t\t_writeJsDoc(w, _methodDescription(method, componentSchemas));\n\t\tw.append(`${_propKey(name)}: `);\n\t\t_writeMethod(w, method, components, preserveWireSchema);\n\t\tw.append(\",\");\n\t\tw.newline();\n\t}\n\tw.dedent();\n\tw.append(\"}\");\n}\nfunction _writeMethod(w, method, components, preserveWireSchema) {\n\tconst docs = _collectMemberDocs(method);\n\tif (method.result === void 0) {\n\t\tw.append(\"notificationType(\").newline();\n\t\tw.indent();\n\t\t_writeSchema(w, method.params, components, preserveWireSchema);\n\t\tw.append(\",\").newline();\n\t\tif (docs !== void 0) {\n\t\t\t_writeDocs(w, docs);\n\t\t\tw.append(\",\").newline();\n\t\t}\n\t\tw.dedent();\n\t\tw.append(\")\");\n\t\treturn;\n\t}\n\tw.append(\"requestType(\").newline();\n\tw.indent();\n\t_writeSchema(w, method.params, components, preserveWireSchema);\n\tw.append(\",\").newline();\n\t_writeSchema(w, method.result, components, preserveWireSchema);\n\tw.append(\",\").newline();\n\tif (docs !== void 0) {\n\t\t_writeDocs(w, docs);\n\t\tw.append(\",\").newline();\n\t}\n\tw.dedent();\n\tw.append(\")\");\n\tif ((method.errors?.length ?? 0) > 0) {\n\t\tw.append(\".withErrors([\").newline();\n\t\tw.indent();\n\t\tfor (const error of method.errors) {\n\t\t\tif (error.schema !== void 0) {\n\t\t\t\tw.append(`rpcError(${error.code}, `);\n\t\t\t\t_writeSchema(w, error.schema, components, preserveWireSchema);\n\t\t\t\tw.append(\"),\").newline();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tw.append(error.type === void 0 ? `applicationError(${error.code}, ${JSON.stringify(error.message)}` : `applicationError(${JSON.stringify(error.type)}, { code: ${error.code}, message: ${JSON.stringify(error.message)}`);\n\t\t\tif (error.data !== void 0) {\n\t\t\t\tw.append(error.type === void 0 ? \", \" : \", data: \");\n\t\t\t\t_writeSchema(w, error.data, components, preserveWireSchema);\n\t\t\t}\n\t\t\tif (error.type !== void 0) w.append(\" }\");\n\t\t\tw.append(\"),\").newline();\n\t\t}\n\t\tw.dedent();\n\t\tw.append(\"] as const)\");\n\t}\n\tif (method.clientStream !== void 0 || method.serverStream !== void 0) {\n\t\tw.append(\".withStream({\").newline();\n\t\tw.indent();\n\t\tif (method.clientStream !== void 0) {\n\t\t\tw.append(\"client: \");\n\t\t\t_writeSchema(w, method.clientStream, components, preserveWireSchema);\n\t\t\tw.append(\",\").newline();\n\t\t}\n\t\tif (method.serverStream !== void 0) {\n\t\t\tw.append(\"server: \");\n\t\t\t_writeSchema(w, method.serverStream, components, preserveWireSchema);\n\t\t\tw.append(\",\").newline();\n\t\t}\n\t\tw.dedent();\n\t\tw.append(\"})\");\n\t}\n}\nfunction _collectMemberDocs(method) {\n\tconst docs = {};\n\tif (method.description !== void 0) docs.description = method.description;\n\tif (method.comment !== void 0) docs.comment = method.comment;\n\tif (method.annotations !== void 0 && Object.keys(method.annotations).length > 0) docs.annotations = method.annotations;\n\treturn docs.description === void 0 && docs.comment === void 0 && docs.annotations === void 0 ? void 0 : docs;\n}\nfunction _writeDocs(w, docs) {\n\tw.append(\"{\").newline();\n\tw.indent();\n\tif (docs.description !== void 0) w.append(`description: ${JSON.stringify(docs.description)},`).newline();\n\tif (docs.comment !== void 0) w.append(`comment: ${JSON.stringify(docs.comment)},`).newline();\n\tif (docs.annotations !== void 0) w.append(`annotations: ${JSON.stringify(docs.annotations)},`).newline();\n\tw.dedent();\n\tw.append(\"}\");\n}\n/**\n* Emit a zod expression equivalent to `schema`. The expression begins at\n* the writer's current line position and may span multiple lines; it\n* ends without a trailing newline so the caller can append punctuation.\n*/\nfunction _writeSchema(w, schema, components, preserveWireSchema = false, currentComponent) {\n\tif (schema === true) {\n\t\t_writeMetaWrapped(w, \"z.unknown()\", void 0);\n\t\treturn;\n\t}\n\tif (schema === false) {\n\t\t_writeMetaWrapped(w, \"z.never()\", void 0);\n\t\treturn;\n\t}\n\tconst s = schema;\n\tif (typeof s[\"$ref\"] === \"string\") {\n\t\tconst refName = _parseRef(s[\"$ref\"]);\n\t\tconst varName = components.get(refName);\n\t\tif (varName === void 0) throw new Error(`generateInterface: dangling $ref \"${s[\"$ref\"]}\"`);\n\t\t_writeMetaWrapped(w, varName, _metaOf(s));\n\t\treturn;\n\t}\n\tif (\"const\" in s) {\n\t\t_writeMetaWrapped(w, `z.literal(${_jsonLiteral(s[\"const\"])})`, _metaOf(s));\n\t\treturn;\n\t}\n\tif (Array.isArray(s[\"enum\"])) {\n\t\tconst values = s[\"enum\"];\n\t\tif (values.every((v) => typeof v === \"string\")) {\n\t\t\t_writeMetaWrapped(w, `z.enum([${values.map((v) => JSON.stringify(v)).join(\", \")}])`, _metaOf(s));\n\t\t\treturn;\n\t\t}\n\t\t_writeMetaWrapped(w, `z.union([${values.map((v) => `z.literal(${_jsonLiteral(v)})`).join(\", \")}])`, _metaOf(s));\n\t\treturn;\n\t}\n\tif (Array.isArray(s[\"oneOf\"])) {\n\t\tconst branches = s[\"oneOf\"];\n\t\tconst disc = s[\"discriminator\"];\n\t\tif (disc?.propertyName !== void 0) _writeUnion(w, \"z.discriminatedUnion\", branches, components, preserveWireSchema, currentComponent, disc.propertyName);\n\t\telse _writeUnion(w, \"z.union\", branches, components, preserveWireSchema, currentComponent);\n\t\t_writeMetaSuffix(w, _metaOf(s));\n\t\treturn;\n\t}\n\tif (Array.isArray(s[\"anyOf\"])) {\n\t\t_writeUnion(w, \"z.union\", s[\"anyOf\"], components, preserveWireSchema, currentComponent);\n\t\t_writeMetaSuffix(w, _metaOf(s));\n\t\treturn;\n\t}\n\tif (s[\"type\"] === \"object\") {\n\t\t_writeObject(w, s, components, preserveWireSchema, currentComponent);\n\t\t_writeMetaSuffix(w, _metaOf(s));\n\t\treturn;\n\t}\n\tif (s[\"type\"] === \"array\" && Array.isArray(s[\"prefixItems\"])) {\n\t\t_writeTuple(w, s, components, preserveWireSchema, currentComponent);\n\t\t_writeMetaSuffix(w, _metaOf(s));\n\t\treturn;\n\t}\n\tif (s[\"type\"] === \"array\") {\n\t\tconst items = s[\"items\"] ?? true;\n\t\tw.append(\"z.array(\");\n\t\t_writeSchema(w, items, components, preserveWireSchema, currentComponent);\n\t\tw.append(\")\");\n\t\t_writeMetaSuffix(w, _metaOf(s));\n\t\treturn;\n\t}\n\tconst primitive = _primitiveExpr(s);\n\tif (primitive !== void 0) {\n\t\t_writeMetaWrapped(w, primitive, _metaOf(s));\n\t\treturn;\n\t}\n\tif (_isAnnotationOnlySchema(s)) {\n\t\t_writeMetaWrapped(w, \"z.unknown()\", _metaOf(s));\n\t\treturn;\n\t}\n\tthrow new Error(`generateInterface: unsupported schema: ${JSON.stringify(schema)}`);\n}\nfunction _isAnnotationOnlySchema(schema) {\n\treturn ![\n\t\t\"$ref\",\n\t\t\"const\",\n\t\t\"enum\",\n\t\t\"anyOf\",\n\t\t\"oneOf\",\n\t\t\"type\",\n\t\t\"properties\",\n\t\t\"items\",\n\t\t\"prefixItems\",\n\t\t\"additionalProperties\"\n\t].some((key) => Object.hasOwn(schema, key));\n}\nfunction _writeObject(w, s, components, preserveWireSchema, currentComponent) {\n\tconst properties = s[\"properties\"] ?? {};\n\tconst required = new Set(s[\"required\"] ?? []);\n\tconst additional = s[\"additionalProperties\"];\n\tconst constructor = additional === false || additional === void 0 ? \"z.object\" : \"z.looseObject\";\n\tconst keys = Object.keys(properties);\n\tif (keys.length === 0) w.append(`${constructor}({})`);\n\telse {\n\t\tw.append(`${constructor}({`).newline();\n\t\tw.indent();\n\t\tfor (const key of keys) {\n\t\t\tconst property = properties[key];\n\t\t\t_writeJsDoc(w, _schemaDescription(property));\n\t\t\tif (currentComponent !== void 0 && _containsRef(property, currentComponent)) {\n\t\t\t\tw.append(`get ${_propKey(key)}() {`).newline();\n\t\t\t\tw.indent();\n\t\t\t\tw.append(\"return \");\n\t\t\t\t_writeSchema(w, property, components, preserveWireSchema, currentComponent);\n\t\t\t\tif (!required.has(key)) w.append(\".optional()\");\n\t\t\t\tw.append(\";\").newline();\n\t\t\t\tw.dedent();\n\t\t\t\tw.append(\"},\").newline();\n\t\t\t} else {\n\t\t\t\tw.append(`${_propKey(key)}: `);\n\t\t\t\t_writeSchema(w, property, components, preserveWireSchema, currentComponent);\n\t\t\t\tif (!required.has(key)) w.append(\".optional()\");\n\t\t\t\tw.append(\",\").newline();\n\t\t\t}\n\t\t}\n\t\tw.dedent();\n\t\tw.append(\"})\");\n\t}\n\tif (additional !== false && additional !== void 0 && additional !== true) {\n\t\tw.append(\".catchall(\");\n\t\t_writeSchema(w, additional, components, preserveWireSchema, currentComponent);\n\t\tw.append(\")\");\n\t}\n}\nfunction _writeTuple(w, s, components, preserveWireSchema, currentComponent) {\n\tconst prefix = s[\"prefixItems\"];\n\tw.append(\"z.tuple([\").newline();\n\tw.indent();\n\tfor (const item of prefix) {\n\t\t_writeSchema(w, item, components, preserveWireSchema, currentComponent);\n\t\tw.append(\",\").newline();\n\t}\n\tw.dedent();\n\tw.append(\"])\");\n\tconst rest = s[\"items\"];\n\tif (rest !== void 0 && rest !== false) {\n\t\tw.append(\".rest(\");\n\t\t_writeSchema(w, rest, components, preserveWireSchema, currentComponent);\n\t\tw.append(\")\");\n\t}\n}\nfunction _writeUnion(w, constructor, branches, components, preserveWireSchema, currentComponent, discriminator) {\n\tif (constructor === \"z.discriminatedUnion\" && discriminator !== void 0) w.append(`${constructor}(${JSON.stringify(discriminator)}, [`).newline();\n\telse w.append(`${constructor}([`).newline();\n\tw.indent();\n\tfor (const branch of branches) {\n\t\t_writeSchema(w, branch, components, preserveWireSchema, currentComponent);\n\t\tw.append(\",\").newline();\n\t}\n\tw.dedent();\n\tw.append(\"])\");\n}\nfunction _primitiveExpr(s) {\n\tconst type = s[\"type\"];\n\tconst format = s[\"format\"];\n\tswitch (type) {\n\t\tcase \"null\": return \"z.null()\";\n\t\tcase \"boolean\": return \"z.boolean()\";\n\t\tcase \"string\": return _stringExpr(format);\n\t\tcase \"integer\": return _integerExpr(format);\n\t\tcase \"number\": return _numberExpr(format);\n\t\tdefault: return;\n\t}\n}\nfunction _stringExpr(format) {\n\tif (format === void 0) return \"z.string()\";\n\tswitch (format) {\n\t\tcase \"email\": return \"z.email()\";\n\t\tcase \"uri\":\n\t\tcase \"url\": return \"z.url()\";\n\t\tcase \"uuid\": return \"z.uuid()\";\n\t\tcase \"date-time\": return \"z.iso.datetime()\";\n\t\tcase \"date\": return \"z.iso.date()\";\n\t\tcase \"time\": return \"z.iso.time()\";\n\t\tcase \"duration\": return \"z.iso.duration()\";\n\t\tcase \"ipv4\": return \"z.ipv4()\";\n\t\tcase \"ipv6\": return \"z.ipv6()\";\n\t\tcase \"base64\": return \"z.base64()\";\n\t\tcase \"base64url\": return \"z.base64url()\";\n\t\tcase \"nanoid\": return \"z.nanoid()\";\n\t\tcase \"cuid\": return \"z.cuid()\";\n\t\tcase \"cuid2\": return \"z.cuid2()\";\n\t\tcase \"ulid\": return \"z.ulid()\";\n\t\tdefault: return \"z.string()\";\n\t}\n}\nfunction _integerExpr(format) {\n\tswitch (format) {\n\t\tcase \"int32\": return \"z.int32()\";\n\t\tcase \"uint32\": return \"z.uint32()\";\n\t\tcase \"int64\": return \"z.int()\";\n\t\tcase \"uint64\": return \"z.int().nonnegative()\";\n\t\tcase void 0: return \"z.int()\";\n\t\tdefault: return \"z.int()\";\n\t}\n}\nfunction _numberExpr(format) {\n\tswitch (format) {\n\t\tcase \"float32\": return \"z.float32()\";\n\t\tcase \"float64\": return \"z.float64()\";\n\t\tcase void 0: return \"z.number()\";\n\t\tdefault: return \"z.number()\";\n\t}\n}\nfunction _metaOf(s) {\n\tconst meta = {};\n\tif (typeof s[\"description\"] === \"string\") meta.description = s[\"description\"];\n\tif (typeof s[\"title\"] === \"string\") meta.title = s[\"title\"];\n\treturn meta.description === void 0 && meta.title === void 0 ? void 0 : meta;\n}\n/** Wrap a single-line zod expression with `.describe()` / `.meta()`. */\nfunction _writeMetaWrapped(w, expr, meta) {\n\tw.append(expr);\n\t_writeMetaSuffix(w, meta);\n}\nfunction _writeMetaSuffix(w, meta) {\n\tif (meta === void 0) return;\n\tif (meta.title === void 0 && meta.description !== void 0) {\n\t\tw.append(`.describe(${JSON.stringify(meta.description)})`);\n\t\treturn;\n\t}\n\tconst entries = [];\n\tif (meta.title !== void 0) entries.push(`title: ${JSON.stringify(meta.title)}`);\n\tif (meta.description !== void 0) entries.push(`description: ${JSON.stringify(meta.description)}`);\n\tw.append(`.meta({ ${entries.join(\", \")} })`);\n}\nfunction _methodDescription(method, components) {\n\tif (method.description !== void 0) return method.description;\n\tif (method.params === true || method.params === false) return void 0;\n\tconst params = method.params;\n\tif (typeof params[\"$ref\"] !== \"string\") return _schemaDescription(method.params);\n\treturn _schemaDescription(components[_parseRef(params[\"$ref\"])]);\n}\nfunction _schemaDescription(schema) {\n\tif (schema === void 0 || schema === true || schema === false) return void 0;\n\tconst value = schema;\n\tif (typeof value[\"description\"] === \"string\") return value[\"description\"];\n\treturn typeof value[\"title\"] === \"string\" ? value[\"title\"] : void 0;\n}\nfunction _writeJsDoc(w, description) {\n\tif (description === void 0 || description.length === 0) return;\n\tw.writeLine(\"/**\");\n\tfor (const line of description.replaceAll(\"*/\", \"*\\\\/\").split(/\\r?\\n/)) w.writeLine(line.length === 0 ? \" *\" : ` * ${line}`);\n\tw.writeLine(\" */\");\n}\nfunction _sortComponents(schemas) {\n\tconst result = [];\n\tconst visiting = /* @__PURE__ */ new Set();\n\tconst visited = /* @__PURE__ */ new Set();\n\tconst visit = (name) => {\n\t\tif (visited.has(name)) return;\n\t\tif (visiting.has(name)) return;\n\t\tconst schema = schemas[name];\n\t\tif (schema === void 0) return;\n\t\tvisiting.add(name);\n\t\tfor (const dependency of _collectRefs(schema)) if (dependency !== name && schemas[dependency] !== void 0) visit(dependency);\n\t\tvisiting.delete(name);\n\t\tvisited.add(name);\n\t\tresult.push([name, schema]);\n\t};\n\tfor (const name of Object.keys(schemas)) visit(name);\n\treturn result;\n}\n/** Find every node belonging to a strongly-connected component with a cycle. */\nfunction _findCyclicComponents(schemas) {\n\tlet nextIndex = 0;\n\tconst index = /* @__PURE__ */ new Map();\n\tconst lowLink = /* @__PURE__ */ new Map();\n\tconst stack = [];\n\tconst onStack = /* @__PURE__ */ new Set();\n\tconst cyclic = /* @__PURE__ */ new Set();\n\tconst visit = (name) => {\n\t\tindex.set(name, nextIndex);\n\t\tlowLink.set(name, nextIndex++);\n\t\tstack.push(name);\n\t\tonStack.add(name);\n\t\tconst dependencies = [..._collectRefs(schemas[name])].filter((ref) => schemas[ref] !== void 0);\n\t\tfor (const dependency of dependencies) if (!index.has(dependency)) {\n\t\t\tvisit(dependency);\n\t\t\tlowLink.set(name, Math.min(lowLink.get(name), lowLink.get(dependency)));\n\t\t} else if (onStack.has(dependency)) lowLink.set(name, Math.min(lowLink.get(name), index.get(dependency)));\n\t\tif (lowLink.get(name) !== index.get(name)) return;\n\t\tconst component = [];\n\t\tlet current;\n\t\tdo {\n\t\t\tcurrent = stack.pop();\n\t\t\tonStack.delete(current);\n\t\t\tcomponent.push(current);\n\t\t} while (current !== name);\n\t\tif (component.length > 1 || _collectRefs(schemas[name]).has(name)) for (const item of component) cyclic.add(item);\n\t};\n\tfor (const name of Object.keys(schemas)) if (!index.has(name)) visit(name);\n\treturn cyclic;\n}\nfunction _collectRefs(value, refs = /* @__PURE__ */ new Set()) {\n\tif (value === null || typeof value !== \"object\") return refs;\n\tif (Array.isArray(value)) {\n\t\tfor (const item of value) _collectRefs(item, refs);\n\t\treturn refs;\n\t}\n\tconst record = value;\n\tif (typeof record[\"$ref\"] === \"string\") refs.add(_parseRef(record[\"$ref\"]));\n\tfor (const [key, child] of Object.entries(record)) if (!key.startsWith(\"x-\")) _collectRefs(child, refs);\n\treturn refs;\n}\nfunction _containsRef(schema, name) {\n\treturn _collectRefs(schema).has(name);\n}\nfunction _propKey(name) {\n\treturn /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name);\n}\nfunction _jsonLiteral(value) {\n\treturn JSON.stringify(value);\n}\nfunction _parseRef(ref) {\n\treturn componentSchemaName(ref);\n}\nfunction _toComponentVar(name) {\n\treturn _toIdentifier(name) + \"Schema\";\n}\nfunction _toIdentifier(name) {\n\tconst sanitized = name.replace(/[^A-Za-z0-9_$]/g, \"_\");\n\treturn /^[A-Za-z_$]/.test(sanitized) ? sanitized : `_${sanitized}`;\n}\nfunction _allocateComponentNames(schemas) {\n\treturn _allocateNames(Object.keys(schemas), _toComponentVar, /* @__PURE__ */ new Set([\n\t\t\"z\",\n\t\t\"defineInterface\",\n\t\t\"InterfaceDefinition\",\n\t\t\"notificationType\",\n\t\t\"requestType\",\n\t\t\"wireSchema\"\n\t]));\n}\nfunction _allocatePayloadNames(schemas, cyclic) {\n\treturn _allocateNames(Object.keys(schemas).filter((name) => cyclic.has(name)), _toIdentifier, /* @__PURE__ */ new Set([\n\t\t..._typescriptReservedWords,\n\t\t\"z\",\n\t\t\"Array\",\n\t\t\"LinkRpcInterfaceSchema\",\n\t\t\"InterfaceDefinition\"\n\t]));\n}\nconst _typescriptReservedWords = [\n\t\"any\",\n\t\"as\",\n\t\"asserts\",\n\t\"async\",\n\t\"await\",\n\t\"bigint\",\n\t\"boolean\",\n\t\"break\",\n\t\"case\",\n\t\"catch\",\n\t\"class\",\n\t\"const\",\n\t\"constructor\",\n\t\"continue\",\n\t\"debugger\",\n\t\"declare\",\n\t\"default\",\n\t\"delete\",\n\t\"do\",\n\t\"else\",\n\t\"enum\",\n\t\"export\",\n\t\"extends\",\n\t\"false\",\n\t\"finally\",\n\t\"for\",\n\t\"from\",\n\t\"function\",\n\t\"get\",\n\t\"global\",\n\t\"if\",\n\t\"implements\",\n\t\"import\",\n\t\"in\",\n\t\"infer\",\n\t\"instanceof\",\n\t\"interface\",\n\t\"intrinsic\",\n\t\"is\",\n\t\"keyof\",\n\t\"let\",\n\t\"module\",\n\t\"namespace\",\n\t\"never\",\n\t\"new\",\n\t\"null\",\n\t\"number\",\n\t\"object\",\n\t\"of\",\n\t\"package\",\n\t\"private\",\n\t\"protected\",\n\t\"public\",\n\t\"readonly\",\n\t\"require\",\n\t\"return\",\n\t\"satisfies\",\n\t\"set\",\n\t\"static\",\n\t\"string\",\n\t\"super\",\n\t\"switch\",\n\t\"symbol\",\n\t\"this\",\n\t\"throw\",\n\t\"true\",\n\t\"try\",\n\t\"type\",\n\t\"typeof\",\n\t\"undefined\",\n\t\"unique\",\n\t\"unknown\",\n\t\"using\",\n\t\"var\",\n\t\"void\",\n\t\"while\",\n\t\"with\",\n\t\"yield\"\n];\nfunction _allocateNames(names, candidate, used) {\n\tconst result = /* @__PURE__ */ new Map();\n\tfor (const name of names) {\n\t\tconst base = candidate(name);\n\t\tlet allocated = base;\n\t\tlet suffix = 2;\n\t\twhile (used.has(allocated)) allocated = `${base}_${suffix++}`;\n\t\tused.add(allocated);\n\t\tresult.set(name, allocated);\n\t}\n\treturn result;\n}\nfunction _deriveExportName(id) {\n\tconst parts = id.split(/[^A-Za-z0-9]+/).filter((p) => p.length > 0);\n\tif (parts.length === 0) return \"iface\";\n\treturn parts[0].toLowerCase() + parts.slice(1).map((p) => p[0].toUpperCase() + p.slice(1).toLowerCase()).join(\"\") + \"Interface\";\n}\n//#endregion\n//#region src/schema/staticHubSchema.ts\nfunction parseStaticHubSchema(value) {\n\tconst root = expectRecord(value, \"hub schema\");\n\tconst rawServices = root.services === void 0 ? [] : expectArray(root.services, \"services\");\n\tconst interfaceSchemas = expectArray(root.interfaceSchemas, \"interfaceSchemas\").map((schema, index) => parseInterfaceSchema(schema, `interfaceSchemas[${index}]`));\n\tconst schemasByKey = /* @__PURE__ */ new Map();\n\tfor (const schema of interfaceSchemas) {\n\t\tconst key = interfaceKey(schema.id, schema.hash);\n\t\tif (schemasByKey.has(key)) throw new Error(`interfaceSchemas contains duplicate ${schema.id}@${schema.hash}`);\n\t\tschemasByKey.set(key, schema);\n\t}\n\tconst services = rawServices.map((service, index) => parseService(service, `services[${index}]`));\n\tconst serviceIds = /* @__PURE__ */ new Set();\n\tfor (const [serviceIndex, service] of services.entries()) {\n\t\tif (serviceIds.has(service.serviceId)) throw new Error(`Duplicate serviceId '${service.serviceId}'`);\n\t\tserviceIds.add(service.serviceId);\n\t\tconst interfaceIds = /* @__PURE__ */ new Set();\n\t\tfor (const [interfaceIndex, ref] of service.interfaces.entries()) {\n\t\t\tif (interfaceIds.has(ref.interfaceId)) throw new Error(`Duplicate interface '${ref.interfaceId}' in service '${service.serviceId}'`);\n\t\t\tinterfaceIds.add(ref.interfaceId);\n\t\t\trequireResolvedReference(ref, schemasByKey, `services[${serviceIndex}].interfaces[${interfaceIndex}]`);\n\t\t}\n\t}\n\tconst defaultInterface = root.defaultInterface === void 0 ? void 0 : parseInterfaceReference(root.defaultInterface, \"defaultInterface\");\n\tif (defaultInterface !== void 0) {\n\t\trequireResolvedReference(defaultInterface, schemasByKey, \"defaultInterface\");\n\t\tconst rootInterface = services.find((service) => service.serviceId === \"\")?.interfaces.find((ref) => ref.interfaceId === defaultInterface.interfaceId);\n\t\tif (rootInterface !== void 0 && rootInterface.interfaceHash !== defaultInterface.interfaceHash) throw new Error(`defaultInterface conflicts with root '${defaultInterface.interfaceId}'`);\n\t}\n\tconst prefixes = /* @__PURE__ */ new Set();\n\tconst bareInterfaces = root.bareInterfaces === void 0 ? void 0 : expectArray(root.bareInterfaces, \"bareInterfaces\").map((value, index) => {\n\t\tconst path = `bareInterfaces[${index}]`;\n\t\tconst binding = expectRecord(value, path);\n\t\tif (typeof binding.prefix !== \"string\") throw new Error(`${path}.prefix must be a string`);\n\t\tvalidateBarePrefix(binding.prefix);\n\t\tif (prefixes.has(binding.prefix)) throw new Error(`Duplicate bare prefix '${binding.prefix}'`);\n\t\tprefixes.add(binding.prefix);\n\t\tconst ref = parseInterfaceReference(binding.interface, `${path}.interface`);\n\t\trequireResolvedReference(ref, schemasByKey, `${path}.interface`);\n\t\tif (binding.prefix === \"\" && defaultInterface !== void 0 && interfaceKey(ref.interfaceId, ref.interfaceHash) !== interfaceKey(defaultInterface.interfaceId, defaultInterface.interfaceHash)) throw new Error(\"Empty bare prefix conflicts with defaultInterface\");\n\t\treturn {\n\t\t\tinterface: ref,\n\t\t\tprefix: binding.prefix\n\t\t};\n\t});\n\treturn {\n\t\t...root.services === void 0 ? {} : { services },\n\t\t...defaultInterface === void 0 ? {} : { defaultInterface },\n\t\t...bareInterfaces === void 0 ? {} : { bareInterfaces },\n\t\tinterfaceSchemas\n\t};\n}\nfunction parseService(value, path) {\n\tconst service = expectRecord(value, path);\n\tif (typeof service.serviceId !== \"string\") throw new Error(`${path}.serviceId must be a string`);\n\tif (service.serviceId.includes(\"::\") || !/^[\\x20-\\x7e]*$/.test(service.serviceId)) throw new Error(`${path}.serviceId must be printable ASCII without \"::\"`);\n\treturn {\n\t\tserviceId: service.serviceId,\n\t\tinterfaces: expectArray(service.interfaces, `${path}.interfaces`).map((ref, index) => parseInterfaceReference(ref, `${path}.interfaces[${index}]`))\n\t};\n}\nfunction parseInterfaceReference(value, path) {\n\tconst ref = expectRecord(value, path);\n\tif (typeof ref.interfaceId !== \"string\" || ref.interfaceId.length === 0) throw new Error(`${path}.interfaceId must be a non-empty string`);\n\tif (typeof ref.interfaceHash !== \"string\" || ref.interfaceHash.length === 0) throw new Error(`${path}.interfaceHash must be a non-empty string`);\n\treturn {\n\t\tinterfaceId: ref.interfaceId,\n\t\tinterfaceHash: ref.interfaceHash\n\t};\n}\nfunction parseInterfaceSchema(value, path) {\n\tconst schema = expectRecord(value, path);\n\tif (typeof schema.id !== \"string\" || schema.id.length === 0) throw new Error(`${path}.id must be a non-empty string`);\n\tif (typeof schema.hash !== \"string\" || schema.hash.length === 0) throw new Error(`${path}.hash must be a non-empty string`);\n\tif (typeof schema.methods !== \"object\" || schema.methods === null || Array.isArray(schema.methods)) throw new Error(`${path}.methods must be an object`);\n\tif (schema.tags !== void 0 && (!Array.isArray(schema.tags) || schema.tags.some((tag) => typeof tag !== \"string\"))) throw new Error(`${path}.tags must be an array of strings`);\n\tfor (const [name, method] of Object.entries(schema.methods)) {\n\t\tif (name.length === 0) throw new Error(`${path}.methods keys must be non-empty strings`);\n\t\tconst parsed = expectRecord(method, `${path}.methods.${name}`);\n\t\tif (!Object.hasOwn(parsed, \"params\")) throw new Error(`${path}.methods.${name}.params is required`);\n\t}\n\tconst typed = schema;\n\tvalidateInterfaceErrors(typed);\n\tconst computedHash = computeInterfaceHash(typed);\n\tif (computedHash !== typed.hash) throw new Error(`${path} hash mismatch for ${typed.id}: declared ${typed.hash}, computed ${computedHash}`);\n\treturn typed;\n}\nfunction requireResolvedReference(ref, schemasByKey, path) {\n\tif (!schemasByKey.has(interfaceKey(ref.interfaceId, ref.interfaceHash))) throw new Error(`${path} ${formatReference(ref)} does not resolve to an interface schema`);\n}\nfunction formatReference(ref) {\n\treturn `${ref.interfaceId}@${ref.interfaceHash}`;\n}\nfunction interfaceKey(interfaceId, interfaceHash) {\n\treturn `${interfaceId}\\0${interfaceHash}`;\n}\nfunction expectRecord(value, path) {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new Error(`${path} must be an object`);\n\treturn value;\n}\nfunction expectArray(value, path) {\n\tif (!Array.isArray(value)) throw new Error(`${path} must be an array`);\n\treturn value;\n}\n//#endregion\n//#region src/schema/codegen/generateTsContract.ts\n/** Generate one reusable definition per schema and immutable, typed route descriptors. */\nfunction generateTsContract(document, options = {}) {\n\tconst contract = parseStaticHubSchema(document);\n\tconst imports = options.linkRpcImport ?? \"@hediet/linkrpc\";\n\tconst chunks = [\n\t\t`import { applicationError, rpcError, bareInterfaceTarget, defaultInterfaceTarget, interfaceTarget, InterfaceDefinition, notificationType, requestType, type BareInterfaceTarget, type DefaultInterfaceTarget, type QualifiedInterfaceTarget, type LinkRpcInterfaceSchema } from ${JSON.stringify(imports)};`,\n\t\t\"import { z } from \\\"zod\\\";\",\n\t\t\"\"\n\t];\n\tconst names = /* @__PURE__ */ new Set([\n\t\t\"applicationError\",\n\t\t\"rpcError\",\n\t\t\"bareInterfaceTarget\",\n\t\t\"defaultInterfaceTarget\",\n\t\t\"interfaceTarget\",\n\t\t\"InterfaceDefinition\",\n\t\t\"notificationType\",\n\t\t\"requestType\",\n\t\t\"LinkRpcInterfaceSchema\",\n\t\t\"z\",\n\t\t\"BareInterfaceTarget\",\n\t\t\"DefaultInterfaceTarget\",\n\t\t\"QualifiedInterfaceTarget\"\n\t]);\n\tconst usedInterfaceKeys = /* @__PURE__ */ new Set();\n\tconst usedBindingKeys = /* @__PURE__ */ new Set();\n\tconst definitionNames = /* @__PURE__ */ new Map();\n\tfunction allocate(name, key) {\n\t\tif (!/^[$A-Z_a-z][$\\w]*$/.test(name) || reservedWords.has(name) || name.startsWith(\"$contract\")) throw new Error(`Invalid TypeScript export name '${name}' for '${key}'`);\n\t\tif (names.has(name)) throw new Error(`Generated name '${name}' collides for '${key}'; provide explicit naming overrides`);\n\t\tnames.add(name);\n\t\treturn name;\n\t}\n\tconst schemas = [...contract.interfaceSchemas].sort((a, b) => compare(`${a.id}@${a.hash}`, `${b.id}@${b.hash}`));\n\tfor (const [index, schema] of schemas.entries()) {\n\t\tconst key = `${schema.id}@${schema.hash}`;\n\t\tusedInterfaceKeys.add(key);\n\t\tconst name = allocate(options.interfaceNames?.[key] ?? `${identifier(schema.id)}Interface`, key);\n\t\tdefinitionNames.set(key, name);\n\t\tconst source = generateTsInterface(schema, {\n\t\t\texportName: \"definition\",\n\t\t\tpreserveWireSchema: true,\n\t\t\tomitImports: true\n\t\t});\n\t\tchunks.push(`namespace $contract${index} {`, source.trimEnd().split(\"\\n\").map((line) => ` ${line}`).join(\"\\n\"), \"}\");\n\t\tchunks.push(`export const ${name}: typeof $contract${index}.definition = $contract${index}.definition;`, \"\");\n\t}\n\tfunction binding(ref, key, derived, type, expression) {\n\t\tusedBindingKeys.add(key);\n\t\tconst name = allocate(options.bindingNames?.[key] ?? derived, key);\n\t\tconst definition = definitionNames.get(`${ref.interfaceId}@${ref.interfaceHash}`);\n\t\tchunks.push(`export const ${name}: ${type}<typeof ${definition}> = ${expression(definition)};`);\n\t}\n\tfor (const service of [...contract.services ?? []].sort((a, b) => compare(a.serviceId, b.serviceId))) for (const ref of [...service.interfaces].sort((a, b) => compare(a.interfaceId, b.interfaceId))) {\n\t\tconst key = `${ref.interfaceId}@${ref.interfaceHash}`;\n\t\tconst base = identifier(ref.interfaceId);\n\t\tbinding(ref, service.serviceId === \"\" ? `root:${key}` : `service:${service.serviceId}:${key}`, service.serviceId === \"\" ? `${base}Root` : `${identifier(service.serviceId)}${upper(base)}Service`, \"QualifiedInterfaceTarget\", (name) => `interfaceTarget(${name}, { serviceId: ${JSON.stringify(service.serviceId)} })`);\n\t}\n\tif (contract.defaultInterface) binding(contract.defaultInterface, \"default\", `${identifier(contract.defaultInterface.interfaceId)}Default`, \"DefaultInterfaceTarget\", (name) => `defaultInterfaceTarget(${name})`);\n\tfor (const bare of [...contract.bareInterfaces ?? []].sort((a, b) => compare(a.prefix, b.prefix))) binding(bare.interface, `bare:${bare.prefix}`, `${identifier(bare.prefix || bare.interface.interfaceId)}Bare`, \"BareInterfaceTarget\", (name) => `bareInterfaceTarget(${name}, { prefix: ${JSON.stringify(bare.prefix)} })`);\n\tfor (const [overrides, used] of [[options.interfaceNames, usedInterfaceKeys], [options.bindingNames, usedBindingKeys]]) for (const key of Object.keys(overrides ?? {})) if (!used.has(key)) throw new Error(`Unknown naming override '${key}'`);\n\treturn `${chunks.join(\"\\n\")}\\n`;\n}\nfunction identifier(value) {\n\tconst name = value.split(/[^A-Za-z0-9_$]+/).filter(Boolean).map((word, index) => index === 0 ? word[0].toLowerCase() + word.slice(1) : upper(word)).join(\"\") || \"interface\";\n\treturn /^[0-9]/.test(name) ? `_${name}` : name;\n}\nfunction upper(value) {\n\treturn value[0].toUpperCase() + value.slice(1);\n}\nfunction compare(a, b) {\n\treturn a < b ? -1 : a > b ? 1 : 0;\n}\nconst reservedWords = new Set(\"break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with implements interface let package private protected public static yield await\".split(\" \"));\n//#endregion\n//#region src/protocol/methodName.ts\n/**\n* Parse a JSON-RPC method string. Returns `undefined` if any segment is\n* empty or the segment count is out of range.\n*/\nfunction parseMethodName(method) {\n\tconst parts = method.split(\"::\");\n\tif (parts.length === 3 && parts[0].length === 0 && parts[1].length > 0 && parts[2].length > 0) return {\n\t\tkind: \"interface\",\n\t\tinterfaceId: parts[1],\n\t\tmember: parts[2]\n\t};\n\tif (parts.some((p) => p.length === 0)) return void 0;\n\tif (parts.length === 1) return {\n\t\tkind: \"bare\",\n\t\tmember: parts[0]\n\t};\n\tif (parts.length === 2) return {\n\t\tkind: \"interface\",\n\t\tinterfaceId: parts[0],\n\t\tmember: parts[1]\n\t};\n\tif (parts.length === 3) return {\n\t\tkind: \"full\",\n\t\tserviceId: parts[0],\n\t\tinterfaceId: parts[1],\n\t\tmember: parts[2]\n\t};\n}\n/**\n* Convert a parsed method string to a {@link CallTarget} for capability\n* matching. Interface-form calls are addressed to the root service —\n* represented as an empty `serviceId`. Throws on `bare` form (no\n* interface context) and on malformed input.\n*/\nfunction methodNameToTarget(method) {\n\tconst p = parseMethodName(method);\n\tif (!p) throw new Error(`linkrpc: malformed method: ${method}`);\n\tif (p.kind === \"bare\") throw new Error(`linkrpc: bare method has no interface context: ${method}`);\n\tif (p.kind === \"interface\") return {\n\t\tserviceId: \"\",\n\t\tinterfaceId: p.interfaceId,\n\t\tmember: p.member\n\t};\n\treturn {\n\t\tserviceId: p.serviceId,\n\t\tinterfaceId: p.interfaceId,\n\t\tmember: p.member\n\t};\n}\n//#endregion\n//#region src/protocol/signedObject.ts\n/**\n* The HubRPC **signed-object** standard: one rule for committing a\n* signature (and a content hash) over any JSON object.\n*\n* > The signature `obj.$hubrpcSignature[domain]` covers\n* > `jcs({ [domainValue(domain)]: obj without $hubrpcSignature and $hubrpcUnsigned })`.\n*\n* Both reserved keys are stripped before canonicalization — on **every**\n* object, call or capability alike:\n*\n* - {@link HUBRPC_SIGNATURE_KEY} (`$hubrpcSignature`) holds the signature\n* itself (a domain-keyed map of `{ keyId, sig }` entries). It can't sign\n* itself, so it's excluded.\n* - {@link HUBRPC_UNSIGNED_KEY} (`$hubrpcUnsigned`) holds extrinsic\n* *attachments* (e.g. the presented capability bag) authored by someone\n* other than this signer, so it's excluded too.\n*\n* Domain separation is intrinsic: the per-domain {@link signingDomainValue}\n* is the sole key of the canonicalized wrapper object. A `\"call\"` signature\n* can therefore never verify as a `\"capability\"` (or vice-versa). The domain\n* is *supplied by context* by signer and verifier;\n* the on-wire `$hubrpcSignature` key is a convenience index, never a trust\n* claim.\n*\n* This module is pure (no private keys, no `crypto.verify`): it only defines\n* the canonical bytes. Signing/verifying live in `../identity/signedObject`.\n*/\n/** Reserved wire-key: the signature map `{ [domain]: SignatureEnvelope }`. */\nconst HUBRPC_SIGNATURE_KEY = \"$hubrpcSignature\";\n/** Reserved wire-key: extrinsic unsigned attachments (e.g. the capability bag). */\nconst HUBRPC_UNSIGNED_KEY = \"$hubrpcUnsigned\";\n/** Reserved wire-key: signed call meta, present only on calls (dodges the JSON-RPC param namespace). */\nconst HUBRPC_META_KEY = \"$hubrpc\";\n/** @deprecated Use {@link HUBRPC_SIGNATURE_KEY}. */\nconst LINKRPC_SIGNATURE_KEY = HUBRPC_SIGNATURE_KEY;\n/** @deprecated Use {@link HUBRPC_UNSIGNED_KEY}. */\nconst LINKRPC_UNSIGNED_KEY = HUBRPC_UNSIGNED_KEY;\n/** @deprecated Use {@link HUBRPC_META_KEY}. */\nconst LINKRPC_META_KEY = HUBRPC_META_KEY;\n/**\n* The domain-separation key. It includes the frozen signature-suite version\n* and becomes the sole key of the object passed to JCS.\n*/\nfunction signingDomainValue(domain) {\n\treturn `hubrpc-sig/v1/${domain}`;\n}\n/**\n* THE bytes a signature commits to (and a content hash hashes) for `obj` in\n* `domain`: `jcs({ [domainValue(domain)]: obj minus the two reserved keys })`.\n*/\nfunction signingInput(domain, obj) {\n\tconst signed = { ...obj };\n\tdelete signed[HUBRPC_SIGNATURE_KEY];\n\tdelete signed[HUBRPC_UNSIGNED_KEY];\n\treturn jcsCanonicalizeBytes({ [signingDomainValue(domain)]: signed });\n}\n/**\n* Content identity of a signed object: `base64url(sha256(signingInput(...)))`.\n* The single operation behind both a capability's `callBind.payloadHash`\n* (domain `\"call\"`) and a child capability's `parentHash` (domain\n* `\"capability\"`).\n*/\nfunction signedHash(domain, obj) {\n\treturn bytesToBase64Url(sha256$1(signingInput(domain, obj)));\n}\n/** Read the signature envelope for `domain` off an object's `$hubrpcSignature` map. */\nfunction readSignature(obj, domain) {\n\tconst sigs = obj[HUBRPC_SIGNATURE_KEY];\n\tif (sigs === null || typeof sigs !== \"object\") return void 0;\n\tconst entry = sigs[domain];\n\tif (entry === null || typeof entry !== \"object\") return void 0;\n\tconst { keyId, sig } = entry;\n\tif (typeof keyId !== \"string\" || typeof sig !== \"string\") return void 0;\n\treturn {\n\t\tkeyId,\n\t\tsig\n\t};\n}\n/** The {@link KeyId} the signer used for `domain` (the unsigned routing hint), if any. */\nfunction getKeyId(obj, domain) {\n\treturn readSignature(obj, domain)?.keyId;\n}\n/**\n* Return a copy of `obj` with `$hubrpcSignature[domain]` set to `envelope`,\n* preserving any sibling-domain signatures already present.\n*/\nfunction withSignature(obj, domain, envelope) {\n\tconst prev = obj[HUBRPC_SIGNATURE_KEY];\n\treturn {\n\t\t...obj,\n\t\t[HUBRPC_SIGNATURE_KEY]: {\n\t\t\t...prev,\n\t\t\t[domain]: envelope\n\t\t}\n\t};\n}\n//#endregion\n//#region src/protocol/linkRpcEnvelope.ts\n/**\n* The linkrpc signing/cap system accepts only plain-object user params (or\n* none). Reject arrays/primitives at the boundary so \"strip `$hubrpc*`, the\n* rest is the signed user params\" stays unambiguous.\n*/\nfunction requireObjectParams(userParams) {\n\tif (userParams === void 0) return {};\n\tif (userParams === null || typeof userParams !== \"object\" || Array.isArray(userParams)) throw new Error(\"linkrpc: user params must be a plain JSON object or undefined\");\n\treturn userParams;\n}\n/**\n* Return the application-authored portion of a LinkRPC params value.\n*\n* Routing and gate layers must continue forwarding the original wire params so\n* every chained hub can independently verify the envelope. Terminal dispatch\n* may use this derived value for application-schema validation without mutating\n* or replacing the wire message.\n*/\nfunction stripLinkRpcWireMeta(wireParams) {\n\tif (wireParams === void 0) return void 0;\n\tif (wireParams === null || typeof wireParams !== \"object\" || Array.isArray(wireParams)) return wireParams;\n\tconst object = wireParams;\n\tconst reserved = [\n\t\tHUBRPC_META_KEY,\n\t\tHUBRPC_SIGNATURE_KEY,\n\t\tHUBRPC_UNSIGNED_KEY\n\t];\n\tif (!reserved.some((key) => key in object)) return object;\n\tconst userParams = {};\n\tfor (const key of Object.keys(object)) {\n\t\tif (reserved.includes(key)) continue;\n\t\tuserParams[key] = object[key];\n\t}\n\treturn userParams;\n}\n//#endregion\n//#region src/hub/common/reflection.interfaces.ts\nconst defaultsInterface = defineInterface({\n\tid: \"hubrpc.defaults\",\n\tdescription: \"Reflection: preset default service / interface on this connection.\"\n}, {\n\tget: requestType(object({}), object({\n\t\tserviceId: optional(string()),\n\t\tinterfaceId: optional(string()),\n\t\t/** Hash of the preset interface, if known. */\n\t\tinterfaceHash: optional(string())\n\t})),\n\tlistBindings: requestType(object({}), object({ bindings: array(object({\n\t\tprefix: string(),\n\t\tserviceId: optional(string()),\n\t\tinterfaceId: string(),\n\t\tinterfaceHash: string()\n\t})) }))\n});\n/**\n* A single root-principal requirement. `transitive: true` means the requirement\n* also applies to every service reachable *through* this one — i.e. when this\n* listing is a `hubrpc.directory` reference, everything it lists inherits the\n* requirement (also as transitive).\n*/\nconst zRootPrincipalReq = object({\n\tprincipal: string(),\n\ttransitive: optional(boolean())\n});\n/** One OR-set. The set is satisfied by holding *any one* of its principals. */\nconst zRootPrincipalSet = array(zRootPrincipalReq);\nconst zServiceIdPattern = union([object({ exact: string() }), object({ prefix: string() })]);\nconst zServiceListing = object({\n\tserviceId: string(),\n\tinterfaceId: string(),\n\t/** Hash of the interface as implemented by this service. */\n\tinterfaceHash: string(),\n\t/** Optional, non-authoritative discovery labels of this implemented interface. */\n\ttags: optional(array(string())),\n\t/** Optional non-normative description of the owning service. */\n\tserviceDescription: optional(string()),\n\t/**\n\t* Root principals required to access this service, in CNF: the caller must\n\t* satisfy **every** set (AND), and a set is satisfied by **any one** of its\n\t* principals (OR). Omitted/empty => no root-principal requirement.\n\t*/\n\trootPrincipalSets: optional(array(zRootPrincipalSet)),\n\t/**\n\t* Service-id regions reachable through this referral. Meaningful only for\n\t* `hubrpc.directory` entries; omission defaults to the referral service-id\n\t* subtree.\n\t*/\n\treachableServiceIds: optional(array(zServiceIdPattern))\n});\nconst directoryInterface = defineInterface({\n\tid: \"hubrpc.directory\",\n\tdescription: \"Reflection: list services exposed by this endpoint. Can also list other directory services that can be explored.\"\n}, {\n\tlist: requestType(object({\n\t\t/** Filter: only return services implementing this interface id. */\n\t\tinterfaceId: optional(string()),\n\t\t/** Filter: only return services whose interface id starts with this prefix. */\n\t\tinterfaceIdPrefix: optional(string()),\n\t\t/** Filter: only return entries for this service id. */\n\t\tserviceId: optional(string()),\n\t\t/** Union filter used to constrain a transitive directory walk. */\n\t\tserviceIdScopes: optional(array(zServiceIdPattern)),\n\t\t/** Paging: opaque continuation token from a previous response. */\n\t\tcursor: optional(string()),\n\t\t/** Paging: max items in this page. Server MAY return fewer. */\n\t\tlimit: optional(number().check(int(), positive())),\n\t\t/** Soft cap on time the server spends gathering this page, in ms. */\n\t\ttimeoutMs: optional(number().check(int(), nonnegative()))\n\t}), object({\n\t\titems: array(zServiceListing),\n\t\t/** Omitted => no more pages. */\n\t\tnextCursor: optional(string()),\n\t\t/** True if `timeoutMs` cut the page short before exhausting results. */\n\t\ttruncated: optional(boolean())\n\t})),\n\t/**\n\t* Coarse change tap on the directory.\n\t*\n\t* `watch` is a long-lived streaming request that emits an **empty tick**\n\t* whenever the (optionally filtered) directory *might* have changed. The\n\t* tick carries no delta and no payload — its only meaning is \"re-`list`\n\t* now\". The consumer reconciles against its own last snapshot.\n\t*\n\t* This keeps the server stateless: it never computes or replays\n\t* per-item deltas, never does an initial-sync replay. Over-emission is\n\t* allowed (the consumer re-lists and finds nothing new); under-emission\n\t* is not. Ticks are coalesced. The `interfaceId` / `serviceId` filters\n\t* mirror `list` and are a relevance hint, not a guarantee.\n\t*\n\t* The request resolves when the caller cancels (or the connection\n\t* drops); the runtime auto-detaches the stream when it settles.\n\t*/\n\twatch: requestType(object({\n\t\t/** Relevance hint: changes touching this interface id. */\n\t\tinterfaceId: optional(string()),\n\t\t/** Relevance hint: changes touching an interface id with this prefix. */\n\t\tinterfaceIdPrefix: optional(string()),\n\t\t/** Relevance hint: changes touching this service id. */\n\t\tserviceId: optional(string()),\n\t\t/** Relevance hint: changes within any of these service-id regions. */\n\t\tserviceIdScopes: optional(array(zServiceIdPattern))\n\t}), object({})).withStream({ \n\t/** Empty tick: \"the directory may have changed; re-list.\" */\nserver: object({}) })\n});\n/**\n* A `directoryInterface.watch` handler for a **static** directory. It opens the\n* stream, never ticks, and resolves when the caller cancels. Dynamic providers,\n* including {@link LinkRpcConnection.enableReflection}, use a change-emitting\n* implementation instead.\n*/\nfunction directoryWatchNever(_params, _ctx, stream) {\n\treturn new Promise((resolve) => {\n\t\tif (stream.signal.aborted) {\n\t\t\tresolve({});\n\t\t\treturn;\n\t\t}\n\t\tstream.signal.addEventListener(\"abort\", () => resolve({}), { once: true });\n\t});\n}\nconst schemasInterface = defineInterface({\n\tid: \"hubrpc.schemas\",\n\tdescription: \"Reflection: fetch interface schemas by id (+ optional hash). Must serve the interfaces advertised in this endpoint's directory.\"\n}, { get: requestType(object({\n\tinterfaceId: string(),\n\t/** Omit => server picks the version it exposes. */\n\thash: optional(string())\n}), object({ \n/** A full `SvcInterfaceSchema`. */\nschema: unknown() })) });\n//#endregion\n//#region src/connection/requestTimeout.ts\nconst DEFAULT_RPC_TIMEOUT_MS = 5e3;\nasync function withRpcTimeout(request, target, timeoutMs = DEFAULT_RPC_TIMEOUT_MS) {\n\tif (timeoutMs <= 0) return request;\n\tlet timer;\n\tconst timeout = new Promise((_resolve, reject) => {\n\t\ttimer = setTimeout(() => {\n\t\t\tconst reason = `${target} timed out after ${timeoutMs}ms`;\n\t\t\ttry {\n\t\t\t\tPromise.resolve(request.cancel(reason)).catch(() => {});\n\t\t\t} finally {\n\t\t\t\ttry {\n\t\t\t\t\trequest.dispose?.(reason);\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t\treject(new Error(reason));\n\t\t}, timeoutMs);\n\t});\n\ttry {\n\t\treturn await Promise.race([request, timeout]);\n\t} finally {\n\t\tif (timer !== void 0) clearTimeout(timer);\n\t}\n}\n//#endregion\n//#region src/hub/common/directoryWalk.ts\nasync function fetchDirectory(channel, opts = {}) {\n\tconst method = opts.target ? `${opts.target}::hubrpc.directory::list` : \"hubrpc.directory::list\";\n\tconst all = [];\n\tlet cursor;\n\twhile (true) {\n\t\tconst params = {};\n\t\tif (opts.interfaceId !== void 0) params.interfaceId = opts.interfaceId;\n\t\tif (opts.interfaceIdPrefix !== void 0) params.interfaceIdPrefix = opts.interfaceIdPrefix;\n\t\tif (opts.serviceId !== void 0) params.serviceId = opts.serviceId;\n\t\tif (opts.serviceIdScopes !== void 0) params.serviceIdScopes = [...opts.serviceIdScopes];\n\t\tif (opts.limit !== void 0) params.limit = opts.limit;\n\t\tif (opts.timeoutMs !== void 0) params.timeoutMs = opts.timeoutMs;\n\t\tif (cursor !== void 0) params.cursor = cursor;\n\t\tconst call = channel.sendRequestWithStream(method, params, { interfaceHash: directoryInterface.schemaHash });\n\t\tconst target = opts.target ?? \"<root>\";\n\t\tconst page = await withRpcTimeout(Object.assign(call.result, {\n\t\t\tcancel: (reason) => call.cancel(reason),\n\t\t\tdispose: (reason) => call.dispose?.(reason)\n\t\t}), `hub directory service '${target}'`, opts.timeoutMs ?? 5e3);\n\t\tfor (const it of page.items) {\n\t\t\tif (it.tags !== void 0 && (!Array.isArray(it.tags) || !it.tags.every((tag) => typeof tag === \"string\"))) throw new Error(`Invalid directory tags for \"${it.serviceId}::${it.interfaceId}\"`);\n\t\t\tall.push({\n\t\t\t\tserviceId: it.serviceId,\n\t\t\t\tinterfaceId: it.interfaceId,\n\t\t\t\thash: it.interfaceHash,\n\t\t\t\t...it.tags === void 0 ? {} : { tags: [...it.tags] },\n\t\t\t\t...it.path !== void 0 ? { path: it.path } : {},\n\t\t\t\t...it.serviceDescription !== void 0 ? { serviceDescription: it.serviceDescription } : {},\n\t\t\t\t...Array.isArray(it.rootPrincipalSets) ? { rootPrincipalSets: it.rootPrincipalSets } : {},\n\t\t\t\t...Array.isArray(it.reachableServiceIds) ? { reachableServiceIds: it.reachableServiceIds } : {}\n\t\t\t});\n\t\t}\n\t\tif (!page.nextCursor) break;\n\t\tcursor = page.nextCursor;\n\t}\n\treturn all;\n}\nasync function fetchSchema(channel, interfaceId, hash, target, timeoutMs = DEFAULT_RPC_TIMEOUT_MS) {\n\tconst method = target ? `${target}::hubrpc.schemas::get` : \"hubrpc.schemas::get\";\n\tconst params = { interfaceId };\n\tif (hash !== void 0) params.hash = hash;\n\tconst call = channel.sendRequestWithStream(method, params);\n\treturn (await withRpcTimeout(Object.assign(call.result, {\n\t\tcancel: (reason) => call.cancel(reason),\n\t\tdispose: (reason) => call.dispose?.(reason)\n\t}), `hub schema '${interfaceId}' at '${target ?? \"<root>\"}'`, timeoutMs)).schema;\n}\nfunction findMethodInSchema(schema, methodName) {\n\treturn schema.methods[methodName];\n}\n/** Default recursion depth when walking the bus. */\nconst DEFAULT_WALK_DEPTH = 5;\nconst DIRECTORY_INTERFACE_ID = \"hubrpc.directory\";\nconst ROOT_NODE_KEY = \"\\0root\";\n/** Segment-aware service-id pattern matching (`foo` includes `foo/bar`, not `foobar`). */\nfunction serviceIdMatchesPattern(serviceId, pattern) {\n\tif (\"exact\" in pattern) return serviceId === pattern.exact;\n\treturn pattern.prefix === \"\" || serviceId === pattern.prefix || serviceId.startsWith(`${pattern.prefix}/`);\n}\n/** Whether a service id is included by a union of patterns. `undefined` means unfiltered. */\nfunction serviceIdMatchesScopes(serviceId, scopes) {\n\treturn scopes === void 0 || scopes.some((pattern) => serviceIdMatchesPattern(serviceId, pattern));\n}\n/** Canonicalize a pattern union by removing duplicates and contained patterns. */\nfunction normalizeServiceIdScopes(scopes) {\n\tconst unique = /* @__PURE__ */ new Map();\n\tfor (const pattern of scopes) unique.set(patternKey(pattern), pattern);\n\tconst patterns = [...unique.values()];\n\treturn patterns.filter((candidate, index) => !patterns.some((other, otherIndex) => index !== otherIndex && patternContains(other, candidate))).sort((a, b) => patternKey(a).localeCompare(patternKey(b)));\n}\n/** Pairwise intersection of two pattern unions. */\nfunction intersectServiceIdScopes(left, right) {\n\tconst intersections = [];\n\tfor (const a of left) for (const b of right) {\n\t\tconst intersection = intersectPattern(a, b);\n\t\tif (intersection !== void 0) intersections.push(intersection);\n\t}\n\treturn normalizeServiceIdScopes(intersections);\n}\nfunction intersectPattern(left, right) {\n\tif (\"exact\" in left) {\n\t\tif (\"exact\" in right) return left.exact === right.exact ? left : void 0;\n\t\treturn serviceIdMatchesPattern(left.exact, right) ? left : void 0;\n\t}\n\tif (\"exact\" in right) return serviceIdMatchesPattern(right.exact, left) ? right : void 0;\n\tif (serviceIdMatchesPattern(left.prefix, right)) return left;\n\tif (serviceIdMatchesPattern(right.prefix, left)) return right;\n}\nfunction patternContains(container, candidate) {\n\tif (\"exact\" in container) return \"exact\" in candidate && container.exact === candidate.exact;\n\tif (\"exact\" in candidate) return serviceIdMatchesPattern(candidate.exact, container);\n\treturn serviceIdMatchesPattern(candidate.prefix, container);\n}\nfunction patternKey(pattern) {\n\treturn \"exact\" in pattern ? `e:${pattern.exact}` : `p:${pattern.prefix}`;\n}\nfunction scopesKey(scopes) {\n\treturn normalizeServiceIdScopes(scopes).map(patternKey).join(\"\\0\");\n}\nasync function walkHubDetailed(channel, opts = {}) {\n\treturn new HubDirectoryExplorer(channel, opts).explore();\n}\n/**\n* Backward-compatible wrapper over {@link walkHubDetailed} that returns only the\n* reachable listings, dropping the inaccessible-directory report.\n*/\nasync function walkHub(channel, opts = {}) {\n\treturn (await walkHubDetailed(channel, opts)).listings;\n}\n/**\n* Reusable directory graph explorer and watcher.\n*\n* The class keeps one native snapshot per directory target. A watch tick\n* re-lists only its source target; outgoing referral changes then propagate\n* through affected descendants. Unchanged siblings retain both their snapshot\n* and watch. Multi-parent targets are queried with the normalized union of all\n* incoming path scopes.\n*/\nvar HubDirectoryExplorer = class {\n\t_channel;\n\t_options;\n\t_maxDepth;\n\t_initialScopes;\n\t_nodes = /* @__PURE__ */ new Map();\n\t_unlockAttempted = /* @__PURE__ */ new Set();\n\t_listeners = /* @__PURE__ */ new Set();\n\t_graphListeners = /* @__PURE__ */ new Set();\n\t_pendingTicks = /* @__PURE__ */ new Set();\n\t_watchRetryTimers = /* @__PURE__ */ new Map();\n\t_watchRetryDelays = /* @__PURE__ */ new Map();\n\t_initialized = false;\n\t_disposed = false;\n\t_watching = false;\n\t_complete = false;\n\t_revision = 0;\n\t_work = Promise.resolve();\n\t_explorePromise;\n\tconstructor(_channel, _options = {}) {\n\t\tthis._channel = _channel;\n\t\tthis._options = _options;\n\t\tthis._maxDepth = _options.maxDepth ?? 5;\n\t\tthis._initialScopes = normalizeServiceIdScopes(_options.serviceIdScopes ?? [{ prefix: \"\" }]);\n\t\tthis._nodes.set(ROOT_NODE_KEY, this._createRootNode());\n\t}\n\t/** Perform a fresh bounded exploration without starting watches. */\n\texplore() {\n\t\tthis._throwIfDisposed();\n\t\tif (this._explorePromise !== void 0) return this._explorePromise;\n\t\tconst promise = this._explore();\n\t\tthis._explorePromise = promise;\n\t\tconst clear = () => {\n\t\t\tif (this._explorePromise === promise) this._explorePromise = void 0;\n\t\t};\n\t\tpromise.then(clear, clear);\n\t\treturn promise;\n\t}\n\tasync _explore() {\n\t\tif (this._initialized || this._nodes.get(ROOT_NODE_KEY)?.state !== \"unexplored\") this._resetForExplore();\n\t\tconst root = this._nodes.get(ROOT_NODE_KEY);\n\t\tawait this._loadNode(root);\n\t\tif (this._disposed) return {\n\t\t\tlistings: [],\n\t\t\tinaccessible: []\n\t\t};\n\t\tawait this._reconcileScopesFromRoot();\n\t\tawait this._pruneUnreachable();\n\t\tthis._initialized = true;\n\t\tif (this._watching) await this._synchronizeWatches();\n\t\tthis._settle();\n\t\treturn this.result;\n\t}\n\t/** Current deduplicated graph snapshot. */\n\tget result() {\n\t\tconst best = /* @__PURE__ */ new Map();\n\t\tfor (const node of this._nodes.values()) {\n\t\t\tif (!node.loaded) continue;\n\t\t\tfor (const item of node.listings) {\n\t\t\t\tconst effective = mergePrincipalSets(item.rootPrincipalSets, node.inherited);\n\t\t\t\tconst tagged = {\n\t\t\t\t\t...item,\n\t\t\t\t\t...effective.length > 0 ? { rootPrincipalSets: effective } : {},\n\t\t\t\t\tdiscoveredFrom: node.target ?? \"\"\n\t\t\t\t};\n\t\t\t\tconst key = listingKey(item);\n\t\t\t\tconst existing = best.get(key);\n\t\t\t\tif (!existing || _isAuthoritative(tagged, existing)) best.set(key, tagged);\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tlistings: [...best.values()].filter((item) => this._options.interfaceId === void 0 || item.interfaceId === this._options.interfaceId).filter((item) => this._options.interfaceIdPrefix === void 0 || item.interfaceId.startsWith(this._options.interfaceIdPrefix)).filter((item) => this._options.serviceId === void 0 || item.serviceId === this._options.serviceId),\n\t\t\tinaccessible: [...this._nodes.values()].filter((node) => node.key !== ROOT_NODE_KEY && node.inaccessibleReason !== void 0).map((node) => ({\n\t\t\t\tserviceId: node.target,\n\t\t\t\treason: node.inaccessibleReason\n\t\t\t}))\n\t\t};\n\t}\n\t/** Current complete-or-progressive directory graph report. */\n\tget graphSnapshot() {\n\t\tconst root = this._nodes.get(ROOT_NODE_KEY) ?? this._createRootNode();\n\t\tconst directories = [...this._nodes.values()].filter((node) => node.key !== ROOT_NODE_KEY).sort((a, b) => (a.target ?? \"\").localeCompare(b.target ?? \"\")).map((node) => this._nodeReport(node));\n\t\treturn {\n\t\t\trevision: this._revision,\n\t\t\tcomplete: this._complete,\n\t\t\troot: this._nodeReport(root),\n\t\t\tdirectories,\n\t\t\tresult: this.result\n\t\t};\n\t}\n\t/**\n\t* Subscribe to progressive graph reports. The listener is registered before\n\t* receiving a synchronous current snapshot, avoiding the subscribe/explore\n\t* race for both idle and already-running explorers.\n\t*/\n\tsubscribe(listener) {\n\t\tthis._throwIfDisposed();\n\t\tthis._graphListeners.add(listener);\n\t\tthis._deliverGraphEvent(listener, {\n\t\t\ttype: \"snapshot\",\n\t\t\treason: \"subscribed\",\n\t\t\tsnapshot: this.graphSnapshot\n\t\t});\n\t\tlet active = true;\n\t\treturn () => {\n\t\t\tif (!active) return;\n\t\t\tactive = false;\n\t\t\tthis._graphListeners.delete(listener);\n\t\t};\n\t}\n\t/**\n\t* Explore once, then watch every reachable directory. Resolves after the\n\t* initial graph and watches are established.\n\t*/\n\tasync watch(listener) {\n\t\tthis._throwIfDisposed();\n\t\tthis._listeners.add(listener);\n\t\tthis._watching = true;\n\t\tif (!this._initialized) await this.explore();\n\t\telse {\n\t\t\tthis._startReconciliation();\n\t\t\tawait this._synchronizeWatches();\n\t\t\tthis._settle();\n\t\t}\n\t\tlet active = true;\n\t\treturn () => {\n\t\t\tif (!active) return;\n\t\t\tactive = false;\n\t\t\tthis._listeners.delete(listener);\n\t\t\tif (this._listeners.size === 0) {\n\t\t\t\tthis._watching = false;\n\t\t\t\tthis._stopAllWatches();\n\t\t\t}\n\t\t};\n\t}\n\t/** Wait until all currently queued watch reconciliation has settled. */\n\tasync whenIdle() {\n\t\tawait this._work;\n\t}\n\tdispose() {\n\t\tif (this._disposed) return;\n\t\tthis._disposed = true;\n\t\tthis._listeners.clear();\n\t\tthis._pendingTicks.clear();\n\t\tthis._stopAllWatches(false);\n\t\tthis._graphListeners.clear();\n\t\tthis._clearNodes();\n\t}\n\tasync _loadNode(node, reconcileOutgoing = true) {\n\t\tif (node.loading) {\n\t\t\tnode.reloadRequested = true;\n\t\t\treturn;\n\t\t}\n\t\tnode.loading = true;\n\t\tthis._updateNode(node, \"loading\", () => {\n\t\t\tnode.state = \"loading\";\n\t\t});\n\t\ttry {\n\t\t\tdo {\n\t\t\t\tnode.reloadRequested = false;\n\t\t\t\tconst scopesAtRequest = node.scopes;\n\t\t\t\tlet listings;\n\t\t\t\ttry {\n\t\t\t\t\tlistings = await fetchDirectory(this._channel, {\n\t\t\t\t\t\ttarget: node.target,\n\t\t\t\t\t\tserviceIdScopes: scopesAtRequest,\n\t\t\t\t\t\ttimeoutMs: this._options.timeoutMs ?? 5e3\n\t\t\t\t\t});\n\t\t\t\t\tif (this._disposed) break;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (this._disposed) break;\n\t\t\t\t\tif (await this._tryUnlock(node)) {\n\t\t\t\t\t\tnode.reloadRequested = true;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst previous = this._nodeReport(node);\n\t\t\t\t\tnode.inaccessibleReason = errorMessage(error);\n\t\t\t\t\tthis._options.log?.(`hub directory list(${node.target ?? \"<root>\"}) failed: ${node.inaccessibleReason}`);\n\t\t\t\t\tif (node.loaded) node.listings = node.listings.filter((item) => serviceIdMatchesScopes(item.serviceId, node.scopes));\n\t\t\t\t\tnode.state = \"inaccessible\";\n\t\t\t\t\tthis._emitNodeUpdated(node, previous, \"inaccessible\");\n\t\t\t\t\tif (node.loaded && reconcileOutgoing) await this._reconcileOutgoing(node);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (scopesKey(scopesAtRequest) !== scopesKey(node.scopes)) {\n\t\t\t\t\tnode.reloadRequested = true;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst previous = this._nodeReport(node);\n\t\t\t\tnode.inaccessibleReason = void 0;\n\t\t\t\tnode.loaded = true;\n\t\t\t\tnode.listings = listings.filter((item) => serviceIdMatchesScopes(item.serviceId, node.scopes));\n\t\t\t\tnode.state = \"loaded\";\n\t\t\t\tthis._emitNodeUpdated(node, previous, \"loaded\");\n\t\t\t\tif (reconcileOutgoing) await this._reconcileOutgoing(node);\n\t\t\t} while (node.reloadRequested && !this._disposed);\n\t\t} finally {\n\t\t\tnode.loading = false;\n\t\t}\n\t}\n\tasync _tryUnlock(node) {\n\t\tif (node.target === void 0 || this._options.unlockGatedDirectory === void 0 || this._unlockAttempted.has(node.target)) return false;\n\t\tthis._unlockAttempted.add(node.target);\n\t\ttry {\n\t\t\treturn await this._options.unlockGatedDirectory(node.target);\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\tasync _reconcileOutgoing(node) {\n\t\tconst next = this._outgoingFor(node.scopes, node.inherited, node.depth, node.listings);\n\t\tconst affected = /* @__PURE__ */ new Set([...node.outgoing.keys(), ...next.keys()]);\n\t\tnode.outgoing = next;\n\t\tfor (const childKey of affected) {\n\t\t\tif (this._disposed) return;\n\t\t\tconst contribution = next.get(childKey);\n\t\t\tlet child = this._nodes.get(childKey);\n\t\t\tlet previous;\n\t\t\tif (contribution === void 0) {\n\t\t\t\tif (child === void 0) continue;\n\t\t\t\tprevious = this._nodeReport(child);\n\t\t\t\tchild.parents.delete(node.key);\n\t\t\t} else {\n\t\t\t\tif (child === void 0) {\n\t\t\t\t\tchild = this._createNode(childKey);\n\t\t\t\t\tchild.parents.set(node.key, contribution);\n\t\t\t\t\tthis._deriveNodeFromParents(child);\n\t\t\t\t\tthis._nodes.set(childKey, child);\n\t\t\t\t\tthis._emitNodeAdded(child);\n\t\t\t\t\tawait this._loadNode(child);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tprevious = this._nodeReport(child);\n\t\t\t\tchild.parents.set(node.key, contribution);\n\t\t\t}\n\t\t\tawait this._updateNodeFromParents(child, previous);\n\t\t}\n\t}\n\t_outgoingFor(scopes, inherited, depth, listings) {\n\t\tconst outgoing = /* @__PURE__ */ new Map();\n\t\tif (depth >= this._maxDepth) return outgoing;\n\t\tfor (const item of listings) {\n\t\t\tif (item.interfaceId !== DIRECTORY_INTERFACE_ID || !serviceIdMatchesScopes(item.serviceId, scopes)) continue;\n\t\t\tconst childScopes = intersectServiceIdScopes(scopes, item.reachableServiceIds ?? [{ prefix: item.serviceId }]);\n\t\t\tif (childScopes.length === 0) continue;\n\t\t\tconst childKey = this._nodeKeyForTarget(item.serviceId);\n\t\t\tif (childKey === ROOT_NODE_KEY) continue;\n\t\t\tconst contribution = {\n\t\t\t\tscopes: childScopes,\n\t\t\t\tinherited: mergePrincipalSets(inherited, transitiveReqsOf(item.rootPrincipalSets)),\n\t\t\t\tdepth: depth + 1\n\t\t\t};\n\t\t\tconst previous = outgoing.get(childKey);\n\t\t\toutgoing.set(childKey, previous === void 0 ? contribution : mergeContributions(previous, contribution));\n\t\t}\n\t\treturn outgoing;\n\t}\n\t_createRootNode() {\n\t\treturn {\n\t\t\tkey: ROOT_NODE_KEY,\n\t\t\ttarget: this._options.rootTarget,\n\t\t\tparents: /* @__PURE__ */ new Map(),\n\t\t\tscopes: [...this._initialScopes],\n\t\t\tinherited: [],\n\t\t\tdepth: 0,\n\t\t\tlistings: [],\n\t\t\toutgoing: /* @__PURE__ */ new Map(),\n\t\t\tloaded: false,\n\t\t\tloading: false,\n\t\t\treloadRequested: false,\n\t\t\tstate: \"unexplored\"\n\t\t};\n\t}\n\t_createNode(key) {\n\t\treturn {\n\t\t\tkey,\n\t\t\ttarget: key.slice(2),\n\t\t\tparents: /* @__PURE__ */ new Map(),\n\t\t\tscopes: [],\n\t\t\tinherited: [],\n\t\t\tdepth: Number.POSITIVE_INFINITY,\n\t\t\tlistings: [],\n\t\t\toutgoing: /* @__PURE__ */ new Map(),\n\t\t\tloaded: false,\n\t\t\tloading: false,\n\t\t\treloadRequested: false,\n\t\t\tstate: \"unexplored\"\n\t\t};\n\t}\n\tasync _updateNodeFromParents(node, previous = this._nodeReport(node)) {\n\t\tif (node.key === ROOT_NODE_KEY || node.parents.size === 0) return;\n\t\tconst { scopes, inherited, depth } = this._derivedNodeState(node);\n\t\tif (!(scopesKey(scopes) !== scopesKey(node.scopes) || principalSetsKey(inherited) !== principalSetsKey(node.inherited) || depth !== node.depth)) return;\n\t\tnode.scopes = scopes;\n\t\tnode.inherited = inherited;\n\t\tnode.depth = depth;\n\t\tthis._emitNodeUpdated(node, previous, \"referral\");\n\t\tawait this._loadNode(node);\n\t}\n\t_deriveNodeFromParents(node) {\n\t\tconst derived = this._derivedNodeState(node);\n\t\tnode.scopes = derived.scopes;\n\t\tnode.inherited = derived.inherited;\n\t\tnode.depth = derived.depth;\n\t}\n\t_derivedNodeState(node) {\n\t\tconst contributions = [...node.parents.values()];\n\t\treturn {\n\t\t\tscopes: normalizeServiceIdScopes(contributions.flatMap((value) => value.scopes)),\n\t\t\tinherited: mergePrincipalSets(...contributions.map((value) => value.inherited)),\n\t\t\tdepth: Math.min(...contributions.map((value) => value.depth))\n\t\t};\n\t}\n\t/**\n\t* Rebuild incoming contributions from the root seed. Starting with no\n\t* non-root contributions computes the least fixed point, so a disconnected\n\t* or narrowed cycle cannot keep scopes contributed by its previous state.\n\t*/\n\tasync _reconcileScopesFromRoot() {\n\t\tconst maxRounds = Math.max(16, (this._nodes.size + (Number.isFinite(this._maxDepth) ? this._maxDepth : 256)) * 4);\n\t\tfor (let round = 0; round < maxRounds; round++) {\n\t\t\tconst computed = this._computeScopeFixedPoint();\n\t\t\tlet relisted = false;\n\t\t\tconst ordered = [...computed.states.entries()].sort(([, left], [, right]) => left.depth - right.depth);\n\t\t\tfor (const [key, state] of ordered) {\n\t\t\t\tif (key === ROOT_NODE_KEY) {\n\t\t\t\t\tconst root = this._nodes.get(ROOT_NODE_KEY);\n\t\t\t\t\troot.outgoing = computed.outgoing.get(key) ?? /* @__PURE__ */ new Map();\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tlet node = this._nodes.get(key);\n\t\t\t\tif (node === void 0) {\n\t\t\t\t\tnode = this._createNode(key);\n\t\t\t\t\tnode.parents = computed.parents.get(key) ?? /* @__PURE__ */ new Map();\n\t\t\t\t\tnode.scopes = state.scopes;\n\t\t\t\t\tnode.inherited = state.inherited;\n\t\t\t\t\tnode.depth = state.depth;\n\t\t\t\t\tnode.outgoing = computed.outgoing.get(key) ?? /* @__PURE__ */ new Map();\n\t\t\t\t\tthis._nodes.set(key, node);\n\t\t\t\t\tthis._emitNodeAdded(node);\n\t\t\t\t\tawait this._loadNode(node, false);\n\t\t\t\t\trelisted = true;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst parents = computed.parents.get(key) ?? /* @__PURE__ */ new Map();\n\t\t\t\tconst scopesChanged = scopesKey(node.scopes) !== scopesKey(state.scopes);\n\t\t\t\tconst inheritedChanged = principalSetsKey(node.inherited) !== principalSetsKey(state.inherited);\n\t\t\t\tconst depthChanged = node.depth !== state.depth;\n\t\t\t\tconst parentsChanged = parentContributionsKey(node.parents) !== parentContributionsKey(parents);\n\t\t\t\tconst previous = scopesChanged || inheritedChanged || depthChanged || parentsChanged ? this._nodeReport(node) : void 0;\n\t\t\t\tnode.parents = parents;\n\t\t\t\tnode.scopes = state.scopes;\n\t\t\t\tnode.inherited = state.inherited;\n\t\t\t\tnode.depth = state.depth;\n\t\t\t\tnode.outgoing = computed.outgoing.get(key) ?? /* @__PURE__ */ new Map();\n\t\t\t\tif (previous !== void 0) this._emitNodeUpdated(node, previous, \"referral\");\n\t\t\t\tif (scopesChanged) {\n\t\t\t\t\tawait this._loadNode(node, false);\n\t\t\t\t\trelisted = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst unreachable = [...this._nodes.values()].filter((node) => !computed.states.has(node.key)).sort((a, b) => b.depth - a.depth || a.key.localeCompare(b.key));\n\t\t\tfor (const node of unreachable) {\n\t\t\t\tconst previous = this._nodeReport(node);\n\t\t\t\tthis._stopWatch(node, false);\n\t\t\t\tthis._nodes.delete(node.key);\n\t\t\t\tthis._emitNodeRemoved(previous);\n\t\t\t}\n\t\t\tif (!relisted) return;\n\t\t}\n\t\tthrow new Error(\"Hub directory scope reconciliation did not converge\");\n\t}\n\t_computeScopeFixedPoint() {\n\t\tconst states = /* @__PURE__ */ new Map();\n\t\tconst parents = /* @__PURE__ */ new Map();\n\t\tconst outgoing = /* @__PURE__ */ new Map();\n\t\tstates.set(ROOT_NODE_KEY, {\n\t\t\tscopes: [...this._initialScopes],\n\t\t\tinherited: [],\n\t\t\tdepth: 0\n\t\t});\n\t\tparents.set(ROOT_NODE_KEY, /* @__PURE__ */ new Map());\n\t\tconst queue = [ROOT_NODE_KEY];\n\t\tconst processed = /* @__PURE__ */ new Map();\n\t\twhile (queue.length > 0) {\n\t\t\tconst key = queue.shift();\n\t\t\tconst state = states.get(key);\n\t\t\tif (state === void 0) continue;\n\t\t\tconst stateKey = derivedStateKey(state);\n\t\t\tif (processed.get(key) === stateKey) continue;\n\t\t\tprocessed.set(key, stateKey);\n\t\t\tconst node = this._nodes.get(key);\n\t\t\tconst next = node === void 0 ? /* @__PURE__ */ new Map() : this._outgoingFor(state.scopes, state.inherited, state.depth, node.listings);\n\t\t\toutgoing.set(key, next);\n\t\t\tfor (const [childKey, contribution] of next) {\n\t\t\t\tconst childParents = parents.get(childKey) ?? /* @__PURE__ */ new Map();\n\t\t\t\tchildParents.set(key, contribution);\n\t\t\t\tparents.set(childKey, childParents);\n\t\t\t\tconst childState = derivedStateFromParents(childParents);\n\t\t\t\tconst oldState = states.get(childKey);\n\t\t\t\tif (oldState === void 0 || derivedStateKey(oldState) !== derivedStateKey(childState)) {\n\t\t\t\t\tstates.set(childKey, childState);\n\t\t\t\t\tqueue.push(childKey);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tstates,\n\t\t\tparents,\n\t\t\toutgoing\n\t\t};\n\t}\n\tasync _pruneUnreachable() {\n\t\tconst reachable = /* @__PURE__ */ new Set();\n\t\tconst queue = [ROOT_NODE_KEY];\n\t\twhile (queue.length > 0) {\n\t\t\tconst key = queue.shift();\n\t\t\tif (reachable.has(key)) continue;\n\t\t\treachable.add(key);\n\t\t\tconst node = this._nodes.get(key);\n\t\t\tif (node === void 0) continue;\n\t\t\tfor (const childKey of node.outgoing.keys()) queue.push(childKey);\n\t\t}\n\t\tconst removedNodes = [...this._nodes.values()].filter((node) => !reachable.has(node.key)).sort((a, b) => b.depth - a.depth || a.key.localeCompare(b.key));\n\t\tif (removedNodes.length === 0) return;\n\t\tconst removed = new Set(removedNodes.map((node) => node.key));\n\t\tfor (const node of removedNodes) {\n\t\t\tconst previous = this._nodeReport(node);\n\t\t\tthis._stopWatch(node, false);\n\t\t\tthis._nodes.delete(node.key);\n\t\t\tthis._emitNodeRemoved(previous);\n\t\t}\n\t\tfor (const node of this._nodes.values()) {\n\t\t\tconst previous = this._nodeReport(node);\n\t\t\tlet changed = false;\n\t\t\tfor (const parentKey of removed) changed = node.parents.delete(parentKey) || changed;\n\t\t\tif (changed) await this._updateNodeFromParents(node, previous);\n\t\t}\n\t}\n\t/**\n\t* Every changed watch scope uses list/watch/list: callers reach this method\n\t* only after a list under the current scope, then the replacement watch is\n\t* installed before a verification list. Either the verification sees a\n\t* handoff mutation or the new watch ticks for it.\n\t*/\n\tasync _synchronizeWatches() {\n\t\tconst maxPasses = Math.max(8, this._nodes.size * 4);\n\t\tfor (let pass = 0; pass < maxPasses && !this._disposed; pass++) {\n\t\t\tconst pending = [...this._nodes.values()].filter((node) => node.watch === void 0 || node.watchScopesKey !== scopesKey(node.scopes)).sort((a, b) => a.depth - b.depth || a.key.localeCompare(b.key));\n\t\t\tif (pending.length === 0) return;\n\t\t\tlet installed = false;\n\t\t\tfor (const node of pending) {\n\t\t\t\tif (this._nodes.get(node.key) !== node) continue;\n\t\t\t\tinstalled = this._replaceWatch(node) || installed;\n\t\t\t\tif (node.watchScopesKey === scopesKey(node.scopes)) {\n\t\t\t\t\tawait this._loadNode(node);\n\t\t\t\t\tawait this._reconcileScopesFromRoot();\n\t\t\t\t\tawait this._pruneUnreachable();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!installed) return;\n\t\t}\n\t\tthrow new Error(\"Hub directory watch synchronization did not converge\");\n\t}\n\t_replaceWatch(node) {\n\t\tif (!this._watching || this._disposed) return false;\n\t\tconst method = node.target === void 0 ? \"hubrpc.directory::watch\" : `${node.target}::hubrpc.directory::watch`;\n\t\tconst params = { serviceIdScopes: [...node.scopes] };\n\t\tlet call;\n\t\ttry {\n\t\t\tcall = this._channel.sendRequestWithStream(method, params, { onStreamMessage: () => this._queueTick(node.key) });\n\t\t} catch (error) {\n\t\t\tthis._options.log?.(`hub directory watch(${node.target ?? \"<root>\"}) failed: ${errorMessage(error)}`);\n\t\t\tthis._scheduleWatchRetry(node);\n\t\t\treturn false;\n\t\t}\n\t\tconst previous = this._nodeReport(node);\n\t\tconst oldWatch = node.watch;\n\t\tnode.watch = call;\n\t\tnode.watchScopesKey = scopesKey(node.scopes);\n\t\tthis._emitNodeUpdated(node, previous, \"watch-started\");\n\t\tif (oldWatch !== void 0) try {\n\t\t\toldWatch.cancel(\"directory explorer watch scope replaced\");\n\t\t} catch {}\n\t\tcall.result.then(() => {\n\t\t\tif (this._disposed || node.watch !== call) return;\n\t\t\tconst previous = this._nodeReport(node);\n\t\t\tnode.watch = void 0;\n\t\t\tnode.watchScopesKey = void 0;\n\t\t\tthis._emitNodeUpdated(node, previous, \"watch-ended\");\n\t\t\tthis._scheduleWatchRetry(node);\n\t\t}, (error) => {\n\t\t\tif (this._disposed || node.watch !== call) return;\n\t\t\tconst previous = this._nodeReport(node);\n\t\t\tnode.watch = void 0;\n\t\t\tnode.watchScopesKey = void 0;\n\t\t\tthis._options.log?.(`hub directory watch(${node.target ?? \"<root>\"}) ended: ${errorMessage(error)}`);\n\t\t\tthis._emitNodeUpdated(node, previous, \"watch-ended\");\n\t\t\tthis._scheduleWatchRetry(node);\n\t\t});\n\t\treturn true;\n\t}\n\t_queueTick(key) {\n\t\tif (this._disposed || !this._nodes.has(key)) return;\n\t\tthis._watchRetryDelays.delete(key);\n\t\tthis._pendingTicks.add(key);\n\t\tthis._startReconciliation();\n\t\tthis._work = this._work.then(async () => {\n\t\t\twhile (this._pendingTicks.size > 0 && !this._disposed) {\n\t\t\t\tconst nextKey = this._pendingTicks.values().next().value;\n\t\t\t\tthis._pendingTicks.delete(nextKey);\n\t\t\t\tconst node = this._nodes.get(nextKey);\n\t\t\t\tif (node === void 0) continue;\n\t\t\t\tawait this._loadNode(node);\n\t\t\t\tawait this._reconcileScopesFromRoot();\n\t\t\t\tawait this._pruneUnreachable();\n\t\t\t\tawait this._synchronizeWatches();\n\t\t\t\tconst change = {\n\t\t\t\t\ttarget: node.target,\n\t\t\t\t\tresult: this.result\n\t\t\t\t};\n\t\t\t\tfor (const listener of [...this._listeners]) try {\n\t\t\t\t\tlistener(change);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis._options.log?.(`hub directory change listener failed: ${errorMessage(error)}`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis._settle();\n\t\t}).catch((error) => {\n\t\t\tthis._options.log?.(`hub directory reconciliation failed: ${errorMessage(error)}`);\n\t\t\tthis._settle();\n\t\t});\n\t}\n\t_stopWatch(node, emit = true) {\n\t\tthis._clearWatchRetry(node.key);\n\t\tconst watch = node.watch;\n\t\tif (watch === void 0) return;\n\t\tconst previous = emit ? this._nodeReport(node) : void 0;\n\t\tnode.watch = void 0;\n\t\tnode.watchScopesKey = void 0;\n\t\ttry {\n\t\t\twatch.cancel(\"directory explorer watch stopped\");\n\t\t} catch {}\n\t\tif (previous !== void 0) this._emitNodeUpdated(node, previous, \"watch-stopped\");\n\t}\n\t_stopAllWatches(emit = true) {\n\t\tfor (const node of this._nodes.values()) this._stopWatch(node, emit);\n\t\tfor (const key of [...this._watchRetryTimers.keys()]) this._clearWatchRetry(key);\n\t}\n\t_scheduleWatchRetry(node) {\n\t\tif (!this._watching || this._disposed || this._nodes.get(node.key) !== node || this._watchRetryTimers.has(node.key)) return;\n\t\tconst delay = this._watchRetryDelays.get(node.key) ?? 200;\n\t\tthis._watchRetryDelays.set(node.key, Math.min(5e3, delay * 2));\n\t\tconst timer = setTimeout(() => {\n\t\t\tthis._watchRetryTimers.delete(node.key);\n\t\t\tif (!this._watching || this._disposed || this._nodes.get(node.key) !== node || node.watch !== void 0) return;\n\t\t\tthis._startReconciliation();\n\t\t\tthis._work = this._work.then(async () => {\n\t\t\t\tawait this._synchronizeWatches();\n\t\t\t\tthis._settle();\n\t\t\t}).catch((error) => {\n\t\t\t\tthis._options.log?.(`hub directory watch retry failed: ${errorMessage(error)}`);\n\t\t\t\tthis._settle();\n\t\t\t\tthis._scheduleWatchRetry(node);\n\t\t\t});\n\t\t}, delay);\n\t\tthis._watchRetryTimers.set(node.key, timer);\n\t}\n\t_clearWatchRetry(key) {\n\t\tconst timer = this._watchRetryTimers.get(key);\n\t\tif (timer !== void 0) clearTimeout(timer);\n\t\tthis._watchRetryTimers.delete(key);\n\t\tthis._watchRetryDelays.delete(key);\n\t}\n\t_clearNodes() {\n\t\tthis._stopAllWatches(false);\n\t\tthis._nodes.clear();\n\t\tthis._unlockAttempted.clear();\n\t\tthis._pendingTicks.clear();\n\t\tthis._initialized = false;\n\t}\n\t_resetForExplore() {\n\t\tthis._complete = false;\n\t\tthis._emitSnapshot(\"reset\");\n\t\tthis._stopAllWatches(false);\n\t\tconst addressed = [...this._nodes.values()].filter((node) => node.key !== ROOT_NODE_KEY).sort((a, b) => b.depth - a.depth || a.key.localeCompare(b.key));\n\t\tfor (const node of addressed) {\n\t\t\tconst previous = this._nodeReport(node);\n\t\t\tthis._nodes.delete(node.key);\n\t\t\tthis._emitNodeRemoved(previous, \"reset\");\n\t\t}\n\t\tconst previousRoot = this._nodes.get(ROOT_NODE_KEY);\n\t\tconst root = this._createRootNode();\n\t\tthis._nodes.set(ROOT_NODE_KEY, root);\n\t\tif (previousRoot !== void 0) this._emitNodeUpdated(root, this._nodeReport(previousRoot), \"reset\");\n\t\tthis._unlockAttempted.clear();\n\t\tthis._pendingTicks.clear();\n\t\tthis._initialized = false;\n\t}\n\t_updateNode(node, reason, update) {\n\t\tconst previous = this._nodeReport(node);\n\t\tupdate();\n\t\tthis._emitNodeUpdated(node, previous, reason);\n\t}\n\t_nodeReport(node) {\n\t\tconst parents = [...node.parents.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([parentKey, contribution]) => ({\n\t\t\ttarget: this._targetForKey(parentKey),\n\t\t\tscopes: cloneScopes(contribution.scopes),\n\t\t\tdepth: contribution.depth\n\t\t}));\n\t\treturn {\n\t\t\ttarget: this._targetForKey(node.key),\n\t\t\tstate: node.state,\n\t\t\teffectiveScopes: cloneScopes(node.scopes),\n\t\t\tdepth: node.depth,\n\t\t\tparents,\n\t\t\tnativeListings: node.listings.map(cloneListing),\n\t\t\t...node.inaccessibleReason === void 0 ? {} : { inaccessibleReason: node.inaccessibleReason },\n\t\t\twatching: node.watch !== void 0\n\t\t};\n\t}\n\t_targetForKey(key) {\n\t\tif (key === ROOT_NODE_KEY) return this._options.rootTarget === void 0 ? { kind: \"root\" } : {\n\t\t\tkind: \"root\",\n\t\t\tserviceId: this._options.rootTarget\n\t\t};\n\t\treturn {\n\t\t\tkind: \"addressed\",\n\t\t\tserviceId: key.slice(2)\n\t\t};\n\t}\n\t_emitNodeAdded(node) {\n\t\tthis._revision++;\n\t\tthis._emitGraphEvent({\n\t\t\ttype: \"node-added\",\n\t\t\treason: \"referral\",\n\t\t\tnode: this._nodeReport(node),\n\t\t\tsnapshot: this.graphSnapshot\n\t\t});\n\t}\n\t_emitNodeUpdated(node, previous, reason) {\n\t\tthis._revision++;\n\t\tthis._emitGraphEvent({\n\t\t\ttype: \"node-updated\",\n\t\t\treason,\n\t\t\tprevious,\n\t\t\tnode: this._nodeReport(node),\n\t\t\tsnapshot: this.graphSnapshot\n\t\t});\n\t}\n\t_emitNodeRemoved(previous, reason = \"unreachable\") {\n\t\tthis._revision++;\n\t\tthis._emitGraphEvent({\n\t\t\ttype: \"node-removed\",\n\t\t\treason,\n\t\t\tprevious,\n\t\t\tsnapshot: this.graphSnapshot\n\t\t});\n\t}\n\t_startReconciliation() {\n\t\tif (!this._complete) return;\n\t\tthis._complete = false;\n\t\tthis._emitSnapshot(\"reconciliation-started\");\n\t}\n\t_settle() {\n\t\tif (this._complete || this._disposed) return;\n\t\tthis._complete = true;\n\t\tthis._revision++;\n\t\tthis._emitGraphEvent({\n\t\t\ttype: \"settled\",\n\t\t\tsnapshot: this.graphSnapshot\n\t\t});\n\t}\n\t_emitSnapshot(reason) {\n\t\tthis._revision++;\n\t\tthis._emitGraphEvent({\n\t\t\ttype: \"snapshot\",\n\t\t\treason,\n\t\t\tsnapshot: this.graphSnapshot\n\t\t});\n\t}\n\t_emitGraphEvent(event) {\n\t\tfor (const listener of this._graphListeners) this._deliverGraphEvent(listener, event);\n\t}\n\t_deliverGraphEvent(listener, event) {\n\t\ttry {\n\t\t\tlistener(event);\n\t\t} catch (error) {\n\t\t\tthis._options.log?.(`hub directory graph listener failed: ${errorMessage(error)}`);\n\t\t}\n\t}\n\t_nodeKeyForTarget(target) {\n\t\tconst isImplicitRoot = this._options.rootTarget === void 0 && target === \"\";\n\t\treturn target === this._options.rootTarget || isImplicitRoot ? ROOT_NODE_KEY : `s:${target}`;\n\t}\n\t_throwIfDisposed() {\n\t\tif (this._disposed) throw new Error(\"HubDirectoryExplorer is disposed\");\n\t}\n};\nfunction mergeContributions(left, right) {\n\treturn {\n\t\tscopes: normalizeServiceIdScopes([...left.scopes, ...right.scopes]),\n\t\tinherited: mergePrincipalSets(left.inherited, right.inherited),\n\t\tdepth: Math.min(left.depth, right.depth)\n\t};\n}\nfunction derivedStateFromParents(parents) {\n\tconst contributions = [...parents.values()];\n\treturn {\n\t\tscopes: normalizeServiceIdScopes(contributions.flatMap((value) => value.scopes)),\n\t\tinherited: mergePrincipalSets(...contributions.map((value) => value.inherited)),\n\t\tdepth: Math.min(...contributions.map((value) => value.depth))\n\t};\n}\nfunction derivedStateKey(state) {\n\treturn `${scopesKey(state.scopes)}\\u0001${principalSetsKey(state.inherited)}\\u0001${state.depth}`;\n}\nfunction parentContributionsKey(parents) {\n\treturn [...parents.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([key, contribution]) => `${key}\\u0002${derivedStateKey(contribution)}`).join(\"\u0003\");\n}\nfunction mergePrincipalSets(...groups) {\n\tconst unique = /* @__PURE__ */ new Map();\n\tfor (const group of groups) for (const set of group ?? []) {\n\t\tconst copy = set.map((requirement) => ({ ...requirement }));\n\t\tconst key = JSON.stringify(copy);\n\t\tif (!unique.has(key)) unique.set(key, copy);\n\t}\n\treturn [...unique.values()];\n}\nfunction principalSetsKey(sets) {\n\treturn JSON.stringify(sets);\n}\nfunction listingKey(item) {\n\treturn `${item.serviceId}\\u0000${item.interfaceId}\\u0000${item.hash}`;\n}\nfunction cloneScopes(scopes) {\n\treturn scopes.map((scope) => ({ ...scope }));\n}\nfunction cloneListing(item) {\n\treturn {\n\t\t...item,\n\t\t...item.tags === void 0 ? {} : { tags: [...item.tags] },\n\t\t...item.rootPrincipalSets === void 0 ? {} : { rootPrincipalSets: item.rootPrincipalSets.map((set) => set.map((requirement) => ({ ...requirement }))) },\n\t\t...item.reachableServiceIds === void 0 ? {} : { reachableServiceIds: cloneScopes(item.reachableServiceIds) }\n\t};\n}\nfunction errorMessage(error) {\n\treturn error instanceof Error ? error.message : String(error);\n}\n/**\n* Extract the `transitive` requirements of a CNF requirement collection as\n* singleton AND-sets (kept transitive), so they keep flowing down further hops.\n*/\nfunction transitiveReqsOf(sets) {\n\treturn (sets ?? []).flatMap((set) => set.filter((req) => req.transitive === true)).map((req) => [req]);\n}\n/**\n* Prefer a listing whose reporter (`discoveredFrom`) equals its own `serviceId`\n* — that's the participant speaking about itself, and is more authoritative\n* than an aggregator forwarding it.\n*/\nfunction _isAuthoritative(candidate, current) {\n\tconst candidateDirect = candidate.discoveredFrom === candidate.serviceId;\n\tconst currentDirect = current.discoveredFrom === current.serviceId;\n\treturn candidateDirect && !currentDirect;\n}\n//#endregion\n//#region src/connection/channel.ts\nvar Channel = class Channel {\n\tsender;\n\t_setHandler;\n\t_setWireObserver;\n\tconstructor(sender, _setHandler, _setWireObserver) {\n\t\tthis.sender = sender;\n\t\tthis._setHandler = _setHandler;\n\t\tthis._setWireObserver = _setWireObserver;\n\t}\n\t/** Bind the inbound request/notification handler. May be called before or after construction of {@link LinkRpcConnection}. */\n\tsetRequestHandler(handler) {\n\t\tthis._setHandler(handler);\n\t}\n\t/**\n\t* Install the endpoint inspection observer at the JSON-RPC wire boundary.\n\t* Intended for {@link LinkRpcConnection}; ordinary consumers should use the\n\t* public `hubrpc.traffic` service instead.\n\t*/\n\tsetWireMessageObserver(observer) {\n\t\tthis._setWireObserver?.(observer);\n\t}\n\t/**\n\t* Compose this channel with a sender-side decorator (typically the\n\t* signing layer). The decorator wraps {@link sender} only; the\n\t* {@link setRequestHandler} binding is shared with the original channel\n\t* so the receive side is bound exactly once regardless of decoration depth.\n\t*/\n\twithSender(decorate) {\n\t\treturn new Channel(decorate(this.sender), this._setHandler, this._setWireObserver);\n\t}\n};\nvar RpcError = class extends Error {\n\tcode;\n\torigin;\n\tdata;\n\thasData;\n\tconstructor(message, code, data, origin = \"local\", hasData = data !== void 0) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t\tthis.origin = origin;\n\t\tthis.message = message;\n\t\tthis.name = \"RpcError\";\n\t\tthis.hasData = hasData;\n\t\tif (hasData) this.data = data;\n\t}\n};\n//#endregion\n//#region src/connection/jsonRpcChannel.ts\n/**\n* How often a streaming-enabled call emits a `toCallee` keepalive ping so a\n* routing hub's per-request idle timer never reaps the in-flight request.\n* Must stay comfortably below the hub's idle timeout (default 30 min).\n*/\nconst KEEPALIVE_PING_INTERVAL_MS = 6e5;\n/**\n* Minimal JSON-RPC 2.0 channel: correlates requests with responses,\n* dispatches incoming requests/notifications to a handler.\n*\n* Construct via {@link JsonRpcChannel.create}: it returns a\n* {@link Channel} factory which materialises the live channel once a\n* handler is supplied via `.connect(handler)`. The handler is fixed for\n* the channel's lifetime — no setter, no mid-flight swap.\n*\n* The outbound `TOutCtx` of the produced sender is `unknown` — this\n* channel ignores per-call ctx entirely. Decorators (e.g.\n* `SigningSender`) lift it to a concrete shape.\n*/\nvar JsonRpcChannel = class JsonRpcChannel {\n\t_transport;\n\t_requestsDeferred;\n\t/**\n\t* Wrap a transport in a {@link Channel}. The channel's sender is live\n\t* immediately; call {@link Channel.setRequestHandler} (or pass the channel\n\t* to {@link LinkRpcConnection}) to bind the inbound handler.\n\t*/\n\tstatic create(transport) {\n\t\treturn this.createWithClose(transport).channel;\n\t}\n\t/**\n\t* Wrap a transport with lifecycle hooks. deferRequests queues requests,\n\t* notifications, and their input streams until resumeRequests is called.\n\t* Responses and output streams remain live for setup-time outbound calls.\n\t*/\n\tstatic createWithClose(transport, options = {}) {\n\t\tconst jrc = new JsonRpcChannel(transport, options.deferRequests === true);\n\t\treturn {\n\t\t\tchannel: new Channel(jrc, (h) => jrc.setRequestHandler(h), (observer) => jrc.setWireMessageObserver(observer)),\n\t\t\tclose: () => jrc.close(),\n\t\t\tresumeRequests: () => jrc.resumeRequests()\n\t\t};\n\t}\n\t_nextId = 1;\n\t_pending = /* @__PURE__ */ new Map();\n\t/**\n\t* Per-request callbacks invoked when a {@link STREAM_METHOD}\n\t* notification arrives with a matching `requestId`. Used in both\n\t* directions: outgoing-request callers register here keyed by the\n\t* id they sent; per-call incoming-request stream handles register\n\t* keyed by the id they observed. Entries are removed when the\n\t* corresponding request completes (response received for outgoing,\n\t* response sent for incoming).\n\t*/\n\t_streamListeners = /* @__PURE__ */ new Map();\n\t/**\n\t* Per-incoming-request handlers for reserved `control` messages\n\t* (cancel / ping / pong) arriving as stream notifications. Keyed\n\t* by the id observed; removed when the request settles.\n\t*/\n\t_streamControl = /* @__PURE__ */ new Map();\n\t_incomingAborts = /* @__PURE__ */ new Map();\n\t_handler;\n\t_wireObserver;\n\t_closeError;\n\t_deferredMessages = [];\n\tsetRequestHandler(handler) {\n\t\tthis._handler = handler;\n\t}\n\tsetWireMessageObserver(observer) {\n\t\tthis._wireObserver = observer;\n\t}\n\tconstructor(_transport, _requestsDeferred) {\n\t\tthis._transport = _transport;\n\t\tthis._requestsDeferred = _requestsDeferred;\n\t\tthis._transport.setListener((m) => this._onMessage(m));\n\t}\n\tresumeRequests() {\n\t\twhile (this._deferredMessages.length > 0) this._dispatchMessage(this._deferredMessages.shift());\n\t\tthis._requestsDeferred = false;\n\t}\n\tasync sendRequest(method, params, opts) {\n\t\tthis._throwIfClosed();\n\t\tconst id = this._nextId++;\n\t\tconst req = {\n\t\t\tjsonrpc: \"2.0\",\n\t\t\tid,\n\t\t\tmethod\n\t\t};\n\t\tif (params !== void 0) req.params = params;\n\t\tconst promise = new Promise((resolve, reject) => {\n\t\t\tthis._pending.set(String(id), {\n\t\t\t\tresolve,\n\t\t\t\treject\n\t\t\t});\n\t\t});\n\t\tthis._observeOutbound(req, opts);\n\t\ttry {\n\t\t\tawait this._transport.send(req);\n\t\t} catch (error) {\n\t\t\tthis._pending.delete(String(id));\n\t\t\tthis._observeSendFailure(id, error);\n\t\t\tthrow error;\n\t\t}\n\t\treturn promise;\n\t}\n\tasync sendNotification(method, params, opts) {\n\t\tthis._throwIfClosed();\n\t\tconst n = {\n\t\t\tjsonrpc: \"2.0\",\n\t\t\tmethod\n\t\t};\n\t\tif (params !== void 0) n.params = params;\n\t\tthis._observeOutbound(n, opts);\n\t\tawait this._transport.send(n);\n\t}\n\tsendRequestWithStream(method, params, opts) {\n\t\tthis._throwIfClosed();\n\t\tconst id = this._nextId++;\n\t\tconst key = String(id);\n\t\tlet resolveResult;\n\t\tlet rejectResult;\n\t\tconst result = new Promise((resolve, reject) => {\n\t\t\tresolveResult = resolve;\n\t\t\trejectResult = reject;\n\t\t});\n\t\tthis._pending.set(key, {\n\t\t\tresolve: resolveResult,\n\t\t\treject: rejectResult\n\t\t});\n\t\tif (opts?.onStreamMessage) this._streamListeners.set(key, opts.onStreamMessage);\n\t\tconst pinger = this._makePinger(id, StreamDir.toCallee);\n\t\tthis._streamControl.set(key, pinger.onControl);\n\t\tconst ping = setInterval(() => {\n\t\t\tthis._sendStream(id, StreamDir.toCallee, { control: { type: StreamControlType.ping } });\n\t\t}, KEEPALIVE_PING_INTERVAL_MS);\n\t\tping.unref?.();\n\t\tconst stopPing = () => {\n\t\t\tclearInterval(ping);\n\t\t\tpinger.dispose();\n\t\t\tthis._streamControl.delete(key);\n\t\t};\n\t\tconst dispose = (reason = \"streaming request disposed\") => {\n\t\t\tif (!this._pending.delete(key)) return;\n\t\t\tthis._streamListeners.delete(key);\n\t\t\tstopPing();\n\t\t\trejectResult(new RpcError(reason, ErrorCode.cancelled));\n\t\t};\n\t\tresult.then(stopPing, stopPing);\n\t\t(async () => {\n\t\t\tconst req = {\n\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\tid,\n\t\t\t\tmethod\n\t\t\t};\n\t\t\tif (params !== void 0) req.params = params;\n\t\t\tthis._observeOutbound(req, opts);\n\t\t\tawait this._transport.send(req);\n\t\t})().catch((err) => {\n\t\t\tthis._pending.delete(key);\n\t\t\tthis._streamListeners.delete(key);\n\t\t\tthis._observeSendFailure(id, err);\n\t\t\tstopPing();\n\t\t\trejectResult(err instanceof Error ? err : new Error(String(err)));\n\t\t});\n\t\treturn {\n\t\t\tresult,\n\t\t\tsend: (payload) => this._sendStream(id, StreamDir.toCallee, { payload }),\n\t\t\tcancel: (reason) => this._sendStream(id, StreamDir.toCallee, { control: reason !== void 0 ? {\n\t\t\t\ttype: StreamControlType.cancel,\n\t\t\t\treason\n\t\t\t} : { type: StreamControlType.cancel } }),\n\t\t\tdispose,\n\t\t\tping: pinger.ping\n\t\t};\n\t}\n\t/**\n\t* Build the symmetric ping/pong machinery for one in-flight request.\n\t*\n\t* `outboundDir` is the direction *this* side emits controls in\n\t* (`toCallee` for the caller, `toCaller` for the callee). A received\n\t* ping is answered with a pong in that same direction, echoing the\n\t* ping's nonce; a received pong resolves the matching outstanding\n\t* {@link ping} probe.\n\t*/\n\t_makePinger(requestId, outboundDir) {\n\t\tconst pending = /* @__PURE__ */ new Map();\n\t\tlet nextNonce = 1;\n\t\tconst ping = () => {\n\t\t\tconst nonce = `${requestId}:${nextNonce++}`;\n\t\t\tconst p = new Promise((resolve, reject) => pending.set(nonce, {\n\t\t\t\tresolve,\n\t\t\t\treject\n\t\t\t}));\n\t\t\tthis._sendStream(requestId, outboundDir, { control: {\n\t\t\t\ttype: StreamControlType.ping,\n\t\t\t\tnonce\n\t\t\t} });\n\t\t\treturn p;\n\t\t};\n\t\tconst onControl = (control) => {\n\t\t\tif (control.type === StreamControlType.ping) this._sendStream(requestId, outboundDir, { control: {\n\t\t\t\ttype: StreamControlType.pong,\n\t\t\t\tnonce: control.nonce\n\t\t\t} });\n\t\t\telse if (control.type === StreamControlType.pong && control.nonce !== void 0) {\n\t\t\t\tconst waiter = pending.get(control.nonce);\n\t\t\t\tif (waiter) {\n\t\t\t\t\tpending.delete(control.nonce);\n\t\t\t\t\twaiter.resolve();\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tconst dispose = () => {\n\t\t\tconst err = new RpcError(\"Request settled before pong\", ErrorCode.cancelled);\n\t\t\tfor (const w of pending.values()) w.reject(err);\n\t\t\tpending.clear();\n\t\t};\n\t\treturn {\n\t\t\tping,\n\t\t\tonControl,\n\t\t\tdispose\n\t\t};\n\t}\n\t/**\n\t* Emit a stream notification ({@link STREAM_METHOD}) associated with\n\t* an in-flight request. Internal: outgoing-side callers reach this\n\t* via {@link RawStreamingCall.send} / `cancel`; incoming-side handlers\n\t* reach it via {@link IncomingStream.send}.\n\t*/\n\tasync _sendStream(requestId, dir, fields) {\n\t\tthis._throwIfClosed();\n\t\tconst params = {\n\t\t\trequestId,\n\t\t\tdir,\n\t\t\t...fields\n\t\t};\n\t\tconst n = {\n\t\t\tjsonrpc: \"2.0\",\n\t\t\tmethod: STREAM_METHOD,\n\t\t\tparams\n\t\t};\n\t\tthis._observeOutbound(n);\n\t\tawait this._transport.send(n);\n\t}\n\tclose() {\n\t\tif (this._closeError) return;\n\t\tconst error = new RpcError(\"Connection closed\", ErrorCode.peerDisconnected);\n\t\tthis._closeError = error;\n\t\tthis._deferredMessages.length = 0;\n\t\tfor (const abort of this._incomingAborts.values()) abort.abort(error);\n\t\tthis._incomingAborts.clear();\n\t\tthis._transport.dispose();\n\t\tfor (const p of this._pending.values()) p.reject(error);\n\t\tthis._pending.clear();\n\t\tthis._streamListeners.clear();\n\t\tthis._streamControl.clear();\n\t}\n\t_throwIfClosed() {\n\t\tif (this._closeError) throw this._closeError;\n\t}\n\t_onMessage(m) {\n\t\tthis._observeInbound(m);\n\t\tif (this._requestsDeferred && !isResponse(m) && !(isNotification(m) && m.method === STREAM_METHOD && m.params?.dir === StreamDir.toCaller)) {\n\t\t\tthis._deferredMessages.push(m);\n\t\t\treturn;\n\t\t}\n\t\tthis._dispatchMessage(m);\n\t}\n\t_dispatchMessage(m) {\n\t\tconst ctx = m.context;\n\t\tif (isResponse(m)) {\n\t\t\tif (m.id === null) return;\n\t\t\tconst key = String(m.id);\n\t\t\tconst pending = this._pending.get(key);\n\t\t\tif (!pending) return;\n\t\t\tthis._pending.delete(key);\n\t\t\tthis._streamListeners.delete(key);\n\t\t\tif (\"error\" in m) {\n\t\t\t\tconst e = m.error;\n\t\t\t\tconst err = new RpcError(e.message, e.code, e.data, \"remote\", Object.hasOwn(e, \"data\"));\n\t\t\t\tpending.reject(err);\n\t\t\t} else pending.resolve(m.result);\n\t\t\treturn;\n\t\t}\n\t\tif (isRequest(m)) {\n\t\t\tthis._handleRequest(m, ctx).catch(() => {});\n\t\t\treturn;\n\t\t}\n\t\tif (isNotification(m)) {\n\t\t\tif (m.method === STREAM_METHOD) {\n\t\t\t\tthis._handleStreamNotification(m);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis._handleNotification(m, ctx);\n\t\t\treturn;\n\t\t}\n\t}\n\t_handleStreamNotification(m) {\n\t\tconst params = m.params;\n\t\tif (!params) return;\n\t\tconst requestId = params.requestId;\n\t\tif (requestId === void 0) return;\n\t\tconst key = String(requestId);\n\t\tif (params.control) {\n\t\t\tthis._streamControl.get(key)?.(params.control);\n\t\t\treturn;\n\t\t}\n\t\tconst listener = this._streamListeners.get(key);\n\t\tif (!listener) return;\n\t\tlistener(params.payload);\n\t}\n\tasync _handleRequest(m, context) {\n\t\tconst key = String(m.id);\n\t\tconst pinger = this._makePinger(m.id, StreamDir.toCaller);\n\t\tconst stream = {\n\t\t\tsend: (payload) => this._sendStream(m.id, StreamDir.toCaller, { payload }),\n\t\t\tonMessage: (listener) => {\n\t\t\t\tif (listener) this._streamListeners.set(key, listener);\n\t\t\t\telse this._streamListeners.delete(key);\n\t\t\t},\n\t\t\tping: pinger.ping\n\t\t};\n\t\tconst abort = new AbortController();\n\t\tthis._incomingAborts.set(key, abort);\n\t\tthis._streamControl.set(key, (control) => {\n\t\t\tif (control.type === StreamControlType.cancel) abort.abort(new RpcError(control.reason ?? \"cancelled\", ErrorCode.cancelled));\n\t\t\telse pinger.onControl(control);\n\t\t});\n\t\tlet result;\n\t\ttry {\n\t\t\tif (!this._handler) result = { error: {\n\t\t\t\tcode: ErrorCode.methodNotFound,\n\t\t\t\tmessage: `No handler registered on this endpoint (method: ${m.method}).`\n\t\t\t} };\n\t\t\telse try {\n\t\t\t\tresult = await this._handler.handleRequest({\n\t\t\t\t\tmethod: m.method,\n\t\t\t\t\tparams: m.params,\n\t\t\t\t\tcontext,\n\t\t\t\t\tstream,\n\t\t\t\t\tsignal: abort.signal\n\t\t\t\t});\n\t\t\t} catch (e) {\n\t\t\t\tresult = { error: {\n\t\t\t\t\tcode: ErrorCode.internalError,\n\t\t\t\t\tmessage: e instanceof Error ? e.message : String(e)\n\t\t\t\t} };\n\t\t\t}\n\t\t} finally {\n\t\t\tthis._streamListeners.delete(key);\n\t\t\tthis._streamControl.delete(key);\n\t\t\tthis._incomingAborts.delete(key);\n\t\t\tpinger.dispose();\n\t\t}\n\t\tif (\"result\" in result) {\n\t\t\tconst response = {\n\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\tid: m.id,\n\t\t\t\tresult: result.result\n\t\t\t};\n\t\t\tthis._observeOutbound(response);\n\t\t\tawait this._transport.send(response);\n\t\t} else {\n\t\t\tconst resp = {\n\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\tid: m.id,\n\t\t\t\terror: result.error\n\t\t\t};\n\t\t\tthis._observeOutbound(resp);\n\t\t\tawait this._transport.send(resp);\n\t\t}\n\t}\n\t_handleNotification(m, context) {\n\t\tif (!this._handler) return;\n\t\ttry {\n\t\t\tthis._handler.handleNotification({\n\t\t\t\tmethod: m.method,\n\t\t\t\tparams: m.params,\n\t\t\t\tcontext,\n\t\t\t\tstream: _NOOP_STREAM,\n\t\t\t\tsignal: _NEVER_ABORT\n\t\t\t});\n\t\t} catch {}\n\t}\n\t_observeInbound(message) {\n\t\tconst observer = this._wireObserver;\n\t\tif (observer === void 0) return;\n\t\tobserver(\"inbound\", message);\n\t}\n\t_observeOutbound(message, opts) {\n\t\tconst observer = this._wireObserver;\n\t\tif (observer === void 0) return;\n\t\tobserver(\"outbound\", message);\n\t}\n\t_observeSendFailure(requestId, error) {\n\t\tif (this._wireObserver === void 0) return;\n\t\tthis._observeInbound({\n\t\t\tjsonrpc: \"2.0\",\n\t\t\tid: requestId,\n\t\t\terror: {\n\t\t\t\tcode: ErrorCode.peerDisconnected,\n\t\t\t\tmessage: error instanceof Error ? error.message : String(error)\n\t\t\t}\n\t\t});\n\t}\n};\n/** Stub stream handle for notifications, which carry no request id. */\nconst _NOOP_STREAM = {\n\tsend: () => Promise.resolve(),\n\tonMessage: () => {},\n\tping: () => Promise.resolve()\n};\n/** A signal that never aborts — handed to notification handlers. */\nconst _NEVER_ABORT = new AbortController().signal;\n//#endregion\n//#region src/connection/interfaceTarget.ts\nfunction interfaceTarget(iface, options = {}) {\n\tconst serviceId = options.serviceId ?? \"\";\n\tif (serviceId.includes(\"::\") || !/^[\\x20-\\x7e]*$/.test(serviceId)) throw new Error(\"Service id must contain only printable ASCII and must not contain \\\"::\\\".\");\n\treturn Object.freeze({\n\t\tmode: \"qualified\",\n\t\tinterface: iface,\n\t\tserviceId\n\t});\n}\nfunction defaultInterfaceTarget(iface) {\n\treturn Object.freeze({\n\t\tmode: \"default\",\n\t\tinterface: iface\n\t});\n}\nfunction isInterfaceTarget(value) {\n\treturn typeof value === \"object\" && value !== null && \"interface\" in value && \"mode\" in value && (value.mode === \"qualified\" || value.mode === \"default\" || value.mode === \"bare\");\n}\n//#endregion\n//#region src/connection/linkRpcConnection.ts\n/**\n* High-level linkrpc connection. Layers method-name routing and zod-driven\n* validation on top of a plain JSON-RPC channel.\n*\n* Typed proxies built by this class merely forward each call's\n* `interfaceHash` hint to the channel so the signer stamps it into the\n* `$hubrpc` envelope.\n*\n* `TInCtx` is the per-call out-of-band context the connection's transport\n* carries. Default `undefined` covers cross-process and ordinary in-process\n* transports. The hub's self/overlay connections instantiate with a\n* concrete `TInCtx` (e.g. `Participant`) so handlers can see who originated\n* the call.\n*\n* `TOutCtx` is the per-call override / extension bag the outbound sender\n* understands (see {@link SendOpts.ctx}). It only ever flows into the\n* sender as input, so it is a contravariant type parameter. Default `any`\n* keeps the bare `LinkRpcConnection` a valid supertype for holders that do\n* not care about the outbound ctx; pass a concrete shape (e.g.\n* `SigningCallCtx`) to get precise {@link get} typing. The connection\n* itself is agnostic to its contents — it merely forwards the `ctx`\n* defaults supplied to {@link get}.\n*/\nvar LinkRpcConnection = class LinkRpcConnection {\n\t/**\n\t* Convenience: build a {@link JsonRpcChannel} `Channel` from the\n\t* given transport and wrap it in an `LinkRpcConnection`. Use this\n\t* when you have a transport at hand and don't need a decorator\n\t* stack (e.g. signing).\n\t*/\n\tstatic fromTransport(transport, options = {}) {\n\t\treturn new LinkRpcConnection(JsonRpcChannel.create(transport), options);\n\t}\n\t/** Underlying JSON-RPC sender — useful for callers that need raw access (e.g. to call hub-served methods that bypass the interface registry). */\n\tchannel;\n\t/** key = `${serviceId ?? \"\"}::${interfaceId}` */\n\t_registry = /* @__PURE__ */ new Map();\n\t/** Descriptions for services that have been registered with a `serviceDescription`. */\n\t_serviceDescriptions = /* @__PURE__ */ new Map();\n\t/** Root-node-id requirement sets recorded per serviceId. */\n\t_serviceRootPrincipalSets = /* @__PURE__ */ new Map();\n\t_directoryWatchers = /* @__PURE__ */ new Set();\n\t_directoryListeners = /* @__PURE__ */ new Set();\n\t_inspection;\n\t_inspectionHost;\n\t_serviceInspectionRegistrations = /* @__PURE__ */ new Map();\n\t_wireObservers = /* @__PURE__ */ new Set();\n\t_closeListeners = /* @__PURE__ */ new Set();\n\t_closed = false;\n\t_wireChannel;\n\t_validateOutboundParams;\n\t/** Bare-method bindings, keyed by their exact wire prefix. */\n\t_bareBindings = /* @__PURE__ */ new Map();\n\t_generateTopologyId;\n\t/**\n\t* Construct from a {@link Channel} (binds the inbound handler and uses\n\t* `channel.sender` for outbound calls) or from a bare\n\t* {@link IRequestSender} (send-only — no inbound handler is registered,\n\t* useful for bootstrap flows like `createManagedIdentity`).\n\t*/\n\tconstructor(channel, options = {}) {\n\t\tthis._validateOutboundParams = options.validateOutboundParams !== false;\n\t\tthis._generateTopologyId = options.generateTopologyId ?? createInspectionId;\n\t\tif (\"sender\" in channel) {\n\t\t\tthis._wireChannel = channel;\n\t\t\tthis.channel = channel.sender;\n\t\t\tchannel.setRequestHandler({\n\t\t\t\thandleRequest: (c) => this._handleRequest(c),\n\t\t\t\thandleNotification: (c) => this._handleNotification(c)\n\t\t\t});\n\t\t} else {\n\t\t\tthis._wireChannel = void 0;\n\t\t\tthis.channel = channel;\n\t\t}\n\t}\n\tget(ifaceOrTarget, opts) {\n\t\treturn this._getClient(ifaceOrTarget, opts, false);\n\t}\n\t_getClient(ifaceOrTarget, opts, allFailuresAsValues) {\n\t\tif (isInterfaceTarget(ifaceOrTarget)) {\n\t\t\tif (opts !== void 0) throw new Error(`${allFailuresAsValues ? \"getResultClient\" : \"get\"}: ${ifaceOrTarget.mode === \"bare\" ? \"bare \" : \"\"}interface targets do not accept service or call options.`);\n\t\t\tif (ifaceOrTarget.mode === \"bare\") return this._buildBareClient(ifaceOrTarget.interface, ifaceOrTarget.prefix, allFailuresAsValues);\n\t\t\treturn this._buildClient(ifaceOrTarget.interface, ifaceOrTarget.mode === \"qualified\" ? { serviceId: ifaceOrTarget.serviceId } : {}, void 0, ifaceOrTarget.mode === \"default\", allFailuresAsValues);\n\t\t}\n\t\treturn this._buildClient(ifaceOrTarget, opts ?? {}, void 0, false, allFailuresAsValues);\n\t}\n\t/**\n\t* Get a typed client that emits foreign-protocol bare method names.\n\t* Unlike {@link get}, these calls carry no LinkRPC interface metadata.\n\t*/\n\tgetBare(iface, opts = {}) {\n\t\treturn this._buildBareClient(iface, opts.prefix ?? \"\", false);\n\t}\n\t_buildBareClient(iface, prefix, allFailuresAsValues) {\n\t\tvalidateBarePrefix(prefix);\n\t\tfor (const [name, member] of Object.entries(iface.members)) if (member.kind === \"request\" && (member.clientStreamSchema !== void 0 || member.serverStreamSchema !== void 0)) throw new Error(`getBare: streaming method \"${name}\" is not supported on foreign wires.`);\n\t\treturn this._buildClient(iface, {}, prefix, false, allFailuresAsValues);\n\t}\n\tgetResultClient(ifaceOrTarget, opts) {\n\t\treturn this._getClient(ifaceOrTarget, opts, true);\n\t}\n\t/** Get a service-scoped handle; all interfaces obtained from it route via `serviceId` (form 3). */\n\tservice(serviceId) {\n\t\treturn new ServiceHandle(this, serviceId);\n\t}\n\t/** Register handlers, adding preset routing when passed a default or bare target. */\n\tregister(ifaceOrTarget, handlers, opts = {}) {\n\t\tif (isInterfaceTarget(ifaceOrTarget)) {\n\t\t\tif (ifaceOrTarget.mode === \"qualified\") {\n\t\t\t\tif (opts.serviceId !== void 0 && opts.serviceId !== ifaceOrTarget.serviceId) throw new Error(\"register: serviceId conflicts with interface target.\");\n\t\t\t\treturn this._register(ifaceOrTarget.interface, handlers, {\n\t\t\t\t\t...opts,\n\t\t\t\t\tserviceId: ifaceOrTarget.serviceId || void 0\n\t\t\t\t}, false);\n\t\t\t}\n\t\t\tconst prefix = ifaceOrTarget.mode === \"bare\" ? ifaceOrTarget.prefix : \"\";\n\t\t\tvalidateBarePrefix(prefix);\n\t\t\treturn this._register(ifaceOrTarget.interface, handlers, opts, false, prefix);\n\t\t}\n\t\treturn this._register(ifaceOrTarget, handlers, opts, false);\n\t}\n\t/** Register inspection contracts without recursively enabling service inspection. */\n\tregisterInspection(iface, handlers, opts = {}) {\n\t\treturn this._register(iface, handlers, opts, true);\n\t}\n\t/** Observe this connection without replacing another inspection scope's observer. */\n\tobserveWireMessages(observer) {\n\t\tif (this._closed) throw new Error(\"Connection is closed\");\n\t\tif (this._wireChannel === void 0) throw new Error(\"Connection has no observable wire channel\");\n\t\tthis._wireObservers.add(observer);\n\t\tthis._wireChannel.setWireMessageObserver((direction, message) => {\n\t\t\tfor (const listener of [...this._wireObservers]) try {\n\t\t\t\tlistener(direction, message);\n\t\t\t} catch {}\n\t\t});\n\t\treturn { dispose: () => {\n\t\t\tthis._wireObservers.delete(observer);\n\t\t\tif (this._wireObservers.size === 0) this._wireChannel?.setWireMessageObserver(void 0);\n\t\t} };\n\t}\n\tonDidClose(listener) {\n\t\tif (this._closed) throw new Error(\"Connection is closed\");\n\t\tthis._closeListeners.add(listener);\n\t\treturn { dispose: () => {\n\t\t\tthis._closeListeners.delete(listener);\n\t\t} };\n\t}\n\t_register(iface, handlers, opts, internalInspection, barePrefix) {\n\t\tconst serviceId = opts.serviceId;\n\t\tconst key = `${serviceId ?? \"\"}::${iface.info.id}`;\n\t\tif (this._registry.has(key)) throw new Error(`Interface \"${iface.info.id}\" already registered${serviceId ? ` under service \"${serviceId}\"` : \"\"}.`);\n\t\tif (barePrefix !== void 0 && this._bareBindings.has(barePrefix)) throw new Error(`Bare interface prefix \"${barePrefix}\" is already registered.`);\n\t\tlet descriptionWasAdded = false;\n\t\tif (opts.serviceDescription !== void 0) {\n\t\t\tif (serviceId === void 0) throw new Error(\"register: `serviceDescription` requires `serviceId`.\");\n\t\t\tconst existing = this._serviceDescriptions.get(serviceId);\n\t\t\tif (existing !== void 0 && existing !== opts.serviceDescription) throw new Error(`register: conflicting descriptions for service \"${serviceId}\".`);\n\t\t\tdescriptionWasAdded = existing === void 0;\n\t\t}\n\t\tlet rootPrincipalSetsWereAdded = false;\n\t\tif (opts.rootPrincipalSets !== void 0) {\n\t\t\tif (serviceId === void 0) throw new Error(\"register: `rootPrincipalSets` requires `serviceId`.\");\n\t\t\tconst existing = this._serviceRootPrincipalSets.get(serviceId);\n\t\t\tif (existing !== void 0 && !rootPrincipalSetsEqual(existing, opts.rootPrincipalSets)) throw new Error(`register: conflicting rootPrincipalSets for service \"${serviceId}\".`);\n\t\t\trootPrincipalSetsWereAdded = existing === void 0;\n\t\t}\n\t\tconst entry = {\n\t\t\tiface,\n\t\t\thandlers: iface.flattenHandlers(handlers),\n\t\t\tserviceId,\n\t\t\tinternalInspection\n\t\t};\n\t\tif (descriptionWasAdded) this._serviceDescriptions.set(serviceId, opts.serviceDescription);\n\t\tif (rootPrincipalSetsWereAdded) this._serviceRootPrincipalSets.set(serviceId, opts.rootPrincipalSets);\n\t\tthis._registry.set(key, entry);\n\t\tif (barePrefix !== void 0) this._bareBindings.set(barePrefix, {\n\t\t\tprefix: barePrefix,\n\t\t\tentry\n\t\t});\n\t\tthis._notifyDirectoryWatchers(entry, descriptionWasAdded || rootPrincipalSetsWereAdded);\n\t\tif (!internalInspection && serviceId !== void 0 && this._inspection !== void 0 && !this._serviceInspectionRegistrations.has(serviceId)) try {\n\t\t\tthis._installServiceInspection(serviceId);\n\t\t} catch (error) {\n\t\t\tthis._registry.delete(key);\n\t\t\tif (barePrefix !== void 0) this._bareBindings.delete(barePrefix);\n\t\t\tif (descriptionWasAdded) this._serviceDescriptions.delete(serviceId);\n\t\t\tif (rootPrincipalSetsWereAdded) this._serviceRootPrincipalSets.delete(serviceId);\n\t\t\tthis._notifyDirectoryWatchers(entry);\n\t\t\tthrow error;\n\t\t}\n\t\tlet disposed = false;\n\t\treturn { dispose: () => {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\tif (this._registry.get(key) !== entry) return;\n\t\t\tthis._registry.delete(key);\n\t\t\tfor (const [prefix, binding] of this._bareBindings) if (binding.entry === entry) this._bareBindings.delete(prefix);\n\t\t\tthis._notifyDirectoryWatchers(entry);\n\t\t\tif (serviceId !== void 0 && !this._hasBusinessServiceRegistration(serviceId)) {\n\t\t\t\tthis._removeServiceInspection(serviceId);\n\t\t\t\tthis._serviceDescriptions.delete(serviceId);\n\t\t\t\tthis._serviceRootPrincipalSets.delete(serviceId);\n\t\t\t}\n\t\t} };\n\t}\n\t/** Snapshot of every interface currently registered on this connection. */\n\tlistRegisteredInterfaces() {\n\t\treturn Array.from(this._registry.values()).map((r) => {\n\t\t\tconst sid = r.serviceId ?? \"\";\n\t\t\tconst item = {\n\t\t\t\tserviceId: sid,\n\t\t\t\tinterfaceId: r.iface.info.id,\n\t\t\t\tinterfaceHash: r.iface.schemaHash\n\t\t\t};\n\t\t\tif (r.iface.info.tags !== void 0) item.tags = r.iface.info.tags;\n\t\t\tconst desc = sid === \"\" ? void 0 : this._serviceDescriptions.get(sid);\n\t\t\tif (desc !== void 0) item.serviceDescription = desc;\n\t\t\tconst sets = sid === \"\" ? void 0 : this._serviceRootPrincipalSets.get(sid);\n\t\t\tif (sets !== void 0) item.rootPrincipalSets = sets;\n\t\t\treturn item;\n\t\t});\n\t}\n\t/** Subscribe to coarse local directory changes; listeners must re-list. */\n\tonDidChangeDirectory(listener) {\n\t\tthis._directoryListeners.add(listener);\n\t\treturn () => this._directoryListeners.delete(listener);\n\t}\n\t/**\n\t* Look up a registered interface definition by id (and optional content\n\t* hash). Returns `undefined` if no registered interface matches.\n\t*/\n\tfindRegisteredInterface(interfaceId, hash) {\n\t\tlet selected;\n\t\tfor (const r of this._registry.values()) {\n\t\t\tif (r.iface.info.id !== interfaceId) continue;\n\t\t\tif (hash !== void 0 && r.iface.schemaHash !== hash) continue;\n\t\t\tif (selected === void 0 || preferRicherInterfaceSchema(selected.toSchema(), r.iface.toSchema()) === r.iface.toSchema()) selected = r.iface;\n\t\t}\n\t\treturn selected;\n\t}\n\t/**\n\t* Register the three linkrpc reflection interfaces (`defaults`,\n\t* `directory`, `schemas`), backed by this connection's live registry.\n\t*\n\t* By default they live under the root service (form-2 reachable as\n\t* `hubrpc.directory::list`). Pass `serviceId` to additionally mount\n\t* them under a specific service — useful for participants that live\n\t* behind a hub, so callers can reach reflection via form-3\n\t* `<serviceId>::hubrpc.directory::list`.\n\t*\n\t* Idempotent: re-registering the same `(serviceId, interfaceId)` pair\n\t* is a no-op.\n\t*/\n\tenableReflection(opts = {}) {\n\t\tconst key = `${opts.serviceId ?? \"\"}::${defaultsInterface.info.id}`;\n\t\tif (this._registry.has(key)) return { dispose() {} };\n\t\tconst prefix = `${opts.serviceId ?? \"\"}::`;\n\t\tfor (const iface of [directoryInterface, schemasInterface]) if (this._registry.has(`${prefix}${iface.info.id}`)) throw new Error(`enableReflection: partial reflection registration for service \"${opts.serviceId ?? \"\"}\".`);\n\t\tconst regOpts = opts.serviceId !== void 0 ? { serviceId: opts.serviceId } : {};\n\t\tconst registrations = [];\n\t\tregistrations.push(this.register(defaultsInterface, {\n\t\t\tget: () => {\n\t\t\t\tconst binding = this._bareBindings.get(\"\");\n\t\t\t\tif (!binding) return {};\n\t\t\t\treturn {\n\t\t\t\t\tserviceId: binding.entry.serviceId,\n\t\t\t\t\tinterfaceId: binding.entry.iface.info.id,\n\t\t\t\t\tinterfaceHash: binding.entry.iface.schemaHash\n\t\t\t\t};\n\t\t\t},\n\t\t\tlistBindings: () => ({ bindings: Array.from(this._bareBindings.values()).sort((a, b) => a.prefix < b.prefix ? -1 : a.prefix > b.prefix ? 1 : 0).map((binding) => ({\n\t\t\t\tprefix: binding.prefix,\n\t\t\t\tserviceId: binding.entry.serviceId,\n\t\t\t\tinterfaceId: binding.entry.iface.info.id,\n\t\t\t\tinterfaceHash: binding.entry.iface.schemaHash\n\t\t\t})) })\n\t\t}, regOpts));\n\t\tregistrations.push(this.register(directoryInterface, {\n\t\t\tlist: ({ interfaceId, interfaceIdPrefix, serviceId, serviceIdScopes, cursor, limit }) => {\n\t\t\t\tconst all = this.listRegisteredInterfaces().filter((r) => opts.serviceId === void 0 || r.serviceId === opts.serviceId).filter((r) => interfaceId === void 0 || r.interfaceId === interfaceId).filter((r) => interfaceIdPrefix === void 0 || r.interfaceId.startsWith(interfaceIdPrefix)).filter((r) => serviceId === void 0 || r.serviceId === serviceId).filter((r) => serviceIdMatchesScopes(r.serviceId, serviceIdScopes));\n\t\t\t\tconst start = cursor === void 0 ? 0 : Number.parseInt(cursor, 10) || 0;\n\t\t\t\tconst end = limit === void 0 ? all.length : Math.min(all.length, start + limit);\n\t\t\t\tconst page = all.slice(start, end).map((r) => ({\n\t\t\t\t\tserviceId: r.serviceId,\n\t\t\t\t\tinterfaceId: r.interfaceId,\n\t\t\t\t\tinterfaceHash: r.interfaceHash,\n\t\t\t\t\ttags: r.tags === void 0 ? void 0 : [...r.tags],\n\t\t\t\t\tserviceDescription: r.serviceDescription,\n\t\t\t\t\trootPrincipalSets: r.rootPrincipalSets?.map((set) => set.map((p) => ({ ...p })))\n\t\t\t\t}));\n\t\t\t\treturn end < all.length ? {\n\t\t\t\t\titems: page,\n\t\t\t\t\tnextCursor: String(end)\n\t\t\t\t} : { items: page };\n\t\t\t},\n\t\t\twatch: (params, _ctx, stream) => new Promise((resolve) => {\n\t\t\t\tconst watcher = {\n\t\t\t\t\tinterfaceId: params.interfaceId,\n\t\t\t\t\tinterfaceIdPrefix: params.interfaceIdPrefix,\n\t\t\t\t\tserviceId: params.serviceId,\n\t\t\t\t\tserviceIdScopes: params.serviceIdScopes,\n\t\t\t\t\tsend: () => stream.send({})\n\t\t\t\t};\n\t\t\t\tthis._directoryWatchers.add(watcher);\n\t\t\t\tconst finish = () => {\n\t\t\t\t\tthis._directoryWatchers.delete(watcher);\n\t\t\t\t\tresolve({});\n\t\t\t\t};\n\t\t\t\tif (stream.signal.aborted) {\n\t\t\t\t\tfinish();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tstream.signal.addEventListener(\"abort\", finish, { once: true });\n\t\t\t})\n\t\t}, regOpts));\n\t\tregistrations.push(this.register(schemasInterface, { get: ({ interfaceId, hash }) => {\n\t\t\tconst iface = this.findRegisteredInterface(interfaceId, hash);\n\t\t\tif (!iface) throw new RpcError(\"Interface not found\", ErrorCode.methodNotFound, {\n\t\t\t\treason: \"unknown-interface\",\n\t\t\t\tinterfaceId,\n\t\t\t\thash\n\t\t\t});\n\t\t\treturn { schema: iface.toSchema() };\n\t\t} }, regOpts));\n\t\tif (opts.serviceId !== void 0) try {\n\t\t\tthis.enableReflection();\n\t\t} catch (error) {\n\t\t\tfor (const registration of registrations.reverse()) registration.dispose();\n\t\t\tthrow error;\n\t\t}\n\t\tlet disposed = false;\n\t\treturn { dispose: () => {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\tfor (const registration of registrations.reverse()) registration.dispose();\n\t\t} };\n\t}\n\t_notifyDirectoryWatchers(entry, serviceMetadataChanged = false) {\n\t\tfor (const listener of this._directoryListeners) try {\n\t\t\tlistener();\n\t\t} catch {}\n\t\tfor (const watcher of this._directoryWatchers) {\n\t\t\tif (watcher.pending) continue;\n\t\t\tconst directlyMatches = directoryWatcherMatchesEntry(watcher, entry);\n\t\t\tconst metadataMatches = serviceMetadataChanged && entry.serviceId !== void 0 && [...this._registry.values()].some((candidate) => candidate.serviceId === entry.serviceId && directoryWatcherMatchesEntry(watcher, candidate));\n\t\t\tif (!directlyMatches && !metadataMatches) continue;\n\t\t\twatcher.pending = true;\n\t\t\tqueueMicrotask(() => {\n\t\t\t\twatcher.pending = false;\n\t\t\t\tif (this._directoryWatchers.has(watcher)) watcher.send();\n\t\t\t});\n\t\t}\n\t}\n\t/**\n\t* Enable the root `hubrpc.node::getNodeId` topology-bootstrap service.\n\t*\n\t* The generated ids are stable while this registration is active. They are\n\t* unauthenticated correlation labels only; callers must not use them for\n\t* identity, capability, or authorization decisions.\n\t*/\n\tenableInspection(descriptors) {\n\t\tif (this._inspection !== void 0) return this._inspection;\n\t\tconst info = {\n\t\t\tnodeId: this._generateTopologyId(\"node\"),\n\t\t\tportId: this._generateTopologyId(\"port\"),\n\t\t\t...descriptors !== void 0 ? { descriptors: [...descriptors] } : {}\n\t\t};\n\t\tconst registration = this._register(nodeInterface, { getNodeId: () => info }, {}, true);\n\t\tconst host = new InspectionHost({\n\t\t\tnodeId: info.nodeId,\n\t\t\tdescriptors\n\t\t});\n\t\ttry {\n\t\t\tif (this._wireChannel !== void 0) host.trackConnection(this, { portId: info.portId });\n\t\t} catch (error) {\n\t\t\thost.dispose();\n\t\t\tregistration.dispose();\n\t\t\tthrow error;\n\t\t}\n\t\tthis._inspectionHost = host;\n\t\tlet disposed = false;\n\t\tconst result = {\n\t\t\t...info,\n\t\t\tobserveTraffic: (observer) => host.observeTraffic(observer),\n\t\t\tdispose: () => {\n\t\t\t\tif (disposed) return;\n\t\t\t\tdisposed = true;\n\t\t\t\tfor (const serviceId of [...this._serviceInspectionRegistrations.keys()]) this._removeServiceInspection(serviceId);\n\t\t\t\thost.dispose();\n\t\t\t\tif (this._inspectionHost === host) this._inspectionHost = void 0;\n\t\t\t\tregistration.dispose();\n\t\t\t\tif (this._inspection === result) this._inspection = void 0;\n\t\t\t}\n\t\t};\n\t\tthis._inspection = result;\n\t\ttry {\n\t\t\tconst services = new Set(Array.from(this._registry.values()).filter((entry) => entry.serviceId !== void 0 && !entry.internalInspection).map((entry) => entry.serviceId));\n\t\t\tfor (const serviceId of services) this._installServiceInspection(serviceId);\n\t\t} catch (error) {\n\t\t\tresult.dispose();\n\t\t\tthrow error;\n\t\t}\n\t\treturn result;\n\t}\n\t/** Number of active endpoint traffic stream subscribers. */\n\tget trafficObserverCount() {\n\t\treturn this._inspectionHost?.observerCount ?? 0;\n\t}\n\tclose() {\n\t\tif (this._closed) return;\n\t\tthis._closed = true;\n\t\tfor (const listener of [...this._closeListeners]) listener();\n\t\tthis._closeListeners.clear();\n\t\tthis._inspection?.dispose();\n\t\tthis._wireObservers.clear();\n\t\tthis._wireChannel?.setWireMessageObserver(void 0);\n\t\tthis.channel.close();\n\t}\n\t_buildClient(iface, opts, barePrefix, defaultRoute = false, allFailuresAsValues = false) {\n\t\tconst { serviceId, ...ctxRest } = opts;\n\t\tconst sendOpts = barePrefix === void 0 ? {\n\t\t\tctx: ctxRest,\n\t\t\tinterfaceHash: iface.schemaHash\n\t\t} : void 0;\n\t\tconst prefix = barePrefix ?? (defaultRoute ? \"\" : serviceId ? `${serviceId}::${iface.info.id}::` : `${iface.info.id}::`);\n\t\tconst proxy = Object.create(null);\n\t\tfor (const [name, member] of Object.entries(iface.members)) {\n\t\t\tconst wireMethod = `${prefix}${name}`;\n\t\t\tif (member.kind === \"request\") {\n\t\t\t\tif (member.clientStreamSchema !== void 0 || member.serverStreamSchema !== void 0) {\n\t\t\t\t\tconst serverStreamSchema = member.serverStreamSchema;\n\t\t\t\t\tproxy[name] = (params, callOpts) => {\n\t\t\t\t\t\tconst userListener = callOpts?.onMessage;\n\t\t\t\t\t\tconst onStreamMessage = userListener !== void 0 ? (raw) => {\n\t\t\t\t\t\t\tif (serverStreamSchema !== void 0) {\n\t\t\t\t\t\t\t\tconst r = safeParse(serverStreamSchema, raw);\n\t\t\t\t\t\t\t\tif (!r.success) return;\n\t\t\t\t\t\t\t\tuserListener(r.data);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tuserListener(raw);\n\t\t\t\t\t\t} : void 0;\n\t\t\t\t\t\tconst channelOpts = onStreamMessage !== void 0 ? {\n\t\t\t\t\t\t\t...sendOpts,\n\t\t\t\t\t\t\tonStreamMessage\n\t\t\t\t\t\t} : sendOpts;\n\t\t\t\t\t\tlet call;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tthis._validateOutboundParamsFor(member, wireMethod, params);\n\t\t\t\t\t\t\tcall = this.channel.sendRequestWithStream(wireMethod, params, channelOpts);\n\t\t\t\t\t\t} catch (cause) {\n\t\t\t\t\t\t\tif (!allFailuresAsValues) throw cause;\n\t\t\t\t\t\t\tcall = {\n\t\t\t\t\t\t\t\tresult: Promise.reject(cause),\n\t\t\t\t\t\t\t\tsend: () => {\n\t\t\t\t\t\t\t\t\tthrow cause;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tcancel: () => {\n\t\t\t\t\t\t\t\t\tthrow cause;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tping: async () => {\n\t\t\t\t\t\t\t\t\tthrow cause;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst checked = addCheckedResult(call.result.then((raw) => validateWireResult(member.resultSchema, raw, wireMethod)), member, allFailuresAsValues);\n\t\t\t\t\t\treturn Object.assign(checked, {\n\t\t\t\t\t\t\tsend: async (payload) => call.send(payload),\n\t\t\t\t\t\t\tcancel: async (reason) => call.cancel(reason),\n\t\t\t\t\t\t\tdispose: (reason) => call.dispose?.(reason),\n\t\t\t\t\t\t\tping: () => call.ping()\n\t\t\t\t\t\t});\n\t\t\t\t\t};\n\t\t\t\t} else proxy[name] = (params) => {\n\t\t\t\t\treturn addCheckedResult((async () => {\n\t\t\t\t\t\tthis._validateOutboundParamsFor(member, wireMethod, params);\n\t\t\t\t\t\tconst raw = await this.channel.sendRequest(wireMethod, params, sendOpts);\n\t\t\t\t\t\treturn validateWireResult(member.resultSchema, raw, wireMethod);\n\t\t\t\t\t})(), member, allFailuresAsValues);\n\t\t\t\t};\n\t\t\t} else {\n\t\t\t\tconst notify = (params) => {\n\t\t\t\t\tthis._validateOutboundParamsFor(member, wireMethod, params);\n\t\t\t\t\tthis.channel.sendNotification(wireMethod, params, sendOpts);\n\t\t\t\t};\n\t\t\t\tproxy[name] = barePrefix === void 0 ? async (params) => notify(params) : notify;\n\t\t\t}\n\t\t}\n\t\treturn iface.nestClient(proxy);\n\t}\n\t_validateOutboundParamsFor(member, wireMethod, params) {\n\t\tif (!this._validateOutboundParams) return;\n\t\tvalidateValue(member.paramsSchema, params, `Invalid params for ${wireMethod}`, ErrorCode.invalidParams);\n\t}\n\tasync _handleRequest(call) {\n\t\tconst parsed = this._parseRouted(call.method);\n\t\tif (!parsed.ok) return notFound(parsed.reason, call.method);\n\t\tconst { entry, memberName } = parsed;\n\t\tconst member = entry.iface.members[memberName];\n\t\tif (!member) return notFound(\"unknown-method\", call.method);\n\t\tconst handler = entry.handlers[memberName];\n\t\tif (!handler) return notFound(\"unknown-method\", call.method);\n\t\tconst userParams = stripLinkRpcWireMeta(call.params);\n\t\tconst parsedParams = safeParse(member.paramsSchema, userParams);\n\t\tif (!parsedParams.success) return { error: {\n\t\t\tcode: ErrorCode.invalidParams,\n\t\t\tmessage: \"Invalid params\",\n\t\t\tdata: { issues: parsedParams.error.issues }\n\t\t} };\n\t\tif (member.kind !== \"request\") return notFound(\"unknown-method\", call.method);\n\t\tconst stream = this._buildStreamApi(call.stream, call.signal, member);\n\t\ttry {\n\t\t\tconst result = await handler(parsedParams.data, call.context, stream);\n\t\t\tconst encodedError = encodeApplicationError(member, result);\n\t\t\tif (encodedError !== void 0) return { error: encodedError };\n\t\t\tvalidateValue(member.resultSchema, result, `Invalid result for ${call.method}`, ErrorCode.internalError);\n\t\t\treturn { result: result === void 0 ? null : result };\n\t\t} catch (e) {\n\t\t\tif (e instanceof RpcError) return { error: {\n\t\t\t\tcode: e.code,\n\t\t\t\tmessage: e.message,\n\t\t\t\tdata: e.data\n\t\t\t} };\n\t\t\treturn { error: {\n\t\t\t\tcode: ErrorCode.internalError,\n\t\t\t\tmessage: e instanceof Error ? e.message : String(e)\n\t\t\t} };\n\t\t}\n\t}\n\t_buildStreamApi(callStream, signal, member) {\n\t\treturn {\n\t\t\tsend: (payload) => {\n\t\t\t\tif (member.serverStreamSchema) {\n\t\t\t\t\tconst r = safeParse(member.serverStreamSchema, payload);\n\t\t\t\t\tif (!r.success) throw new Error(`Server stream payload failed schema validation: ${r.error.message}`);\n\t\t\t\t}\n\t\t\t\treturn callStream.send(payload);\n\t\t\t},\n\t\t\tonMessage: (listener) => {\n\t\t\t\tcallStream.onMessage((raw) => {\n\t\t\t\t\tif (member.clientStreamSchema) {\n\t\t\t\t\t\tconst r = safeParse(member.clientStreamSchema, raw);\n\t\t\t\t\t\tif (!r.success) return;\n\t\t\t\t\t\tlistener(r.data);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t},\n\t\t\tping: () => callStream.ping(),\n\t\t\tsignal\n\t\t};\n\t}\n\t_handleNotification(call) {\n\t\tconst parsed = this._parseRouted(call.method);\n\t\tif (!parsed.ok) return;\n\t\tconst { entry, memberName } = parsed;\n\t\tconst member = entry.iface.members[memberName];\n\t\tif (member?.kind !== \"notification\") return;\n\t\tconst handler = entry.handlers[memberName];\n\t\tif (!handler) return;\n\t\tconst userParams = stripLinkRpcWireMeta(call.params);\n\t\tconst parsedParams = safeParse(member.paramsSchema, userParams);\n\t\tif (!parsedParams.success) return;\n\t\thandler(parsedParams.data, call.context);\n\t}\n\t_parseRouted(method) {\n\t\tconst parsed = parseMethodName(method);\n\t\tif (!parsed) return {\n\t\t\tok: false,\n\t\t\treason: \"bad-method-grammar\"\n\t\t};\n\t\tif (parsed.kind === \"bare\") {\n\t\t\tlet selected;\n\t\t\tfor (const binding of this._bareBindings.values()) if (parsed.member.startsWith(binding.prefix) && (selected === void 0 || binding.prefix.length > selected.prefix.length)) selected = binding;\n\t\t\tif (!selected) return {\n\t\t\t\tok: false,\n\t\t\t\treason: \"no-preset\"\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tentry: selected.entry,\n\t\t\t\tmemberName: parsed.member.slice(selected.prefix.length)\n\t\t\t};\n\t\t}\n\t\tconst serviceId = parsed.kind === \"full\" ? parsed.serviceId : void 0;\n\t\tconst key = `${serviceId ?? \"\"}::${parsed.interfaceId}`;\n\t\tconst entry = this._registry.get(key);\n\t\tif (!entry) return {\n\t\t\tok: false,\n\t\t\treason: serviceId ? \"unknown-service\" : \"unknown-interface\"\n\t\t};\n\t\treturn {\n\t\t\tok: true,\n\t\t\tentry,\n\t\t\tmemberName: parsed.member\n\t\t};\n\t}\n\t_installServiceInspection(serviceId) {\n\t\tif (this._serviceInspectionRegistrations.has(serviceId)) return;\n\t\tconst info = this._inspection;\n\t\tconst host = this._inspectionHost;\n\t\tif (info === void 0 || host === void 0) return;\n\t\tthis._serviceInspectionRegistrations.set(serviceId, [host.expose(this, {\n\t\t\tserviceId,\n\t\t\tportId: info.portId\n\t\t})]);\n\t}\n\t_removeServiceInspection(serviceId) {\n\t\tconst registrations = this._serviceInspectionRegistrations.get(serviceId);\n\t\tif (registrations === void 0) return;\n\t\tthis._serviceInspectionRegistrations.delete(serviceId);\n\t\tfor (const registration of registrations.reverse()) registration.dispose();\n\t}\n\t_hasBusinessServiceRegistration(serviceId) {\n\t\treturn Array.from(this._registry.values()).some((entry) => entry.serviceId === serviceId && !entry.internalInspection);\n\t}\n};\nfunction createInspectionId(kind) {\n\tconst bytes = /* @__PURE__ */ new Uint8Array(16);\n\tglobalThis.crypto.getRandomValues(bytes);\n\treturn `${kind}:${bytesToBase64Url(bytes)}`;\n}\n/** Structural equality for two CNF root-node-id requirement collections. */\nfunction rootPrincipalSetsEqual(a, b) {\n\tif (a.length !== b.length) return false;\n\tfor (let i = 0; i < a.length; i++) {\n\t\tconst sa = a[i];\n\t\tconst sb = b[i];\n\t\tif (sa.length !== sb.length) return false;\n\t\tfor (let j = 0; j < sa.length; j++) {\n\t\t\tif (sa[j].principal !== sb[j].principal) return false;\n\t\t\tif (sa[j].transitive === true !== (sb[j].transitive === true)) return false;\n\t\t}\n\t}\n\treturn true;\n}\nfunction directoryWatcherMatchesEntry(watcher, entry) {\n\tconst serviceId = entry.serviceId ?? \"\";\n\treturn (watcher.interfaceId === void 0 || watcher.interfaceId === entry.iface.info.id) && (watcher.interfaceIdPrefix === void 0 || entry.iface.info.id.startsWith(watcher.interfaceIdPrefix)) && (watcher.serviceId === void 0 || watcher.serviceId === serviceId) && serviceIdMatchesScopes(serviceId, watcher.serviceIdScopes);\n}\nfunction addCheckedResult(promise, member, allFailuresAsValues = false) {\n\tconst settled = promise.then((value) => ({\n\t\tok: true,\n\t\tvalue\n\t}), (cause) => ({\n\t\tok: false,\n\t\terror: decodeCheckedError(cause, member.applicationErrors),\n\t\tcause\n\t}));\n\tconst result = settled.then((outcome) => {\n\t\tif (outcome.ok) return outcome.value;\n\t\tif (allFailuresAsValues) return new RpcFailure(outcome.error.kind === \"application\" ? {\n\t\t\tkind: \"application\",\n\t\t\terror: outcome.error\n\t\t} : {\n\t\t\tkind: \"generic\",\n\t\t\terror: outcome.error\n\t\t});\n\t\tif (outcome.error.kind === \"application\") return new RpcFailure(outcome.error);\n\t\tthrow outcome.error.kind === \"nonCompliantServer\" ? outcome.error : outcome.cause;\n\t});\n\treturn Object.assign(result, { result: async () => {\n\t\tresult.catch(() => {});\n\t\tconst outcome = await settled;\n\t\treturn outcome.ok ? outcome : {\n\t\t\tok: false,\n\t\t\terror: outcome.error\n\t\t};\n\t} });\n}\nfunction decodeCheckedError(cause, descriptors) {\n\tif (cause instanceof NonCompliantServerError) return cause;\n\tif (!(cause instanceof RpcError) || cause.origin !== \"remote\") return {\n\t\tkind: cause instanceof RpcError && cause.origin === \"transport\" ? \"transport\" : \"local\",\n\t\tcause\n\t};\n\tconst original = {\n\t\tcode: cause.code,\n\t\tmessage: cause.message,\n\t\t...cause.hasData ? { data: cause.data } : {}\n\t};\n\tconst candidates = descriptors.filter((candidate) => candidate.code === cause.code).sort((a, b) => Number(b.type !== void 0) - Number(a.type !== void 0));\n\tconst body = {\n\t\tmessage: cause.message,\n\t\t...cause.hasData ? { data: cause.data } : {}\n\t};\n\tconst issues = [];\n\tfor (const descriptor of candidates) {\n\t\tconst parsed = parseDeclaredErrorBody(descriptor, body);\n\t\tif (!parsed.success) {\n\t\t\tissues.push(...parsed.issues);\n\t\t\tcontinue;\n\t\t}\n\t\tif (descriptor.type === void 0) return brandApplicationError({\n\t\t\t...parsed.data,\n\t\t\tkind: \"application\",\n\t\t\tcode: descriptor.code\n\t\t});\n\t\tconst envelope = parsed.data.data;\n\t\treturn brandApplicationError({\n\t\t\tkind: \"application\",\n\t\t\tcode: descriptor.code,\n\t\t\tmessage: parsed.data.message,\n\t\t\ttype: descriptor.type,\n\t\t\t...typeof envelope === \"object\" && envelope !== null && \"data\" in envelope ? { data: envelope.data } : {}\n\t\t});\n\t}\n\tif (candidates.length > 0) return new NonCompliantServerError(original, issues);\n\treturn {\n\t\tkind: \"remote\",\n\t\t...original\n\t};\n}\nfunction encodeApplicationError(member, value) {\n\tif (!isApplicationErrorValue(value)) return void 0;\n\tconst candidate = value;\n\tconst descriptor = member.applicationErrors.find((error) => error.code === candidate.code && error.type === candidate.type && (error.bodySchema !== void 0 || error.type !== void 0 || error.message === candidate.message));\n\tif (descriptor === void 0) throw new RpcError(`Undeclared application error ${String(candidate.code)}`, ErrorCode.internalError);\n\tconst data = Object.hasOwn(value, \"data\") ? { data: value.data } : {};\n\tconst body = {\n\t\tmessage: value.message,\n\t\t...descriptor.type === void 0 ? data : { data: {\n\t\t\ttype: descriptor.type,\n\t\t\t...data\n\t\t} }\n\t};\n\tconst parsed = parseDeclaredErrorBody(descriptor, body);\n\tconst issues = parsed.success ? jsonIssues(body) : parsed.issues;\n\tif (issues.length > 0) throw new RpcError(`Invalid data for application error ${descriptor.code}`, ErrorCode.internalError, { issues: issues.map((issue) => ({ ...issue })) });\n\treturn {\n\t\tcode: descriptor.code,\n\t\t...body\n\t};\n}\nfunction validateWireResult(schema, raw, wireMethod) {\n\tconst value = normalizeWireResult(schema, raw);\n\tvalidateValue(schema, value, `Invalid result for ${wireMethod}`, ErrorCode.internalError);\n\treturn value;\n}\n/** Validate at both ends without stripping extra keys or applying schema transforms. */\nfunction validateValue(schema, value, message, code) {\n\tconst checked = safeParse(schema, value);\n\tif (!checked.success) throw new RpcError(message, code, { issues: checked.error.issues });\n}\n/** Undo the server's undefined → null convention only when the schema rejects null. */\nfunction normalizeWireResult(schema, raw) {\n\tif (raw !== null) return raw;\n\tif (safeParse(schema, null).success) return null;\n\tif (safeParse(schema, void 0).success) return void 0;\n\treturn null;\n}\n/** Service-scoped handle returned by `connection.service(id)`. */\nvar ServiceHandle = class {\n\t_connection;\n\t_serviceId;\n\tconstructor(_connection, _serviceId) {\n\t\tthis._connection = _connection;\n\t\tthis._serviceId = _serviceId;\n\t}\n\tgetResultClient(iface, opts = {}) {\n\t\treturn this._connection.getResultClient(iface, {\n\t\t\t...opts,\n\t\t\tserviceId: this._serviceId\n\t\t});\n\t}\n\tget(iface, opts = {}) {\n\t\treturn this._connection.get(iface, {\n\t\t\t...opts,\n\t\t\tserviceId: this._serviceId\n\t\t});\n\t}\n\tregister(ifaceOrTarget, handlers, opts = {}) {\n\t\treturn this._connection.register(ifaceOrTarget, handlers, {\n\t\t\t...opts,\n\t\t\tserviceId: this._serviceId\n\t\t});\n\t}\n};\nfunction notFound(reason, method) {\n\treturn { error: {\n\t\tcode: ErrorCode.methodNotFound,\n\t\tmessage: `Method not found: ${method}`,\n\t\tdata: {\n\t\t\treason,\n\t\t\tmethod\n\t\t}\n\t} };\n}\n//#endregion\n//#region src/schema/exportStaticHubSchema.ts\n/** Export a complete static contract, failing on missing reflection, schemas, or truncated discovery. */\nasync function exportStaticHubSchema(channel, options = {}) {\n\tif (options.maxDepth !== void 0 && (!Number.isSafeInteger(options.maxDepth) || options.maxDepth < 0)) throw new Error(\"maxDepth must be a non-negative integer\");\n\tconst cursors = /* @__PURE__ */ new Map();\n\tconst timed = {\n\t\tclose: () => {},\n\t\tsendRequest: (method, params, opts) => {\n\t\t\tconst call = channel.sendRequestWithStream(method, params, opts);\n\t\t\treturn withRpcTimeout(Object.assign(call.result, {\n\t\t\t\tcancel: (reason) => call.cancel(reason),\n\t\t\t\tdispose: (reason) => call.dispose?.(reason)\n\t\t\t}), `contract export ${method}`, options.timeoutMs);\n\t\t},\n\t\tsendNotification: (method, params, opts) => channel.sendNotification(method, params, opts),\n\t\tsendRequestWithStream: (method, params, opts) => {\n\t\t\tconst call = channel.sendRequestWithStream(method, params, opts);\n\t\t\tif (!method.endsWith(\"hubrpc.directory::list\")) return call;\n\t\t\treturn {\n\t\t\t\tsend: (payload) => call.send(payload),\n\t\t\t\tcancel: (reason) => call.cancel(reason),\n\t\t\t\tdispose: (reason) => call.dispose?.(reason),\n\t\t\t\tping: () => call.ping(),\n\t\t\t\tresult: call.result.then((raw) => {\n\t\t\t\t\tconst parsed = safeParse(directoryInterface.members.list.resultSchema, raw);\n\t\t\t\t\tif (!parsed.success) throw new Error(`Invalid directory response from ${method}`);\n\t\t\t\t\tconst page = parsed.data;\n\t\t\t\t\tif (page.truncated) throw new Error(`Truncated directory response from ${method}`);\n\t\t\t\t\tif (!params || typeof params !== \"object\" || !(\"cursor\" in params)) cursors.set(method, /* @__PURE__ */ new Set());\n\t\t\t\t\tif (page.nextCursor !== void 0) {\n\t\t\t\t\t\tconst seen = cursors.get(method);\n\t\t\t\t\t\tif (seen.has(page.nextCursor)) throw new Error(`Repeated directory cursor from ${method}`);\n\t\t\t\t\t\tseen.add(page.nextCursor);\n\t\t\t\t\t}\n\t\t\t\t\treturn raw;\n\t\t\t\t})\n\t\t\t};\n\t\t}\n\t};\n\tconst connection = new LinkRpcConnection(timed);\n\tconst explorer = new HubDirectoryExplorer(timed, {\n\t\trootTarget: options.serviceId,\n\t\tmaxDepth: options.maxDepth,\n\t\ttimeoutMs: options.timeoutMs\n\t});\n\ttry {\n\t\tawait explorer.explore();\n\t\tconst snapshot = explorer.graphSnapshot;\n\t\tconst incomplete = [snapshot.root, ...snapshot.directories].filter((node) => node.state !== \"loaded\");\n\t\tif (!snapshot.complete || incomplete.length !== 0 || snapshot.result.inaccessible.length !== 0) throw new Error(`Incomplete contract directory discovery: ${incomplete.map((node) => `${node.target.serviceId ?? \"<root>\"}: ${node.inaccessibleReason ?? node.state}`).join(\", \")}`);\n\t\tconst explored = new Set([snapshot.root, ...snapshot.directories].map((node) => node.target.serviceId ?? \"\"));\n\t\tfor (const listing of snapshot.result.listings) if (listing.interfaceId === directoryInterface.info.id && !explored.has(listing.serviceId)) throw new Error(`Incomplete contract directory discovery: '${listing.serviceId}' exceeds maxDepth`);\n\t\tconst defaults = connection.get(defaultsInterface, { serviceId: options.serviceId });\n\t\tconst preset = await defaults.get({});\n\t\tconst { bindings } = await defaults.listBindings({});\n\t\tif (preset.interfaceId === void 0 !== (preset.interfaceHash === void 0)) throw new Error(\"Incomplete default interface reference: both interfaceId and interfaceHash are required\");\n\t\tif (preset.serviceId !== void 0 && preset.interfaceId === void 0) throw new Error(\"A service-only preset cannot be represented by defaultInterface\");\n\t\tconst services = /* @__PURE__ */ new Map();\n\t\tconst schemas = /* @__PURE__ */ new Map();\n\t\tconst resolvedSources = /* @__PURE__ */ new Map();\n\t\tasync function resolve(ref, serviceId) {\n\t\t\tconst key = `${ref.interfaceId}@${ref.interfaceHash}`;\n\t\t\tconst sources = resolvedSources.get(key) ?? /* @__PURE__ */ new Set();\n\t\t\tif (sources.has(serviceId)) return;\n\t\t\tconst { schema } = await connection.get(schemasInterface, { serviceId }).get({\n\t\t\t\tinterfaceId: ref.interfaceId,\n\t\t\t\thash: ref.interfaceHash\n\t\t\t});\n\t\t\tconst validated = parseStaticHubSchema({ interfaceSchemas: [schema] }).interfaceSchemas[0];\n\t\t\tif (validated.id !== ref.interfaceId || validated.hash !== ref.interfaceHash) throw new Error(`Schema response does not match ${key}`);\n\t\t\tsources.add(serviceId);\n\t\t\tresolvedSources.set(key, sources);\n\t\t\tconst existing = schemas.get(key);\n\t\t\tschemas.set(key, existing === void 0 ? validated : preferRicherInterfaceSchema(existing, validated));\n\t\t}\n\t\tfor (const listing of snapshot.result.listings) {\n\t\t\tconst ref = {\n\t\t\t\tinterfaceId: listing.interfaceId,\n\t\t\t\tinterfaceHash: listing.hash\n\t\t\t};\n\t\t\tconst interfaces = services.get(listing.serviceId) ?? [];\n\t\t\tinterfaces.push(ref);\n\t\t\tservices.set(listing.serviceId, interfaces);\n\t\t\tawait resolve(ref, listing.discoveredFrom || void 0);\n\t\t}\n\t\tconst defaultInterface = preset.interfaceId === void 0 ? void 0 : {\n\t\t\tinterfaceId: preset.interfaceId,\n\t\t\tinterfaceHash: preset.interfaceHash\n\t\t};\n\t\tif (defaultInterface) await resolve(defaultInterface, options.serviceId ?? preset.serviceId);\n\t\tfor (const binding of bindings) await resolve(binding, options.serviceId ?? binding.serviceId);\n\t\tconst compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;\n\t\treturn parseStaticHubSchema({\n\t\t\tinterfaceSchemas: [...schemas.values()].sort((a, b) => compare(`${a.id}@${a.hash}`, `${b.id}@${b.hash}`)),\n\t\t\tservices: [...services].sort(([a], [b]) => compare(a, b)).map(([serviceId, interfaces]) => ({\n\t\t\t\tserviceId,\n\t\t\t\tinterfaces: interfaces.sort((a, b) => compare(a.interfaceId, b.interfaceId))\n\t\t\t})),\n\t\t\t...defaultInterface === void 0 ? {} : { defaultInterface },\n\t\t\tbareInterfaces: bindings.map(({ prefix, interfaceId, interfaceHash }) => ({\n\t\t\t\tprefix,\n\t\t\t\tinterface: {\n\t\t\t\t\tinterfaceId,\n\t\t\t\t\tinterfaceHash\n\t\t\t\t}\n\t\t\t})).sort((a, b) => compare(a.prefix, b.prefix))\n\t\t});\n\t} finally {\n\t\texplorer.dispose();\n\t}\n}\n//#endregion\n//#region src/protocol/capability.ts\n/**\n* Structural wire-shape check for an untrusted signed capability. This does\n* not establish authenticity; callers must still verify its signature and\n* delegation chain.\n*/\nfunction hasSignedCapabilityShape(value) {\n\tif (!_isRecord(value)) return false;\n\tif (typeof value.issuer !== \"string\" || typeof value.audience !== \"string\" || typeof value.nonce !== \"string\" || !Array.isArray(value.permissions) || !value.permissions.every(_hasPermissionShape) || value.expiresAtMs !== void 0 && typeof value.expiresAtMs !== \"number\" || value.parentHash !== void 0 && typeof value.parentHash !== \"string\") return false;\n\treturn readSignature(value, \"capability\") !== void 0;\n}\nfunction _hasPermissionShape(value) {\n\tif (!_isRecord(value) || !_isRecord(value.target)) return false;\n\tconst target = value.target;\n\tif (!_hasPatternShape(target.serviceId) || !_hasPatternShape(target.interfaceId) || !Array.isArray(target.members) || !target.members.every(_hasPatternShape) || target.interfaceHash !== void 0 && typeof target.interfaceHash !== \"string\" || value.canInvoke !== void 0 && typeof value.canInvoke !== \"boolean\" || value.canDelegate !== void 0 && typeof value.canDelegate !== \"boolean\") return false;\n\tif (value.params !== void 0) {\n\t\tif (!_isRecord(value.params) || !Object.values(value.params).every(_hasParamMatcherShape)) return false;\n\t}\n\tif (value.callBind !== void 0) {\n\t\tif (!_isRecord(value.callBind) || value.callBind.alg !== \"sha256\" || typeof value.callBind.payloadHash !== \"string\") return false;\n\t}\n\treturn true;\n}\nfunction _hasPatternShape(value) {\n\tif (!_isRecord(value)) return false;\n\treturn \"exact\" in value && typeof value.exact === \"string\" || \"prefix\" in value && typeof value.prefix === \"string\";\n}\nfunction _hasParamMatcherShape(value) {\n\tif (!_isRecord(value)) return false;\n\tif (\"exact\" in value) return true;\n\tif (\"enum\" in value) return Array.isArray(value.enum);\n\tif (\"prefix\" in value) return typeof value.prefix === \"string\";\n\tif (\"subsetOf\" in value) return Array.isArray(value.subsetOf) && value.subsetOf.every((item) => typeof item === \"string\");\n\treturn value.any === true;\n}\nfunction _isRecord(value) {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n/**\n* Addressing match for a single permission: do its\n* `serviceId`/`interfaceId`/`interfaceHash`/`members` patterns admit\n* `target`?\n*/\nfunction permissionMatchesTarget(target, perm) {\n\treturn _targetMismatchReason(target, perm) === void 0;\n}\nvar TargetMismatchReason = class {\n\tmismatch;\n\tconstructor(mismatch) {\n\t\tthis.mismatch = mismatch;\n\t}\n\ttoString() {\n\t\tconst mismatch = this.mismatch;\n\t\tswitch (mismatch.kind) {\n\t\t\tcase \"serviceId\":\n\t\t\tcase \"interfaceId\": return `${mismatch.kind} ${JSON.stringify(mismatch.actual)} does not match ${_formatPattern(mismatch.expected)}`;\n\t\t\tcase \"interfaceHash\": return `interfaceHash ${mismatch.actual === void 0 ? \"<none>\" : JSON.stringify(mismatch.actual)} does not match required ${JSON.stringify(mismatch.expected)}`;\n\t\t\tcase \"invalidMembers\": return \"permission target has invalid members\";\n\t\t\tcase \"member\": {\n\t\t\t\tconst allowed = mismatch.expected.map(_formatPattern).join(\", \") || \"<none>\";\n\t\t\t\treturn `member ${JSON.stringify(mismatch.actual)} does not match allowed patterns [${allowed}]`;\n\t\t\t}\n\t\t}\n\t}\n};\nfunction _targetMismatchReason(target, perm) {\n\tconst t = perm.target;\n\tif (!_patternMatches(target.serviceId, t.serviceId, \"/\")) return new TargetMismatchReason({\n\t\tkind: \"serviceId\",\n\t\tactual: target.serviceId,\n\t\texpected: t.serviceId\n\t});\n\tif (!_patternMatches(target.interfaceId, t.interfaceId, \".\")) return new TargetMismatchReason({\n\t\tkind: \"interfaceId\",\n\t\tactual: target.interfaceId,\n\t\texpected: t.interfaceId\n\t});\n\tif (t.interfaceHash !== void 0 && target.interfaceHash !== t.interfaceHash) return new TargetMismatchReason({\n\t\tkind: \"interfaceHash\",\n\t\tactual: target.interfaceHash,\n\t\texpected: t.interfaceHash\n\t});\n\tif (!Array.isArray(t.members)) return new TargetMismatchReason({ kind: \"invalidMembers\" });\n\tif (!t.members.some((m) => _patternMatches(target.member, m, \"\"))) return new TargetMismatchReason({\n\t\tkind: \"member\",\n\t\tactual: target.member,\n\t\texpected: t.members\n\t});\n}\nfunction _patternMatches(value, pat, delim) {\n\tif (\"exact\" in pat) return value === pat.exact;\n\tconst p = pat.prefix;\n\tif (p === \"\") return true;\n\tif (value === p) return true;\n\tif (delim === \"\") return value.startsWith(p);\n\treturn value.startsWith(p + delim);\n}\nfunction _formatPattern(pattern) {\n\treturn \"exact\" in pattern ? `exact ${JSON.stringify(pattern.exact)}` : `prefix ${JSON.stringify(pattern.prefix)}`;\n}\n/**\n* Strict allowlist match for {@link Permission.params}. The set of\n* top-level keys in the call MUST equal the declared set; values must\n* satisfy their matchers. Nested objects/arrays are compared as opaque\n* JSON values via canonical-JSON equality. Pure (no crypto).\n*/\nfunction matchParams(declared, actualParams) {\n\tconst declaredKeys = Object.keys(declared).sort();\n\tconst actualObj = actualParams !== null && typeof actualParams === \"object\" && !Array.isArray(actualParams) ? actualParams : void 0;\n\tconst actualKeys = actualObj ? Object.keys(actualObj).sort() : [];\n\tif (declaredKeys.length !== actualKeys.length || declaredKeys.some((k, i) => k !== actualKeys[i])) return {\n\t\tok: false,\n\t\treason: `param keys mismatch (declared=${declaredKeys.join(\",\")}, actual=${actualKeys.join(\",\")})`\n\t};\n\tfor (const k of declaredKeys) if (!_matchParamValue(declared[k], actualObj[k])) return {\n\t\tok: false,\n\t\treason: `param \"${k}\" does not match`\n\t};\n\treturn { ok: true };\n}\nfunction _matchParamValue(matcher, value) {\n\tif (\"any\" in matcher) return true;\n\tif (\"prefix\" in matcher) return typeof value === \"string\" && value.startsWith(matcher.prefix);\n\tif (\"subsetOf\" in matcher) return Array.isArray(value) && value.every((v) => typeof v === \"string\" && matcher.subsetOf.includes(v));\n\tif (\"exact\" in matcher) return jcsCanonicalize(matcher.exact) === jcsCanonicalize(value);\n\tif (\"enum\" in matcher) {\n\t\tconst v = jcsCanonicalize(value);\n\t\treturn matcher.enum.some((opt) => jcsCanonicalize(opt) === v);\n\t}\n\treturn false;\n}\n/**\n* Does `permission` admit `call` for the given `ability`? Checks, in\n* order: the ability flag (`canInvoke`/`canDelegate`, both default\n* `false`), the target address, the optional `params` allowlist, and the\n* optional `callBind` hash-binding. Pure.\n*/\nfunction permissionPermits(call, permission, ability) {\n\tif (!(ability === \"invoke\" ? permission.canInvoke === true : permission.canDelegate === true)) return {\n\t\tok: false,\n\t\treason: `permission does not grant ${ability}`\n\t};\n\tconst targetMismatch = _targetMismatchReason(call.target, permission);\n\tif (targetMismatch !== void 0) return {\n\t\tok: false,\n\t\treason: `permission does not address this call: ${targetMismatch.toString()}`\n\t};\n\tif (permission.params !== void 0) {\n\t\tconst r = matchParams(permission.params, call.params);\n\t\tif (!r.ok) return {\n\t\t\tok: false,\n\t\t\treason: `params: ${r.reason}`\n\t\t};\n\t}\n\tif (permission.callBind !== void 0) {\n\t\tif (permission.callBind.alg !== \"sha256\") return {\n\t\t\tok: false,\n\t\t\treason: `callBind: unsupported hash alg (${permission.callBind.alg})`\n\t\t};\n\t\tif (call.callHash !== permission.callBind.payloadHash) return {\n\t\t\tok: false,\n\t\t\treason: \"callBind: payload hash mismatch\"\n\t\t};\n\t}\n\treturn { ok: true };\n}\n/**\n* Does `cap` admit `call` for the given `ability`? True iff **any** of its\n* permissions does (the union over permissions). This is one *link's*\n* judgment; chain intersection is enforced by {@link verifyChain}.\n*/\nfunction capabilityPermits(call, cap, ability) {\n\tlet lastReason = `no permission grants ${ability} for this call`;\n\tfor (const permission of cap.permissions) {\n\t\tconst r = permissionPermits(call, permission, ability);\n\t\tif (r.ok) return { ok: true };\n\t\tlastReason = r.reason;\n\t}\n\treturn {\n\t\tok: false,\n\t\treason: lastReason\n\t};\n}\n//#endregion\n//#region src/transport/messageTransport.ts\n/**\n* Observe every message crossing a transport without changing its buffering or\n* lifecycle behavior.\n*/\nfunction traceMessageTransport(transport, trace) {\n\treturn {\n\t\tsend(message) {\n\t\t\ttrace(\"send\", message);\n\t\t\treturn transport.send(message);\n\t\t},\n\t\tsetListener(listener) {\n\t\t\ttransport.setListener(listener === void 0 ? void 0 : (message) => {\n\t\t\t\ttrace(\"receive\", message);\n\t\t\t\tlistener(message);\n\t\t\t});\n\t\t},\n\t\tdispose() {\n\t\t\ttransport.dispose();\n\t\t}\n\t};\n}\n/**\n* Pipe two transports together: every message one receives is forwarded to\n* the other's `send`. Returns a disposable that detaches both listeners.\n*\n* Neither transport is disposed — the caller owns their lifecycle. This is\n* the building block for relays (e.g. bridging a `WindowMessageTransport`\n* for an iframe to a multiplexer channel).\n*/\nfunction connectTransports(a, b) {\n\ta.setListener((m) => void b.send(m));\n\tb.setListener((m) => void a.send(m));\n\treturn { dispose() {\n\t\ta.setListener(void 0);\n\t\tb.setListener(void 0);\n\t} };\n}\n/**\n* Two in-memory transports wired back-to-back. Useful for tests and for\n* same-process bridges.\n*\n* Generic in the per-direction payload type so asymmetric pairs (e.g. one\n* side sends plain `JsonRpcMessage`, the other side sends\n* `JsonRpcMessage & { context: Participant }`) are expressible at the type\n* level. At runtime both halves just hand objects through by reference.\n*/\nvar TransportPair = class {\n\ta;\n\tb;\n\tconstructor() {\n\t\tconst aT = new _InMemoryTransport();\n\t\tconst bT = new _InMemoryTransport();\n\t\taT._peer = bT;\n\t\tbT._peer = aT;\n\t\tthis.a = aT;\n\t\tthis.b = bT;\n\t}\n};\nvar _InMemoryTransport = class {\n\t_peer;\n\t_listener;\n\t_buffer = [];\n\t_closed = false;\n\tsend(message) {\n\t\tif (this._closed || this._peer._closed) return;\n\t\tthis._peer._deliver(message);\n\t}\n\tsetListener(listener) {\n\t\tthis._listener = listener;\n\t\tif (listener) while (this._buffer.length > 0 && this._listener) {\n\t\t\tconst m = this._buffer.shift();\n\t\t\tthis._listener(m);\n\t\t}\n\t}\n\tdispose() {\n\t\tthis._closed = true;\n\t}\n\t_deliver(m) {\n\t\tif (this._listener) this._listener(m);\n\t\telse this._buffer.push(m);\n\t}\n};\n//#endregion\n//#region src/transport/multiplexedTransport.ts\nvar MultiplexedTransport = class MultiplexedTransport {\n\tstatic create(base, channels) {\n\t\treturn new MultiplexedTransport(base, channels);\n\t}\n\t/** Logical transports keyed by the friendly channel names. */\n\ttransports;\n\t_base;\n\t_byId = /* @__PURE__ */ new Map();\n\t_usedIds = /* @__PURE__ */ new Set();\n\t_disposed = false;\n\tconstructor(base, channels) {\n\t\tthis._base = base;\n\t\tconst transports = {};\n\t\tfor (const name of Object.keys(channels)) {\n\t\t\tconst id = channels[name];\n\t\t\ttransports[name] = this._createChannel(id);\n\t\t}\n\t\tthis.transports = transports;\n\t\tbase.setListener((data) => {\n\t\t\t(data == null ? void 0 : this._byId.get(data.ch))?._deliver(data.m);\n\t\t});\n\t}\n\t/**\n\t* Add a logical channel after the multiplexer has started.\n\t*\n\t* Channel ids are permanently retired when disposed. This prevents a late\n\t* envelope for an old iframe from being delivered to a replacement iframe.\n\t*/\n\taddChannel(id) {\n\t\tif (this._disposed) throw new Error(\"Cannot add a channel to a disposed multiplexed transport.\");\n\t\treturn this._createChannel(id);\n\t}\n\tdispose() {\n\t\tif (this._disposed) return;\n\t\tthis._disposed = true;\n\t\tthis._base.setListener(void 0);\n\t\tfor (const t of [...this._byId.values()]) t.dispose();\n\t\tthis._byId.clear();\n\t}\n\t_createChannel(id) {\n\t\tif (id.length === 0) throw new Error(\"Multiplexed transport channel ids must not be empty.\");\n\t\tif (this._usedIds.has(id)) throw new Error(`Multiplexed transport channel id \"${id}\" has already been used.`);\n\t\tthis._usedIds.add(id);\n\t\tconst t = new _ChannelTransport(this._base, id, () => {\n\t\t\tif (this._byId.get(id) === t) this._byId.delete(id);\n\t\t});\n\t\tthis._byId.set(id, t);\n\t\treturn t;\n\t}\n};\nvar _ChannelTransport = class {\n\t_base;\n\t_ch;\n\t_onDispose;\n\t_listener;\n\t_buffer = [];\n\t_closed = false;\n\tconstructor(_base, _ch, _onDispose) {\n\t\tthis._base = _base;\n\t\tthis._ch = _ch;\n\t\tthis._onDispose = _onDispose;\n\t}\n\tsend(message) {\n\t\tif (this._closed) return;\n\t\tthis._base.send({\n\t\t\t$mux: \"v1\",\n\t\t\tch: this._ch,\n\t\t\tm: message\n\t\t});\n\t}\n\tsetListener(listener) {\n\t\tthis._listener = listener;\n\t\tif (listener) while (this._buffer.length > 0 && this._listener) listener(this._buffer.shift());\n\t}\n\tdispose() {\n\t\tif (this._closed) return;\n\t\tthis._closed = true;\n\t\tthis._listener = void 0;\n\t\tthis._buffer.length = 0;\n\t\tthis._onDispose();\n\t}\n\t_deliver(m) {\n\t\tif (this._closed) return;\n\t\tif (this._listener) this._listener(m);\n\t\telse this._buffer.push(m);\n\t}\n};\n//#endregion\n//#region src/connection/channelConnector.ts\nconst DEFAULT_INITIAL_BACKOFF_MS = 250;\nconst DEFAULT_MAX_BACKOFF_MS = 6e4;\n/**\n* Drives a connect / (re)connect loop over a raw {@link ConnectableChannel}.\n*\n* Unlike connection-level helpers, this works at the channel layer: the\n* caller composes identity / signing on top of the channel handed to\n* {@link keepConnected} (e.g. `SigningSender.wrapChannel(channel, { principal })`).\n*\n* Construct via {@link ChannelConnector.once} (a single, already-open channel\n* that never redials) or {@link ChannelConnector.expBackoff} (re-open via a\n* factory with exponential backoff after each close).\n*/\nvar ChannelConnector = class ChannelConnector {\n\t_open;\n\t_redial;\n\t_initialBackoffMs;\n\t_maxBackoffMs;\n\tconstructor(_open, _redial, _initialBackoffMs, _maxBackoffMs) {\n\t\tthis._open = _open;\n\t\tthis._redial = _redial;\n\t\tthis._initialBackoffMs = _initialBackoffMs;\n\t\tthis._maxBackoffMs = _maxBackoffMs;\n\t}\n\t/**\n\t* A connector over a single channel (or a promise of one). Never redials;\n\t* the loop ends when the channel closes or {@link KeepConnectedHandle.stop}\n\t* fires.\n\t*/\n\tstatic once(channel) {\n\t\treturn new ChannelConnector(async () => channel, false, DEFAULT_INITIAL_BACKOFF_MS, DEFAULT_MAX_BACKOFF_MS);\n\t}\n\t/**\n\t* A redialing connector: `open` is called once per attempt, and the loop\n\t* reconnects with exponential backoff after each close (or failed open).\n\t*/\n\tstatic expBackoff(open, opts = {}) {\n\t\treturn new ChannelConnector(open, true, opts.initialBackoffMs ?? DEFAULT_INITIAL_BACKOFF_MS, opts.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS);\n\t}\n\t/**\n\t* Run `onConnect` on every (re)connect with the freshly opened channel.\n\t* The callback typically wraps the channel with signing and registers\n\t* handlers. Returns once the loop exits (see {@link KeepConnectedHandle}).\n\t*/\n\tkeepConnected(onConnect, opts = {}) {\n\t\tlet stopped = false;\n\t\tlet current;\n\t\tconst stop = () => {\n\t\t\tif (stopped) return;\n\t\t\tstopped = true;\n\t\t\tconst c = current;\n\t\t\tcurrent = void 0;\n\t\t\tc?.close?.();\n\t\t};\n\t\tif (opts.signal) {\n\t\t\tif (opts.signal.aborted) stopped = true;\n\t\t\telse opts.signal.addEventListener(\"abort\", stop, { once: true });\n\t\t}\n\t\treturn {\n\t\t\tdone: (async () => {\n\t\t\t\tlet backoff = this._initialBackoffMs;\n\t\t\t\twhile (!stopped) {\n\t\t\t\t\tlet channel;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tchannel = await this._open();\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tif (stopped || !this._redial) throw e;\n\t\t\t\t\t\tawait _delay(backoff, opts.signal);\n\t\t\t\t\t\tbackoff = Math.min(backoff * 2, this._maxBackoffMs);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (stopped) {\n\t\t\t\t\t\tchannel.close?.();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcurrent = channel;\n\t\t\t\t\tlet isClosed = false;\n\t\t\t\t\tconst closed = new Promise((resolve) => {\n\t\t\t\t\t\tchannel.onClose(() => {\n\t\t\t\t\t\t\tisClosed = true;\n\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait onConnect({ channel });\n\t\t\t\t\t\tbackoff = this._initialBackoffMs;\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tif (!isClosed) {\n\t\t\t\t\t\t\tchannel.close?.();\n\t\t\t\t\t\t\tthrow e;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (current === channel) current = void 0;\n\t\t\t\t\t\tif (stopped || !this._redial) return;\n\t\t\t\t\t\tawait _delay(backoff, opts.signal);\n\t\t\t\t\t\tbackoff = Math.min(backoff * 2, this._maxBackoffMs);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tawait closed;\n\t\t\t\t\tif (current === channel) current = void 0;\n\t\t\t\t\tif (stopped || !this._redial) return;\n\t\t\t\t}\n\t\t\t})(),\n\t\t\tstop\n\t\t};\n\t}\n};\nfunction _delay(ms, signal) {\n\treturn new Promise((resolve) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(timer);\n\t\t\tresolve();\n\t\t};\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n//#endregion\n//#region src/connection/endpointUri.ts\nconst TOKEN_PARAM = \"token\";\nconst BROKER_PARAM = \"broker\";\nconst COMMAND_PARAM = \"command\";\nconst ARGV_PARAM = \"argv\";\nconst PROVISION_SLOT_PARAM = \"provisionSlot\";\nconst ENV_PARAM = \"env\";\nconst CWD_PARAM = \"cwd\";\nfunction _tryParseUrl(uri) {\n\ttry {\n\t\treturn new URL(uri);\n\t} catch {\n\t\treturn;\n\t}\n}\nfunction _looksLikeWsUrl(uri) {\n\treturn /^wss?:\\/\\//i.test(uri);\n}\n/** True for a Windows named-pipe path (`\\\\.\\pipe\\…` or `\\\\?\\pipe\\…`). */\nfunction _isWindowsPipePath(path) {\n\treturn /^\\\\\\\\[.?]\\\\pipe\\\\/i.test(path);\n}\nfunction _parseCommand(url) {\n\tconst argv = url.searchParams.getAll(ARGV_PARAM);\n\tif (argv.length > 0) return { argv };\n\tconst command = url.searchParams.get(COMMAND_PARAM);\n\tif (command !== null) return { command };\n\tthrow new Error(`endpoint '${url.protocol}' requires a '${COMMAND_PARAM}' or '${ARGV_PARAM}' query parameter`);\n}\n/** Parse repeated `env=KEY=VALUE` params into a record (first `=` splits). */\nfunction _parseEnv(url) {\n\tconst entries = url.searchParams.getAll(ENV_PARAM);\n\tif (entries.length === 0) return;\n\tconst env = {};\n\tfor (const entry of entries) {\n\t\tconst eq = entry.indexOf(\"=\");\n\t\tif (eq === -1) throw new Error(`endpoint '${ENV_PARAM}' param must be 'KEY=VALUE', got '${entry}'`);\n\t\tenv[entry.slice(0, eq)] = entry.slice(eq + 1);\n\t}\n\treturn env;\n}\n/**\n* Parse a strict endpoint URI into an {@link ResolvedEndpoint}. Throws on an\n* unknown scheme or a malformed command endpoint. A bare (scheme-less) string\n* is auto-detected as `ws`/`wss` URL or a socket path.\n*/\nfunction parseEndpointUri(uri) {\n\tconst trimmed = uri.trim();\n\tif (trimmed === \"\") throw new Error(\"endpoint URI is empty\");\n\tconst url = _tryParseUrl(trimmed);\n\tif (!url) {\n\t\tif (_looksLikeWsUrl(trimmed)) return {\n\t\t\tkind: \"ws\",\n\t\t\turl: trimmed\n\t\t};\n\t\treturn {\n\t\t\tkind: \"socket\",\n\t\t\tpath: trimmed\n\t\t};\n\t}\n\tswitch (url.protocol) {\n\t\tcase \"ws:\":\n\t\tcase \"wss:\": {\n\t\t\tconst token = url.searchParams.get(TOKEN_PARAM) ?? void 0;\n\t\t\turl.searchParams.delete(TOKEN_PARAM);\n\t\t\tconst cleanUrl = url.toString();\n\t\t\treturn token !== void 0 ? {\n\t\t\t\tkind: \"ws\",\n\t\t\t\turl: cleanUrl,\n\t\t\t\ttoken\n\t\t\t} : {\n\t\t\t\tkind: \"ws\",\n\t\t\t\turl: cleanUrl\n\t\t\t};\n\t\t}\n\t\tcase \"ws-no-init:\": return {\n\t\t\tkind: \"ws-no-init\",\n\t\t\turl: new URL(trimmed.replace(/^ws-no-init:/i, \"ws:\")).toString()\n\t\t};\n\t\tcase \"unix:\": {\n\t\t\tconst token = url.searchParams.get(TOKEN_PARAM) ?? void 0;\n\t\t\tconst brokerMode = _parseBrokerMode(url);\n\t\t\treturn {\n\t\t\t\tkind: \"socket\",\n\t\t\t\tpath: decodeURIComponent(url.pathname),\n\t\t\t\t...token !== void 0 ? { token } : {},\n\t\t\t\t...brokerMode !== void 0 ? { brokerMode } : {}\n\t\t\t};\n\t\t}\n\t\tcase \"npipe:\": {\n\t\t\tconst token = url.searchParams.get(TOKEN_PARAM) ?? void 0;\n\t\t\tconst brokerMode = _parseBrokerMode(url);\n\t\t\treturn {\n\t\t\t\tkind: \"socket\",\n\t\t\t\tpath: `\\\\\\\\${url.host === \"\" ? \".\" : url.host}${decodeURIComponent(url.pathname).replace(/\\//g, \"\\\\\")}`,\n\t\t\t\t...token !== void 0 ? { token } : {},\n\t\t\t\t...brokerMode !== void 0 ? { brokerMode } : {}\n\t\t\t};\n\t\t}\n\t\tcase \"cmd-stdio:\": {\n\t\t\tconst env = _parseEnv(url);\n\t\t\tconst cwd = url.searchParams.get(CWD_PARAM) ?? void 0;\n\t\t\treturn {\n\t\t\t\tkind: \"cmd-stdio\",\n\t\t\t\tcommand: _parseCommand(url),\n\t\t\t\t...env !== void 0 ? { env } : {},\n\t\t\t\t...cwd !== void 0 ? { cwd } : {}\n\t\t\t};\n\t\t}\n\t\tcase \"cmd:\": {\n\t\t\tconst command = _parseCommand(url);\n\t\t\tconst provisionSlot = url.searchParams.get(PROVISION_SLOT_PARAM) ?? void 0;\n\t\t\tconst env = _parseEnv(url);\n\t\t\tconst cwd = url.searchParams.get(CWD_PARAM) ?? void 0;\n\t\t\treturn {\n\t\t\t\tkind: \"cmd-env\",\n\t\t\t\tcommand,\n\t\t\t\t...provisionSlot !== void 0 ? { provisionSlot } : {},\n\t\t\t\t...env !== void 0 ? { env } : {},\n\t\t\t\t...cwd !== void 0 ? { cwd } : {}\n\t\t\t};\n\t\t}\n\t\tdefault: throw new Error(`unsupported endpoint scheme '${url.protocol}' (expected unix:, npipe:, ws:, wss:, ws-no-init:, cmd:, or cmd-stdio:)`);\n\t}\n}\nconst REDACTED = \"***\";\nfunction _appendToken(params, token, reveal) {\n\tif (token === void 0) return;\n\tparams.set(TOKEN_PARAM, reveal ? token : REDACTED);\n}\nfunction _parseBrokerMode(url) {\n\tconst value = url.searchParams.get(BROKER_PARAM);\n\tif (value === null) return void 0;\n\tif (value === \"linkrpc\" || value === \"raw\") return value;\n\tthrow new Error(`endpoint '${BROKER_PARAM}' param must be 'linkrpc' or 'raw', got '${value}'`);\n}\nfunction _appendCommand(params, command) {\n\tif (\"argv\" in command) for (const a of command.argv) params.append(ARGV_PARAM, a);\n\telse params.set(COMMAND_PARAM, command.command);\n}\nfunction _appendEnv(params, env) {\n\tif (env === void 0) return;\n\tfor (const [key, value] of Object.entries(env)) params.append(ENV_PARAM, `${key}=${value}`);\n}\n/**\n* Render an {@link ResolvedEndpoint} back to a canonical strict URI. The token is\n* redacted (`***`) unless `revealToken` is set, so the result is paste-safe for\n* logs. Round-trips with {@link parseEndpointUri} when `revealToken` is true.\n*/\nfunction formatEndpointUri(spec, options) {\n\tconst reveal = options?.revealToken === true;\n\tswitch (spec.kind) {\n\t\tcase \"socket\": {\n\t\t\tconst params = new URLSearchParams();\n\t\t\t_appendToken(params, spec.token, reveal);\n\t\t\tif (spec.brokerMode !== void 0) params.set(BROKER_PARAM, spec.brokerMode);\n\t\t\tconst query = params.toString();\n\t\t\tconst suffix = query === \"\" ? \"\" : `?${query}`;\n\t\t\tif (_isWindowsPipePath(spec.path)) {\n\t\t\t\tconst m = spec.path.match(/^\\\\\\\\([.?])\\\\(.*)$/);\n\t\t\t\treturn `npipe://${m ? m[1] : \".\"}/${(m ? m[2] : spec.path).replace(/\\\\/g, \"/\")}${suffix}`;\n\t\t\t}\n\t\t\treturn `unix:${spec.path}${suffix}`;\n\t\t}\n\t\tcase \"ws\": {\n\t\t\tconst url = new URL(spec.url);\n\t\t\t_appendToken(url.searchParams, spec.token, reveal);\n\t\t\treturn url.toString();\n\t\t}\n\t\tcase \"ws-no-init\": return spec.url.replace(/^ws:/i, \"ws-no-init:\");\n\t\tcase \"cmd-stdio\": {\n\t\t\tconst params = new URLSearchParams();\n\t\t\t_appendCommand(params, spec.command);\n\t\t\t_appendEnv(params, spec.env);\n\t\t\tif (spec.cwd !== void 0) params.set(CWD_PARAM, spec.cwd);\n\t\t\treturn `cmd-stdio:?${params.toString()}`;\n\t\t}\n\t\tcase \"cmd-env\": {\n\t\t\tconst params = new URLSearchParams();\n\t\t\t_appendCommand(params, spec.command);\n\t\t\tif (spec.provisionSlot !== void 0) params.set(PROVISION_SLOT_PARAM, spec.provisionSlot);\n\t\t\t_appendEnv(params, spec.env);\n\t\t\tif (spec.cwd !== void 0) params.set(CWD_PARAM, spec.cwd);\n\t\t\treturn `cmd:?${params.toString()}`;\n\t\t}\n\t}\n}\n/** True for endpoints that connect to existing, possibly-remote infrastructure. */\nfunction isHubEndpoint(spec) {\n\treturn spec.kind === \"socket\" && spec.brokerMode !== \"raw\" || spec.kind === \"ws\";\n}\n//#endregion\n//#region ../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/errors.js\n/**\n* The base error class of hpke-js.\n* @group Errors\n*/\nvar HpkeError = class extends Error {\n\tconstructor(e) {\n\t\tlet message;\n\t\tif (e instanceof Error) message = e.message;\n\t\telse if (typeof e === \"string\") message = e;\n\t\telse message = \"\";\n\t\tsuper(message);\n\t\tthis.name = this.constructor.name;\n\t}\n};\n/**\n* Invalid parameter.\n* @group Errors\n*/\nvar InvalidParamError = class extends HpkeError {};\n/**\n* Public or private key serialization failure.\n* @group Errors\n*/\nvar SerializeError = class extends HpkeError {};\n/**\n* Public or private key deserialization failure.\n* @group Errors\n*/\nvar DeserializeError = class extends HpkeError {};\n/**\n* encap() failure.\n* @group Errors\n*/\nvar EncapError = class extends HpkeError {};\n/**\n* decap() failure.\n* @group Errors\n*/\nvar DecapError = class extends HpkeError {};\n/**\n* Secret export failure.\n* @group Errors\n*/\nvar ExportError = class extends HpkeError {};\n/**\n* seal() failure.\n* @group Errors\n*/\nvar SealError = class extends HpkeError {};\n/**\n* open() failure.\n* @group Errors\n*/\nvar OpenError = class extends HpkeError {};\n/**\n* Sequence number overflow on the encryption context.\n* @group Errors\n*/\nvar MessageLimitReachedError = class extends HpkeError {};\n/**\n* Key pair derivation failure.\n* @group Errors\n*/\nvar DeriveKeyPairError = class extends HpkeError {};\n/**\n* Not supported failure.\n* @group Errors\n*/\nvar NotSupportedError = class extends HpkeError {};\nconst dntGlobalThis = createMergeProxy(globalThis, {});\nfunction createMergeProxy(baseObj, extObj) {\n\treturn new Proxy(baseObj, {\n\t\tget(_target, prop, _receiver) {\n\t\t\tif (prop in extObj) return extObj[prop];\n\t\t\telse return baseObj[prop];\n\t\t},\n\t\tset(_target, prop, value) {\n\t\t\tif (prop in extObj) delete extObj[prop];\n\t\t\tbaseObj[prop] = value;\n\t\t\treturn true;\n\t\t},\n\t\tdeleteProperty(_target, prop) {\n\t\t\tlet success = false;\n\t\t\tif (prop in extObj) {\n\t\t\t\tdelete extObj[prop];\n\t\t\t\tsuccess = true;\n\t\t\t}\n\t\t\tif (prop in baseObj) {\n\t\t\t\tdelete baseObj[prop];\n\t\t\t\tsuccess = true;\n\t\t\t}\n\t\t\treturn success;\n\t\t},\n\t\townKeys(_target) {\n\t\t\tconst baseKeys = Reflect.ownKeys(baseObj);\n\t\t\tconst extKeys = Reflect.ownKeys(extObj);\n\t\t\tconst extKeysSet = new Set(extKeys);\n\t\t\treturn [...baseKeys.filter((k) => !extKeysSet.has(k)), ...extKeys];\n\t\t},\n\t\tdefineProperty(_target, prop, desc) {\n\t\t\tif (prop in extObj) delete extObj[prop];\n\t\t\tReflect.defineProperty(baseObj, prop, desc);\n\t\t\treturn true;\n\t\t},\n\t\tgetOwnPropertyDescriptor(_target, prop) {\n\t\t\tif (prop in extObj) return Reflect.getOwnPropertyDescriptor(extObj, prop);\n\t\t\telse return Reflect.getOwnPropertyDescriptor(baseObj, prop);\n\t\t},\n\t\thas(_target, prop) {\n\t\t\treturn prop in extObj || prop in baseObj;\n\t\t}\n\t});\n}\n//#endregion\n//#region ../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/algorithm.js\nasync function loadSubtleCrypto() {\n\tif (dntGlobalThis !== void 0 && globalThis.crypto !== void 0) return globalThis.crypto.subtle;\n\ttry {\n\t\tconst { webcrypto } = await import(\"./_empty-crypto-Bi0tGx5K.js\");\n\t\treturn webcrypto.subtle;\n\t} catch (e) {\n\t\tthrow new NotSupportedError(e);\n\t}\n}\nvar NativeAlgorithm = class {\n\tconstructor() {\n\t\tObject.defineProperty(this, \"_api\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t}\n\tasync _setup() {\n\t\tif (this._api !== void 0) return;\n\t\tthis._api = await loadSubtleCrypto();\n\t}\n};\n//#endregion\n//#region ../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/identifiers.js\n/**\n* The supported HPKE modes.\n*/\nconst Mode = {\n\tBase: 0,\n\tPsk: 1,\n\tAuth: 2,\n\tAuthPsk: 3\n};\n/**\n* The supported Key Encapsulation Mechanism (KEM) identifiers.\n*/\nconst KemId = {\n\tNotAssigned: 0,\n\tDhkemP256HkdfSha256: 16,\n\tDhkemP384HkdfSha384: 17,\n\tDhkemP521HkdfSha512: 18,\n\tDhkemSecp256k1HkdfSha256: 19,\n\tDhkemX25519HkdfSha256: 32,\n\tDhkemX448HkdfSha512: 33,\n\tHybridkemX25519Kyber768: 48,\n\tMlKem512: 64,\n\tMlKem768: 65,\n\tMlKem1024: 66,\n\tXWing: 25722\n};\n/**\n* The supported Key Derivation Function (KDF) identifiers.\n*/\nconst KdfId = {\n\tHkdfSha256: 1,\n\tHkdfSha384: 2,\n\tHkdfSha512: 3,\n\tSha3256: 4,\n\tSha3384: 5,\n\tSha3512: 6,\n\tShake128: 16,\n\tShake256: 17,\n\tTurboShake128: 18,\n\tTurboShake256: 19\n};\n/**\n* The supported Authenticated Encryption with Associated Data (AEAD) identifiers.\n*/\nconst AeadId = {\n\tAes128Gcm: 1,\n\tAes256Gcm: 2,\n\tChacha20Poly1305: 3,\n\tExportOnly: 65535\n};\nconst EMPTY = /* @__PURE__ */ new Uint8Array(0);\n//#endregion\n//#region ../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/interfaces/kemInterface.js\nconst SUITE_ID_HEADER_KEM = /* @__PURE__ */ new Uint8Array([\n\t75,\n\t69,\n\t77,\n\t0,\n\t0\n]);\n//#endregion\n//#region ../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/kdfs/hkdf.js\nconst HPKE_VERSION = /* @__PURE__ */ new Uint8Array([\n\t72,\n\t80,\n\t75,\n\t69,\n\t45,\n\t118,\n\t49\n]);\nfunction toUint8Array(input) {\n\treturn new Uint8Array(toArrayBuffer(input));\n}\nfunction toArrayBuffer(input) {\n\tif (input instanceof ArrayBuffer) return input;\n\tif (ArrayBuffer.isView(input)) return new Uint8Array(input.buffer, input.byteOffset, input.byteLength).slice().buffer;\n\treturn new Uint8Array(input).slice().buffer;\n}\nvar HkdfNative = class extends NativeAlgorithm {\n\tconstructor() {\n\t\tsuper();\n\t\tObject.defineProperty(this, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: KdfId.HkdfSha256\n\t\t});\n\t\tObject.defineProperty(this, \"hashSize\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: 0\n\t\t});\n\t\tObject.defineProperty(this, \"_suiteId\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: EMPTY\n\t\t});\n\t\tObject.defineProperty(this, \"algHash\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: {\n\t\t\t\tname: \"HMAC\",\n\t\t\t\thash: \"SHA-256\",\n\t\t\t\tlength: 256\n\t\t\t}\n\t\t});\n\t}\n\tinit(suiteId) {\n\t\tthis._suiteId = suiteId;\n\t}\n\tbuildLabeledIkm(label, ikm) {\n\t\tthis._checkInit();\n\t\tconst ret = new Uint8Array(7 + this._suiteId.byteLength + label.byteLength + ikm.byteLength);\n\t\tret.set(HPKE_VERSION, 0);\n\t\tret.set(this._suiteId, 7);\n\t\tret.set(label, 7 + this._suiteId.byteLength);\n\t\tret.set(ikm, 7 + this._suiteId.byteLength + label.byteLength);\n\t\treturn ret;\n\t}\n\tbuildLabeledInfo(label, info, len) {\n\t\tthis._checkInit();\n\t\tconst ret = new Uint8Array(9 + this._suiteId.byteLength + label.byteLength + info.byteLength);\n\t\tret.set(new Uint8Array([0, len]), 0);\n\t\tret.set(HPKE_VERSION, 2);\n\t\tret.set(this._suiteId, 9);\n\t\tret.set(label, 9 + this._suiteId.byteLength);\n\t\tret.set(info, 9 + this._suiteId.byteLength + label.byteLength);\n\t\treturn ret;\n\t}\n\tasync extract(salt, ikm) {\n\t\tawait this._setup();\n\t\tconst saltBuf = salt.byteLength === 0 ? new ArrayBuffer(this.hashSize) : toArrayBuffer(salt);\n\t\tif (saltBuf.byteLength !== this.hashSize) throw new InvalidParamError(\"The salt length must be the same as the hashSize\");\n\t\tconst ikmBuf = toArrayBuffer(ikm);\n\t\tconst key = await this._api.importKey(\"raw\", saltBuf, this.algHash, false, [\"sign\"]);\n\t\treturn await this._api.sign(\"HMAC\", key, ikmBuf);\n\t}\n\tasync expand(prk, info, len) {\n\t\tawait this._setup();\n\t\tconst prkBuf = toArrayBuffer(prk);\n\t\tconst key = await this._api.importKey(\"raw\", prkBuf, this.algHash, false, [\"sign\"]);\n\t\tconst okm = new ArrayBuffer(len);\n\t\tconst okmBytes = new Uint8Array(okm);\n\t\tlet prev = EMPTY;\n\t\tconst mid = toUint8Array(info);\n\t\tconst tail = /* @__PURE__ */ new Uint8Array(1);\n\t\tif (len > 255 * this.hashSize) throw new Error(\"Entropy limit reached\");\n\t\tconst tmp = new Uint8Array(this.hashSize + mid.length + 1);\n\t\tfor (let i = 1, cur = 0; cur < okmBytes.length; i++) {\n\t\t\ttail[0] = i;\n\t\t\ttmp.set(prev, 0);\n\t\t\ttmp.set(mid, prev.length);\n\t\t\ttmp.set(tail, prev.length + mid.length);\n\t\t\tprev = new Uint8Array(await this._api.sign(\"HMAC\", key, tmp.slice(0, prev.length + mid.length + 1)));\n\t\t\tif (okmBytes.length - cur >= prev.length) {\n\t\t\t\tokmBytes.set(prev, cur);\n\t\t\t\tcur += prev.length;\n\t\t\t} else {\n\t\t\t\tokmBytes.set(prev.slice(0, okmBytes.length - cur), cur);\n\t\t\t\tcur += okmBytes.length - cur;\n\t\t\t}\n\t\t}\n\t\treturn okm;\n\t}\n\tasync extractAndExpand(salt, ikm, info, len) {\n\t\tawait this._setup();\n\t\tconst ikmBuf = toArrayBuffer(ikm);\n\t\tconst baseKey = await this._api.importKey(\"raw\", ikmBuf, \"HKDF\", false, [\"deriveBits\"]);\n\t\treturn await this._api.deriveBits({\n\t\t\tname: \"HKDF\",\n\t\t\thash: this.algHash.hash,\n\t\t\tsalt: toArrayBuffer(salt),\n\t\t\tinfo: toArrayBuffer(info)\n\t\t}, baseKey, len * 8);\n\t}\n\tasync labeledExtract(salt, label, ikm) {\n\t\treturn await this.extract(salt, this.buildLabeledIkm(label, ikm));\n\t}\n\tasync labeledExpand(prk, label, info, len) {\n\t\treturn await this.expand(prk, this.buildLabeledInfo(label, info, len), len);\n\t}\n\t_checkInit() {\n\t\tif (this._suiteId === EMPTY) throw new Error(\"Not initialized. Call init()\");\n\t}\n};\nvar HkdfSha256Native = class extends HkdfNative {\n\tconstructor() {\n\t\tsuper(...arguments);\n\t\t/** KdfId.HkdfSha256 (0x0001) */\n\t\tObject.defineProperty(this, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: KdfId.HkdfSha256\n\t\t});\n\t\t/** 32 */\n\t\tObject.defineProperty(this, \"hashSize\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: 32\n\t\t});\n\t\t/** The parameters for Web Cryptography API */\n\t\tObject.defineProperty(this, \"algHash\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: {\n\t\t\t\tname: \"HMAC\",\n\t\t\t\thash: \"SHA-256\",\n\t\t\t\tlength: 256\n\t\t\t}\n\t\t});\n\t}\n};\n//#endregion\n//#region ../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/utils/misc.js\n/**\n* Checks whetehr the type of input is CryptoKeyPair or not.\n*/\nconst isCryptoKeyPair = (x) => typeof x === \"object\" && x !== null && typeof x.privateKey === \"object\" && typeof x.publicKey === \"object\";\n/**\n* Converts integer to octet string. I2OSP implementation.\n*/\nfunction i2Osp(n, w) {\n\tif (w <= 0) throw new Error(\"i2Osp: too small size\");\n\tif (n >= 256 ** w) throw new Error(\"i2Osp: too large integer\");\n\tconst ret = new Uint8Array(w);\n\tfor (let i = 0; i < w && n; i++) {\n\t\tret[w - (i + 1)] = n % 256;\n\t\tn = Math.floor(n / 256);\n\t}\n\treturn ret;\n}\n/**\n* Concatenates two Uint8Arrays.\n* @param a Uint8Array\n* @param b Uint8Array\n* @returns Concatenated Uint8Array\n*/\nfunction concat(a, b) {\n\tconst ret = new Uint8Array(a.length + b.length);\n\tret.set(a, 0);\n\tret.set(b, a.length);\n\treturn ret;\n}\n/**\n* Decodes Base64Url-encoded data.\n* @param v Base64Url-encoded string\n* @returns Uint8Array\n*/\nfunction base64UrlToBytes(v) {\n\tconst base64 = v.replace(/-/g, \"+\").replace(/_/g, \"/\");\n\tconst byteString = atob(base64);\n\tconst ret = new Uint8Array(byteString.length);\n\tfor (let i = 0; i < byteString.length; i++) ret[i] = byteString.charCodeAt(i);\n\treturn ret;\n}\n/**\n* XOR for Uint8Array.\n*/\nfunction xor(a, b) {\n\tif (a.byteLength !== b.byteLength) throw new Error(\"xor: different length inputs\");\n\tconst buf = new Uint8Array(a.byteLength);\n\tfor (let i = 0; i < a.byteLength; i++) buf[i] = a[i] ^ b[i];\n\treturn buf;\n}\n//#endregion\n//#region ../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/kems/dhkem.js\nconst LABEL_EAE_PRK = /* @__PURE__ */ new Uint8Array([\n\t101,\n\t97,\n\t101,\n\t95,\n\t112,\n\t114,\n\t107\n]);\nconst LABEL_SHARED_SECRET = /* @__PURE__ */ new Uint8Array([\n\t115,\n\t104,\n\t97,\n\t114,\n\t101,\n\t100,\n\t95,\n\t115,\n\t101,\n\t99,\n\t114,\n\t101,\n\t116\n]);\nfunction concat3(a, b, c) {\n\tconst ret = new Uint8Array(a.length + b.length + c.length);\n\tret.set(a, 0);\n\tret.set(b, a.length);\n\tret.set(c, a.length + b.length);\n\treturn ret;\n}\nvar Dhkem = class {\n\tconstructor(id, prim, kdf) {\n\t\tObject.defineProperty(this, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tObject.defineProperty(this, \"secretSize\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: 0\n\t\t});\n\t\tObject.defineProperty(this, \"encSize\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: 0\n\t\t});\n\t\tObject.defineProperty(this, \"publicKeySize\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: 0\n\t\t});\n\t\tObject.defineProperty(this, \"privateKeySize\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: 0\n\t\t});\n\t\tObject.defineProperty(this, \"_prim\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tObject.defineProperty(this, \"_kdf\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tthis.id = id;\n\t\tthis._prim = prim;\n\t\tthis._kdf = kdf;\n\t\tconst suiteId = new Uint8Array(SUITE_ID_HEADER_KEM);\n\t\tsuiteId.set(i2Osp(this.id, 2), 3);\n\t\tthis._kdf.init(suiteId);\n\t}\n\tasync serializePublicKey(key) {\n\t\treturn await this._prim.serializePublicKey(key);\n\t}\n\tasync deserializePublicKey(key) {\n\t\treturn await this._prim.deserializePublicKey(toArrayBuffer(key));\n\t}\n\tasync serializePrivateKey(key) {\n\t\treturn await this._prim.serializePrivateKey(key);\n\t}\n\tasync deserializePrivateKey(key) {\n\t\treturn await this._prim.deserializePrivateKey(toArrayBuffer(key));\n\t}\n\tasync importKey(format, key, isPublic = true) {\n\t\treturn await this._prim.importKey(format, key, isPublic);\n\t}\n\tasync generateKeyPair() {\n\t\treturn await this._prim.generateKeyPair();\n\t}\n\tasync deriveKeyPair(ikm) {\n\t\tconst rawIkm = toArrayBuffer(ikm);\n\t\tif (rawIkm.byteLength > 8192) throw new InvalidParamError(\"Too long ikm\");\n\t\treturn await this._prim.deriveKeyPair(rawIkm);\n\t}\n\tasync encap(params) {\n\t\tlet ke;\n\t\tif (params.ekm === void 0) ke = await this.generateKeyPair();\n\t\telse if (isCryptoKeyPair(params.ekm)) ke = params.ekm;\n\t\telse ke = await this.deriveKeyPair(params.ekm);\n\t\tconst enc = await this._prim.serializePublicKey(ke.publicKey);\n\t\tconst pkrm = await this._prim.serializePublicKey(params.recipientPublicKey);\n\t\ttry {\n\t\t\tlet dh;\n\t\t\tif (params.senderKey === void 0) dh = new Uint8Array(await this._prim.dh(ke.privateKey, params.recipientPublicKey));\n\t\t\telse {\n\t\t\t\tconst sks = isCryptoKeyPair(params.senderKey) ? params.senderKey.privateKey : params.senderKey;\n\t\t\t\tdh = concat(new Uint8Array(await this._prim.dh(ke.privateKey, params.recipientPublicKey)), new Uint8Array(await this._prim.dh(sks, params.recipientPublicKey)));\n\t\t\t}\n\t\t\tlet kemContext;\n\t\t\tif (params.senderKey === void 0) kemContext = concat(new Uint8Array(enc), new Uint8Array(pkrm));\n\t\t\telse {\n\t\t\t\tconst pks = isCryptoKeyPair(params.senderKey) ? params.senderKey.publicKey : await this._prim.derivePublicKey(params.senderKey);\n\t\t\t\tconst pksm = await this._prim.serializePublicKey(pks);\n\t\t\t\tkemContext = concat3(new Uint8Array(enc), new Uint8Array(pkrm), new Uint8Array(pksm));\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tenc,\n\t\t\t\tsharedSecret: await this._generateSharedSecret(dh, kemContext)\n\t\t\t};\n\t\t} catch (e) {\n\t\t\tthrow new EncapError(e);\n\t\t}\n\t}\n\tasync decap(params) {\n\t\tconst enc = toArrayBuffer(params.enc);\n\t\tconst pke = await this._prim.deserializePublicKey(enc);\n\t\tconst skr = isCryptoKeyPair(params.recipientKey) ? params.recipientKey.privateKey : params.recipientKey;\n\t\tconst pkr = isCryptoKeyPair(params.recipientKey) ? params.recipientKey.publicKey : await this._prim.derivePublicKey(params.recipientKey);\n\t\tconst pkrm = await this._prim.serializePublicKey(pkr);\n\t\ttry {\n\t\t\tlet dh;\n\t\t\tif (params.senderPublicKey === void 0) dh = new Uint8Array(await this._prim.dh(skr, pke));\n\t\t\telse dh = concat(new Uint8Array(await this._prim.dh(skr, pke)), new Uint8Array(await this._prim.dh(skr, params.senderPublicKey)));\n\t\t\tlet kemContext;\n\t\t\tif (params.senderPublicKey === void 0) kemContext = concat(new Uint8Array(enc), new Uint8Array(pkrm));\n\t\t\telse {\n\t\t\t\tconst pksm = await this._prim.serializePublicKey(params.senderPublicKey);\n\t\t\t\tkemContext = new Uint8Array(enc.byteLength + pkrm.byteLength + pksm.byteLength);\n\t\t\t\tkemContext.set(new Uint8Array(enc), 0);\n\t\t\t\tkemContext.set(new Uint8Array(pkrm), enc.byteLength);\n\t\t\t\tkemContext.set(new Uint8Array(pksm), enc.byteLength + pkrm.byteLength);\n\t\t\t}\n\t\t\treturn await this._generateSharedSecret(dh, kemContext);\n\t\t} catch (e) {\n\t\t\tthrow new DecapError(e);\n\t\t}\n\t}\n\tasync _generateSharedSecret(dh, kemContext) {\n\t\tconst labeledIkm = this._kdf.buildLabeledIkm(LABEL_EAE_PRK, dh);\n\t\tconst labeledInfo = this._kdf.buildLabeledInfo(LABEL_SHARED_SECRET, kemContext, this.secretSize);\n\t\treturn await this._kdf.extractAndExpand(EMPTY, labeledIkm, labeledInfo, this.secretSize);\n\t}\n};\n//#endregion\n//#region ../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/interfaces/dhkemPrimitives.js\nconst KEM_USAGES = [\"deriveBits\"];\nconst LABEL_DKP_PRK = /* @__PURE__ */ new Uint8Array([\n\t100,\n\t107,\n\t112,\n\t95,\n\t112,\n\t114,\n\t107\n]);\nconst LABEL_SK = /* @__PURE__ */ new Uint8Array([115, 107]);\n//#endregion\n//#region ../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/interfaces/aeadEncryptionContext.js\nconst AEAD_USAGES = [\"encrypt\", \"decrypt\"];\n//#endregion\n//#region ../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/aeads/aesGcm.js\nvar AesGcmContext = class extends NativeAlgorithm {\n\tconstructor(key) {\n\t\tsuper();\n\t\tObject.defineProperty(this, \"_rawKey\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tObject.defineProperty(this, \"_key\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tthis._rawKey = toArrayBuffer(key);\n\t}\n\tasync seal(iv, data, aad) {\n\t\tawait this._setupKey();\n\t\tconst alg = {\n\t\t\tname: \"AES-GCM\",\n\t\t\tiv: toArrayBuffer(iv),\n\t\t\tadditionalData: toArrayBuffer(aad)\n\t\t};\n\t\treturn await this._api.encrypt(alg, this._key, toArrayBuffer(data));\n\t}\n\tasync open(iv, data, aad) {\n\t\tawait this._setupKey();\n\t\tconst alg = {\n\t\t\tname: \"AES-GCM\",\n\t\t\tiv: toArrayBuffer(iv),\n\t\t\tadditionalData: toArrayBuffer(aad)\n\t\t};\n\t\treturn await this._api.decrypt(alg, this._key, toArrayBuffer(data));\n\t}\n\tasync _setupKey() {\n\t\tif (this._key !== void 0) return;\n\t\tawait this._setup();\n\t\tconst key = await this._importKey(this._rawKey);\n\t\tnew Uint8Array(this._rawKey).fill(0);\n\t\tthis._key = key;\n\t}\n\tasync _importKey(key) {\n\t\treturn await this._api.importKey(\"raw\", key, { name: \"AES-GCM\" }, true, AEAD_USAGES);\n\t}\n};\n/**\n* The AES-128-GCM for HPKE AEAD implementing {@link AeadInterface}.\n*\n* When using `@hpke/core`, the instance of this class must be specified\n* to the `aead` parameter of {@link CipherSuiteParams} instead of `AeadId.Aes128Gcm`.\n*\n* @example\n*\n* ```ts\n* import {\n* Aes128Gcm,\n* CipherSuite,\n* DhkemP256HkdfSha256,\n* HkdfSha256,\n* } from \"@hpke/core\";\n*\n* const suite = new CipherSuite({\n* kem: new DhkemP256HkdfSha256(),\n* kdf: new HkdfSha256(),\n* aead: new Aes128Gcm(),\n* });\n* ```\n*/\nvar Aes128Gcm = class {\n\tconstructor() {\n\t\t/** AeadId.Aes128Gcm (0x0001) */\n\t\tObject.defineProperty(this, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: AeadId.Aes128Gcm\n\t\t});\n\t\t/** 16 */\n\t\tObject.defineProperty(this, \"keySize\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: 16\n\t\t});\n\t\t/** 12 */\n\t\tObject.defineProperty(this, \"nonceSize\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: 12\n\t\t});\n\t\t/** 16 */\n\t\tObject.defineProperty(this, \"tagSize\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: 16\n\t\t});\n\t}\n\tcreateEncryptionContext(key) {\n\t\treturn new AesGcmContext(key);\n\t}\n};\n/**\n* The AES-256-GCM for HPKE AEAD implementing {@link AeadInterface}.\n*\n* When using `@hpke/core`, the instance of this class must be specified\n* to the `aead` parameter of {@link CipherSuiteParams} instead of `AeadId.Aes256Gcm`\n* as follows:\n*\n* @example\n*\n* ```ts\n* import {\n* Aes256Gcm,\n* CipherSuite,\n* DhkemP256HkdfSha256,\n* HkdfSha256,\n* } from \"@hpke/core\";\n*\n* const suite = new CipherSuite({\n* kem: new DhkemP256HkdfSha256(),\n* kdf: new HkdfSha256(),\n* aead: new Aes256Gcm(),\n* });\n* ```\n*/\nvar Aes256Gcm = class extends Aes128Gcm {\n\tconstructor() {\n\t\tsuper(...arguments);\n\t\t/** AeadId.Aes256Gcm (0x0002) */\n\t\tObject.defineProperty(this, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: AeadId.Aes256Gcm\n\t\t});\n\t\t/** 32 */\n\t\tObject.defineProperty(this, \"keySize\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: 32\n\t\t});\n\t\t/** 12 */\n\t\tObject.defineProperty(this, \"nonceSize\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: 12\n\t\t});\n\t\t/** 16 */\n\t\tObject.defineProperty(this, \"tagSize\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: 16\n\t\t});\n\t}\n};\n//#endregion\n//#region ../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/utils/emitNotSupported.js\nfunction emitNotSupported() {\n\treturn new Promise((_resolve, reject) => {\n\t\treject(new NotSupportedError(\"Not supported\"));\n\t});\n}\n//#endregion\n//#region ../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/exporterContext.js\nconst LABEL_SEC = new Uint8Array([\n\t115,\n\t101,\n\t99\n]);\nvar ExporterContextImpl = class {\n\tconstructor(api, kdf, exporterSecret) {\n\t\tObject.defineProperty(this, \"_api\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tObject.defineProperty(this, \"exporterSecret\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tObject.defineProperty(this, \"_kdf\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tthis._api = api;\n\t\tthis._kdf = kdf;\n\t\tthis.exporterSecret = exporterSecret;\n\t}\n\tasync seal(_data, _aad) {\n\t\treturn await emitNotSupported();\n\t}\n\tasync open(_data, _aad) {\n\t\treturn await emitNotSupported();\n\t}\n\tasync export(exporterContext, len) {\n\t\tconst rawExporterContext = toArrayBuffer(exporterContext);\n\t\tif (rawExporterContext.byteLength > 8192) throw new InvalidParamError(\"Too long exporter context\");\n\t\ttry {\n\t\t\treturn await this._kdf.labeledExpand(this.exporterSecret, LABEL_SEC, new Uint8Array(rawExporterContext), len);\n\t\t} catch (e) {\n\t\t\tthrow new ExportError(e);\n\t\t}\n\t}\n};\nvar RecipientExporterContextImpl = class extends ExporterContextImpl {};\nvar SenderExporterContextImpl = class extends ExporterContextImpl {\n\tconstructor(api, kdf, exporterSecret, enc) {\n\t\tsuper(api, kdf, exporterSecret);\n\t\tObject.defineProperty(this, \"enc\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tthis.enc = enc;\n\t}\n};\n//#endregion\n//#region ../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/encryptionContext.js\nvar EncryptionContextImpl = class extends ExporterContextImpl {\n\tconstructor(api, kdf, params) {\n\t\tsuper(api, kdf, params.exporterSecret);\n\t\tObject.defineProperty(this, \"_aead\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tObject.defineProperty(this, \"_nK\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tObject.defineProperty(this, \"_nN\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tObject.defineProperty(this, \"_nT\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tObject.defineProperty(this, \"_ctx\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tif (params.key === void 0 || params.baseNonce === void 0 || params.seq === void 0) throw new Error(\"Required parameters are missing\");\n\t\tthis._aead = params.aead;\n\t\tthis._nK = this._aead.keySize;\n\t\tthis._nN = this._aead.nonceSize;\n\t\tthis._nT = this._aead.tagSize;\n\t\tconst key = this._aead.createEncryptionContext(params.key);\n\t\tthis._ctx = {\n\t\t\tkey,\n\t\t\tbaseNonce: params.baseNonce,\n\t\t\tseq: params.seq\n\t\t};\n\t}\n\tcomputeNonce(k) {\n\t\tconst seqBytes = i2Osp(k.seq, k.baseNonce.byteLength);\n\t\treturn xor(k.baseNonce, seqBytes).buffer;\n\t}\n\tincrementSeq(k) {\n\t\tif (k.seq > Number.MAX_SAFE_INTEGER) throw new MessageLimitReachedError(\"Message limit reached\");\n\t\tk.seq += 1;\n\t}\n};\n//#endregion\n//#region ../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/mutex.js\nvar __classPrivateFieldGet$2 = function(receiver, state, kind, f) {\n\tif (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n\tif (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n\treturn kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet$2 = function(receiver, state, value, kind, f) {\n\tif (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n\tif (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n\tif (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n\treturn kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;\n};\nvar _Mutex_locked;\nvar Mutex = class {\n\tconstructor() {\n\t\t_Mutex_locked.set(this, Promise.resolve());\n\t}\n\tasync lock() {\n\t\tlet releaseLock;\n\t\tconst nextLock = new Promise((resolve) => {\n\t\t\treleaseLock = resolve;\n\t\t});\n\t\tconst previousLock = __classPrivateFieldGet$2(this, _Mutex_locked, \"f\");\n\t\t__classPrivateFieldSet$2(this, _Mutex_locked, nextLock, \"f\");\n\t\tawait previousLock;\n\t\treturn releaseLock;\n\t}\n};\n_Mutex_locked = /* @__PURE__ */ new WeakMap();\n//#endregion\n//#region ../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/recipientContext.js\nvar __classPrivateFieldGet$1 = function(receiver, state, kind, f) {\n\tif (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n\tif (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n\treturn kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet$1 = function(receiver, state, value, kind, f) {\n\tif (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n\tif (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n\tif (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n\treturn kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;\n};\nvar _RecipientContextImpl_mutex;\nvar RecipientContextImpl = class extends EncryptionContextImpl {\n\tconstructor() {\n\t\tsuper(...arguments);\n\t\t_RecipientContextImpl_mutex.set(this, void 0);\n\t}\n\tasync open(data, aad = EMPTY.buffer) {\n\t\t__classPrivateFieldSet$1(this, _RecipientContextImpl_mutex, __classPrivateFieldGet$1(this, _RecipientContextImpl_mutex, \"f\") ?? new Mutex(), \"f\");\n\t\tconst release = await __classPrivateFieldGet$1(this, _RecipientContextImpl_mutex, \"f\").lock();\n\t\tlet pt;\n\t\ttry {\n\t\t\tpt = await this._ctx.key.open(this.computeNonce(this._ctx), toArrayBuffer(data), toArrayBuffer(aad));\n\t\t} catch (e) {\n\t\t\tthrow new OpenError(e);\n\t\t} finally {\n\t\t\trelease();\n\t\t}\n\t\tthis.incrementSeq(this._ctx);\n\t\treturn pt;\n\t}\n};\n_RecipientContextImpl_mutex = /* @__PURE__ */ new WeakMap();\n//#endregion\n//#region ../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/senderContext.js\nvar __classPrivateFieldGet = function(receiver, state, kind, f) {\n\tif (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n\tif (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n\treturn kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = function(receiver, state, value, kind, f) {\n\tif (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n\tif (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n\tif (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n\treturn kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;\n};\nvar _SenderContextImpl_mutex;\nvar SenderContextImpl = class extends EncryptionContextImpl {\n\tconstructor(api, kdf, params, enc) {\n\t\tsuper(api, kdf, params);\n\t\tObject.defineProperty(this, \"enc\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\t_SenderContextImpl_mutex.set(this, void 0);\n\t\tthis.enc = enc;\n\t}\n\tasync seal(data, aad = EMPTY.buffer) {\n\t\t__classPrivateFieldSet(this, _SenderContextImpl_mutex, __classPrivateFieldGet(this, _SenderContextImpl_mutex, \"f\") ?? new Mutex(), \"f\");\n\t\tconst release = await __classPrivateFieldGet(this, _SenderContextImpl_mutex, \"f\").lock();\n\t\tlet ct;\n\t\ttry {\n\t\t\tct = await this._ctx.key.seal(this.computeNonce(this._ctx), toArrayBuffer(data), toArrayBuffer(aad));\n\t\t} catch (e) {\n\t\t\tthrow new SealError(e);\n\t\t} finally {\n\t\t\trelease();\n\t\t}\n\t\tthis.incrementSeq(this._ctx);\n\t\treturn ct;\n\t}\n};\n_SenderContextImpl_mutex = /* @__PURE__ */ new WeakMap();\n//#endregion\n//#region ../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/cipherSuiteNative.js\nconst LABEL_BASE_NONCE = new Uint8Array([\n\t98,\n\t97,\n\t115,\n\t101,\n\t95,\n\t110,\n\t111,\n\t110,\n\t99,\n\t101\n]);\nconst LABEL_EXP = new Uint8Array([\n\t101,\n\t120,\n\t112\n]);\nconst LABEL_INFO_HASH = new Uint8Array([\n\t105,\n\t110,\n\t102,\n\t111,\n\t95,\n\t104,\n\t97,\n\t115,\n\t104\n]);\nconst LABEL_KEY = new Uint8Array([\n\t107,\n\t101,\n\t121\n]);\nconst LABEL_PSK_ID_HASH = new Uint8Array([\n\t112,\n\t115,\n\t107,\n\t95,\n\t105,\n\t100,\n\t95,\n\t104,\n\t97,\n\t115,\n\t104\n]);\nconst LABEL_SECRET = new Uint8Array([\n\t115,\n\t101,\n\t99,\n\t114,\n\t101,\n\t116\n]);\nconst SUITE_ID_HEADER_HPKE = new Uint8Array([\n\t72,\n\t80,\n\t75,\n\t69,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0\n]);\n/**\n* The Hybrid Public Key Encryption (HPKE) ciphersuite,\n* which is implemented using only\n* {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n*\n* This is the super class of {@link CipherSuite} and the same as\n* {@link https://jsr.io/@hpke/core/doc/~/CipherSuite | @hpke/core#CipherSuite} as follows:\n* which supports only the ciphersuites that can be implemented on the native\n* {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n* Therefore, the following cryptographic algorithms are not supported for now:\n* - DHKEM(X25519, HKDF-SHA256)\n* - DHKEM(X448, HKDF-SHA512)\n* - ChaCha20Poly1305\n*\n* In addtion, the HKDF functions contained in this class can only derive\n* keys of the same length as the `hashSize`.\n*\n* If you want to use the unsupported cryptographic algorithms\n* above or derive keys longer than the `hashSize`,\n* please use {@link CipherSuite}.\n*\n* This class provides following functions:\n*\n* - Creates encryption contexts both for senders and recipients.\n* - {@link createSenderContext}\n* - {@link createRecipientContext}\n* - Provides single-shot encryption API.\n* - {@link seal}\n* - {@link open}\n*\n* The calling of the constructor of this class is the starting\n* point for HPKE operations for both senders and recipients.\n*\n* @example Use only ciphersuites supported by Web Cryptography API.\n*\n* ```ts\n* import {\n* Aes128Gcm,\n* DhkemP256HkdfSha256,\n* HkdfSha256,\n* CipherSuite,\n* } from \"@hpke/core\";\n*\n* const suite = new CipherSuite({\n* kem: new DhkemP256HkdfSha256(),\n* kdf: new HkdfSha256(),\n* aead: new Aes128Gcm(),\n* });\n* ```\n*\n* @example Use a ciphersuite which is currently not supported by Web Cryptography API.\n*\n* ```ts\n* import { Aes128Gcm, HkdfSha256, CipherSuite } from \"@hpke/core\";\n* // Use an extension module.\n* import { DhkemX25519HkdfSha256 } from \"@hpke/dhkem-x25519\";\n*\n* const suite = new CipherSuite({\n* kem: new DhkemX25519HkdfSha256(),\n* kdf: new HkdfSha256(),\n* aead: new Aes128Gcm(),\n* });\n* ```\n*/\nvar CipherSuiteNative = class extends NativeAlgorithm {\n\t/**\n\t* @param params A set of parameters for building a cipher suite.\n\t*\n\t* If the error occurred, throws {@link InvalidParamError}.\n\t*\n\t* @throws {@link InvalidParamError}\n\t*/\n\tconstructor(params) {\n\t\tsuper();\n\t\tObject.defineProperty(this, \"_kem\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tObject.defineProperty(this, \"_kdf\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tObject.defineProperty(this, \"_aead\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tObject.defineProperty(this, \"_suiteId\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tif (typeof params.kem === \"number\") throw new InvalidParamError(\"KemId cannot be used\");\n\t\tthis._kem = params.kem;\n\t\tif (typeof params.kdf === \"number\") throw new InvalidParamError(\"KdfId cannot be used\");\n\t\tthis._kdf = params.kdf;\n\t\tif (typeof params.aead === \"number\") throw new InvalidParamError(\"AeadId cannot be used\");\n\t\tthis._aead = params.aead;\n\t\tthis._suiteId = new Uint8Array(SUITE_ID_HEADER_HPKE);\n\t\tthis._suiteId.set(i2Osp(this._kem.id, 2), 4);\n\t\tthis._suiteId.set(i2Osp(this._kdf.id, 2), 6);\n\t\tthis._suiteId.set(i2Osp(this._aead.id, 2), 8);\n\t\tthis._kdf.init(this._suiteId);\n\t}\n\t/**\n\t* Gets the KEM context of the ciphersuite.\n\t*/\n\tget kem() {\n\t\treturn this._kem;\n\t}\n\t/**\n\t* Gets the KDF context of the ciphersuite.\n\t*/\n\tget kdf() {\n\t\treturn this._kdf;\n\t}\n\t/**\n\t* Gets the AEAD context of the ciphersuite.\n\t*/\n\tget aead() {\n\t\treturn this._aead;\n\t}\n\t/**\n\t* Creates an encryption context for a sender.\n\t*\n\t* If the error occurred, throws {@link DecapError} | {@link ValidationError}.\n\t*\n\t* @param params A set of parameters for the sender encryption context.\n\t* @returns A sender encryption context.\n\t* @throws {@link EncapError}, {@link ValidationError}\n\t*/\n\tasync createSenderContext(params) {\n\t\tthis._validateInputLength(params);\n\t\tawait this._setup();\n\t\tconst dh = await this._kem.encap(params);\n\t\tlet mode;\n\t\tif (params.psk !== void 0) mode = params.senderKey !== void 0 ? Mode.AuthPsk : Mode.Psk;\n\t\telse mode = params.senderKey !== void 0 ? Mode.Auth : Mode.Base;\n\t\treturn await this._keyScheduleS(mode, dh.sharedSecret, dh.enc, params);\n\t}\n\t/**\n\t* Creates an encryption context for a recipient.\n\t*\n\t* If the error occurred, throws {@link DecapError}\n\t* | {@link DeserializeError} | {@link ValidationError}.\n\t*\n\t* @param params A set of parameters for the recipient encryption context.\n\t* @returns A recipient encryption context.\n\t* @throws {@link DecapError}, {@link DeserializeError}, {@link ValidationError}\n\t*/\n\tasync createRecipientContext(params) {\n\t\tthis._validateInputLength(params);\n\t\tawait this._setup();\n\t\tconst sharedSecret = await this._kem.decap(params);\n\t\tlet mode;\n\t\tif (params.psk !== void 0) mode = params.senderPublicKey !== void 0 ? Mode.AuthPsk : Mode.Psk;\n\t\telse mode = params.senderPublicKey !== void 0 ? Mode.Auth : Mode.Base;\n\t\treturn await this._keyScheduleR(mode, sharedSecret, params);\n\t}\n\t/**\n\t* Encrypts a message to a recipient.\n\t*\n\t* If the error occurred, throws `EncapError` | `MessageLimitReachedError` | `SealError` | `ValidationError`.\n\t*\n\t* @param params A set of parameters for building a sender encryption context.\n\t* @param pt A plain text as bytes to be encrypted.\n\t* @param aad Additional authenticated data as bytes fed by an application.\n\t* @returns A cipher text and an encapsulated key as bytes.\n\t* @throws {@link EncapError}, {@link MessageLimitReachedError}, {@link SealError}, {@link ValidationError}\n\t*/\n\tasync seal(params, pt, aad = EMPTY.buffer) {\n\t\tconst ctx = await this.createSenderContext(params);\n\t\treturn {\n\t\t\tct: await ctx.seal(pt, aad),\n\t\t\tenc: ctx.enc\n\t\t};\n\t}\n\t/**\n\t* Decrypts a message from a sender.\n\t*\n\t* If the error occurred, throws `DecapError` | `DeserializeError` | `OpenError` | `ValidationError`.\n\t*\n\t* @param params A set of parameters for building a recipient encryption context.\n\t* @param ct An encrypted text as bytes to be decrypted.\n\t* @param aad Additional authenticated data as bytes fed by an application.\n\t* @returns A decrypted plain text as bytes.\n\t* @throws {@link DecapError}, {@link DeserializeError}, {@link OpenError}, {@link ValidationError}\n\t*/\n\tasync open(params, ct, aad = EMPTY.buffer) {\n\t\treturn await (await this.createRecipientContext(params)).open(ct, aad);\n\t}\n\tasync _keySchedule(mode, sharedSecret, params) {\n\t\tconst pskId = params.psk === void 0 ? EMPTY : toUint8Array(params.psk.id);\n\t\tconst pskIdHash = await this._kdf.labeledExtract(EMPTY, LABEL_PSK_ID_HASH, pskId);\n\t\tconst info = params.info === void 0 ? EMPTY : toUint8Array(params.info);\n\t\tconst infoHash = await this._kdf.labeledExtract(EMPTY, LABEL_INFO_HASH, info);\n\t\tconst keyScheduleContext = new Uint8Array(1 + pskIdHash.byteLength + infoHash.byteLength);\n\t\tkeyScheduleContext.set(new Uint8Array([mode]), 0);\n\t\tkeyScheduleContext.set(new Uint8Array(pskIdHash), 1);\n\t\tkeyScheduleContext.set(new Uint8Array(infoHash), 1 + pskIdHash.byteLength);\n\t\tconst psk = params.psk === void 0 ? EMPTY : toUint8Array(params.psk.key);\n\t\tconst ikm = this._kdf.buildLabeledIkm(LABEL_SECRET, psk);\n\t\tconst exporterSecretInfo = this._kdf.buildLabeledInfo(LABEL_EXP, keyScheduleContext, this._kdf.hashSize);\n\t\tconst exporterSecret = await this._kdf.extractAndExpand(sharedSecret, ikm, exporterSecretInfo, this._kdf.hashSize);\n\t\tif (this._aead.id === AeadId.ExportOnly) return {\n\t\t\taead: this._aead,\n\t\t\texporterSecret\n\t\t};\n\t\tconst keyInfo = this._kdf.buildLabeledInfo(LABEL_KEY, keyScheduleContext, this._aead.keySize);\n\t\tconst key = await this._kdf.extractAndExpand(sharedSecret, ikm, keyInfo, this._aead.keySize);\n\t\tconst baseNonceInfo = this._kdf.buildLabeledInfo(LABEL_BASE_NONCE, keyScheduleContext, this._aead.nonceSize);\n\t\tconst baseNonce = await this._kdf.extractAndExpand(sharedSecret, ikm, baseNonceInfo, this._aead.nonceSize);\n\t\treturn {\n\t\t\taead: this._aead,\n\t\t\texporterSecret,\n\t\t\tkey,\n\t\t\tbaseNonce: new Uint8Array(baseNonce),\n\t\t\tseq: 0\n\t\t};\n\t}\n\tasync _keyScheduleS(mode, sharedSecret, enc, params) {\n\t\tconst res = await this._keySchedule(mode, sharedSecret, params);\n\t\tif (res.key === void 0) return new SenderExporterContextImpl(this._api, this._kdf, res.exporterSecret, enc);\n\t\treturn new SenderContextImpl(this._api, this._kdf, res, enc);\n\t}\n\tasync _keyScheduleR(mode, sharedSecret, params) {\n\t\tconst res = await this._keySchedule(mode, sharedSecret, params);\n\t\tif (res.key === void 0) return new RecipientExporterContextImpl(this._api, this._kdf, res.exporterSecret);\n\t\treturn new RecipientContextImpl(this._api, this._kdf, res);\n\t}\n\t_validateInputLength(params) {\n\t\tif (params.info !== void 0 && params.info.byteLength > 268435456) throw new InvalidParamError(\"Too long info\");\n\t\tif (params.psk !== void 0) {\n\t\t\tif (params.psk.key.byteLength < 32) throw new InvalidParamError(`PSK must have at least 32 bytes`);\n\t\t\tif (params.psk.key.byteLength > 8192) throw new InvalidParamError(\"Too long psk.key\");\n\t\t\tif (params.psk.id.byteLength > 8192) throw new InvalidParamError(\"Too long psk.id\");\n\t\t}\n\t}\n};\n//#endregion\n//#region ../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/native.js\n/**\n* The Hybrid Public Key Encryption (HPKE) ciphersuite,\n* which is implemented using only\n* {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n*\n* This class is the same as\n* {@link https://jsr.io/@hpke/core/doc/~/CipherSuiteNative | @hpke/core#CipherSuiteNative} as follows:\n* which supports only the ciphersuites that can be implemented on the native\n* {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n* Therefore, the following cryptographic algorithms are not supported for now:\n* - `DHKEM(X448, HKDF-SHA512)`\n* - `ChaCha20Poly1305`\n*\n* In addtion, the HKDF functions contained in this `CipherSuiteNative`\n* class can only derive keys of the same length as the `hashSize`.\n*\n* If you want to use the unsupported cryptographic algorithms\n* above or derive keys longer than the `hashSize`,\n* please use {@link https://jsr.io/@hpke/hpke-js/doc/~/CipherSuite | hpke-js#CipherSuite}.\n*\n* This class provides following functions:\n*\n* - Creates encryption contexts both for senders and recipients.\n* - {@link createSenderContext}\n* - {@link createRecipientContext}\n* - Provides single-shot encryption API.\n* - {@link seal}\n* - {@link open}\n*\n* The calling of the constructor of this class is the starting\n* point for HPKE operations for both senders and recipients.\n*\n* @example Use only ciphersuites supported by Web Cryptography API.\n*\n* ```ts\n* import {\n* Aes128Gcm,\n* DhkemP256HkdfSha256,\n* HkdfSha256,\n* CipherSuite,\n* } from \"@hpke/core\";\n*\n* const suite = new CipherSuite({\n* kem: new DhkemP256HkdfSha256(),\n* kdf: new HkdfSha256(),\n* aead: new Aes128Gcm(),\n* });\n* ```\n*\n* @example Use DHKEM(X25519, HKDF-SHA256).\n*\n* ```ts\n* import {\n* Aes128Gcm,\n* CipherSuite,\n* DhkemX25519HkdfSha256,\n* HkdfSha256,\n* } from \"@hpke/core\";\n* const suite = new CipherSuite({\n* kem: new DhkemX25519HkdfSha256(),\n* kdf: new HkdfSha256(),\n* aead: new Aes128Gcm(),\n* });\n* ```\n*/\nvar CipherSuite = class extends CipherSuiteNative {};\n/**\n* The HKDF-SHA256 for HPKE KDF implementing {@link KdfInterface}.\n*\n* When using `@hpke/core`, the instance of this class must be specified\n* to the `kem` parameter of {@link CipherSuiteParams} instead of `KdfId.HkdfSha256`.\n*\n* The KDF class can only derive keys of the same length as the `hashSize`.\n* If you want to derive keys longer than the `hashSize`,\n* please use {@link https://jsr.io/@hpke/hpke-js/doc/~/CipherSuite | hpke-js#CipherSuite}.\n*\n* @example\n*\n* ```ts\n* import {\n* Aes128Gcm,\n* CipherSuite,\n* DhkemP256HkdfSha256,\n* HkdfSha256,\n* } from \"@hpke/core\";\n*\n* const suite = new CipherSuite({\n* kem: new DhkemP256HkdfSha256(),\n* kdf: new HkdfSha256(),\n* aead: new Aes128Gcm(),\n* });\n* ```\n*/\nvar HkdfSha256 = class extends HkdfSha256Native {};\n//#endregion\n//#region ../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/kems/dhkemPrimitives/x25519.js\nconst ALG_NAME = \"X25519\";\nconst PKCS8_ALG_ID_X25519 = new Uint8Array([\n\t48,\n\t46,\n\t2,\n\t1,\n\t0,\n\t48,\n\t5,\n\t6,\n\t3,\n\t43,\n\t101,\n\t110,\n\t4,\n\t34,\n\t4,\n\t32\n]);\nconst BASE_POINT_X25519 = /* @__PURE__ */ (() => {\n\tconst p = /* @__PURE__ */ new Uint8Array(32);\n\tp[0] = 9;\n\treturn p;\n})();\nvar X25519 = class extends NativeAlgorithm {\n\tconstructor(hkdf) {\n\t\tsuper();\n\t\tObject.defineProperty(this, \"_hkdf\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tObject.defineProperty(this, \"_alg\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tObject.defineProperty(this, \"_nPk\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tObject.defineProperty(this, \"_nSk\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tObject.defineProperty(this, \"_nDh\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tObject.defineProperty(this, \"_pkcs8AlgId\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: void 0\n\t\t});\n\t\tthis._alg = { name: ALG_NAME };\n\t\tthis._hkdf = hkdf;\n\t\tthis._nPk = 32;\n\t\tthis._nSk = 32;\n\t\tthis._nDh = 32;\n\t\tthis._pkcs8AlgId = PKCS8_ALG_ID_X25519;\n\t}\n\tasync serializePublicKey(key) {\n\t\tawait this._setup();\n\t\ttry {\n\t\t\treturn await this._api.exportKey(\"raw\", key);\n\t\t} catch (e) {\n\t\t\tthrow new SerializeError(e);\n\t\t}\n\t}\n\tasync deserializePublicKey(key) {\n\t\tawait this._setup();\n\t\ttry {\n\t\t\treturn await this._importRawKey(toArrayBuffer(key), true);\n\t\t} catch (e) {\n\t\t\tthrow new DeserializeError(e);\n\t\t}\n\t}\n\tasync serializePrivateKey(key) {\n\t\tawait this._setup();\n\t\ttry {\n\t\t\tconst jwk = await this._api.exportKey(\"jwk\", key);\n\t\t\tif (!(\"d\" in jwk)) throw new Error(\"Not private key\");\n\t\t\treturn base64UrlToBytes(jwk[\"d\"]).buffer;\n\t\t} catch (e) {\n\t\t\tthrow new SerializeError(e);\n\t\t}\n\t}\n\tasync deserializePrivateKey(key) {\n\t\tawait this._setup();\n\t\ttry {\n\t\t\treturn await this._importRawKey(toArrayBuffer(key), false);\n\t\t} catch (e) {\n\t\t\tthrow new DeserializeError(e);\n\t\t}\n\t}\n\tasync importKey(format, key, isPublic) {\n\t\tawait this._setup();\n\t\ttry {\n\t\t\tif (format === \"raw\") return await this._importRawKey(key, isPublic);\n\t\t\tif (key instanceof ArrayBuffer) throw new Error(\"Invalid jwk key format\");\n\t\t\treturn await this._importJWK(key, isPublic);\n\t\t} catch (e) {\n\t\t\tthrow new DeserializeError(e);\n\t\t}\n\t}\n\tasync generateKeyPair() {\n\t\tawait this._setup();\n\t\ttry {\n\t\t\treturn await this._api.generateKey(ALG_NAME, true, KEM_USAGES);\n\t\t} catch (e) {\n\t\t\tthrow new NotSupportedError(e);\n\t\t}\n\t}\n\tasync deriveKeyPair(ikm) {\n\t\tawait this._setup();\n\t\ttry {\n\t\t\tconst rawIkm = toArrayBuffer(ikm);\n\t\t\tconst dkpPrk = await this._hkdf.labeledExtract(EMPTY, LABEL_DKP_PRK, new Uint8Array(rawIkm));\n\t\t\tconst rawSk = await this._hkdf.labeledExpand(dkpPrk, LABEL_SK, EMPTY, this._nSk);\n\t\t\tconst rawSkBytes = new Uint8Array(rawSk);\n\t\t\tconst sk = await this._deserializePkcs8Key(rawSkBytes);\n\t\t\trawSkBytes.fill(0);\n\t\t\treturn {\n\t\t\t\tprivateKey: sk,\n\t\t\t\tpublicKey: await this.derivePublicKey(sk)\n\t\t\t};\n\t\t} catch (e) {\n\t\t\tthrow new DeriveKeyPairError(e);\n\t\t}\n\t}\n\tasync derivePublicKey(key) {\n\t\tawait this._setup();\n\t\ttry {\n\t\t\tconst jwk = await this._api.exportKey(\"jwk\", key);\n\t\t\tdelete jwk[\"d\"];\n\t\t\tdelete jwk[\"key_ops\"];\n\t\t\treturn await this._api.importKey(\"jwk\", jwk, this._alg, true, []);\n\t\t} catch {\n\t\t\ttry {\n\t\t\t\tconst bp = await this._api.importKey(\"raw\", BASE_POINT_X25519.buffer, this._alg, true, []);\n\t\t\t\tconst bits = await this._api.deriveBits({\n\t\t\t\t\tname: ALG_NAME,\n\t\t\t\t\tpublic: bp\n\t\t\t\t}, key, this._nPk * 8);\n\t\t\t\treturn await this._api.importKey(\"raw\", bits, this._alg, true, []);\n\t\t\t} catch (e) {\n\t\t\t\tthrow new DeserializeError(e);\n\t\t\t}\n\t\t}\n\t}\n\tasync dh(sk, pk) {\n\t\tawait this._setup();\n\t\ttry {\n\t\t\treturn await this._api.deriveBits({\n\t\t\t\tname: ALG_NAME,\n\t\t\t\tpublic: pk\n\t\t\t}, sk, this._nDh * 8);\n\t\t} catch (e) {\n\t\t\tthrow new SerializeError(e);\n\t\t}\n\t}\n\tasync _importRawKey(key, isPublic) {\n\t\tif (isPublic && key.byteLength !== this._nPk) throw new Error(\"Invalid public key for the ciphersuite\");\n\t\tif (!isPublic && key.byteLength !== this._nSk) throw new Error(\"Invalid private key for the ciphersuite\");\n\t\tif (isPublic) return await this._api.importKey(\"raw\", key, this._alg, true, []);\n\t\treturn await this._deserializePkcs8Key(new Uint8Array(key));\n\t}\n\tasync _importJWK(key, isPublic) {\n\t\tif (typeof key.kty === \"undefined\" || key.kty !== \"OKP\") throw new Error(`Invalid kty: ${key.crv}`);\n\t\tif (typeof key.crv === \"undefined\" || key.crv !== ALG_NAME) throw new Error(`Invalid crv: ${key.crv}`);\n\t\tif (isPublic) {\n\t\t\tif (typeof key.d !== \"undefined\") throw new Error(\"Invalid key: `d` should not be set\");\n\t\t\treturn await this._api.importKey(\"jwk\", key, this._alg, true, []);\n\t\t}\n\t\tif (typeof key.d === \"undefined\") throw new Error(\"Invalid key: `d` not found\");\n\t\treturn await this._api.importKey(\"jwk\", key, this._alg, true, KEM_USAGES);\n\t}\n\tasync _deserializePkcs8Key(k) {\n\t\tconst pkcs8Key = new Uint8Array(this._pkcs8AlgId.length + k.length);\n\t\tpkcs8Key.set(this._pkcs8AlgId, 0);\n\t\tpkcs8Key.set(k, this._pkcs8AlgId.length);\n\t\treturn await this._api.importKey(\"pkcs8\", pkcs8Key, this._alg, true, KEM_USAGES);\n\t}\n};\n//#endregion\n//#region ../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/kems/dhkemX25519.js\n/**\n* The DHKEM(X25519, HKDF-SHA256) for HPKE KEM implementing {@link KemInterface}.\n*\n* The instance of this class can be specified to the\n* {@link https://jsr.io/@hpke/core/doc/~/CipherSuiteParams | CipherSuiteParams} as follows:\n*\n* @example\n*\n* ```ts\n* import {\n* Aes128Gcm,\n* CipherSuite,\n* HkdfSha256,\n* DhkemX25519HkdfSha256,\n* } from \"@hpke/core\";\n*\n* const suite = new CipherSuite({\n* kem: new DhkemX25519HkdfSha256(),\n* kdf: new HkdfSha256(),\n* aead: new Aes128Gcm(),\n* });\n* ```\n*/\nvar DhkemX25519HkdfSha256 = class extends Dhkem {\n\tconstructor() {\n\t\tconst kdf = new HkdfSha256Native();\n\t\tsuper(KemId.DhkemX25519HkdfSha256, new X25519(kdf), kdf);\n\t\t/** KemId.DhkemX25519HkdfSha256 (0x0020) */\n\t\tObject.defineProperty(this, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: KemId.DhkemX25519HkdfSha256\n\t\t});\n\t\t/** 32 */\n\t\tObject.defineProperty(this, \"secretSize\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: 32\n\t\t});\n\t\t/** 32 */\n\t\tObject.defineProperty(this, \"encSize\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: 32\n\t\t});\n\t\t/** 32 */\n\t\tObject.defineProperty(this, \"publicKeySize\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: 32\n\t\t});\n\t\t/** 32 */\n\t\tObject.defineProperty(this, \"privateKeySize\", {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: 32\n\t\t});\n\t}\n};\n//#endregion\n//#region src/crypto/ed25519CryptoProvider.ts\n/**\n* The single place in linkrpc that touches the Web Crypto API\n* (`globalThis.crypto.subtle`). These low-level functions are surfaced to the\n* rest of the codebase through the `./crypto` facade — import from there, not\n* from this file.\n*\n* Web Crypto is available unchanged in modern browsers and in Node 20+, so\n* there is no longer a node-specific vs. web-specific implementation — this\n* one file works in both runtimes.\n*/\nconst _PKCS8_PREFIX = new Uint8Array([\n\t48,\n\t46,\n\t2,\n\t1,\n\t0,\n\t48,\n\t5,\n\t6,\n\t3,\n\t43,\n\t101,\n\t112,\n\t4,\n\t34,\n\t4,\n\t32\n]);\nconst _PKCS8_X25519_PREFIX = new Uint8Array([\n\t48,\n\t46,\n\t2,\n\t1,\n\t0,\n\t48,\n\t5,\n\t6,\n\t3,\n\t43,\n\t101,\n\t110,\n\t4,\n\t34,\n\t4,\n\t32\n]);\nfunction _wrapPkcs8(seed, prefix = _PKCS8_PREFIX) {\n\tconst out = new Uint8Array(prefix.length + seed.length);\n\tout.set(prefix, 0);\n\tout.set(seed, prefix.length);\n\treturn out;\n}\nconst _ALG = \"Ed25519\";\nconst _ENC_LEN = 32;\nlet _hpkeSuiteInstance;\nfunction _hpkeSuite() {\n\treturn _hpkeSuiteInstance ??= new CipherSuite({\n\t\tkem: new DhkemX25519HkdfSha256(),\n\t\tkdf: new HkdfSha256(),\n\t\taead: new Aes256Gcm()\n\t});\n}\nfunction _concat(a, b) {\n\tconst out = new Uint8Array(a.length + b.length);\n\tout.set(a, 0);\n\tout.set(b, a.length);\n\treturn out;\n}\nfunction _toBuffer(bytes) {\n\treturn bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);\n}\n/** Generate a fresh Ed25519 keypair (raw 32-byte seed + 32-byte public key). */\nasync function generateEd25519Keypair() {\n\tconst kp = await crypto.subtle.generateKey(_ALG, true, [\"sign\", \"verify\"]);\n\tconst pub = new Uint8Array(await crypto.subtle.exportKey(\"raw\", kp.publicKey));\n\tconst pkcs8 = new Uint8Array(await crypto.subtle.exportKey(\"pkcs8\", kp.privateKey));\n\treturn {\n\t\tpublicKey: pub,\n\t\tprivateKey: new Uint8Array(pkcs8.subarray(pkcs8.length - 32))\n\t};\n}\n/** Ed25519 sign `message` with a raw 32-byte seed private key. */\nasync function ed25519Sign(privateKey, message) {\n\tconst key = await crypto.subtle.importKey(\"pkcs8\", _wrapPkcs8(privateKey), _ALG, false, [\"sign\"]);\n\tconst sig = await crypto.subtle.sign(_ALG, key, new Uint8Array(message));\n\treturn new Uint8Array(sig);\n}\n/** Ed25519 verify. Returns `false` (never throws) on malformed input. */\nasync function ed25519Verify(publicKey, message, sig) {\n\ttry {\n\t\tconst key = await crypto.subtle.importKey(\"raw\", new Uint8Array(publicKey), _ALG, false, [\"verify\"]);\n\t\treturn await crypto.subtle.verify(_ALG, key, new Uint8Array(sig), new Uint8Array(message));\n\t} catch {\n\t\treturn false;\n\t}\n}\n/**\n* Deterministically derive an Ed25519 keypair from a raw 32-byte seed (the\n* seed *is* the private key). The public key is recovered via a JWK round-trip\n* (`importKey` pkcs8 → `exportKey` jwk → `x`). For tests / reproducible\n* identities — NOT for production key generation, which must be random.\n*/\nasync function ed25519KeypairFromSeed(seed) {\n\tif (seed.length !== 32) throw new Error(\"ed25519KeypairFromSeed: seed must be 32 bytes\");\n\tconst key = await crypto.subtle.importKey(\"pkcs8\", _wrapPkcs8(seed), _ALG, true, [\"sign\"]);\n\tconst jwk = await crypto.subtle.exportKey(\"jwk\", key);\n\tif (!jwk.x) throw new Error(\"ed25519KeypairFromSeed: failed to derive public key\");\n\treturn {\n\t\tpublicKey: base64UrlToBytes$1(jwk.x),\n\t\tprivateKey: new Uint8Array(seed)\n\t};\n}\n/**\n* Deterministically derive an X25519 keypair from a raw 32-byte scalar (the\n* scalar *is* the private key). Public key recovered via the same JWK\n* round-trip. For tests / reproducible identities only.\n*/\nasync function x25519KeypairFromSeed$1(seed) {\n\tif (seed.length !== 32) throw new Error(\"x25519KeypairFromSeed: seed must be 32 bytes\");\n\tconst key = await crypto.subtle.importKey(\"pkcs8\", _wrapPkcs8(seed, _PKCS8_X25519_PREFIX), \"X25519\", true, [\"deriveBits\"]);\n\tconst jwk = await crypto.subtle.exportKey(\"jwk\", key);\n\tif (!jwk.x) throw new Error(\"x25519KeypairFromSeed: failed to derive public key\");\n\treturn {\n\t\tpublicKey: base64UrlToBytes$1(jwk.x),\n\t\tprivateKey: new Uint8Array(seed)\n\t};\n}\n/** Generate a fresh X25519 keypair (raw 32-byte scalar + 32-byte public key). */\nasync function generateX25519Keypair$1() {\n\tconst suite = _hpkeSuite();\n\tconst kp = await suite.kem.generateKeyPair();\n\treturn {\n\t\tpublicKey: new Uint8Array(await suite.kem.serializePublicKey(kp.publicKey)),\n\t\tprivateKey: new Uint8Array(await suite.kem.serializePrivateKey(kp.privateKey))\n\t};\n}\n/**\n* HPKE-base-mode single-shot seal. Output blob layout is\n* `enc (32 B) || ciphertext || tag (16 B)`. `domain` is bound into both the\n* HPKE `info` parameter and the AEAD AAD.\n*/\nasync function hpkeSeal$1(args) {\n\tconst recipientPublicKey = await _hpkeSuite().kem.deserializePublicKey(_toBuffer(args.recipientPublicKey));\n\tconst sender = await _hpkeSuite().createSenderContext({\n\t\trecipientPublicKey,\n\t\tinfo: _toBuffer(args.domain)\n\t});\n\tconst ctAndTag = new Uint8Array(await sender.seal(_toBuffer(args.plaintext), _toBuffer(args.domain)));\n\treturn _concat(new Uint8Array(sender.enc), ctAndTag);\n}\n/**\n* HPKE-base-mode single-shot open. Throws on any tag failure (wrong domain,\n* wrong recipient key, or tampered blob); the error deliberately does NOT\n* distinguish these cases.\n*/\nasync function hpkeOpen$1(args) {\n\tif (args.blob.length < 48) throw new Error(\"hpkeOpen: blob too short\");\n\tconst enc = args.blob.subarray(0, _ENC_LEN);\n\tconst ctAndTag = args.blob.subarray(_ENC_LEN);\n\tconst recipientKey = await _hpkeSuite().kem.deserializePrivateKey(_toBuffer(args.recipientPrivateKey));\n\tconst recipient = await _hpkeSuite().createRecipientContext({\n\t\trecipientKey,\n\t\tenc: _toBuffer(enc),\n\t\tinfo: _toBuffer(args.domain)\n\t});\n\treturn new Uint8Array(await recipient.open(_toBuffer(ctAndTag), _toBuffer(args.domain)));\n}\n//#endregion\n//#region src/crypto/crypto.ts\nvar crypto_exports = /* @__PURE__ */ __exportAll({\n\tgenerateKeypair: () => generateKeypair,\n\tgenerateX25519Keypair: () => generateX25519Keypair,\n\thpkeOpen: () => hpkeOpen,\n\thpkeSeal: () => hpkeSeal,\n\tkeypairFromSeed: () => keypairFromSeed,\n\tsha256: () => sha256,\n\tsign: () => sign,\n\tverify: () => verify,\n\tx25519KeypairFromSeed: () => x25519KeypairFromSeed\n});\n/** Generate a fresh Ed25519 keypair (raw 32-byte seed + 32-byte public key). */\nfunction generateKeypair() {\n\treturn generateEd25519Keypair();\n}\n/**\n* Deterministically derive an Ed25519 keypair from a raw 32-byte seed. For\n* tests / reproducible identities only — production keys must be random\n* (use {@link generateKeypair}).\n*/\nfunction keypairFromSeed(seed) {\n\treturn ed25519KeypairFromSeed(seed);\n}\n/**\n* Deterministically derive an X25519 keypair from a raw 32-byte scalar. For\n* tests / reproducible identities only.\n*/\nfunction x25519KeypairFromSeed(seed) {\n\treturn x25519KeypairFromSeed$1(seed);\n}\n/** Ed25519 sign `message` with a raw 32-byte seed private key. */\nfunction sign(privateKey, message) {\n\treturn ed25519Sign(privateKey, message);\n}\n/** Ed25519 verify. Returns `false` (never throws) on malformed input. */\nfunction verify(publicKey, message, sig) {\n\treturn ed25519Verify(publicKey, message, sig);\n}\n/** Generate a fresh X25519 keypair (raw 32-byte scalar + 32-byte public key). */\nfunction generateX25519Keypair() {\n\treturn generateX25519Keypair$1();\n}\n/**\n* HPKE-base-mode single-shot seal. Output blob layout is\n* `enc (32 B) || ciphertext || tag (16 B)`; `domain` is bound into both the\n* HPKE `info` parameter and the AEAD AAD.\n*/\nfunction hpkeSeal(args) {\n\treturn hpkeSeal$1(args);\n}\n/**\n* HPKE-base-mode single-shot open. Throws on any tag failure (wrong domain,\n* wrong recipient key, or tampered blob); the error deliberately does NOT\n* distinguish these cases.\n*/\nfunction hpkeOpen(args) {\n\treturn hpkeOpen$1(args);\n}\n/** SHA-256 digest (synchronous, dependency-free). */\nfunction sha256(bytes) {\n\treturn sha256$1(bytes);\n}\n//#endregion\n//#region src/identity/signedObject.ts\n/**\n* Identity-layer signing over the {@link signingInput linkrpc signed-object\n* standard}. These need a {@link SigningIdentity} / public key, so they live\n* in the identity layer; the pure byte definitions stay in\n* `../protocol/signedObject`.\n*/\n/**\n* Sign `obj` in `domain` with `identity`, returning a copy with\n* `$hubrpcSignature[domain]` populated (sibling signatures preserved). The\n* signature commits to {@link signingInput}`(domain, obj)`; the signer's\n* {@link SigningIdentity.publicSigningIdentity}.keyId is stamped alongside it\n* as the (unsigned) routing hint.\n*/\nasync function signObject(domain, obj, identity) {\n\tconst sig = await identity.sign(signingInput(domain, obj));\n\treturn withSignature(obj, domain, {\n\t\tkeyId: identity.publicSigningIdentity.keyId,\n\t\tsig: bytesToBase64Url(sig)\n\t});\n}\n/**\n* Verify `obj`'s `domain` signature against `signerKey` (a raw public key).\n* Returns `false` (never throws) on a missing/malformed signature.\n*/\nasync function verifyObject(domain, obj, signerKey) {\n\tconst env = readSignature(obj, domain);\n\tif (env === void 0) return false;\n\tlet sigBytes;\n\ttry {\n\t\tsigBytes = base64UrlToBytes$1(env.sig);\n\t} catch {\n\t\treturn false;\n\t}\n\treturn verify(signerKey, signingInput(domain, obj), sigBytes);\n}\n//#endregion\n//#region src/identity/signedRpcEnvelope.ts\n/**\n* Sign a single JSON-RPC call. Produces the wire-form params with the\n* `$hubrpc` (signed meta) and `$hubrpcSignature.call` envelopes attached,\n* plus the call content hash.\n*/\nasync function signRpcCall(opts) {\n\tconst userParams = requireObjectParams(opts.params);\n\tconst nonce = opts.nonce ?? _randomNonce();\n\tconst signedAtMs = opts.nowMs ?? Date.now();\n\tconst callMeta = {\n\t\tmethod: opts.method,\n\t\tnonce: bytesToBase64Url(nonce),\n\t\tsignedAtMs,\n\t\tprincipal: opts.signingIdentity.publicSigningIdentity.principal,\n\t\t...opts.interfaceHash !== void 0 ? { interfaceHash: opts.interfaceHash } : {}\n\t};\n\tconst signedParams = {\n\t\t...userParams,\n\t\t[HUBRPC_META_KEY]: callMeta\n\t};\n\tconst callHash = signedHash(\"call\", signedParams);\n\treturn {\n\t\twireParams: await signObject(\"call\", signedParams, opts.signingIdentity),\n\t\tcallMeta,\n\t\tcallHash\n\t};\n}\n/**\n* Attach capabilities to a {@link SignedRpcCall.wireParams}. Capabilities\n* ride in `$hubrpcUnsigned.capabilities` — they are NOT part of what the\n* signature commits to (which is why this is a separate step). Returns a\n* new wireParams object; the input is not mutated.\n*/\nfunction attachCapabilities(wireParams, capabilities) {\n\tif (capabilities.length === 0) return wireParams;\n\tconst obj = wireParams;\n\tconst merged = {\n\t\t...obj[HUBRPC_UNSIGNED_KEY],\n\t\tcapabilities\n\t};\n\treturn {\n\t\t...obj,\n\t\t[HUBRPC_UNSIGNED_KEY]: merged\n\t};\n}\n/**\n* Verify the identity envelope on a JSON-RPC call. Does **not** evaluate\n* capability chains or caveats — that is the hub / authoriser's job.\n*\n* A signed call carries `$hubrpc` (with `principal`) and a `call` signature\n* under `$hubrpcSignature`. The signature is checked against\n* `signingInput(\"call\", wireParams)` (the reserved keys are stripped by the\n* signed-object standard). Bare/unsigned calls return `identity: undefined`.\n*/\nasync function verifyRpcCall(opts) {\n\tconst { wireParams } = opts;\n\tconst meta = _extractObject(wireParams, HUBRPC_META_KEY);\n\tconst userParams = stripLinkRpcWireMeta(wireParams);\n\tif (meta === void 0) {\n\t\tif (opts.requireSigned) return {\n\t\t\tok: false,\n\t\t\treason: \"missing $hubrpc envelope\"\n\t\t};\n\t\treturn {\n\t\t\tok: true,\n\t\t\tidentity: void 0,\n\t\t\tparams: userParams\n\t\t};\n\t}\n\tif (typeof meta.method !== \"string\" || typeof meta.nonce !== \"string\" || typeof meta.signedAtMs !== \"number\" || meta.principal !== void 0 && typeof meta.principal !== \"string\" || meta.interfaceHash !== void 0 && typeof meta.interfaceHash !== \"string\") return {\n\t\tok: false,\n\t\treason: \"malformed linkrpc envelope\"\n\t};\n\tif (meta.method !== opts.wireMethod) return {\n\t\tok: false,\n\t\treason: \"method mismatch\"\n\t};\n\tconst now = opts.nowMs ?? Date.now();\n\tconst skew = opts.maxSkewMs ?? 3e5;\n\tif (Math.abs(meta.signedAtMs - now) > skew) return {\n\t\tok: false,\n\t\treason: `timestamp skew > ${skew}ms`\n\t};\n\tconst signature = readSignature(wireParams, \"call\");\n\tif (meta.principal === void 0 || signature === void 0) {\n\t\tif (opts.requireSigned) return {\n\t\t\tok: false,\n\t\t\treason: \"unsigned call\"\n\t\t};\n\t\treturn {\n\t\t\tok: true,\n\t\t\tidentity: void 0,\n\t\t\tparams: userParams\n\t\t};\n\t}\n\tconst resolved = resolveSigningKey({\n\t\tprincipal: meta.principal,\n\t\tkeyId: signature.keyId,\n\t\ttimeMs: meta.signedAtMs\n\t});\n\tif (resolved === void 0) return {\n\t\tok: false,\n\t\treason: `unresolvable signing key for principal ${meta.principal}`\n\t};\n\tif (!await verifyObject(\"call\", wireParams, resolved.publicKey)) return {\n\t\tok: false,\n\t\treason: \"bad signature\"\n\t};\n\tconst callHash = signedHash(\"call\", wireParams);\n\tconst unsigned = _extractObject(wireParams, HUBRPC_UNSIGNED_KEY);\n\tconst capabilities = Array.isArray(unsigned?.capabilities) ? unsigned.capabilities : [];\n\treturn {\n\t\tok: true,\n\t\tidentity: {\n\t\t\tcallMeta: meta,\n\t\t\tsigner: meta.principal,\n\t\t\tcallHash,\n\t\t\tcapabilities\n\t\t},\n\t\tparams: userParams\n\t};\n}\nfunction _extractObject(wireParams, key) {\n\tif (wireParams === null || typeof wireParams !== \"object\" || Array.isArray(wireParams)) return;\n\tconst env = wireParams[key];\n\tif (env === void 0 || env === null || typeof env !== \"object\" || Array.isArray(env)) return;\n\treturn env;\n}\nfunction _randomNonce() {\n\tconst out = /* @__PURE__ */ new Uint8Array(16);\n\tglobalThis.crypto.getRandomValues(out);\n\treturn out;\n}\n//#endregion\n//#region src/identity/capBag.ts\nconst DEFAULT_STORAGE_KEY = \"hubrpc.caps.v1\";\n/**\n* A process-lifetime bag of hub-issued capabilities. Plug\n* {@link CapBag.provider} straight into a connection's cap provider so every\n* outbound signed call carries whatever caps have been granted so far. The\n* hub picks whichever cap matches the call per dispatch.\n*\n* When constructed with {@link CapBagOptions.storage} the bag hydrates from\n* (and persists to) storage, so the next process spawn for the same identity\n* reuses its grants without re-prompting.\n*/\nvar CapBag = class CapBag {\n\t/** Create a bag, hydrating from storage when one was supplied. */\n\tstatic async load(options = {}) {\n\t\tconst bag = new CapBag(options);\n\t\tawait bag._hydrate();\n\t\treturn bag;\n\t}\n\t_caps = [];\n\t_storage;\n\t_storageKey;\n\t_onWarn;\n\tconstructor(options) {\n\t\tthis._storage = options.storage;\n\t\tthis._storageKey = options.storageKey ?? DEFAULT_STORAGE_KEY;\n\t\tthis._onWarn = options.onWarn ?? (() => {});\n\t}\n\tget capabilities() {\n\t\treturn this._caps;\n\t}\n\t/**\n\t* A {@link CapProvider} reflecting the bag at call-time. Assign it to\n\t* `HubClientHandle.signing.capProvider` or pass it through\n\t* `SigningSenderConfig.capProvider`.\n\t*/\n\tprovider = async () => this._caps.length > 0 ? { capabilities: this._caps } : {};\n\t/** Append capabilities and persist (when backed by storage). */\n\tasync add(...caps) {\n\t\tif (caps.length === 0) return;\n\t\tthis._caps.push(...caps);\n\t\tawait this._persist();\n\t}\n\t/** Drop all capabilities and persist the empty bag. */\n\tasync clear() {\n\t\tif (this._caps.length === 0) return;\n\t\tthis._caps.length = 0;\n\t\tawait this._persist();\n\t}\n\tasync _hydrate() {\n\t\tif (!this._storage) return;\n\t\ttry {\n\t\t\tconst persisted = await this._storage.get(this._storageKey);\n\t\t\tif (!Array.isArray(persisted)) return;\n\t\t\tfor (const cap of persisted) if (cap && typeof cap === \"object\" && \"$hubrpcSignature\" in cap) this._caps.push(cap);\n\t\t\telse this._onWarn(`skipping malformed persisted cap`);\n\t\t} catch (e) {\n\t\t\tthis._onWarn(`failed to read caps from storage: ${e.message}`);\n\t\t}\n\t}\n\tasync _persist() {\n\t\tif (!this._storage) return;\n\t\ttry {\n\t\t\tawait this._storage.set(this._storageKey, this._caps);\n\t\t} catch (e) {\n\t\t\tthis._onWarn(`failed to persist caps: ${e.message}`);\n\t\t}\n\t}\n};\n//#endregion\n//#region src/identity/principal.ts\n/**\n* A signing identity bundled with its durable capability set. The\n* {@link SigningIdentity} is fixed for the life of the principal; the\n* {@link CapBag} is mutable and extensible — caps accumulate as the peer grants\n* them.\n*\n* Transient, per-call (one-shot) grants are deliberately NOT part of a\n* principal: that is a separate policy, see `OneShotCapStaging`.\n*\n* Lives in its own module (rather than alongside `SigningSender`) so the\n* `SigningSender` ⇄ `createManagedPrincipal` factory cycle does not run through\n* a top-level `class … extends Principal`: such a cycle would hit a TDZ\n* (\"Class extends value undefined\") depending on module evaluation order.\n*/\nvar Principal = class Principal {\n\tidentity;\n\tcapBag;\n\tstatic async create(identity, capabilities = []) {\n\t\tconst capBag = await CapBag.load();\n\t\tawait capBag.add(...capabilities);\n\t\treturn new Principal(identity, capBag);\n\t}\n\tconstructor(identity, capBag) {\n\t\tthis.identity = identity;\n\t\tthis.capBag = capBag;\n\t}\n\tget id() {\n\t\treturn this.identity.publicSigningIdentity.principal;\n\t}\n};\n//#endregion\n//#region src/identity/identity.ts\n/**\n* The public face of a signing identity: its stable {@link PrincipalId} name\n* and the {@link KeyId} its signatures are stamped with. In Phase 1 (perpetual\n* identities) the keyId is the genesis key embedded in the principal, so it is\n* derived by stripping the `id:` prefix.\n*/\nvar PublicSigningIdentity = class {\n\tprincipal;\n\tconstructor(principal) {\n\t\tthis.principal = principal;\n\t}\n\t/** The {@link KeyId} this identity signs with (its genesis key, in Phase 1). */\n\tget keyId() {\n\t\treturn keyIdForPrincipal(this.principal);\n\t}\n};\n/**\n* {@link SigningIdentity} backed by an in-process keypair. For the common\n* case where the signing material lives in memory. For external HSM-style\n* backends, implement {@link SigningIdentity} directly.\n*/\nvar KeypairSigningIdentity = class KeypairSigningIdentity {\n\t_privateKey;\n\tpublicSigningIdentity;\n\tconstructor(principal, _privateKey) {\n\t\tthis._privateKey = _privateKey;\n\t\tthis.publicSigningIdentity = new PublicSigningIdentity(principal);\n\t}\n\tsign(message) {\n\t\treturn sign(this._privateKey, message);\n\t}\n\tstatic fromKeypair(keypair) {\n\t\treturn new KeypairSigningIdentity(principalForPublicKey(keypair.publicKey), keypair.privateKey);\n\t}\n\t/** Generate a fresh signing identity (Ed25519 keypair). */\n\tstatic async generateNew() {\n\t\treturn KeypairSigningIdentity.fromKeypair(await generateKeypair());\n\t}\n\t/** Restore an identity from its {@link toJson} form. */\n\tstatic fromJson(json) {\n\t\treturn KeypairSigningIdentity.fromKeypair({\n\t\t\tprivateKey: base64UrlToBytes$1(json.privateKey),\n\t\t\tpublicKey: base64UrlToBytes$1(json.publicKey)\n\t\t});\n\t}\n\t/** Serialize the keypair to a JSON-friendly form (base64url keys). */\n\ttoJson() {\n\t\treturn {\n\t\t\tprivateKey: bytesToBase64Url(this._privateKey),\n\t\t\tpublicKey: bytesToBase64Url(publicKeyForKeyId(this.publicSigningIdentity.keyId))\n\t\t};\n\t}\n};\nvar PublicWrappingIdentity = class {\n\twrapPublicKey;\n\tconstructor(wrapPublicKey) {\n\t\tthis.wrapPublicKey = wrapPublicKey;\n\t}\n};\n/**\n* Full {@link Identity} backed by in-process Ed25519 (signing) and X25519\n* (wrapping) keypairs. The local counterpart to a keystore/executor-backed\n* identity — used by self-managed principals that hold their own key\n* material (e.g. loaded from disk). For external HSM-style backends,\n* implement {@link Identity} directly.\n*/\nvar KeypairIdentity = class KeypairIdentity {\n\t_privateKey;\n\t_wrap;\n\tprincipal;\n\twrapPublicKey;\n\tpublicSigningIdentity;\n\tpublicWrappingIdentity;\n\tconstructor(principal, _privateKey, _wrap) {\n\t\tthis._privateKey = _privateKey;\n\t\tthis._wrap = _wrap;\n\t\tthis.principal = principal;\n\t\tthis.wrapPublicKey = _wrap.publicKey;\n\t\tthis.publicSigningIdentity = new PublicSigningIdentity(principal);\n\t\tthis.publicWrappingIdentity = new PublicWrappingIdentity(_wrap.publicKey);\n\t}\n\tsign(message) {\n\t\treturn sign(this._privateKey, message);\n\t}\n\twrap(domain, bytes) {\n\t\treturn hpkeSeal({\n\t\t\trecipientPublicKey: this._wrap.publicKey,\n\t\t\tdomain: new TextEncoder().encode(domain),\n\t\t\tplaintext: bytes\n\t\t});\n\t}\n\tunwrap(domain, blob) {\n\t\treturn hpkeOpen({\n\t\t\trecipientPrivateKey: this._wrap.privateKey,\n\t\t\tdomain: new TextEncoder().encode(domain),\n\t\t\tblob\n\t\t});\n\t}\n\t/** Generate a fresh identity (Ed25519 + X25519 keypairs). */\n\tstatic async generate() {\n\t\tconst ed = await generateKeypair();\n\t\tconst wrap = await generateX25519Keypair();\n\t\treturn new KeypairIdentity(principalForPublicKey(ed.publicKey), ed.privateKey, wrap);\n\t}\n};\n//#endregion\n//#region src/identity/identity.interfaces.ts\nconst zB64 = string();\n/**\n* Per-participant key oracle. Reached on the participant's root overlay\n* (form-2 method names like `identity::sign`). Private key material lives\n* in the executor; the participant only sees the operations.\n*\n* Wire shape:\n* sign / wrap / unwrap all take and return base64url-encoded bytes.\n* `domain` is a caller-chosen string bound into HPKE info and the AEAD\n* AAD. `unwrap` succeeds only when invoked with the exact `domain` that\n* `wrap` was called with. Use a stable, namespaced string (e.g.\n* `secrets.vault.master-key.v1`).\n*/\nconst identityInterface = defineInterface({\n\tid: \"identity\",\n\tdescription: \"Per-participant key oracle: exposes signing and HPKE-based wrap/unwrap for the identity the executor has attached to this participant's root overlay. Private keys never leave the executor.\"\n}, {\n\tgetPrincipal: requestType(object({}), object({ principal: string() })),\n\tgetWrapPublicKey: requestType(object({}), object({ wrapPublicKey: zB64 })),\n\tsign: requestType(object({ bytes: zB64 }), object({ signature: zB64 })),\n\twrap: requestType(object({\n\t\tdomain: string(),\n\t\tbytes: zB64\n\t}), object({ blob: zB64 })),\n\tunwrap: requestType(object({\n\t\tdomain: string(),\n\t\tblob: zB64\n\t}), object({ bytes: zB64 }))\n});\n/**\n* Per-identity persistent key/value store. Reached on the participant's\n* root overlay as `identity.storage::get` etc. — same overlay that serves\n* `identity::*`, same single-participant addressability.\n*\n* Storage scope is the executor's managed-identity slot (e.g.\n* `service:demo`). Lifecycle is bound to the identity: when the executor\n* deletes the identity for a slot, the storage for that slot is wiped in\n* the same operation. New identity issued for the same slot starts empty.\n*\n* The executor encrypts the backing file at rest with the same secret it\n* uses for identity files — see {@link IdentityKeystore} in\n* `@hediet/linkrpc/node`.\n*\n* Keys must match `^[A-Za-z0-9._/-]{1,256}$`. `/` is conventional for\n* namespacing (`caps.v1`, `prefs/foo`) and `list({ prefix })` honours\n* that. Values are arbitrary JSON.\n*/\nconst identityStorageInterface = defineInterface({\n\tid: \"identity.storage\",\n\tdescription: \"Per-identity persistent key/value store. Scope is the executor's managed-identity slot; lifecycle is tied to the identity itself. Backed by an at-rest-encrypted file in the executor.\"\n}, {\n\tget: requestType(object({ key: string() }), object({ value: optional(unknown()) })),\n\tset: requestType(object({\n\t\tkey: string(),\n\t\tvalue: unknown()\n\t}), object({})),\n\tdelete: requestType(object({ key: string() }), object({ existed: boolean() })),\n\tlist: requestType(object({ prefix: optional(string()) }), object({ keys: array(string()) }))\n});\n//#endregion\n//#region src/identity/managedIdentity.ts\n/**\n* Valid `identity.storage` key shape. The interface schema declares\n* `z.string()` so we don't break clients with regex errors at the wire;\n* the executor-side handler applies this stricter check.\n*/\nconst _STORAGE_KEY_RE = /^[A-Za-z0-9._/-]{1,256}$/;\n/**\n* In-process storage backend. Used by tests and by any executor that\n* doesn't need at-rest persistence.\n*/\nvar InMemoryManagedIdentityStorage = class {\n\t_data = /* @__PURE__ */ new Map();\n\tasync get(key) {\n\t\treturn this._data.has(key) ? this._data.get(key) : void 0;\n\t}\n\tasync set(key, value) {\n\t\tthis._data.set(key, value);\n\t}\n\tasync delete(key) {\n\t\treturn this._data.delete(key);\n\t}\n\tasync list(prefix) {\n\t\tconst all = [...this._data.keys()];\n\t\treturn prefix === void 0 ? all : all.filter((k) => k.startsWith(prefix));\n\t}\n};\n/**\n* In-process `ManagedIdentity` that holds the private key in memory and\n* uses the package crypto API. Useful for tests and for hub-side features\n* that want a short-lived identity without touching disk.\n*/\nvar InMemoryManagedIdentity = class InMemoryManagedIdentity {\n\t_ed;\n\t_wrap;\n\tprincipal;\n\twrapPublicKey;\n\tconstructor(_ed, _wrap) {\n\t\tthis._ed = _ed;\n\t\tthis._wrap = _wrap;\n\t\tthis.principal = principalForPublicKey(_ed.publicKey);\n\t\tthis.wrapPublicKey = _wrap.publicKey;\n\t}\n\tget publicSigningIdentity() {\n\t\treturn new PublicSigningIdentity(this.principal);\n\t}\n\tget publicWrappingIdentity() {\n\t\treturn new PublicWrappingIdentity(this.wrapPublicKey);\n\t}\n\tsign(bytes) {\n\t\treturn sign(this._ed.privateKey, bytes);\n\t}\n\twrap(domain, bytes) {\n\t\treturn hpkeSeal({\n\t\t\trecipientPublicKey: this._wrap.publicKey,\n\t\t\tdomain: _encodeDomain(domain),\n\t\t\tplaintext: bytes\n\t\t});\n\t}\n\tunwrap(domain, blob) {\n\t\treturn hpkeOpen({\n\t\t\trecipientPrivateKey: this._wrap.privateKey,\n\t\t\tdomain: _encodeDomain(domain),\n\t\t\tblob\n\t\t});\n\t}\n\t/** Generate a fresh in-memory identity (Ed25519 + X25519 keypairs). */\n\tstatic async generate() {\n\t\tconst ed = await generateKeypair();\n\t\tconst wrap = await generateX25519Keypair();\n\t\treturn new InMemoryManagedIdentity(ed, wrap);\n\t}\n};\n/**\n* Register the `identity` interface on `overlay` so the bound participant\n* can call `identity::sign` etc. on its root overlay. The overlay is\n* private to one participant — no other peer can reach these methods.\n*\n* When `storage` is supplied, the `identity.storage` interface is\n* registered alongside `identity::*`. Lifetime/scope of the backend is\n* the executor's responsibility — for keystore-backed identities the\n* backend lives as long as the identity slot does.\n*\n* Typical caller: the executor (e.g. the VS Code extension), right after\n* `Hub.attachParticipant`, on the `rootOverlay` returned from the attach\n* handle.\n*/\nfunction registerIdentityOnOverlay(overlay, identity, storage) {\n\toverlay.register(identityInterface, {\n\t\tgetPrincipal: async () => ({ principal: identity.principal }),\n\t\tgetWrapPublicKey: async () => ({ wrapPublicKey: bytesToBase64Url(identity.wrapPublicKey) }),\n\t\tsign: async ({ bytes }) => ({ signature: bytesToBase64Url(await identity.sign(base64UrlToBytes$1(bytes))) }),\n\t\twrap: async ({ domain, bytes }) => ({ blob: bytesToBase64Url(await identity.wrap(domain, base64UrlToBytes$1(bytes))) }),\n\t\tunwrap: async ({ domain, blob }) => ({ bytes: bytesToBase64Url(await identity.unwrap(domain, base64UrlToBytes$1(blob))) })\n\t});\n\tif (storage) _registerStorageInterface(overlay, storage);\n}\n/**\n* Like {@link registerIdentityOnOverlay}, but resolves the identity lazily on\n* first use via `resolveIdentity`. The identity is materialized only when the\n* bound participant actually calls `identity::*` — registering the overlay\n* does NOT create or load any identity.\n*\n* This is essential for the consent model: a host can serve `identity::*` on a\n* keystore slot without making the slot privileged (`hasState`) until the app\n* genuinely opts into an identity. `resolveIdentity` is expected to be cheap on\n* repeat calls (the keystore caches in memory), and to reflect lifecycle\n* changes — e.g. after a slot is wiped and re-created (\"Reset Identity\"), the\n* next call resolves the fresh identity.\n*\n* `storage` is registered eagerly because reading/writing storage is itself\n* the privileged act the app must perform to gain state — exposing the\n* interface costs nothing until used.\n*/\nfunction registerLazyIdentityOnOverlay(overlay, resolveIdentity, storage) {\n\toverlay.register(identityInterface, {\n\t\tgetPrincipal: async () => ({ principal: (await resolveIdentity()).principal }),\n\t\tgetWrapPublicKey: async () => ({ wrapPublicKey: bytesToBase64Url((await resolveIdentity()).wrapPublicKey) }),\n\t\tsign: async ({ bytes }) => ({ signature: bytesToBase64Url(await (await resolveIdentity()).sign(base64UrlToBytes$1(bytes))) }),\n\t\twrap: async ({ domain, bytes }) => ({ blob: bytesToBase64Url(await (await resolveIdentity()).wrap(domain, base64UrlToBytes$1(bytes))) }),\n\t\tunwrap: async ({ domain, blob }) => ({ bytes: bytesToBase64Url(await (await resolveIdentity()).unwrap(domain, base64UrlToBytes$1(blob))) })\n\t});\n\tif (storage) _registerStorageInterface(overlay, storage);\n}\nfunction _registerStorageInterface(overlay, storage) {\n\toverlay.register(identityStorageInterface, {\n\t\tget: async ({ key }) => {\n\t\t\t_assertStorageKey(key);\n\t\t\tconst value = await storage.get(key);\n\t\t\treturn value === void 0 ? {} : { value };\n\t\t},\n\t\tset: async ({ key, value }) => {\n\t\t\t_assertStorageKey(key);\n\t\t\tawait storage.set(key, value);\n\t\t\treturn {};\n\t\t},\n\t\tdelete: async ({ key }) => {\n\t\t\t_assertStorageKey(key);\n\t\t\treturn { existed: await storage.delete(key) };\n\t\t},\n\t\tlist: async ({ prefix }) => {\n\t\t\treturn { keys: await storage.list(prefix) };\n\t\t}\n\t});\n}\nfunction _assertStorageKey(key) {\n\tif (!_STORAGE_KEY_RE.test(key)) throw new Error(`identity.storage: invalid key '${key}'. Must match ${_STORAGE_KEY_RE}.`);\n}\n/**\n* Bootstrap a {@link ManagedIdentity} from a sender (typically the raw\n* unsigned sender obtained via `channel.sender` before wrapping with\n* {@link SigningSender}). Makes `identity::*` calls unsigned — the\n* executor's overlay is private to one participant so routing already\n* identifies the caller, preventing signing recursion.\n*\n* The returned identity signs / wraps / unwraps by round-tripping through\n* the executor's `identity::*` overlay; the caller wires it into their\n* {@link SigningSender} configuration (e.g. as a {@link Principal}). No\n* side effects on any existing connection or holder.\n*/\nasync function createManagedIdentity(sender) {\n\tconst conn = new LinkRpcConnection(sender);\n\tconst id = conn.get(identityInterface, { signerOverride: null });\n\tconst storage = conn.get(identityStorageInterface, { signerOverride: null });\n\tconst { principal } = await id.getPrincipal({});\n\tpublicKeyForKeyId(keyIdForPrincipal(principal));\n\tconst { wrapPublicKey: wrapPublicKeyB64 } = await id.getWrapPublicKey({});\n\tconst wrapPublicKey = base64UrlToBytes$1(wrapPublicKeyB64);\n\treturn {\n\t\tprincipal,\n\t\twrapPublicKey,\n\t\tpublicSigningIdentity: new PublicSigningIdentity(principal),\n\t\tpublicWrappingIdentity: new PublicWrappingIdentity(wrapPublicKey),\n\t\tsign: async (message) => {\n\t\t\tconst { signature } = await id.sign({ bytes: bytesToBase64Url(message) });\n\t\t\treturn base64UrlToBytes$1(signature);\n\t\t},\n\t\twrap: async (domain, bytes) => {\n\t\t\tconst { blob } = await id.wrap({\n\t\t\t\tdomain,\n\t\t\t\tbytes: bytesToBase64Url(bytes)\n\t\t\t});\n\t\t\treturn base64UrlToBytes$1(blob);\n\t\t},\n\t\tunwrap: async (domain, blob) => {\n\t\t\tconst { bytes } = await id.unwrap({\n\t\t\t\tdomain,\n\t\t\t\tblob: bytesToBase64Url(blob)\n\t\t\t});\n\t\t\treturn base64UrlToBytes$1(bytes);\n\t\t},\n\t\tstorage: {\n\t\t\tget: async (key) => {\n\t\t\t\tconst { value } = await storage.get({ key });\n\t\t\t\treturn value === void 0 ? void 0 : value;\n\t\t\t},\n\t\t\tset: async (key, value) => {\n\t\t\t\tawait storage.set({\n\t\t\t\t\tkey,\n\t\t\t\t\tvalue\n\t\t\t\t});\n\t\t\t},\n\t\t\tdelete: async (key) => {\n\t\t\t\tconst { existed } = await storage.delete({ key });\n\t\t\t\treturn existed;\n\t\t\t},\n\t\t\tlist: async (prefix) => {\n\t\t\t\tconst { keys } = await storage.list(prefix === void 0 ? {} : { prefix });\n\t\t\t\treturn keys;\n\t\t\t}\n\t\t}\n\t};\n}\nfunction _encodeDomain(domain) {\n\treturn new TextEncoder().encode(domain);\n}\n//#endregion\n//#region src/identity/managedPrincipal.ts\n/**\n* A {@link Principal} that also exposes the executor-backed per-identity\n* {@link ManagedIdentityStorage}. Returned by {@link createManagedPrincipal}\n* so callers can persist their own app state (e.g. a resolved serviceId)\n* alongside the granted capabilities, using the very same durable store the\n* {@link CapBag} hydrates from — no second storage wiring required.\n*/\nvar PrincipalWithStore = class extends Principal {\n\tstore;\n\tconstructor(identity, capBag, store) {\n\t\tsuper(identity, capBag);\n\t\tthis.store = store;\n\t}\n};\n/**\n* Executor-managed principal: the peer signs for us through its\n* `identity::sign` overlay (we never hold a private key). Bootstrapped purely\n* from the outbound `sender` — no side effects on any connection — and caps\n* persist in the executor-backed per-identity storage. Works over any\n* transport whose peer serves the identity overlay (hub *or* stdio).\n*\n* Call this exactly once per channel: it performs the `identity::*` handshake\n* and hydrates the {@link CapBag} from storage. The returned\n* {@link PrincipalWithStore} additionally surfaces that same durable\n* {@link ManagedIdentityStorage} as `store`.\n*/\nasync function createManagedPrincipal(sender) {\n\tconst identity = await createManagedIdentity(sender);\n\treturn new PrincipalWithStore(identity, await CapBag.load({ storage: identity.storage }), identity.storage);\n}\n//#endregion\n//#region src/identity/signingSender.ts\n/**\n* Side-policy for staging *one-shot* capabilities onto the next outbound\n* signed call, independent of any {@link Principal}. The {@link SigningSender}\n* drains the staged caps after attaching them once, so a spent cap never\n* leaks into a later call.\n*\n* Requesting the one-shot grant (prompting the user / hub) lives next to —\n* not inside — the principal: the principal owns identity and durable\n* capabilities; this owns the transient per-call grant.\n*/\nvar OneShotCapStaging = class {\n\t_staged = [];\n\t/** Stage caps for the next signed call. Replaces any still-pending caps. */\n\tstage(caps) {\n\t\tthis._staged = caps;\n\t}\n\t/**\n\t* Take (and clear) the staged caps. Called by {@link SigningSender} once\n\t* per outbound signed call.\n\t*/\n\ttake() {\n\t\tconst caps = this._staged;\n\t\tthis._staged = [];\n\t\treturn caps;\n\t}\n};\nvar SigningSender = class SigningSender {\n\t_inner;\n\t_config;\n\t/**\n\t* Wrap an inner channel with signing. Composes via {@link Channel.withSender}\n\t* so the resulting `Channel<TInCtx, SigningCallCtx>` plugs into\n\t* `LinkRpcConnection`.\n\t*/\n\tstatic wrapChannel(inner, config) {\n\t\treturn inner.withSender((raw) => new SigningSender(raw, config));\n\t}\n\t/**\n\t* Bootstrap an executor-managed {@link Principal} over the **unsigned**\n\t* `channel`, then wrap that same channel with signing driven by it.\n\t*\n\t* Crucially, the `identity::*` handshake that mints the managed principal\n\t* rides the *raw* channel (`channel.sender`), so those bootstrap calls are\n\t* themselves never signed — there is no \"sign the sign call\" recursion and\n\t* no reliance on threading `signerOverride: null` through every transport\n\t* layer. The returned signing {@link Channel} is what callers hand to\n\t* `LinkRpcConnection`; the {@link PrincipalWithStore} is returned alongside\n\t* for caps / per-identity storage / nodeId.\n\t*/\n\tstatic async fromChannelWithManagedPrincipal(channel, config) {\n\t\tconst principal = await createManagedPrincipal(channel.sender);\n\t\treturn {\n\t\t\tchannel: SigningSender.wrapChannel(channel, {\n\t\t\t\t...config,\n\t\t\t\tprincipal\n\t\t\t}),\n\t\t\tprincipal\n\t\t};\n\t}\n\t/**\n\t* Convenience over {@link fromChannelWithManagedPrincipal}: build the\n\t* unsigned {@link JsonRpcChannel} from `transport` first. The common entry\n\t* point for app hosts / services that own a raw {@link IMessageTransport}.\n\t*/\n\tstatic fromTransportWithManagedPrincipal(transport, config) {\n\t\treturn SigningSender.fromChannelWithManagedPrincipal(JsonRpcChannel.create(transport), config);\n\t}\n\tconstructor(_inner, _config) {\n\t\tthis._inner = _inner;\n\t\tthis._config = _config;\n\t}\n\tasync sendRequest(method, params, opts) {\n\t\tconst out = await this._prepareOutbound(method, params, opts);\n\t\treturn this._inner.sendRequest(out.method, out.params);\n\t}\n\tasync sendNotification(method, params, opts) {\n\t\tconst out = await this._prepareOutbound(method, params, opts);\n\t\tawait this._inner.sendNotification(out.method, out.params);\n\t}\n\tsendRequestWithStream(method, params, opts) {\n\t\tconst id$ = this._prepareOutbound(method, params, opts);\n\t\tlet realCall;\n\t\tlet queuedSends = [];\n\t\tlet resolveResult;\n\t\tlet rejectResult;\n\t\tconst result = new Promise((res, rej) => {\n\t\t\tresolveResult = res;\n\t\t\trejectResult = rej;\n\t\t});\n\t\tlet cancelled = false;\n\t\tlet cancelReason;\n\t\tlet disposedReason;\n\t\tid$.then((out) => {\n\t\t\tconst inner = this._inner.sendRequestWithStream(out.method, out.params, opts);\n\t\t\tif (cancelled) inner.cancel(cancelReason);\n\t\t\tif (disposedReason !== void 0) inner.dispose?.(disposedReason);\n\t\t\trealCall = inner;\n\t\t\tinner.result.then(resolveResult, rejectResult);\n\t\t\tif (queuedSends && queuedSends.length > 0) for (const p of queuedSends) inner.send(p);\n\t\t\tqueuedSends = void 0;\n\t\t}).catch((err) => rejectResult(err instanceof Error ? err : new Error(String(err))));\n\t\treturn {\n\t\t\tresult,\n\t\t\tcancel: (reason) => {\n\t\t\t\tcancelled = true;\n\t\t\t\tcancelReason = reason;\n\t\t\t\tif (realCall) realCall.cancel(reason);\n\t\t\t},\n\t\t\tdispose: (reason = \"streaming request disposed\") => {\n\t\t\t\tif (disposedReason !== void 0) return;\n\t\t\t\tdisposedReason = reason;\n\t\t\t\tqueuedSends = void 0;\n\t\t\t\tif (realCall) realCall.dispose?.(reason);\n\t\t\t\trejectResult(new Error(reason));\n\t\t\t},\n\t\t\tsend: async (payload) => {\n\t\t\t\tif (realCall) await realCall.send(payload);\n\t\t\t\telse queuedSends.push(payload);\n\t\t\t},\n\t\t\tping: () => realCall ? realCall.ping() : id$.then(() => realCall.ping())\n\t\t};\n\t}\n\tclose() {\n\t\tthis._inner.close();\n\t}\n\tasync _prepareOutbound(method, params, opts) {\n\t\tconst ctx = opts?.ctx;\n\t\tconst signer = this._resolveSigner(ctx);\n\t\tif (signer === void 0) return {\n\t\t\tmethod,\n\t\t\tparams\n\t\t};\n\t\tconst baseIntent = {\n\t\t\tmethod,\n\t\t\tparams,\n\t\t\t...opts?.interfaceHash !== void 0 ? { interfaceHash: opts.interfaceHash } : {}\n\t\t};\n\t\tconst coords = this._createSigningCoordinates();\n\t\tconst { intent, capabilities } = await this._resolveIntentAndCapabilities(baseIntent, signer, coords, ctx);\n\t\treturn this._signPreparedCall(intent, signer, coords.nonceBytes, capabilities);\n\t}\n\t_resolveSigner(ctx) {\n\t\treturn ctx?.signerOverride === null ? void 0 : ctx?.signerOverride ?? this._config.principal?.identity;\n\t}\n\t_createSigningCoordinates() {\n\t\tconst nonceBytes = _randomNonceBytes();\n\t\treturn {\n\t\t\tnonceBytes,\n\t\t\tnonce: bytesToBase64Url(nonceBytes),\n\t\t\tsignedAtMs: Date.now()\n\t\t};\n\t}\n\tasync _resolveIntentAndCapabilities(baseIntent, signer, coords, ctx) {\n\t\tconst intent = {\n\t\t\tmethod: baseIntent.method,\n\t\t\tparams: baseIntent.params,\n\t\t\t...baseIntent.interfaceHash !== void 0 ? { interfaceHash: baseIntent.interfaceHash } : {},\n\t\t\tsignedAtMs: coords.signedAtMs\n\t\t};\n\t\tlet capabilities;\n\t\tif (ctx?.capsOverride !== void 0) capabilities = ctx.capsOverride;\n\t\telse {\n\t\t\tconst persistent = this._config.principal?.capBag.capabilities ?? [];\n\t\t\tconst oneShot = this._config.oneShotCaps?.take() ?? [];\n\t\t\tcapabilities = oneShot.length > 0 ? [...persistent, ...oneShot] : persistent;\n\t\t\tconst provider = this._config.capProvider;\n\t\t\tif (provider) {\n\t\t\t\tconst provided = await provider({\n\t\t\t\t\tmethod: intent.method,\n\t\t\t\t\tparams: intent.params,\n\t\t\t\t\tsigner: signer.publicSigningIdentity.principal,\n\t\t\t\t\tnonce: coords.nonce,\n\t\t\t\t\tsignedAtMs: intent.signedAtMs,\n\t\t\t\t\t...intent.interfaceHash !== void 0 ? { interfaceHash: intent.interfaceHash } : {}\n\t\t\t\t});\n\t\t\t\tif (provided.method !== void 0) intent.method = provided.method;\n\t\t\t\tif (provided.params !== void 0) intent.params = provided.params;\n\t\t\t\tif (provided.interfaceHash !== void 0) intent.interfaceHash = provided.interfaceHash;\n\t\t\t\tif (provided.signedAtMs !== void 0) intent.signedAtMs = provided.signedAtMs;\n\t\t\t\tif (provided.capabilities !== void 0) capabilities = provided.capabilities;\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tintent,\n\t\t\tcapabilities\n\t\t};\n\t}\n\tasync _signPreparedCall(intent, signer, nonceBytes, capabilities) {\n\t\tconst signed = await signRpcCall({\n\t\t\tmethod: intent.method,\n\t\t\tparams: intent.params,\n\t\t\tsigningIdentity: signer,\n\t\t\tnonce: nonceBytes,\n\t\t\tnowMs: intent.signedAtMs,\n\t\t\t...intent.interfaceHash !== void 0 ? { interfaceHash: intent.interfaceHash } : {}\n\t\t});\n\t\tconst outboundParams = capabilities.length > 0 ? attachCapabilities(signed.wireParams, capabilities) : signed.wireParams;\n\t\treturn {\n\t\t\tmethod: intent.method,\n\t\t\tparams: outboundParams\n\t\t};\n\t}\n};\nfunction _randomNonceBytes() {\n\tconst out = /* @__PURE__ */ new Uint8Array(16);\n\tcrypto.getRandomValues(out);\n\treturn out;\n}\n//#endregion\n//#region src/identity/permissionCoverage.ts\n/** Conservative call-set containment; ability flags are checked by the caller. */\nfunction permissionScopeCovers(granted, requested) {\n\tconst g = granted.target;\n\tconst r = requested.target;\n\tif (!patternCovers(g.serviceId, r.serviceId, \"/\") || !patternCovers(g.interfaceId, r.interfaceId, \".\") || g.interfaceHash !== void 0 && g.interfaceHash !== r.interfaceHash || !r.members.every((member) => g.members.some((allowed) => patternCovers(allowed, member, \"\")))) return false;\n\tif (granted.callBind !== void 0 && (requested.callBind?.alg !== granted.callBind.alg || requested.callBind.payloadHash !== granted.callBind.payloadHash)) return false;\n\tif (granted.params === void 0) return true;\n\tif (requested.params === void 0) return false;\n\tconst requestedParams = requested.params;\n\tconst keys = Object.keys(granted.params);\n\treturn keys.length === Object.keys(requestedParams).length && keys.every((key) => Object.hasOwn(requestedParams, key) && paramCovers(granted.params[key], requestedParams[key]));\n}\nfunction patternCovers(granted, requested, delimiter) {\n\tif (\"exact\" in granted) return \"exact\" in requested && granted.exact === requested.exact;\n\tconst value = \"exact\" in requested ? requested.exact : requested.prefix;\n\treturn granted.prefix === \"\" || value === granted.prefix || value.startsWith(granted.prefix + delimiter);\n}\nfunction paramCovers(granted, requested) {\n\tif (Object.keys(granted).length !== 1 || Object.keys(requested).length !== 1) return false;\n\tif (\"any\" in granted) return true;\n\tif (\"any\" in requested) return false;\n\tif (\"exact\" in requested) return matchParams({ value: granted }, { value: requested.exact }).ok;\n\tif (\"enum\" in requested) return requested.enum.every((value) => matchParams({ value: granted }, { value }).ok);\n\tif (\"prefix\" in requested) return \"prefix\" in granted && requested.prefix.startsWith(granted.prefix);\n\treturn \"subsetOf\" in requested && \"subsetOf\" in granted && requested.subsetOf.every((value) => granted.subsetOf.includes(value));\n}\n//#endregion\n//#region src/identity/capability.ts\n/**\n* Capability **semantics**: the authorization layer over the pure\n* protocol syntax in `../protocol/capability`. This module answers the\n* single question \"may this concrete signed call proceed?\" via\n* {@link permits}, built from the chain verifier {@link verifyChain} and\n* the membership predicate {@link capabilityPermits}. Signing lives here\n* too, since it needs a {@link SigningIdentity}.\n*/\n/**\n* Pure freshness check for a single capability link: `true` when the cap never\n* expires, or its `expiresAtMs` is still in the future at `now + marginMs`.\n*\n* Mirrors the gate's expiry rule in {@link verifyChain}'s link check\n* (`expiresAtMs < nowMs` ⇒ expired) so a producer can decide, *before signing*,\n* whether to re-acquire a cap rather than attach one the gate will reject as\n* `expired`. The `marginMs` safety window absorbs in-flight transit time and\n* client/hub clock skew — pass the call's `signedAtMs` as `now` so the check\n* evaluates expiry against the same instant baked into the envelope.\n*\n* This checks ONE link. Effective authority requires every link in a\n* delegation chain to be unexpired, so a producer attaching a bag should apply\n* this to every cap it would attach (see {@link capBagFreshAt}).\n*/\nfunction capabilityFreshAt(cap, now, marginMs = 0) {\n\treturn cap.expiresAtMs === void 0 || cap.expiresAtMs > now + marginMs;\n}\n/**\n* Freshness over a whole presented bag: `true` only when every cap is fresh at\n* `now + marginMs` (see {@link capabilityFreshAt}). An empty bag is trivially\n* fresh. Use this at the cap-production point to decide whether to re-acquire.\n*/\nfunction capBagFreshAt(caps, now, marginMs = 0) {\n\treturn caps.every((cap) => capabilityFreshAt(cap, now, marginMs));\n}\n/**\n* Verify that some delegation chain among the presented `capabilities`\n* authorizes `call`, and return the issuer at its top (the trust anchor the\n* caller then judges). The bag's topology is inferred: any capability whose\n* `audience` is the caller is tried as a leaf, and parents are resolved out\n* of the same bag by content hash (`parentHash`).\n*\n* Each link must be authentic (signature), unexpired, and bound to the next\n* link's issuer; the **leaf** must grant `invoke` for the call and every\n* **parent** must grant `delegate`. Effective authority is therefore the\n* intersection over the chain — a delegate can only narrow.\n*\n* @internal Chain *authenticity* only — it makes **no** trust decision. The\n* public authorization entry point is {@link permits}, which layers the\n* accepted-root policy on top.\n*/\nasync function verifyChain(capabilities, call, opts) {\n\tconst byHash = /* @__PURE__ */ new Map();\n\tfor (const c of capabilities) byHash.set(signedHash(\"capability\", c), c);\n\tconst resolveParent = (h) => byHash.get(h);\n\tconst maxDepth = opts.maxDepth ?? 16;\n\tlet leafReason;\n\tlet anyReason = \"no presented capability addresses this call\";\n\tlet unacceptedRoot;\n\tfor (const leaf of capabilities) {\n\t\tconst r = await _verifyLink(leaf, opts.expectedAudience, opts.nowMs, maxDepth, true, resolveParent, (link, isLeaf) => capabilityPermits(call, link, isLeaf ? \"invoke\" : \"delegate\"));\n\t\tif (!r.ok) {\n\t\t\tanyReason = r.reason;\n\t\t\tif (leaf.audience === opts.expectedAudience) leafReason = r.reason;\n\t\t\tcontinue;\n\t\t}\n\t\tif (opts.acceptRoot !== void 0 && !opts.acceptRoot(r.rootIssuer)) {\n\t\t\tunacceptedRoot = r.rootIssuer;\n\t\t\tcontinue;\n\t\t}\n\t\treturn {\n\t\t\tok: true,\n\t\t\trootIssuer: r.rootIssuer,\n\t\t\tleafNonce: leaf.nonce\n\t\t};\n\t}\n\tif (unacceptedRoot !== void 0) return {\n\t\tok: false,\n\t\treason: \"no chain roots at an accepted issuer\",\n\t\tverifiedRootIssuer: unacceptedRoot\n\t};\n\treturn {\n\t\tok: false,\n\t\treason: leafReason ?? anyReason\n\t};\n}\nasync function _verifyLink(link, expectedAudience, nowMs, depthLeft, isLeaf, resolveParent, checkPermission) {\n\tif (depthLeft <= 0) return {\n\t\tok: false,\n\t\treason: \"chain too deep\"\n\t};\n\tif (link.audience !== expectedAudience) return {\n\t\tok: false,\n\t\treason: `audience mismatch (expected ${expectedAudience}, got ${link.audience})`\n\t};\n\tif (link.expiresAtMs !== void 0 && link.expiresAtMs < nowMs) return {\n\t\tok: false,\n\t\treason: \"expired\"\n\t};\n\tconst permitted = checkPermission(link, isLeaf);\n\tif (!permitted.ok) return {\n\t\tok: false,\n\t\treason: permitted.reason\n\t};\n\tlet issuerKey;\n\tconst resolved = resolveSigningKey({\n\t\tprincipal: link.issuer,\n\t\tkeyId: readSignature(link, \"capability\")?.keyId ?? \"\",\n\t\ttimeMs: nowMs\n\t});\n\tif (resolved === void 0) return {\n\t\tok: false,\n\t\treason: \"unresolvable issuer key\"\n\t};\n\tissuerKey = resolved.publicKey;\n\tif (!await verifyObject(\"capability\", link, issuerKey)) return {\n\t\tok: false,\n\t\treason: \"bad signature\"\n\t};\n\tif (link.parentHash === void 0) return {\n\t\tok: true,\n\t\trootIssuer: link.issuer\n\t};\n\tconst parent = resolveParent(link.parentHash);\n\tif (parent === void 0) return {\n\t\tok: false,\n\t\treason: \"parent capability not presented\"\n\t};\n\tif (signedHash(\"capability\", parent) !== link.parentHash) return {\n\t\tok: false,\n\t\treason: \"parent hash mismatch\"\n\t};\n\treturn _verifyLink(parent, link.issuer, nowMs, depthLeft - 1, false, resolveParent, checkPermission);\n}\n/**\n* **The** authorization predicate. A call is permitted iff some presented\n* capability (1) addresses the call, (2) has a genuine, well-delegated\n* chain whose leaf audience is the caller (`call.signer`), and (3) roots\n* at an issuer the verifier accepts **for the call's service**.\n*\n* Pure: it reports the verdict (and the `capabilityNonce` / `rootIssuer`\n* for audit) but performs no consumption. Replay is the caller's job — the\n* gate dedups `call.nonce`, so `callBind` grants are single-use for free.\n*\n* `acceptedRootIssuers` is consulted with the call's `serviceId` and returns\n* the accepted {@link AcceptedRootIssuer} anchors; an empty result rejects\n* every capability (fail closed) — trust is the verifier's, never the\n* token's. Anchors flagged `isPublic` are named in the rejection reason when\n* a chain roots at an unaccepted issuer.\n*/\nasync function permits(call, capabilities, acceptedRootIssuers, nowMs, opts) {\n\tif (capabilities.length === 0) return {\n\t\tok: false,\n\t\treason: \"no capabilities were presented with this call\"\n\t};\n\tif (!capabilities.every(hasSignedCapabilityShape)) return {\n\t\tok: false,\n\t\treason: \"malformed capability\"\n\t};\n\tconst accepted = acceptedRootIssuers(call.target.serviceId);\n\tconst acceptedIds = new Set(accepted.map((a) => a.principal));\n\tconst chain = await verifyChain(capabilities, call, {\n\t\texpectedAudience: call.signer,\n\t\tnowMs,\n\t\tacceptRoot: (rootIssuer) => acceptedIds.has(rootIssuer),\n\t\t...opts?.maxDepth !== void 0 ? { maxDepth: opts.maxDepth } : {}\n\t});\n\tif (chain.ok) return {\n\t\tok: true,\n\t\tcapabilityNonce: chain.leafNonce,\n\t\trootIssuer: chain.rootIssuer\n\t};\n\tif (chain.verifiedRootIssuer !== void 0) return {\n\t\tok: false,\n\t\treason: _rootIssuerRejectedReason(call.target.serviceId, chain.verifiedRootIssuer, accepted)\n\t};\n\treturn {\n\t\tok: false,\n\t\treason: chain.reason\n\t};\n}\n/**\n* Reason string for a chain that verified but rooted at an unaccepted issuer.\n* Names the (caller-owned) `rootIssuer` it actually rooted at, plus the\n* `isPublic` accepted anchors to point the caller at the right root.\n*/\nfunction _rootIssuerRejectedReason(serviceId, rootIssuer, accepted) {\n\tconst head = `capability root issuer ${rootIssuer} is not accepted for service \"${serviceId}\"`;\n\tif (accepted.length === 0) return `${head} (no root issuers are accepted for this service)`;\n\tconst publicIds = accepted.filter((a) => a.isPublic).map((a) => a.principal);\n\tif (publicIds.length === 0) return head;\n\treturn `${head}; accepted root issuer(s): ${publicIds.join(\", \")}`;\n}\n/**\n* Sign a `Capability` with a {@link SigningIdentity}. The private key never\n* leaves the identity. The result verifies via {@link verifyChain}.\n*/\nasync function signCapability(capability, issuer) {\n\treturn await signObject(\"capability\", capability, issuer);\n}\n/**\n* Issue and sign a capability, deriving its issuer, nonce, and optional parent\n* hash. The result is plain JSON data and survives a JSON stringify/parse\n* round-trip without reconstruction.\n*/\nasync function issueCapability(issuer, options) {\n\treturn signCapability({\n\t\tissuer: issuer.publicSigningIdentity.principal,\n\t\taudience: options.audience.principal,\n\t\tpermissions: [...options.permissions],\n\t\tnonce: _randomCapabilityNonce(),\n\t\t...options.expiresAtMs !== void 0 ? { expiresAtMs: options.expiresAtMs } : {},\n\t\t...options.parent !== void 0 ? { parentHash: signedHash(\"capability\", options.parent) } : {}\n\t}, issuer);\n}\n/** Expected coverage failure; signing, malformed requests and expiry errors remain distinct. */\nvar CapabilityIssuanceError = class extends Error {\n\tcode;\n\tname = \"CapabilityIssuanceError\";\n\tconstructor(code, message) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t}\n};\n/**\n* Issue complete capability chains from an identity and its current grants.\n* Each requested clause must be fully covered by delegation authority at every\n* ancestor, not merely intersect it. Exact/prefix targets and common parameter\n* narrowing are supported; unsupported coverage is conservatively rejected.\n*\n* Different clauses may use different accepted roots. Expiration is capped at\n* the earliest ancestor expiry. The result contains the new leaves and all\n* ancestors needed by `permits`; retain and forward the entire array.\n*/\nasync function issueCapabilities(issuer, options) {\n\treturn (await prepareCapabilityIssuance(issuer, options)).issue();\n}\n/**\n* Discover authenticated delegation root candidates without signing anything.\n* The issuer itself is not implicitly added. Each link must grant delegation;\n* this does not prove coverage of a requested scope (use preparation for that).\n*/\nasync function getDelegationRootIds(issuer, capabilities) {\n\tconst byHash = _issuanceCapIndex(capabilities);\n\tconst roots = /* @__PURE__ */ new Set();\n\tconst nowMs = Date.now();\n\tfor (const candidate of byHash.values()) {\n\t\tconst verified = await _verifyLink(candidate, issuer.publicSigningIdentity.principal, nowMs, 15, false, (h) => byHash.get(h), (link) => capabilityFreshAt(link, nowMs) && link.permissions.some((p) => p.canDelegate === true && p.target.members.length > 0) ? { ok: true } : {\n\t\t\tok: false,\n\t\t\treason: \"expired or missing delegation authority\"\n\t\t});\n\t\tif (verified.ok) roots.add(verified.rootIssuer);\n\t}\n\treturn [...roots];\n}\n/**\n* Plan issuance without creating bearer capabilities or invoking the signer.\n* Captures immutable internal snapshots of permissions and selected chains, so\n* changes to a live bag or UI proposal cannot replace the confirmed authority.\n* `issue()` rechecks that authority after consent. Remote trust-policy changes\n* are still the recipient's responsibility; this is not a revocation service.\n*/\nasync function prepareCapabilityIssuance(issuer, options) {\n\tconst nowMs = Date.now();\n\tconst requestedExpiry = options.expiresAtMs;\n\tif (requestedExpiry !== void 0 && (!Number.isFinite(requestedExpiry) || requestedExpiry <= nowMs)) throw new Error(\"Capability expiration must be a finite future timestamp\");\n\tif (options.permissions.length === 0 || options.permissions.some((p) => !p.canInvoke && !p.canDelegate || p.target.members.length === 0)) throw new Error(\"At least one non-empty invoke or delegate permission is required\");\n\tconst principal = issuer.publicSigningIdentity.principal;\n\tconst audience = typeof options.audience === \"string\" ? new PublicSigningIdentity(options.audience) : new PublicSigningIdentity(options.audience.principal);\n\tconst permissions = structuredClone(options.permissions);\n\tconst accepted = options.acceptableRootIds === void 0 ? void 0 : new Set(options.acceptableRootIds);\n\tif (accepted?.has(principal)) return _issuancePlan(issuer, audience, [{\n\t\tpermissions,\n\t\trootIssuer: principal,\n\t\texpiresAtMs: requestedExpiry,\n\t\tancestors: []\n\t}]);\n\tconst byHash = _issuanceCapIndex(options.capabilities);\n\tconst grants = [];\n\tfor (const permission of permissions) {\n\t\tlet selected;\n\t\tlet rootIssuer = principal;\n\t\tfor (const candidate of byHash.values()) {\n\t\t\tif (candidate.audience !== principal) continue;\n\t\t\tconst verified = await _verifyLink(candidate, principal, nowMs, 15, false, (h) => byHash.get(h), (link) => _delegationCovers(link, [permission], nowMs));\n\t\t\tif (!verified.ok || accepted && !accepted.has(verified.rootIssuer)) continue;\n\t\t\trootIssuer = verified.rootIssuer;\n\t\t\tselected = [];\n\t\t\tfor (let link = candidate; link; link = link.parentHash === void 0 ? void 0 : byHash.get(link.parentHash)) selected.push(link);\n\t\t\tbreak;\n\t\t}\n\t\tif (!selected) {\n\t\t\tif (accepted === void 0) {\n\t\t\t\tgrants.push({\n\t\t\t\t\tpermissions: [permission],\n\t\t\t\t\trootIssuer: principal,\n\t\t\t\t\texpiresAtMs: requestedExpiry,\n\t\t\t\t\tancestors: []\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow new CapabilityIssuanceError(\"insufficientAuthority\", \"Insufficient delegation authority: no valid accepted chain fully covers the requested permission\");\n\t\t}\n\t\tlet expiresAtMs = requestedExpiry;\n\t\tfor (const cap of selected) if (cap.expiresAtMs !== void 0) expiresAtMs = Math.min(expiresAtMs ?? Infinity, cap.expiresAtMs);\n\t\tgrants.push({\n\t\t\tpermissions: [permission],\n\t\t\trootIssuer,\n\t\t\texpiresAtMs,\n\t\t\tancestors: selected,\n\t\t\tparentHash: signedHash(\"capability\", selected[0])\n\t\t});\n\t}\n\treturn _issuancePlan(issuer, audience, grants);\n}\nfunction _issuanceCapIndex(capabilities) {\n\tconst byHash = /* @__PURE__ */ new Map();\n\tfor (const cap of capabilities) try {\n\t\tif (hasSignedCapabilityShape(cap)) byHash.set(signedHash(\"capability\", cap), structuredClone(cap));\n\t} catch {}\n\treturn byHash;\n}\nfunction _delegationCovers(link, permissions, nowMs) {\n\treturn capabilityFreshAt(link, nowMs) && permissions.every((permission) => permission.target.members.every((member) => link.permissions.some((grant) => grant.canDelegate === true && permissionScopeCovers(grant, {\n\t\t...permission,\n\t\ttarget: {\n\t\t\t...permission.target,\n\t\t\tmembers: [member]\n\t\t}\n\t})))) ? { ok: true } : {\n\t\tok: false,\n\t\treason: \"expired or insufficient delegation scope\"\n\t};\n}\nfunction _issuancePlan(issuer, audience, grants) {\n\tconst issuerId = issuer.publicSigningIdentity.principal;\n\treturn {\n\t\taudience: audience.principal,\n\t\tproposals: grants.map(({ ancestors, ...proposal }) => structuredClone(proposal)),\n\t\tasync issue() {\n\t\t\tif (issuer.publicSigningIdentity.principal !== issuerId) throw new Error(\"Prepared capability issuer changed\");\n\t\t\tconst nowMs = Date.now();\n\t\t\tfor (const grant of grants) {\n\t\t\t\tif (grant.expiresAtMs !== void 0 && grant.expiresAtMs <= nowMs) throw new Error(\"Prepared capability authority expired\");\n\t\t\t\tif (grant.ancestors.length > 0) {\n\t\t\t\t\tconst byHash = _issuanceCapIndex(grant.ancestors);\n\t\t\t\t\tconst verified = await _verifyLink(grant.ancestors[0], issuerId, nowMs, 15, false, (h) => byHash.get(h), (link) => _delegationCovers(link, grant.permissions, nowMs));\n\t\t\t\t\tif (!verified.ok || verified.rootIssuer !== grant.rootIssuer) throw new Error(\"Prepared capability authority is no longer valid\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst result = /* @__PURE__ */ new Map();\n\t\t\tfor (const grant of grants) {\n\t\t\t\tconst leaf = await issueCapability(issuer, {\n\t\t\t\t\taudience,\n\t\t\t\t\tpermissions: grant.permissions,\n\t\t\t\t\texpiresAtMs: grant.expiresAtMs,\n\t\t\t\t\tparent: grant.ancestors[0]\n\t\t\t\t});\n\t\t\t\tfor (const cap of [leaf, ...grant.ancestors]) result.set(signedHash(\"capability\", cap), structuredClone(cap));\n\t\t\t}\n\t\t\tif (grants.some((grant) => grant.expiresAtMs !== void 0 && grant.expiresAtMs <= Date.now())) throw new Error(\"Prepared capability authority expired while signing\");\n\t\t\treturn [...result.values()];\n\t\t}\n\t};\n}\n/** Match a string parameter by prefix. */\nfunction prefix(value) {\n\treturn { prefix: value };\n}\n/**\n* Build an invoke permission from a typed interface member. The helper derives\n* the interface id and schema hash and type-checks parameter matcher names and\n* values against the member's params.\n*/\nfunction invoke(serviceId, iface, member, params) {\n\treturn {\n\t\ttarget: {\n\t\t\tserviceId: { exact: serviceId },\n\t\t\tinterfaceId: { exact: iface.info.id },\n\t\t\tinterfaceHash: iface.schemaHash,\n\t\t\tmembers: [{ exact: member }]\n\t\t},\n\t\tcanInvoke: true,\n\t\t...params !== void 0 ? { params } : {}\n\t};\n}\nfunction _randomCapabilityNonce() {\n\tconst bytes = /* @__PURE__ */ new Uint8Array(16);\n\tglobalThis.crypto.getRandomValues(bytes);\n\treturn bytesToBase64Url(bytes);\n}\n//#endregion\n//#region src/identity/metaEnvelope.ts\n/**\n* Returns a wire-form params object carrying the `$hubrpc` envelope, the\n* `call` signature under `$hubrpcSignature`, and (optionally) capabilities\n* under `$hubrpcUnsigned`.\n*/\nasync function signParams(opts) {\n\tif (opts.params !== void 0 && (typeof opts.params !== \"object\" || Array.isArray(opts.params))) throw new Error(\"signParams: params must be an object or undefined\");\n\tconst signed = await signRpcCall({\n\t\tmethod: opts.method,\n\t\tparams: opts.params ?? void 0,\n\t\tsigningIdentity: opts.signingIdentity,\n\t\t...opts.nowMs !== void 0 ? { nowMs: opts.nowMs } : {},\n\t\t...opts.nonce !== void 0 ? { nonce: opts.nonce } : {},\n\t\t...opts.interfaceHash !== void 0 ? { interfaceHash: opts.interfaceHash } : {}\n\t});\n\treturn opts.capabilities && opts.capabilities.length > 0 ? attachCapabilities(signed.wireParams, opts.capabilities) : signed.wireParams;\n}\nasync function verifyCall(opts) {\n\tconst res = await verifyRpcCall({\n\t\twireMethod: opts.method,\n\t\twireParams: opts.params,\n\t\t...opts.nowMs !== void 0 ? { nowMs: opts.nowMs } : {},\n\t\t...opts.maxSkewMs !== void 0 ? { maxSkewMs: opts.maxSkewMs } : {},\n\t\trequireSigned: opts.requireCapability === true\n\t});\n\tif (!res.ok) return {\n\t\tok: false,\n\t\tkind: \"envelope\",\n\t\treason: res.reason\n\t};\n\tif (!res.identity) return {\n\t\tok: false,\n\t\tkind: \"envelope\",\n\t\treason: \"missing identity envelope\"\n\t};\n\tconst { identity } = res;\n\tif (opts.requireCapability && identity.capabilities.length === 0) return {\n\t\tok: false,\n\t\tkind: \"capability\",\n\t\treason: \"capability required but none provided\"\n\t};\n\tconst params = res.params;\n\tlet strippedParams;\n\tif (params === void 0 || params === null) strippedParams = void 0;\n\telse if (typeof params === \"object\" && !Array.isArray(params)) strippedParams = params;\n\telse strippedParams = void 0;\n\tconst target = opts.parseMethod(opts.method);\n\tif (identity.callMeta.interfaceHash !== void 0) target.interfaceHash = identity.callMeta.interfaceHash;\n\tconst call = {\n\t\ttarget,\n\t\tparams,\n\t\tnonce: identity.callMeta.nonce,\n\t\tsignedAtMs: identity.callMeta.signedAtMs,\n\t\tsigner: identity.signer,\n\t\tcallHash: identity.callHash\n\t};\n\treturn {\n\t\tok: true,\n\t\tsigner: identity.signer,\n\t\tcall,\n\t\tstrippedParams,\n\t\tcapabilities: identity.capabilities,\n\t\tnonce: identity.callMeta.nonce,\n\t\tcallHash: identity.callHash,\n\t\tcallMeta: identity.callMeta,\n\t\tinterfaceHash: identity.callMeta.interfaceHash\n\t};\n}\n//#endregion\n//#region src/identity/seededPrincipal.ts\n/** Derive a domain-separated 32-byte seed from the numeric seed. */\nfunction _seedBytes(domain, seed) {\n\treturn sha256(new TextEncoder().encode(`${domain}:${seed}`));\n}\n/**\n* Build a **random**, in-memory {@link Principal}: a fresh Ed25519 signing\n* identity + X25519 wrapping key, paired with an empty memory-only\n* {@link CapBag}. Full-entropy (unlike {@link createSeededMemoryPrincipal}), so\n* it is safe to sign trusted calls — e.g. an in-process \"agent\" identity a hub\n* admin delegates read authority to (via a minted capability) for directory\n* discovery. The identity is ephemeral: it vanishes with the process.\n*/\nasync function createMemoryPrincipal() {\n\tconst ed = await generateKeypair();\n\tconst wrap = await generateX25519Keypair();\n\treturn new Principal(new KeypairIdentity(principalForPublicKey(ed.publicKey), ed.privateKey, wrap), await CapBag.load());\n}\n/**\n* Build a deterministic {@link Principal} from a numeric seed: a reproducible\n* Ed25519 signing identity (so the nodeId is stable across runs) plus a matching\n* X25519 wrapping key, paired with an empty, memory-only {@link CapBag}.\n*\n* For tests and reproducible local setups ONLY — the key material is derived\n* from a low-entropy seed and must never be used to sign anything trusted.\n*/\nasync function createSeededMemoryPrincipal(opts) {\n\tconst ed = await keypairFromSeed(_seedBytes(\"linkrpc.seed.ed25519\", opts.seed));\n\tconst wrap = await x25519KeypairFromSeed(_seedBytes(\"linkrpc.seed.x25519\", opts.seed));\n\treturn new Principal(new KeypairIdentity(principalForPublicKey(ed.publicKey), ed.privateKey, wrap), await CapBag.load());\n}\n/**\n* Derive a deterministic {@link KeypairSigningIdentity} from a numeric seed: a\n* reproducible Ed25519 signing identity (so the nodeId is stable across runs),\n* with no wrapping key. Use it where only signing/issuing is needed — e.g. a\n* hub admin `issuer` that mints capabilities in tests.\n*\n* For tests and reproducible local setups ONLY — the key material is derived\n* from a low-entropy seed and must never be used to sign anything trusted.\n*/\nasync function createSeededSigningIdentity(opts) {\n\tconst ed = await keypairFromSeed(_seedBytes(\"linkrpc.seed.ed25519\", opts.seed));\n\treturn KeypairSigningIdentity.fromKeypair(ed);\n}\n//#endregion\nexport { exportStaticHubSchema as $, PublicSigningIdentity as A, HUBRPC_UNSIGNED_KEY as At, formatEndpointUri as B, methodNameToTarget as Bt, createManagedIdentity as C, directoryWatchNever as Ct, identityStorageInterface as D, stripLinkRpcWireMeta as Dt, identityInterface as E, requireObjectParams as Et, signRpcCall as F, readSignature as Ft, TransportPair as G, bareInterfaceTarget as Gt, parseEndpointUri as H, generateTsContract as Ht, verifyRpcCall as I, signedHash as It, capabilityPermits as J, matchesJsonSchema as Jt, connectTransports as K, materializeJsonSchema as Kt, crypto_exports as L, signingDomainValue as Lt, Principal as M, LINKRPC_SIGNATURE_KEY as Mt, CapBag as N, LINKRPC_UNSIGNED_KEY as Nt, KeypairIdentity as O, HUBRPC_META_KEY as Ot, attachCapabilities as P, getKeyId as Pt, permissionPermits as Q, generateKeypair as R, signingInput as Rt, InMemoryManagedIdentityStorage as S, directoryInterface as St, registerLazyIdentityOnOverlay as T, zServiceIdPattern as Tt, ChannelConnector as U, parseStaticHubSchema as Ut, isHubEndpoint as V, parseMethodName as Vt, MultiplexedTransport as W, generateTsInterface as Wt, matchParams as X, NonCompliantServerError as Xt, hasSignedCapabilityShape as Y, validateJsonSchema as Yt, permissionMatchesTarget as Z, defineInterfaceTemplate as Zt, OneShotCapStaging as _, walkHub as _t, verifyCall as a, JsonRpcChannel as at, createManagedPrincipal as b, withRpcTimeout as bt, capabilityFreshAt as c, DEFAULT_WALK_DEPTH as ct, issueCapabilities as d, fetchSchema as dt, LinkRpcConnection as et, issueCapability as f, findMethodInSchema as ft, signCapability as g, serviceIdMatchesScopes as gt, prepareCapabilityIssuance as h, serviceIdMatchesPattern as ht, signParams as i, isInterfaceTarget as it, PublicWrappingIdentity as j, LINKRPC_META_KEY as jt, KeypairSigningIdentity as k, HUBRPC_SIGNATURE_KEY as kt, getDelegationRootIds as l, HubDirectoryExplorer as lt, prefix as m, normalizeServiceIdScopes as mt, createSeededMemoryPrincipal as n, defaultInterfaceTarget as nt, CapabilityIssuanceError as o, Channel as ot, permits as p, intersectServiceIdScopes as pt, traceMessageTransport as q, isAssignable as qt, createSeededSigningIdentity as r, interfaceTarget as rt, capBagFreshAt as s, RpcError as st, createMemoryPrincipal as t, ServiceHandle as tt, invoke as u, fetchDirectory as ut, SigningSender as v, walkHubDetailed as vt, registerIdentityOnOverlay as w, schemasInterface as wt, InMemoryManagedIdentity as x, defaultsInterface as xt, PrincipalWithStore as y, DEFAULT_RPC_TIMEOUT_MS as yt, generateX25519Keypair as z, withSignature as zt };\n\n//# sourceMappingURL=src-DYVSK_tz.js.map","import { defineInterface, requestType, schemasInterface } from '@hediet/linkrpc';\nimport { z } from 'zod';\n\nconst empty = z.object({}).default({});\nconst exception = z.object({ message: z.string(), stack: z.string().optional() });\nconst renderEvent = z.object({\n type: z.enum(['console.error', 'console.warn', 'console.log', 'window.error', 'window.unhandledrejection']),\n message: z.string(),\n stack: z.string().optional(),\n});\nconst disposeReport = z.object({\n hasError: z.boolean(),\n errors: z.array(exception).readonly(),\n events: z.array(renderEvent).readonly(),\n});\nconst approval = z.object({\n fixtureId: z.string(),\n originalHash: z.string(),\n modifiedHash: z.string(),\n comment: z.string(),\n approvedAt: z.string(),\n});\nconst approvalKey = z.object({\n fixtureId: z.string(),\n originalHash: z.string(),\n modifiedHash: z.string(),\n});\nconst visualDescriptions = z.object({\n fixtureId: z.string(),\n expectedVisualDescriptions: z.array(z.string()),\n screenshotHash: z.string(),\n});\nconst sessionInfo = z.union([\n z.object({\n name: z.string(), sourceKind: z.enum(['current', 'worktree']), isLoading: z.literal(true),\n }),\n z.object({\n name: z.string(), sourceKind: z.enum(['current', 'worktree']),\n isLoading: z.literal(false).optional(), serverUrl: z.string(), sourceTreeId: z.string(),\n worktreePath: z.string().optional(), ref: z.string().optional(),\n }),\n]);\nconst daemonSessionsSchema = z.array(sessionInfo);\nconst sessions = daemonSessionsSchema;\nconst sessionOperationResult = z.union([z.object({ sessions }), z.object({ error: z.string() })]);\nconst screenshot = z.object({\n hash: z.string().optional(),\n image: z.string().optional(),\n hasError: z.boolean(),\n error: exception.optional(),\n events: z.array(renderEvent).optional(),\n output: z.unknown().optional(),\n});\nconst screenshotTakeResultSchema = screenshot.extend({\n sourceTreeId: z.string(),\n isStable: z.boolean().optional(),\n stabilityScreenshots: z.array(z.object({\n hash: z.string(), delayMs: z.number(), image: z.string().optional(),\n })).optional(),\n previousDispose: disposeReport.optional(),\n currentDispose: disposeReport.optional(),\n});\nconst screenshotTakeResult = screenshotTakeResultSchema;\nconst daemonEventSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('source-change'), sessionName: z.string(), sourceTreeId: z.string() }),\n z.object({ type: z.literal('ref-change'), sessionName: z.string(), newCommit: z.string() }),\n z.object({ type: z.literal('session-change') }),\n z.object({ type: z.literal('log'), level: z.enum(['info', 'debug', 'trace']), message: z.string() }),\n]);\nconst daemonConnectionInitializationSchema = z.object({\n clientName: z.string(),\n});\nconst daemonInitializationInterface = defineInterface({ id: 'component-explorer.daemon-initialization' }, {\n initialize: requestType(daemonConnectionInitializationSchema, z.void()),\n});\nconst fixtureListArgsSchema = z.object({ sessionName: z.string(), sourceTreeId: z.string() });\nconst daemonRpcInterface = defineInterface({ id: 'component-explorer.daemon' }, {\n fixturesList: requestType(fixtureListArgsSchema, z.object({\n fixtures: z.array(z.object({\n fixtureId: z.string(), fixtureName: z.string(), groupPath: z.array(z.string()),\n background: z.enum(['light', 'dark']), labels: z.array(z.string()).readonly(),\n expectedVisualDescriptions: z.array(z.string()).readonly(),\n inputSchema: z.unknown().optional(),\n })),\n loadError: z.string().optional(),\n })),\n screenshotsTake: requestType(z.object({\n fixtureId: z.string(), sourceTreeId: z.string(), sessionName: z.string(),\n includeImage: z.boolean().optional(), stabilityCheck: z.boolean().optional(),\n reloadBeforeRender: z.boolean().optional(), input: z.unknown().optional(),\n disposeAfter: z.boolean().optional(),\n }), screenshotTakeResult),\n screenshotsTakeBatch: requestType(z.object({\n fixtureIds: z.array(z.string()), sourceTreeId: z.string(), sessionName: z.string(),\n includeImages: z.boolean().optional(), reloadBetweenFixtures: z.boolean().optional(),\n input: z.unknown().optional(),\n }), z.object({ sourceTreeId: z.string(), screenshots: z.array(screenshot.extend({ fixtureId: z.string() })) })),\n screenshotsCompare: requestType(z.object({\n fixtureId: z.string(), baselineSessionName: z.string(), baselineSourceTreeId: z.string(),\n currentSessionName: z.string(), currentSourceTreeId: z.string(), includeImages: z.boolean().optional(),\n }), z.object({\n match: z.boolean(), baselineHash: z.string().optional(), currentHash: z.string().optional(),\n baselineImage: z.string().optional(), currentImage: z.string().optional(),\n baselineHasError: z.boolean(), baselineError: exception.optional(),\n baselineEvents: z.array(renderEvent).optional(), baselineOutput: z.unknown().optional(),\n currentHasError: z.boolean(), currentError: exception.optional(),\n currentEvents: z.array(renderEvent).optional(), currentOutput: z.unknown().optional(),\n labels: z.array(z.string()).readonly().optional(), labelsBefore: z.array(z.string()).readonly().optional(),\n approval: approval.optional(),\n })),\n approvalsApprove: requestType(approvalKey.extend({ comment: z.string() }), z.void()),\n approvalsRevoke: requestType(approvalKey, z.void()),\n approvalsList: requestType(z.object({ fixtureId: z.string().optional() }), z.array(approval)),\n approvalsLookup: requestType(approvalKey, z.union([approval, z.null()])),\n visualReviewGetStatus: requestType(visualDescriptions, z.union([\n z.literal('no-expectations'),\n z.object({\n expectedVisualDescriptions: z.array(z.string()).readonly(),\n status: z.enum(['approved', 'needs-review']),\n approval: z.object({ approvedAt: z.string(), comment: z.string() }).optional(),\n }),\n ])),\n visualReviewApprove: requestType(visualDescriptions.extend({ comment: z.string() }), z.void()),\n evaluate: requestType(z.object({\n sessionName: z.string(), sourceTreeId: z.string(), expression: z.string(),\n fixtureId: z.string().optional(),\n }), z.object({ result: z.unknown() })),\n setBrowserVisibility: requestType(z.object({ visible: z.boolean() }), z.object({ visible: z.boolean() })),\n events: requestType(empty, z.void()).withStream({ server: daemonEventSchema }),\n sessions: requestType(empty, sessions),\n restartSession: requestType(z.object({ sessionName: z.string() }), sessions),\n openSession: requestType(z.object({ name: z.string(), ref: z.string() }), sessionOperationResult),\n closeSession: requestType(z.object({ name: z.string() }), sessionOperationResult),\n updateSessionRef: requestType(z.object({ name: z.string(), ref: z.string() }), sessionOperationResult),\n shutdown: requestType(empty, z.void()),\n});\nfunction createDaemonMethods(connection) {\n const rpc = connection.get(daemonRpcInterface);\n return {\n fixtures: { list: rpc.fixturesList },\n screenshots: { take: rpc.screenshotsTake, takeBatch: rpc.screenshotsTakeBatch, compare: rpc.screenshotsCompare },\n approvals: { approve: rpc.approvalsApprove, revoke: rpc.approvalsRevoke, list: rpc.approvalsList, lookup: rpc.approvalsLookup },\n visualReview: { getStatus: rpc.visualReviewGetStatus, approve: rpc.visualReviewApprove },\n evaluate: rpc.evaluate,\n setBrowserVisibility: rpc.setBrowserVisibility,\n events: rpc.events,\n sessions: rpc.sessions,\n restartSession: rpc.restartSession,\n openSession: rpc.openSession,\n closeSession: rpc.closeSession,\n updateSessionRef: rpc.updateSessionRef,\n shutdown: rpc.shutdown,\n };\n}\nasync function initializeDaemonMethods(connection, clientName) {\n const schemas = connection.get(schemasInterface);\n await schemas.get({ interfaceId: daemonInitializationInterface.info.id, hash: daemonInitializationInterface.schemaHash });\n await connection.get(daemonInitializationInterface).initialize({ clientName });\n await schemas.get({ interfaceId: daemonRpcInterface.info.id, hash: daemonRpcInterface.schemaHash });\n return createDaemonMethods(connection);\n}\n\nexport { createDaemonMethods, daemonConnectionInitializationSchema, daemonEventSchema, daemonInitializationInterface, daemonRpcInterface, daemonSessionsSchema, fixtureListArgsSchema, initializeDaemonMethods, screenshotTakeResultSchema };\n//# sourceMappingURL=daemonRpc.js.map\n","import { LinkRpcConnection, type IMessageTransport, type JsonRpcMessage } from '@hediet/linkrpc/web';\nimport { initializeDaemonMethods, type DaemonClient } from '@vscode/component-explorer-common/daemon-rpc';\n\nconst RPC_PATH = '/__explorer/daemon-rpc';\n\nexport async function createBrowserDaemonClient(): Promise<DaemonClient> {\n\tconst url = new URL(RPC_PATH, location.href);\n\turl.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';\n\tconst socket = new WebSocket(url);\n\tlet connection: LinkRpcConnection | undefined;\n\tlet rejectClosed: (error: Error) => void = () => { };\n\tconst closed = new Promise<never>((_, reject) => { rejectClosed = reject; });\n\tconst transport = new BrowserWebSocketTransport(socket, () => {\n\t\tconnection?.close();\n\t\trejectClosed(new Error('Daemon WebSocket closed'));\n\t});\n\tlet disposed = false;\n\tconst dispose = (): void => {\n\t\tif (disposed) { return; }\n\t\tdisposed = true;\n\t\tconnection?.close();\n\t\ttransport.dispose();\n\t};\n\ttry {\n\t\tawait Promise.race([\n\t\t\tnew Promise<void>((resolve, reject) => {\n\t\t\t\tif (socket.readyState === WebSocket.OPEN) { resolve(); return; }\n\t\t\t\tsocket.addEventListener('open', () => resolve(), { once: true });\n\t\t\t\tsocket.addEventListener('error', () => reject(new Error('Daemon WebSocket failed to open')), { once: true });\n\t\t\t}),\n\t\t\tclosed,\n\t\t]);\n\t\tif (socket.readyState !== WebSocket.OPEN) { throw new Error('Daemon WebSocket closed before initialization'); }\n\t\tconnection = LinkRpcConnection.fromTransport(transport);\n\t\tconst methods = await initializeDaemonMethods(connection, 'explorer-ui');\n\t\treturn { methods, dispose };\n\t} catch (error) {\n\t\tdispose();\n\t\tthrow error;\n\t}\n}\n\nclass BrowserWebSocketTransport implements IMessageTransport {\n\tprivate _listener: ((message: JsonRpcMessage) => void) | undefined;\n\tprivate readonly _buffer: JsonRpcMessage[] = [];\n\tprivate _disposed = false;\n\n\tconstructor(private readonly _socket: WebSocket, private readonly _onClose: () => void) {\n\t\t_socket.addEventListener('message', this._handleMessage);\n\t\t_socket.addEventListener('close', this._handleClose);\n\t\t_socket.addEventListener('error', this._handleError);\n\t}\n\n\tsend(message: JsonRpcMessage): void {\n\t\tif (this._socket.readyState !== WebSocket.OPEN) { throw new Error('Daemon WebSocket is not open'); }\n\t\tthis._socket.send(JSON.stringify(message));\n\t}\n\n\tsetListener(listener: ((message: JsonRpcMessage) => void) | undefined): void {\n\t\tthis._listener = listener;\n\t\tif (listener) {\n\t\t\tqueueMicrotask(() => {\n\t\t\t\twhile (this._listener && this._buffer.length) {\n\t\t\t\t\tthis._listener(this._buffer.shift()!);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\tdispose(): void {\n\t\tif (this._disposed) { return; }\n\t\tthis._disposed = true;\n\t\tthis._listener = undefined;\n\t\tthis._buffer.length = 0;\n\t\tthis._socket.removeEventListener('message', this._handleMessage);\n\t\tthis._socket.removeEventListener('close', this._handleClose);\n\t\tthis._socket.removeEventListener('error', this._handleError);\n\t\tthis._socket.close();\n\t}\n\n\tprivate readonly _handleMessage = (event: MessageEvent): void => {\n\t\ttry {\n\t\t\tconst message: unknown = JSON.parse(event.data);\n\t\t\tif (!message || typeof message !== 'object' || !('jsonrpc' in message) || message.jsonrpc !== '2.0') {\n\t\t\t\tthrow new Error('Invalid daemon RPC message');\n\t\t\t}\n\t\t\tif (this._listener) { this._listener(message as JsonRpcMessage); }\n\t\t\telse { this._buffer.push(message as JsonRpcMessage); }\n\t\t} catch {\n\t\t\tthis._socket.close(1003, 'Invalid daemon RPC message');\n\t\t\tthis._onClose();\n\t\t}\n\t};\n\n\tprivate readonly _handleClose = (): void => this._onClose();\n\tprivate readonly _handleError = (): void => {\n\t\tthis._onClose();\n\t\tthis._socket.close();\n\t};\n}\n"],"names":["KEPT_KEYS","normalizeJsonSchema","raw","r","isEmptyObject","types","type","title","description","branch","schema","out","k","v","normalized","normalizeChild","detected","_detectDiscriminator","key","isPlainObject","pk","pv","s","name","branches","branchPropsList","b","props","candidates","_constPropNames","i","seen","allDistinct","rpcFailureBrand","RpcFailure","_a","error","__publicField","ErrorCode","isRequest","m","isNotification","isResponse","applicationErrorBrand","brandApplicationError","value","schemaSources","jsonPointerSegment","bodySchemas","parseDeclaredErrorBody","descriptor","body","parseErrorBody","errorBodySchema","payload","strictObject","literal","string","parsed","safeParse","validationIssues","issues","prefix","issue","path","pointer","jsonIssues","ancestors","child","isApplicationErrorValue","assertApplicationErrorCode","code","assertErrorCode","RequestType","paramsSchema","resultSchema","errorSchema","docs","clientStreamSchema","serverStreamSchema","applicationErrors","other","opts","errors","NotificationType","requestType","params","result","docsOrError","maybeDocs","void$1","notificationType","zodToSvcJsonSchema","options","source","component","addComponent","_b","normalizeZodJsonSchema","toJSONSchema","context","isRecord","definitions","localRefs","collectLocalRefs","componentNamePrefix","encodeComponentNamePart","definitionComponents","definitionName","rootComponent","rewrite","rewriteLocalRefs","definition","componentName","root","componentRef","refs","rewriteLocalRef","ref","encodedName","encodeJsonPointerSegment","components","SchemaValidationError","componentPrefix","componentSchemaRef","componentSchemaName","token","jcsCanonicalize","_canonicalize","object","obj","cv","parts","K","_rotr","x","n","sha256","data","inputLen","bitLen","paddedLen","padded","view","H","W","block","t","w15","w2","s0","s1","a","c","d","e","f","g","h","S1","ch","temp1","temp2","outView","methodSchemaFields","computeInterfaceHash","json","stripNonNormative","normalizeSchemaPositions","digest","methods","method","field","componentSchemas","isNonNormativeKey","isRoot","INTERFACE_TEMPLATES_EXTENSION","attachInterfaceTemplates","mapped","templates","instances","instance","priorTemplate","interfaceTemplatesEqual","normalizeInterfaceTags","tags","getInterfaceTags","validateInterfaceTemplates","metadata","validateTags","_isRecord","id","template","validateInterfaceTemplate","occupied","names","_assertSegment","_validateArguments","target","_validateInstanceMethods","preferRicherInterfaceSchema","existing","candidate","next","_rankingMetadata","prior","_jsonEqual","existingTags","candidateTags","tag","parameters","parameter","_componentSchemas","_methodSchemaFields","_validateTemplateSchema","_schemaChildren","expected","argument","_validateConcreteSchema","expectedComponents","instantiatedMethods","_instantiateMethod","actualComponents","flattenedName","interfaceTemplateMemberName","actual","_methodsEquivalent","member","instantiate","_instantiateSchema","destination","copied","_copyArgumentSchema","_rewriteSchema","sourceKey","rewriteRef","rewriteChild","expectedRest","actualRest","expectedSchema","actualSchema","_schemasEquivalent","expectedErrors","actualErrors","index","left","right","_leftTags","leftStructure","_rightTags","rightStructure","leftComponents","rightComponents","rights","leftRef","rightRef","leftOwn","_toRecord","_withoutRef","rightOwn","resolved","_schemaObjectsEquivalent","leftResolved","rightResolved","leftKeys","l","_isSchema","children","_segmentPattern","label","rightKeys","validateInterfaceErrors","methodName","interfaceTemplateGroup","interfaceDefinitionState","InterfaceDefinition","info","members","frozenSchema","buildSchema","effectiveTags","client","groups","groupedWireNames","group","call","mapping","wireName","handlers","requireObject","where","implementation","flatNames","requireHandler","state","hash","toMethodSchema","convert","position","convertMemberSchema","defineInterface","declarations","entries","isGroup","groupNames","addMember","declaration","_b64UrlAlphabet","bytesToBase64Url","bytes","rem","zTopologyPort","optional","zParticipantDescriptor","number","record","union","boolean","zParticipantDescriptorSource","enum$1","zTopologyNode","array","zTopologyLinkEndpoint","zTopologyTransportEndpoint","int","nonnegative","zTopologyTransportInfo","zTopologyLink","zRouteClaim","zTopologyGraph","topologyInterface","zTrafficTransitEndpoint","zTrafficTransitEvent","unknown","zTrafficOverflowEvent","zTrafficEvent","zTrafficWatchResult","zTrafficWatchParams","zTrafficWatchWithPayloadsParams","trafficInterface","zNodeInfo","nodeInterface","StreamDir","StreamControlType","streamInterface","STREAM_METHOD","TrafficFlowFilter","CorrelatedFlow","transit","TrafficWatchFlowTracker","isTrafficWatchMethod","trafficIgnoreKey","readTrafficIgnoreKey","flow","requestRefsOf","completionRefOf","isTerminal","match","pending","portId","endpoints","completionEndpoint","endpoint","endpointKey","completed","requestRef","DEFAULT_QUEUE_LIMIT","BoundedTrafficSubscription","_options","_send","_onDispose","_queueLimit","resolve","event","withoutPayloads","withCappedPayloads","dropped","_params","_result","rest","maxPayloadBytes","capPayload","maxBytes","encoded","encoder","preview","REQUEST_CORRELATION_RETENTION_MS","MAX_REQUEST_CORRELATIONS","EndpointTrafficInspector","_nodeId","_portId","_emit","_isObserved","direction","message","now","publiclyObserved","base","correlation","map","requestKey","responseMap","streamEndpoint","requestId","timeMs","first","ConnectionInspectionSource","_connection","peer","transport","nodes","links","_listener","listener","inspector","observation","InspectionHost","readPorts","node","port","ports","topology","nextPorts","removed","traffic","registration","connection","close","createPortId","binding","InspectionBinding","registrations","registerOptions","controls","_ctx","stream","observerServiceId","routePortId","mergeNode","previous","routes","fragment","observer","subscriber","send","entry","portIds","remaining","reject","active","finish","invalidate","subscription","dispose","NonCompliantServerError","original","validateBarePrefix","parseMethodName","p","HUBRPC_SIGNATURE_KEY","HUBRPC_UNSIGNED_KEY","HUBRPC_META_KEY","stripLinkRpcWireMeta","wireParams","reserved","userParams","defaultsInterface","zRootPrincipalReq","zRootPrincipalSet","zServiceIdPattern","zServiceListing","directoryInterface","positive","schemasInterface","serviceIdMatchesPattern","serviceId","pattern","serviceIdMatchesScopes","scopes","Channel","sender","_setHandler","_setWireObserver","handler","decorate","RpcError","origin","hasData","KEEPALIVE_PING_INTERVAL_MS","JsonRpcChannel","_transport","_requestsDeferred","jrc","req","promise","resolveResult","rejectResult","pinger","ping","stopPing","reason","err","outboundDir","nextNonce","nonce","control","waiter","w","dir","fields","abort","ctx","response","resp","_NOOP_STREAM","_NEVER_ABORT","isInterfaceTarget","LinkRpcConnection","channel","createInspectionId","ifaceOrTarget","allFailuresAsValues","iface","ServiceHandle","internalInspection","barePrefix","descriptionWasAdded","rootPrincipalSetsWereAdded","rootPrincipalSetsEqual","disposed","sid","item","desc","sets","interfaceId","selected","regOpts","interfaceIdPrefix","serviceIdScopes","cursor","limit","all","start","end","page","set","watcher","serviceMetadataChanged","directlyMatches","directoryWatcherMatchesEntry","metadataMatches","descriptors","host","services","defaultRoute","ctxRest","sendOpts","proxy","wireMethod","callOpts","userListener","onStreamMessage","channelOpts","cause","checked","addCheckedResult","validateWireResult","notify","validateValue","notFound","memberName","parsedParams","encodedError","encodeApplicationError","callStream","signal","kind","sa","sb","j","settled","decodeCheckedError","outcome","envelope","normalizeWireResult","_serviceId","createMergeProxy","baseObj","extObj","_target","prop","_receiver","success","baseKeys","extKeys","extKeysSet","zB64","empty","z","exception","renderEvent","disposeReport","approval","approvalKey","visualDescriptions","sessionInfo","daemonSessionsSchema","sessions","sessionOperationResult","screenshot","screenshotTakeResultSchema","screenshotTakeResult","daemonEventSchema","daemonConnectionInitializationSchema","daemonInitializationInterface","fixtureListArgsSchema","daemonRpcInterface","createDaemonMethods","rpc","initializeDaemonMethods","clientName","schemas","RPC_PATH","createBrowserDaemonClient","url","socket","rejectClosed","closed","_","BrowserWebSocketTransport","_socket","_onClose"],"mappings":";;;;;;AAgBA,MAAMA,KAA4B,oBAAI,IAAI;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAA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