@hediet/linkrpc 0.0.2 → 0.0.3

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.
Files changed (33) hide show
  1. package/README.md +141 -3
  2. package/dist/chunks/{hub.interfaces-Bf4VfWNX.js → hub.interfaces-BWqqhgtT.js} +2 -2
  3. package/dist/chunks/{hub.interfaces-Bf4VfWNX.js.map → hub.interfaces-BWqqhgtT.js.map} +1 -1
  4. package/dist/chunks/{hubAccess-C06qAKao.d.ts → hubAccess-DKl7hDrh.d.ts} +2 -2
  5. package/dist/chunks/{hubAccess-C06qAKao.d.ts.map → hubAccess-DKl7hDrh.d.ts.map} +1 -1
  6. package/dist/chunks/{hubFacade-DtQpGpUy.d.ts → hubFacade-CLgLIvBa.d.ts} +2 -2
  7. package/dist/chunks/{hubFacade-DtQpGpUy.d.ts.map → hubFacade-CLgLIvBa.d.ts.map} +1 -1
  8. package/dist/chunks/{hubFacade-BIB9CoAv.js → hubFacade-rlsBq0ZU.js} +2 -2
  9. package/dist/chunks/{hubFacade-BIB9CoAv.js.map → hubFacade-rlsBq0ZU.js.map} +1 -1
  10. package/dist/chunks/{boundedTrafficSubscription-XZ1KwXZC.js → inspectionHost-BA08eF6h.js} +766 -4
  11. package/dist/chunks/inspectionHost-BA08eF6h.js.map +1 -0
  12. package/dist/chunks/{linkRpcConnection-BadD37ok.d.ts → linkRpcConnection-C_Gs4nZ9.d.ts} +2061 -1682
  13. package/dist/chunks/linkRpcConnection-C_Gs4nZ9.d.ts.map +1 -0
  14. package/dist/chunks/{src-CAhXne71.js → src-BaCs8mWd.js} +2512 -2657
  15. package/dist/chunks/src-BaCs8mWd.js.map +1 -0
  16. package/dist/hub/client/index.d.ts +3 -3
  17. package/dist/hub/client/index.js +3 -3
  18. package/dist/hub/common/index.d.ts +2 -325
  19. package/dist/hub/common/index.d.ts.map +1 -1
  20. package/dist/hub/common/index.js +2 -2
  21. package/dist/index.d.ts +2 -2
  22. package/dist/index.js +3 -3
  23. package/dist/inspection/index.d.ts +87 -2
  24. package/dist/inspection/index.d.ts.map +1 -1
  25. package/dist/inspection/index.js +2 -2
  26. package/dist/node.d.ts +3 -3
  27. package/dist/node.js +4 -4
  28. package/dist/web.d.ts +2 -2
  29. package/dist/web.js +3 -3
  30. package/package.json +7 -2
  31. package/dist/chunks/boundedTrafficSubscription-XZ1KwXZC.js.map +0 -1
  32. package/dist/chunks/linkRpcConnection-BadD37ok.d.ts.map +0 -1
  33. package/dist/chunks/src-CAhXne71.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inspectionHost-BA08eF6h.js","names":["zVoid","union","zAny","zVoid","zEnum","zEnum"],"sources":["../../src/schema/normalize.ts","../../src/schema/memberTypes.ts","../../src/protocol/jcs.ts","../../src/crypto/sha256.ts","../../src/schema/hash.ts","../../src/schema/assertSchemaReferences.ts","../../src/schema/schemaToZod.ts","../../src/connection/interfaceDefinition.ts","../../src/protocol/jsonRpc.ts","../../src/crypto/cryptoProvider.ts","../../src/inspection/inspection.interfaces.ts","../../src/inspection/node.interfaces.ts","../../src/connection/streaming.ts","../../src/inspection/trafficFlowFilter.ts","../../src/inspection/boundedTrafficSubscription.ts","../../src/inspection/endpointTrafficInspector.ts","../../src/inspection/connectionInspectionSource.ts","../../src/inspection/inspectionHost.ts"],"sourcesContent":["import type { LinkRpcJsonSchema, DiscriminatorSchema } from \"./linkRpcJsonSchema\";\n\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 = new Set([\n \"type\", \"format\",\n \"properties\", \"required\", \"additionalProperties\",\n \"items\", \"prefixItems\",\n \"const\", \"enum\",\n \"anyOf\", \"oneOf\", \"discriminator\",\n \"$ref\",\n \"title\", \"description\",\n]);\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 *\n * The output is canonical: structurally equal inputs produce structurally\n * equal outputs, which is what `computeInterfaceHash` relies on.\n */\nexport function normalizeJsonSchema(raw: unknown): LinkRpcJsonSchema {\n if (raw === true || raw === false) return raw;\n if (raw === null || typeof raw !== \"object\") {\n throw new Error(`normalizeJsonSchema: expected object, got ${typeof raw}`);\n }\n if (Array.isArray(raw)) {\n throw new Error(\"normalizeJsonSchema: expected object, got array\");\n }\n\n const r = raw as Record<string, unknown>;\n\n // {\"not\": {}} => false (bottom). Handle before generic descent.\n if (\"not\" in r && isEmptyObject(r[\"not\"])) return false;\n\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(r)) {\n if (!KEPT_KEYS.has(k)) continue;\n const normalized = normalizeChild(k, v);\n if (normalized === undefined) continue;\n out[k] = normalized;\n }\n\n // Object: linkrpc requires `additionalProperties` to be set. Default to\n // closed, matching what zod typically emits for `z.object`.\n if (out[\"type\"] === \"object\" && !(\"additionalProperties\" in out)) {\n out[\"additionalProperties\"] = false;\n }\n\n // `oneOf`: if no explicit `discriminator` survived, try to synthesize\n // one from the branches. Zod's `z.discriminatedUnion` lowers via\n // `z.toJSONSchema` to `oneOf` without a `discriminator` keyword, so\n // without this auto-detection the tag information is invisible to\n // consumers (codegen, consent UIs).\n if (Array.isArray(out[\"oneOf\"]) && !(\"discriminator\" in out)) {\n const detected = _detectDiscriminator(out[\"oneOf\"] as LinkRpcJsonSchema[]);\n if (detected !== undefined) out[\"discriminator\"] = detected;\n }\n\n // Drop a `discriminator` that has no `oneOf` to attach to — it would be\n // meaningless and would just bloat the hash.\n if (\"discriminator\" in out && !Array.isArray(out[\"oneOf\"])) {\n delete out[\"discriminator\"];\n }\n\n // Collapse empty into `true` (top).\n if (Object.keys(out).length === 0) return true;\n\n return out as unknown as LinkRpcJsonSchema;\n}\n\nfunction normalizeChild(key: string, v: unknown): unknown {\n switch (key) {\n case \"properties\": {\n if (!isPlainObject(v)) return {};\n const out: Record<string, LinkRpcJsonSchema> = {};\n for (const [pk, pv] of Object.entries(v)) {\n out[pk] = normalizeJsonSchema(pv);\n }\n return out;\n }\n case \"items\":\n case \"additionalProperties\": {\n if (v === false) return false;\n return normalizeJsonSchema(v);\n }\n case \"prefixItems\":\n case \"anyOf\":\n case \"oneOf\": {\n if (!Array.isArray(v)) return [];\n return v.map((s) => normalizeJsonSchema(s));\n }\n case \"discriminator\": {\n // Only `propertyName` is part of the subset. OpenAPI's `mapping`\n // (and anything else) is dropped — we have no use for it and it\n // would complicate hashing.\n if (!isPlainObject(v)) return undefined;\n const name = (v as Record<string, unknown>)[\"propertyName\"];\n if (typeof name !== \"string\" || name.length === 0) return undefined;\n return { propertyName: name };\n }\n case \"enum\": {\n if (!Array.isArray(v)) return [];\n return v.slice();\n }\n case \"required\": {\n if (!Array.isArray(v)) return [];\n return v.slice().sort();\n }\n default:\n return v;\n }\n}\n\nfunction isEmptyObject(v: unknown): boolean {\n return isPlainObject(v) && Object.keys(v).length === 0;\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === \"object\" && !Array.isArray(v);\n}\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: LinkRpcJsonSchema[]): DiscriminatorSchema | undefined {\n if (branches.length < 2) return undefined;\n // Each branch must be an object schema with `properties`.\n const branchPropsList: Record<string, LinkRpcJsonSchema>[] = [];\n for (const b of branches) {\n if (b === true || b === false) return undefined;\n if ((b as { type?: string }).type !== \"object\") return undefined;\n const props = (b as { properties?: Record<string, LinkRpcJsonSchema> }).properties;\n if (!props) return undefined;\n branchPropsList.push(props);\n }\n // Property names present (with a `const`-valued schema) on every branch.\n const firstConstProps = _constPropNames(branchPropsList[0]);\n let candidates = firstConstProps;\n for (let i = 1; i < branchPropsList.length; i++) {\n candidates = candidates.filter((n) => _constPropNames(branchPropsList[i]).includes(n));\n if (candidates.length === 0) return undefined;\n }\n // Of the surviving candidates, keep those whose const values are\n // pairwise distinct across all branches (a real discriminator).\n for (const name of candidates) {\n const seen = new Set<string>();\n let allDistinct = true;\n for (const props of branchPropsList) {\n const s = props[name] as { const?: unknown };\n const key = JSON.stringify(s.const);\n if (seen.has(key)) { allDistinct = false; break; }\n seen.add(key);\n }\n if (allDistinct) return { propertyName: name };\n }\n return undefined;\n}\n\nfunction _constPropNames(props: Record<string, LinkRpcJsonSchema>): string[] {\n const out: string[] = [];\n for (const [k, v] of Object.entries(props)) {\n if (v === true || v === false) continue;\n if (\"const\" in (v as object)) out.push(k);\n }\n return out;\n}\n","import { void as zVoid } from 'zod/mini';\nimport { toJSONSchema, type $ZodType } from 'zod/v4/core';\nimport { normalizeJsonSchema } from './normalize';\nimport type { MemberAnnotations } from './linkRpcInterfaceSchema';\nimport type { LinkRpcJsonSchema } from './linkRpcJsonSchema';\n\n/**\n * The schema type linkrpc accepts everywhere: the zod *core* base shared by\n * both classic `zod` and `zod/mini`. Typing against it (instead of classic\n * `z.ZodType`) lets callers author interfaces with either flavour — classic\n * for ergonomics, mini for minimal bundle size — while linkrpc's own internal\n * interfaces use mini. `O` is the validated output type.\n */\nexport type Schema<O = unknown> = $ZodType<O>;\n\n/**\n * Marker base for a typed method member. Carries enough metadata to:\n * - validate / parse params at runtime (via the zod schemas),\n * - emit a JSON schema for reflection,\n * - propagate TS types up to the interface definition.\n */\nexport type MemberType = RequestType<any, any, any, any, any, any, any> | NotificationType<any>;\n\nconst applicationErrorBrand: unique symbol = Symbol('linkrpc.applicationError');\n\nexport type ApplicationErrorValue<\n TCode extends number = number,\n TMessage extends string = string,\n TData = never,\n> = {\n readonly kind: 'application';\n readonly code: TCode;\n readonly message: TMessage;\n} & ([TData] extends [never] ? { readonly data?: never; } : { readonly data: TData; });\n\nexport type CreatedApplicationErrorValue<\n TCode extends number = number,\n TMessage extends string = string,\n TData = never,\n> = ApplicationErrorValue<TCode, TMessage, TData> & {\n readonly [applicationErrorBrand]: true;\n};\n\nexport interface ApplicationErrorDescriptor<\n TCode extends number = number,\n TMessage extends string = string,\n TData = never,\n> {\n readonly code: TCode;\n readonly message: TMessage;\n readonly dataSchema?: Schema<TData>;\n readonly create: [TData] extends [never]\n ? () => CreatedApplicationErrorValue<TCode, TMessage, TData>\n : (data: TData) => CreatedApplicationErrorValue<TCode, TMessage, TData>;\n}\n\nexport interface ApplicationErrorDescriptorBase {\n readonly code: number;\n readonly message: string;\n readonly dataSchema?: Schema<any>;\n readonly create: (...args: any[]) => {\n readonly kind: 'application';\n readonly code: number;\n readonly message: string;\n readonly data?: unknown;\n readonly [applicationErrorBrand]: true;\n };\n}\n\nexport type ApplicationErrorOf<T> =\n T extends ApplicationErrorDescriptor<infer C, infer M, infer D>\n ? CreatedApplicationErrorValue<C, M, D>\n : never;\n\n// Legacy schemas can infer `any`; they must neither declare checked errors nor erase result types.\nexport type PublicApplicationErrorOf<T> =\n 0 extends (1 & T) ? never :\n T extends CreatedApplicationErrorValue<infer C, infer M, infer D>\n ? ApplicationErrorValue<C, M, D>\n : never;\n\nexport type DeclaredApplicationErrorOf<T> = 0 extends (1 & T)\n ? never\n : Extract<T, ReturnType<ApplicationErrorDescriptorBase['create']>>;\n\nexport type ApplicationErrorsOf<T extends readonly ApplicationErrorDescriptorBase[]> =\n ApplicationErrorOf<T[number]>;\n\n/** Declare one checked application error for use with {@link RequestType.withErrors}. */\nexport function applicationError<const TCode extends number, const TMessage extends string>(\n code: TCode,\n message: TMessage,\n): ApplicationErrorDescriptor<TCode, TMessage, never>;\nexport function applicationError<const TCode extends number, const TMessage extends string, TData>(\n code: TCode,\n message: TMessage,\n data: Schema<TData>,\n): ApplicationErrorDescriptor<TCode, TMessage, TData>;\nexport function applicationError(\n code: number,\n message: string,\n dataSchema?: Schema<any>,\n): ApplicationErrorDescriptorBase {\n assertApplicationErrorCode(code);\n if (typeof message !== 'string') throw new Error('Application error message must be a string.');\n const create = dataSchema === undefined\n ? function (this: void): CreatedApplicationErrorValue<number, string, never> {\n if (arguments.length !== 0) {\n throw new Error(`Application error ${code} does not accept data.`);\n }\n return Object.freeze({\n kind: 'application' as const,\n code,\n message,\n [applicationErrorBrand]: true as const,\n });\n }\n : function (this: void, data: unknown): CreatedApplicationErrorValue<number, string, unknown> {\n if (arguments.length !== 1) {\n throw new Error(`Application error ${code} requires exactly one data value.`);\n }\n return Object.freeze({\n kind: 'application' as const,\n code,\n message,\n [applicationErrorBrand]: true as const,\n data,\n });\n };\n return Object.freeze({\n code,\n message,\n ...(dataSchema === undefined ? {} : { dataSchema }),\n create,\n }) as ApplicationErrorDescriptorBase;\n}\n\n/** Runtime nominal check for values produced by an application-error descriptor. */\nexport function isApplicationErrorValue(\n value: unknown,\n): value is ReturnType<ApplicationErrorDescriptorBase['create']> {\n return typeof value === 'object' && value !== null\n && (value as { [applicationErrorBrand]?: unknown; })[applicationErrorBrand] === true;\n}\n\nfunction assertApplicationErrorCode(code: number): void {\n if (!Number.isInteger(code) || code < -2147483648 || code > 2147483647) {\n throw new Error(`Application error code ${code} must be a signed 32-bit integer.`);\n }\n if ((code >= -32768 && code <= -32000) || code === -32800) {\n throw new Error(`Application error code ${code} is reserved by JSON-RPC or LinkRPC.`);\n }\n}\n\n/**\n * Optional documentation for a method member.\n *\n * - `description` is the **normative** contract of the method (included in the\n * interface hash — changing it changes `schemaHash`).\n * - `comment` is non-normative implementation notes (stripped from the hash).\n * - `annotations` are normative behavioral claims (e.g. `readOnly`,\n * `idempotent`); included in the hash.\n */\nexport interface MemberDocs {\n description?: string;\n comment?: string;\n annotations?: MemberAnnotations;\n}\n\nexport class RequestType<\n TParams = unknown,\n TResult = void,\n TError = void,\n TClientStream = never,\n TServerStream = never,\n TErrors extends readonly ApplicationErrorDescriptorBase[] = readonly ApplicationErrorDescriptorBase[],\n TLegacyError = TError,\n> {\n public readonly kind = 'request' as const;\n\n constructor(\n public readonly paramsSchema: Schema<TParams>,\n public readonly resultSchema: Schema<TResult>,\n public readonly errorSchema: Schema<TLegacyError>,\n public readonly docs: MemberDocs = {},\n /**\n * Schema for stream messages the **client** may emit on an\n * in-flight call (e.g. cancellation, input). `undefined` means\n * the client may not stream on this method.\n */\n public readonly clientStreamSchema?: Schema<TClientStream>,\n /**\n * Schema for stream messages the **server** may emit while\n * handling an in-flight call (e.g. progress, partial results).\n * `undefined` means the server may not stream on this method.\n */\n public readonly serverStreamSchema?: Schema<TServerStream>,\n /** Checked application errors explicitly declared with `.withErrors()`. */\n public readonly applicationErrors: TErrors = [] as unknown as TErrors,\n ) {\n const seen = new Set<number>();\n for (const error of applicationErrors) {\n assertApplicationErrorCode(error.code);\n if (typeof error.message !== 'string') {\n throw new Error('Application error message must be a string.');\n }\n if (seen.has(error.code)) {\n throw new Error(`Duplicate application error code ${error.code}.`);\n }\n seen.add(error.code);\n }\n this.applicationErrors = Object.freeze([...applicationErrors]) as unknown as TErrors;\n this.errors = this.applicationErrors;\n }\n\n /** Declared checked errors, retained as a tuple for generated-contract consumers. */\n public readonly errors: TErrors;\n\n /** Phantom field — typed-only, do not access at runtime. */\n declare readonly _params: TParams;\n declare readonly _result: TResult;\n declare readonly _error: TError;\n declare readonly _clientStream: TClientStream;\n declare readonly _serverStream: TServerStream;\n\n /**\n * Return a copy of this request type with stream payload schemas\n * attached. Pass `undefined` for either direction to leave it\n * closed.\n * `NoInfer` keeps a contextual MemberMap's `any` stream slots from\n * widening undeclared directions; only the supplied schemas infer payloads.\n */\n public withStream<TClient = TClientStream, TServer = TServerStream>(\n opts: {\n client?: Schema<TClient>;\n server?: Schema<TServer>;\n },\n ): RequestType<TParams, TResult, TError, NoInfer<TClient>, NoInfer<TServer>, TErrors, TLegacyError> {\n return new RequestType<TParams, TResult, TError, TClient, TServer, TErrors, TLegacyError>(\n this.paramsSchema,\n this.resultSchema,\n this.errorSchema,\n this.docs,\n opts.client,\n opts.server,\n this.applicationErrors,\n );\n }\n\n /**\n * Return a copy with an explicit, typed set of checked application errors.\n * The legacy third `requestType` schema remains accepted for compatibility,\n * but does not opt a method into checked errors.\n */\n public withErrors<const TErrors extends readonly ApplicationErrorDescriptorBase[]>(\n errors: TErrors,\n ): RequestType<TParams, TResult, ApplicationErrorsOf<TErrors>, TClientStream, TServerStream, TErrors, TLegacyError> {\n return new RequestType<TParams, TResult, ApplicationErrorsOf<TErrors>, TClientStream, TServerStream, TErrors, TLegacyError>(\n this.paramsSchema,\n this.resultSchema,\n this.errorSchema,\n this.docs,\n this.clientStreamSchema,\n this.serverStreamSchema,\n errors,\n );\n }\n}\n\nexport class NotificationType<TParams = unknown> {\n public readonly kind = 'notification' as const;\n\n constructor(\n public readonly paramsSchema: Schema<TParams>,\n public readonly docs: MemberDocs = {},\n ) { }\n\n declare readonly _params: TParams;\n}\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 */\nexport function requestType<\n TParams,\n TResult = void,\n TError = void,\n>(\n params: Schema<TParams>,\n result?: Schema<TResult>,\n docsOrError?: MemberDocs | Schema<TError>,\n maybeDocs?: MemberDocs,\n): RequestType<TParams, TResult, TError> {\n // A zod schema (params/result/error) vs. a `MemberDocs` object: every\n // Zod 4 schema carries the `_zod` marker (the library-author–blessed way\n // to detect one — see zod's \"For library authors\" guide), which plain\n // docs objects never have. Works for both classic and mini schemas.\n const isErrorSchema = (v: unknown): v is Schema<TError> =>\n typeof v === 'object' && v !== null && '_zod' in v;\n\n const error = isErrorSchema(docsOrError) ? docsOrError : undefined;\n const docs = (!isErrorSchema(docsOrError) ? docsOrError : maybeDocs) ?? {};\n\n return new RequestType(\n params,\n result ?? (zVoid() as unknown as Schema<TResult>),\n error ?? (zVoid() as unknown as Schema<TError>),\n docs,\n );\n}\n\n/**\n * Define a notification method.\n *\n * @example\n * foo: notificationType(z.object({ message: z.string() }))\n */\nexport function notificationType<TParams>(\n params: Schema<TParams>,\n docs: MemberDocs = {},\n): NotificationType<TParams> {\n return new NotificationType(params, docs);\n}\n\nexport interface ZodToSvcJsonSchemaOptions {\n readonly methodName: string;\n readonly schemaPosition: string;\n readonly components: Record<string, LinkRpcJsonSchema>;\n}\n\n/** Convert a zod schema to our restricted SvcJsonSchema subset. */\nexport function zodToSvcJsonSchema(\n schema: Schema,\n options?: ZodToSvcJsonSchemaOptions,\n): LinkRpcJsonSchema {\n // `z.void()` / `z.undefined()` have no JSON-Schema representation —\n // `toJSONSchema` throws on them. Treat them as the trivially-true\n // schema (matches anything); JSON-RPC drops `undefined` from the wire\n // anyway, so this is the right structural answer for \"no value\".\n const type = (schema as { _zod?: { def?: { type?: string; }; }; })._zod?.def?.type;\n if (type === 'void' || type === 'undefined') return true;\n return normalizeZodJsonSchema(toJSONSchema(schema), options);\n}\n\nfunction normalizeZodJsonSchema(\n raw: unknown,\n options: ZodToSvcJsonSchemaOptions | undefined,\n): LinkRpcJsonSchema {\n if (!isRecord(raw)) return normalizeJsonSchema(raw);\n\n const definitions = isRecord(raw.$defs) ? raw.$defs : {};\n const localRefs = collectLocalRefs(raw);\n if (Object.keys(definitions).length === 0 && localRefs.size === 0) {\n return normalizeJsonSchema(raw);\n }\n if (options === undefined) {\n throw new Error(\n 'zodToSvcJsonSchema: local references require a component destination',\n );\n }\n\n const componentNamePrefix =\n `method=${encodeComponentNamePart(options.methodName)}` +\n `&schema=${encodeComponentNamePart(options.schemaPosition)}`;\n const definitionComponents = new Map<string, string>();\n for (const definitionName of Object.keys(definitions)) {\n definitionComponents.set(\n definitionName,\n `${componentNamePrefix}&def=${encodeComponentNamePart(definitionName)}`,\n );\n }\n const rootComponent = localRefs.has('#')\n ? `${componentNamePrefix}&root`\n : undefined;\n const rewrite = (value: unknown): unknown =>\n rewriteLocalRefs(value, definitionComponents, rootComponent);\n\n for (const [definitionName, definition] of Object.entries(definitions)) {\n const componentName = definitionComponents.get(definitionName);\n if (componentName === undefined) {\n throw new Error(`zodToSvcJsonSchema: missing component for \"${definitionName}\"`);\n }\n addComponent(\n options.components,\n componentName,\n normalizeJsonSchema(rewrite(definition)),\n );\n }\n\n const root = rewrite(raw);\n if (rootComponent !== undefined) {\n addComponent(options.components, rootComponent, normalizeJsonSchema(root));\n return { $ref: componentRef(rootComponent) };\n }\n return normalizeJsonSchema(root);\n}\n\nfunction collectLocalRefs(value: unknown, refs = new Set<string>()): ReadonlySet<string> {\n if (Array.isArray(value)) {\n for (const child of value) collectLocalRefs(child, refs);\n return refs;\n }\n if (!isRecord(value)) return refs;\n if (typeof value.$ref === 'string' && value.$ref.startsWith('#')) {\n refs.add(value.$ref);\n }\n for (const child of Object.values(value)) collectLocalRefs(child, refs);\n return refs;\n}\n\nfunction rewriteLocalRefs(\n value: unknown,\n definitionComponents: ReadonlyMap<string, string>,\n rootComponent: string | undefined,\n): unknown {\n if (Array.isArray(value)) {\n return value.map((child) =>\n rewriteLocalRefs(child, definitionComponents, rootComponent));\n }\n if (!isRecord(value)) return value;\n\n const result: Record<string, unknown> = {};\n for (const [key, child] of Object.entries(value)) {\n if (key === '$defs') continue;\n if (key === '$ref' && typeof child === 'string') {\n result[key] = rewriteLocalRef(child, definitionComponents, rootComponent);\n } else {\n result[key] = rewriteLocalRefs(child, definitionComponents, rootComponent);\n }\n }\n return result;\n}\n\nfunction rewriteLocalRef(\n ref: string,\n definitionComponents: ReadonlyMap<string, string>,\n rootComponent: string | undefined,\n): string {\n if (ref === '#') {\n if (rootComponent === undefined) {\n throw new Error('zodToSvcJsonSchema: root reference has no component destination');\n }\n return componentRef(rootComponent);\n }\n\n const definitionPrefix = '#/$defs/';\n if (ref.startsWith(definitionPrefix)) {\n const encodedName = ref.slice(definitionPrefix.length);\n const definitionName = [...definitionComponents.keys()]\n .find((name) => encodeJsonPointerSegment(name) === encodedName);\n const componentName = definitionName === undefined\n ? undefined\n : definitionComponents.get(definitionName);\n if (componentName === undefined) {\n throw new Error(`zodToSvcJsonSchema: dangling local reference \"${ref}\"`);\n }\n return componentRef(componentName);\n }\n\n if (ref.startsWith('#') && !ref.startsWith('#/components/schemas/')) {\n throw new Error(`zodToSvcJsonSchema: unsupported local reference \"${ref}\"`);\n }\n return ref;\n}\n\nfunction addComponent(\n components: Record<string, LinkRpcJsonSchema>,\n name: string,\n schema: LinkRpcJsonSchema,\n): void {\n if (Object.hasOwn(components, name)) {\n throw new Error(`zodToSvcJsonSchema: duplicate component name \"${name}\"`);\n }\n components[name] = schema;\n}\n\nfunction componentRef(name: string): string {\n return `#/components/schemas/${encodeJsonPointerSegment(name)}`;\n}\n\nfunction encodeJsonPointerSegment(value: string): string {\n return value.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n\nfunction encodeComponentNamePart(value: string): string {\n return encodeURIComponent(value).replace(/~/g, '%7E');\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\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\n\n/** RFC 8785 canonical JSON string for `value`. */\nexport function jcsCanonicalize(value: unknown): string {\n const out = _canonicalize(value);\n if (out === undefined) {\n throw new Error(\"jcsCanonicalize: value is not JSON-representable\");\n }\n return out;\n}\n\nconst _encoder = new TextEncoder();\n\n/** UTF-8 bytes of the RFC 8785 canonical JSON for `value`. The thing actually signed / hashed. */\nexport function jcsCanonicalizeBytes(value: unknown): Uint8Array {\n return _encoder.encode(jcsCanonicalize(value));\n}\n\nfunction _canonicalize(object: unknown, seen: Set<object> = new Set()): string | undefined {\n if (typeof object === \"number\" && Number.isNaN(object)) {\n throw new Error(\"NaN is not allowed\");\n }\n if (typeof object === \"number\" && !Number.isFinite(object)) {\n throw new Error(\"Infinity is not allowed\");\n }\n if (object === null || typeof object !== \"object\") {\n return JSON.stringify(object);\n }\n\n const obj = object as { toJSON?: () => unknown } & Record<string, unknown>;\n\n if (typeof obj.toJSON === \"function\") {\n if (seen.has(obj)) throw new Error(\"Circular reference detected\");\n seen.add(obj);\n const result = _canonicalize(obj.toJSON(), seen);\n seen.delete(obj);\n return result;\n }\n\n if (seen.has(obj)) throw new Error(\"Circular reference detected\");\n seen.add(obj);\n\n let result: string;\n if (Array.isArray(obj)) {\n const values = obj.map((cv) => {\n const value = cv === undefined || typeof cv === \"symbol\" ? null : cv;\n return _canonicalize(value, seen);\n });\n result = `[${values.join(\",\")}]`;\n } else {\n const parts: string[] = [];\n for (const key of Object.keys(obj).sort()) {\n const v = obj[key];\n if (v === undefined || typeof v === \"symbol\") continue;\n parts.push(`${JSON.stringify(key)}:${_canonicalize(v, seen)}`);\n }\n result = `{${parts.join(\",\")}}`;\n }\n\n seen.delete(obj);\n return result;\n}\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 */\n\nconst K = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]);\n\nfunction _rotr(x: number, n: number): number {\n return (x >>> n) | (x << (32 - n));\n}\n\nexport function sha256(data: Uint8Array): Uint8Array {\n const inputLen = data.length;\n const bitLen = inputLen * 8;\n // Round up to next 64-byte block leaving room for 0x80 marker + 8-byte length.\n const paddedLen = (inputLen + 9 + 63) & ~63;\n const padded = new Uint8Array(paddedLen);\n padded.set(data);\n padded[inputLen] = 0x80;\n\n const view = new DataView(padded.buffer);\n // Big-endian 64-bit bit length. Bottom 32 bits hold values < 2^32 bits = 2^29 bytes (~512 MiB).\n view.setUint32(paddedLen - 8, Math.floor(bitLen / 0x1_0000_0000), false);\n view.setUint32(paddedLen - 4, bitLen >>> 0, false);\n\n const H = new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,\n 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n ]);\n const W = new Uint32Array(64);\n\n for (let block = 0; block < paddedLen; block += 64) {\n for (let t = 0; t < 16; t++) {\n W[t] = view.getUint32(block + t * 4, false);\n }\n for (let t = 16; t < 64; t++) {\n const w15 = W[t - 15];\n const w2 = W[t - 2];\n const s0 = _rotr(w15, 7) ^ _rotr(w15, 18) ^ (w15 >>> 3);\n const s1 = _rotr(w2, 17) ^ _rotr(w2, 19) ^ (w2 >>> 10);\n W[t] = (W[t - 16] + s0 + W[t - 7] + s1) >>> 0;\n }\n\n let a = H[0], b = H[1], c = H[2], d = H[3];\n let e = H[4], f = H[5], g = H[6], h = H[7];\n for (let t = 0; t < 64; t++) {\n const S1 = _rotr(e, 6) ^ _rotr(e, 11) ^ _rotr(e, 25);\n const ch = (e & f) ^ (~e & g);\n const temp1 = (h + S1 + ch + K[t] + W[t]) >>> 0;\n const S0 = _rotr(a, 2) ^ _rotr(a, 13) ^ _rotr(a, 22);\n const mj = (a & b) ^ (a & c) ^ (b & c);\n const temp2 = (S0 + mj) >>> 0;\n h = g;\n g = f;\n f = e;\n e = (d + temp1) >>> 0;\n d = c;\n c = b;\n b = a;\n a = (temp1 + temp2) >>> 0;\n }\n H[0] = (H[0] + a) >>> 0;\n H[1] = (H[1] + b) >>> 0;\n H[2] = (H[2] + c) >>> 0;\n H[3] = (H[3] + d) >>> 0;\n H[4] = (H[4] + e) >>> 0;\n H[5] = (H[5] + f) >>> 0;\n H[6] = (H[6] + g) >>> 0;\n H[7] = (H[7] + h) >>> 0;\n }\n\n const out = new Uint8Array(32);\n const outView = new DataView(out.buffer);\n for (let i = 0; i < 8; i++) outView.setUint32(i * 4, H[i], false);\n return out;\n}\n","import { jcsCanonicalize } from \"../protocol/jcs\";\nimport { sha256 } from \"../crypto/sha256\";\nimport type { LinkRpcInterfaceSchema, MethodSchema } from \"./linkRpcInterfaceSchema\";\nimport { normalizeJsonSchema } from \"./normalize\";\n\nconst methodSchemaFields = [\n \"params\",\n \"result\",\n \"clientStream\",\n \"serverStream\",\n] as const;\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 */\nexport function computeInterfaceHash(schema: LinkRpcInterfaceSchema): string {\n const normalized = normalizeSchemaPositions(schema);\n const json = jcsCanonicalize(stripNonNormative(normalized, /* isRoot */ true));\n const digest = sha256(new TextEncoder().encode(json));\n const result = Array.from(digest.subarray(0, 8), (b) =>\n b.toString(16).padStart(2, \"0\")\n ).join(\"\");\n return result;\n}\n\nfunction normalizeSchemaPositions(schema: LinkRpcInterfaceSchema): LinkRpcInterfaceSchema {\n const methods: LinkRpcInterfaceSchema[\"methods\"] = Object.fromEntries(\n Object.entries(schema.methods).map(([name, method]) => {\n const normalized: MethodSchema = { ...method };\n for (const field of methodSchemaFields) {\n const value = normalized[field];\n if (value !== undefined) {\n normalized[field] = normalizeJsonSchema(value);\n }\n }\n return [name, normalized];\n }),\n );\n const componentSchemas = schema.components?.schemas;\n const components = componentSchemas === undefined\n ? schema.components\n : {\n ...schema.components,\n schemas: Object.fromEntries(\n Object.entries(componentSchemas).map(([name, value]) => [\n name,\n normalizeJsonSchema(value),\n ]),\n ),\n };\n return {\n ...schema,\n methods,\n ...(components === undefined ? {} : { components }),\n };\n}\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 */\nexport const EXTENSION_PREFIX = \"x-\";\n\n/** True for a key that must not contribute to the interface hash. */\nfunction isNonNormativeKey(key: string, isRoot: boolean): boolean {\n return (\n key === \"comment\" ||\n key.startsWith(EXTENSION_PREFIX) ||\n (isRoot && key === \"hash\")\n );\n}\n\nfunction stripNonNormative(value: unknown, isRoot = false): unknown {\n if (value === null || typeof value !== \"object\") return value;\n if (Array.isArray(value)) return value.map((v) => stripNonNormative(v));\n\n const out: Record<string, unknown> = {};\n for (const k of Object.keys(value as Record<string, unknown>)) {\n if (isNonNormativeKey(k, isRoot)) continue;\n const v = (value as Record<string, unknown>)[k];\n if (v === undefined) continue;\n out[k] = stripNonNormative(v);\n }\n return out;\n}\n","import type { LinkRpcJsonSchema } from './linkRpcJsonSchema';\n\ntype SchemaNode = Exclude<LinkRpcJsonSchema, boolean>;\nconst componentPrefix = '#/components/schemas/';\n\nexport function componentSchemaRef(name: string): string {\n return componentPrefix + name.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n\nexport function componentSchemaName(ref: string): string {\n if (!ref.startsWith(componentPrefix)) {\n throw new Error(`Invalid component reference: ${ref}`);\n }\n const token = ref.slice(componentPrefix.length);\n if (token.includes('/') || /~(?:[^01]|$)/.test(token)) {\n throw new Error(`Invalid component reference token: ${ref}`);\n }\n return token.replace(/~1/g, '/').replace(/~0/g, '~');\n}\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 */\nexport function assertSchemaReferences(\n roots: Iterable<LinkRpcJsonSchema>,\n components: Record<string, LinkRpcJsonSchema> = {},\n): void {\n const nodes = new Set<SchemaNode>();\n const pending = [...roots, ...Object.values(components)];\n const unguarded = new Map<SchemaNode, LinkRpcJsonSchema[]>();\n while (pending.length > 0) {\n const node = pending.pop()!;\n if (typeof node === 'boolean' || nodes.has(node)) continue;\n nodes.add(node);\n const edges: LinkRpcJsonSchema[] = [];\n if ('$ref' in node) {\n const name = componentSchemaName(node.$ref);\n if (!Object.hasOwn(components, name)) {\n throw new Error(`Unresolved component reference: ${node.$ref}`);\n }\n edges.push(components[name]);\n }\n if ('anyOf' in node) edges.push(...node.anyOf);\n if ('oneOf' in node) edges.push(...node.oneOf);\n unguarded.set(node, edges);\n pending.push(...edges);\n if ('type' in node && node.type === 'object') {\n pending.push(...Object.values(node.properties ?? {}), node.additionalProperties);\n }\n if ('type' in node && node.type === 'array') {\n if ('prefixItems' in node) pending.push(...node.prefixItems);\n if (node.items !== undefined) pending.push(node.items);\n }\n }\n\n const visiting = new Set<SchemaNode>();\n const checked = new Set<SchemaNode>();\n const visit = (node: LinkRpcJsonSchema): void => {\n if (typeof node === 'boolean' || checked.has(node)) return;\n if (visiting.has(node)) {\n throw new Error('Unguarded recursive schema: cycle does not descend into a child value');\n }\n visiting.add(node);\n for (const child of unguarded.get(node) ?? []) visit(child);\n visiting.delete(node);\n checked.add(node);\n };\n for (const node of nodes) visit(node);\n}\n","import { z } from \"zod\";\nimport {\n assertSchemaReferences,\n componentSchemaName,\n} from \"./assertSchemaReferences\";\nimport type { LinkRpcJsonSchema } from \"./linkRpcJsonSchema\";\n\nexport interface SchemaToZodContext {\n readonly toZod: (schema: LinkRpcJsonSchema) => z.ZodType<unknown>;\n}\n\n/**\n * Create a recursive LinkRPC-schema validator materializer. Component\n * references are lazy, so self and mutual recursion remain guarded.\n */\nexport function createSchemaToZod(\n components: Record<string, LinkRpcJsonSchema> = {},\n): SchemaToZodContext {\n assertSchemaReferences([], components);\n const refs = new Map<string, z.ZodType<unknown>>();\n const component = (name: string): z.ZodType<unknown> => {\n const existing = refs.get(name);\n if (existing !== undefined) return existing;\n const source = components[name];\n if (source === undefined) throw new Error(`schemaToZod: dangling component reference \"${name}\"`);\n const lazy: z.ZodType<unknown> = z.lazy(() => compile(source));\n refs.set(name, lazy);\n return lazy;\n };\n\n const compile = (schema: LinkRpcJsonSchema): z.ZodType<unknown> => {\n if (schema === true) return z.unknown();\n if (schema === false) return z.never();\n const raw = schema as unknown as Record<string, unknown>;\n if (Array.isArray(raw.type)) {\n return union(raw.type.map((type) =>\n compile({ ...raw, type } as unknown as LinkRpcJsonSchema)\n ));\n }\n let base: z.ZodType<unknown>;\n if (\"$ref\" in schema) {\n base = component(componentSchemaName(schema.$ref));\n } else if (\"const\" in schema) {\n base = valueSchema(schema.const);\n } else if (\"enum\" in schema) {\n base = union(schema.enum.map(valueSchema));\n } else if (\"anyOf\" in schema) {\n base = union(schema.anyOf.map(compile));\n } else if (\"oneOf\" in schema) {\n // LinkRPC's normative structural semantics treat oneOf as a union;\n // exclusivity is only available through rich JSON Schema export.\n base = union(schema.oneOf.map(compile));\n } else if (isAnnotationOnlySchema(raw)) {\n base = z.unknown();\n } else {\n switch (schema.type) {\n case \"null\":\n base = z.null();\n break;\n case \"boolean\":\n base = z.boolean();\n break;\n case \"string\":\n base = stringSchema(schema.format);\n break;\n case \"integer\":\n base = z.number().int();\n break;\n case \"number\":\n base = z.number();\n break;\n case \"array\":\n if (\"prefixItems\" in schema) {\n const tuple = z.tuple(schema.prefixItems.map(compile) as [\n z.ZodType<unknown>,\n ...z.ZodType<unknown>[],\n ]);\n base = schema.items !== undefined && schema.items !== false\n ? tuple.rest(compile(schema.items))\n : tuple;\n } else {\n base = z.array(compile(schema.items));\n }\n break;\n case \"object\": {\n const required = new Set(schema.required ?? []);\n const shape: Record<string, z.ZodType<unknown>> = {};\n for (const [name, property] of Object.entries(schema.properties)) {\n const validator = compile(property);\n shape[name] = required.has(name) ? validator : validator.optional();\n }\n const object = z.object(shape);\n if (schema.additionalProperties === false) {\n base = object.strict();\n } else if (schema.additionalProperties === true) {\n base = object.loose();\n } else {\n base = object.catchall(compile(schema.additionalProperties));\n }\n break;\n }\n }\n }\n return base;\n };\n return {\n toZod(schema): z.ZodType<unknown> {\n assertSchemaReferences([schema], components);\n return compile(schema);\n },\n };\n}\n\nfunction isAnnotationOnlySchema(schema: Record<string, unknown>): boolean {\n const structuralKeys = [\n \"$ref\", \"const\", \"enum\", \"anyOf\", \"oneOf\", \"type\",\n \"properties\", \"items\", \"prefixItems\", \"additionalProperties\",\n ];\n return !structuralKeys.some((key) => Object.hasOwn(schema, key));\n}\n\nexport function schemaToZod(\n schema: LinkRpcJsonSchema,\n components: Record<string, LinkRpcJsonSchema> = {},\n): z.ZodType<unknown> {\n return createSchemaToZod(components).toZod(schema);\n}\n\nfunction union(items: z.ZodType<unknown>[]): z.ZodType<unknown> {\n if (items.length === 0) return z.never();\n if (items.length === 1) return items[0]!;\n return z.union(items as [z.ZodType<unknown>, z.ZodType<unknown>, ...z.ZodType<unknown>[]]);\n}\n\nfunction valueSchema(expected: import(\"../protocol/jsonValue\").JsonValue): z.ZodType<unknown> {\n return z.unknown().refine((actual) => jsonValueEqual(actual, expected), {\n message: `Expected ${JSON.stringify(expected)}`,\n });\n}\n\nfunction jsonValueEqual(actual: unknown, expected: unknown): boolean {\n if (Object.is(actual, expected)) return true;\n if (Array.isArray(actual) && Array.isArray(expected)) {\n return actual.length === expected.length &&\n actual.every((value, index) => jsonValueEqual(value, expected[index]));\n }\n if (\n actual !== null && expected !== null &&\n typeof actual === \"object\" && typeof expected === \"object\" &&\n !Array.isArray(actual) && !Array.isArray(expected)\n ) {\n const actualRecord = actual as Record<string, unknown>;\n const expectedRecord = expected as Record<string, unknown>;\n const keys = Object.keys(actualRecord);\n return keys.length === Object.keys(expectedRecord).length &&\n keys.every((key) =>\n Object.hasOwn(expectedRecord, key) &&\n jsonValueEqual(actualRecord[key], expectedRecord[key])\n );\n }\n return false;\n}\n\nfunction stringSchema(format: string | undefined): z.ZodType<unknown> {\n switch (format) {\n case \"email\": return z.email();\n case \"uri\":\n case \"url\": return z.url();\n case \"uuid\": return z.uuid();\n case \"date-time\": return z.iso.datetime();\n default: return z.string();\n }\n}\n","import { any as zAny, void as zVoid } from 'zod/mini';\nimport type { RequestId } from '../protocol/jsonRpc';\nimport { computeInterfaceHash } from '../schema/hash';\nimport {\n type ApplicationErrorDescriptorBase,\n type DeclaredApplicationErrorOf,\n type PublicApplicationErrorOf,\n applicationError,\n type MemberType,\n NotificationType,\n RequestType,\n type Schema,\n zodToSvcJsonSchema,\n} from '../schema/memberTypes';\nimport { schemaToZod } from '../schema/schemaToZod';\nimport type { MethodSchema, LinkRpcInterfaceSchema } from '../schema/linkRpcInterfaceSchema';\nimport type { LinkRpcJsonSchema } from '../schema/linkRpcJsonSchema';\n\n/**\n * Per-call stream API handed to a request handler as its third argument.\n * Allows the handler to consume {@link STREAM_METHOD} notifications\n * emitted by the caller (`onMessage`) and emit stream notifications to\n * the caller (`send`) while the request is in flight.\n *\n * Members are typed by the originating method's\n * {@link RequestType.clientStreamSchema} / `serverStreamSchema`.\n * Streams whose schema is `undefined` make the corresponding member\n * effectively unusable: `send` is typed `(payload: never) => void` and\n * the registered `onMessage` listener can never fire because the\n * receiver-side validator rejects the wire payload.\n */\nexport interface StreamApi<TClient = unknown, TServer = unknown> {\n /** Emit a server→client stream message. */\n send(payload: TServer): Promise<void>;\n /**\n * Register a listener for client→server stream messages on this\n * request. Calling twice replaces the previous listener.\n */\n onMessage(listener: (payload: TClient) => void): void;\n /**\n * Liveness probe toward the caller: resolves once the caller\n * acknowledges with a matching pong, rejects if the call settles\n * first. Independent of the channel's automatic keepalive ping.\n */\n ping(): Promise<void>;\n /**\n * Aborts when the caller cancels this in-flight request, or when the\n * hub cancels it on the caller's behalf (caller disconnect / idle\n * timeout). Observe it to stop work early and settle the request\n * (e.g. `signal.throwIfAborted()`), which surfaces as a `cancelled`\n * error to the caller.\n */\n readonly signal: AbortSignal;\n}\n\nexport interface InterfaceInfo {\n id: string;\n /**\n * Normative description of the interface (markdown). Part of the\n * interface hash — changing it is a contract change.\n */\n description?: string;\n /** Non-normative implementation notes. Stripped from the hash. */\n comment?: string;\n /**\n * Optional expected content hash (see `computeInterfaceHash`). When\n * set, {@link InterfaceDefinition}'s constructor verifies that the\n * computed {@link InterfaceDefinition.schemaHash} matches and throws\n * otherwise — a guard against silent contract drift when the wire\n * shape changes but a pinned hash was not updated.\n */\n hash?: string;\n}\n\n\nexport type MemberMap = Record<string, MemberType>;\n\n/** Stable wire identity of one member in an interface definition. */\nexport interface InterfaceMemberRef<TName extends string = string> {\n readonly interfaceId: string;\n readonly interfaceHash: string;\n readonly member: TName;\n}\n\nexport type InterfaceMemberRefMap<TMembers extends MemberMap> = {\n readonly [K in keyof TMembers & string]: InterfaceMemberRef<K>;\n};\n\n/**\n * Per-call options accepted by a streaming-enabled client method. Currently\n * only `onMessage` for consuming server→client stream notifications; the\n * caller addresses client→server stream messages via the returned\n * {@link StreamingCall}.\n */\nexport interface StreamCallOptions<TServer> {\n /** Listener for server→client stream messages on this in-flight call. */\n onMessage?: (payload: TServer) => void;\n}\n\n/**\n * Return shape of a streaming-enabled client method. Behaves as a\n * `Promise<TResult>` for the final response, and exposes `send` for\n * emitting client→server stream messages on the in-flight call. The\n * wire request id is also exposed (resolved once the request has\n * been allocated).\n *\n * For methods whose interface schema declares no client stream\n * (`TClient = never`), `send` is typed `(payload: never) => Promise<void>`\n * and is effectively uncallable — matching the runtime behavior, where\n * the receiver would drop client-emitted stream messages anyway.\n */\nexport interface StreamingCall<TResult, TClient> extends Promise<TResult> {\n /** Resolves to the wire request id once the call has been sent. */\n readonly requestId: Promise<RequestId>;\n /** Emit a client→server stream message on this in-flight call. */\n send(payload: TClient): Promise<void>;\n /**\n * Ask the callee to abort this in-flight call. Advisory: the call\n * settles via its normal response (typically a `cancelled` error).\n * `reason` is an open-set diagnostic string (see `StreamControlReason`).\n */\n cancel(reason?: string): Promise<void>;\n /**\n * Stop tracking this call locally. This does not notify the callee; call\n * {@link cancel} first when remote work should also be cancelled.\n */\n dispose?(reason?: string): void;\n /**\n * Liveness probe toward the callee: resolves once the callee\n * acknowledges with a matching pong, rejects if the call settles\n * first. Independent of the channel's automatic keepalive ping.\n */\n ping(): Promise<void>;\n}\n\nexport interface RemoteRpcError {\n readonly kind: 'remote';\n readonly code: number;\n readonly message: string;\n readonly data?: import('../protocol/jsonValue').JsonValue;\n}\n\nexport interface LocalRpcError {\n readonly kind: 'local';\n readonly cause: unknown;\n}\n\nexport type CheckedCallResult<TResult, TApplicationError = never> =\n | { readonly ok: true; readonly value: TResult; }\n | {\n readonly ok: false;\n readonly error: TApplicationError | RemoteRpcError | LocalRpcError;\n };\n\nexport interface CheckedCall<TResult, TApplicationError = never> extends Promise<TResult> {\n /**\n * Settle without throwing. Only an exact code/message/data-schema match is\n * promoted to a typed application error.\n */\n result(): Promise<CheckedCallResult<TResult, TApplicationError>>;\n}\n\n/**\n * `true` iff at least one stream direction is declared (either client or\n * server stream schema present). Used by {@link InterfaceClient} to pick\n * between the plain `Promise<R>` shape and the {@link StreamingCall}\n * shape per method.\n */\ntype _HasStream<TClient, TServer> = [TClient] extends [never] ? ([TServer] extends [never] ? false : true) :\n true;\n\ntype ClientCall<TResult, TApplicationError> = [TApplicationError] extends [never]\n ? Promise<TResult>\n : CheckedCall<TResult, TApplicationError>;\n\n/**\n * Compile-time TypeScript shape of an interface — useful for typed\n * client/server implementations on top of the runtime definition.\n *\n * Methods whose `RequestType` declares stream payloads via\n * `.withStream({ client, server })` return a {@link StreamingCall}\n * augmented with `send`; all others return a plain `Promise<TResult>`.\n *\n * @example\n * type Client = InterfaceClient<typeof myInterface>;\n * // => { bar(p: {...}): Promise<string>; foo(p: {...}): void; }\n */\ntype InterfaceClientMember<TMember> =\n TMember extends RequestType<infer P, infer R, infer E, infer TC, infer TS, any, any> ? (\n _HasStream<TC, TS> extends true ? (params: P, opts?: StreamCallOptions<TS>) =>\n StreamingCall<R, TC> & ClientCall<R, PublicApplicationErrorOf<E>> :\n (params: P) => ClientCall<R, PublicApplicationErrorOf<E>>\n ) :\n TMember extends NotificationType<infer P> ? (params: P) => void :\n never;\n\nexport type InterfaceClient<TDef extends InterfaceDefinition<any>> = {\n [K in keyof TDef['members']]: InterfaceClientMember<TDef['members'][K]>;\n};\n\n/**\n * Compile-time shape of a server implementation for an interface — used by\n * `LinkRpcConnection.register`. Request handlers may return synchronously or\n * via a promise; notification handlers return void.\n *\n * `TCtx` is the call-context type carried by the hosting connection — see\n * `LinkRpcConnection<TCtx>`. For the default connection (`TCtx = undefined`)\n * handlers may take a single params arg; for ctx-aware connections (e.g.\n * the hub's self connection) they may take a second `ctx` arg of the\n * concrete type. A 1-arg handler remains assignable where a 2-arg handler\n * is expected, so existing handlers compile unchanged.\n */\ntype InterfaceHandler<TMember, TCtx> =\n TMember extends RequestType<infer P, infer R, infer E, infer TC, infer TS, any, any> ?\n (params: P, ctx: TCtx, stream: StreamApi<TC, TS>) =>\n R | DeclaredApplicationErrorOf<E> |\n Promise<R | DeclaredApplicationErrorOf<E>> :\n TMember extends NotificationType<infer P> ? (params: P, ctx: TCtx) => void | Promise<void> :\n never;\n\nexport type InterfaceHandlers<\n TDef extends InterfaceDefinition<any>,\n TCtx = undefined,\n> = {\n [K in keyof TDef['members']]: InterfaceHandler<TDef['members'][K], TCtx>;\n };\n\n/**\n * Options accepted by {@link InterfaceDefinition}'s constructor.\n *\n * `frozenSchema` lets callers supply an externally-authored\n * `LinkRpcInterfaceSchema` (e.g. produced by codegen or, in the faker, by an\n * LLM at runtime) verbatim. When set, `toSchema()` returns that document\n * (with `hash` overlaid) and `schemaHash` is computed from it — the\n * `members` map is used only for runtime dispatch (param/result\n * validation, stream routing) and is no longer the source of truth for\n * the wire shape.\n */\nexport interface InterfaceDefinitionOpts {\n frozenSchema?: LinkRpcInterfaceSchema;\n}\n\ninterface InterfaceDefinitionState {\n readonly frozenSchema: LinkRpcInterfaceSchema | undefined;\n schemaCache: LinkRpcInterfaceSchema | undefined;\n hashCache: string | undefined;\n}\n\nconst interfaceDefinitionState = new WeakMap<object, InterfaceDefinitionState>();\n\nexport class InterfaceDefinition<TMembers extends MemberMap> {\n /** Typed wire references for capability and access-request construction. */\n public readonly ref: InterfaceMemberRefMap<TMembers>;\n\n constructor(\n public readonly info: InterfaceInfo,\n public readonly members: TMembers,\n opts: InterfaceDefinitionOpts = {},\n ) {\n validateInterfaceErrors(opts.frozenSchema);\n interfaceDefinitionState.set(this, {\n frozenSchema: opts.frozenSchema,\n schemaCache: undefined,\n hashCache: undefined,\n });\n this.ref = Object.fromEntries(\n Object.keys(members).map((member) => [\n member,\n {\n interfaceId: this.info.id,\n interfaceHash: this.schemaHash,\n member,\n },\n ]),\n ) as InterfaceMemberRefMap<TMembers>;\n if (info.hash !== undefined && this.schemaHash !== info.hash) {\n throw new Error(\n `Interface hash mismatch for \"${info.id}\": expected \"${info.hash}\", got \"${this.schemaHash}\". `\n + `The interface's wire contract changed — update the pinned hash to \"${this.schemaHash}\" after reviewing the change.`,\n );\n }\n }\n\n /** Content hash of this interface (see `computeInterfaceHash`). */\n public get schemaHash(): string {\n const state = interfaceDefinitionState.get(this)!;\n if (state.hashCache === undefined) {\n const base = state.frozenSchema ?? buildSchema(this.info, this.members, '');\n state.hashCache = computeInterfaceHash(base);\n }\n return state.hashCache;\n }\n\n /** Lower the definition to a wire-format `LinkRpcInterfaceSchema`, hash filled in. */\n public toSchema(): LinkRpcInterfaceSchema {\n const state = interfaceDefinitionState.get(this)!;\n if (state.schemaCache === undefined) {\n state.schemaCache = state.frozenSchema !== undefined ?\n { ...state.frozenSchema, hash: this.schemaHash } :\n buildSchema(this.info, this.members, this.schemaHash);\n }\n return state.schemaCache;\n }\n}\n\nfunction buildSchema(\n info: InterfaceInfo,\n members: MemberMap,\n hash: string,\n): LinkRpcInterfaceSchema {\n const methods: Record<string, MethodSchema> = {};\n const components: Record<string, LinkRpcJsonSchema> = {};\n for (const [name, member] of Object.entries(members)) {\n methods[name] = toMethodSchema(name, member, components);\n }\n const schema: LinkRpcInterfaceSchema = {\n id: info.id,\n hash,\n methods,\n };\n if (Object.keys(components).length > 0) schema.components = { schemas: components };\n if (info.description !== undefined) schema.description = info.description;\n if (info.comment !== undefined) schema.comment = info.comment;\n return schema;\n}\n\nfunction toMethodSchema(\n name: string,\n member: MemberType,\n components: Record<string, LinkRpcJsonSchema>,\n): MethodSchema {\n const docs = member.docs;\n\n if (member.kind === 'request') {\n const m: MethodSchema = {\n params: convertMemberSchema(name, 'params', member.paramsSchema, components),\n result: convertMemberSchema(name, 'result', member.resultSchema, components),\n };\n if (member.clientStreamSchema !== undefined) {\n m.clientStream = convertMemberSchema(\n name,\n 'clientStream',\n member.clientStreamSchema,\n components,\n );\n }\n if (member.serverStreamSchema !== undefined) {\n m.serverStream = convertMemberSchema(\n name,\n 'serverStream',\n member.serverStreamSchema,\n components,\n );\n }\n if (member.applicationErrors.length > 0) {\n m.errors = member.applicationErrors.map((error: ApplicationErrorDescriptorBase) => {\n const result: NonNullable<MethodSchema['errors']>[number] = {\n code: error.code,\n message: error.message,\n };\n if (error.dataSchema !== undefined) {\n result.data = convertMemberSchema(\n name,\n `error=${error.code}`,\n error.dataSchema,\n components,\n );\n }\n return result;\n });\n }\n if (docs.description !== undefined) m.description = docs.description;\n if (docs.comment !== undefined) m.comment = docs.comment;\n if (docs.annotations !== undefined) m.annotations = docs.annotations;\n return m;\n }\n\n const m: MethodSchema = {\n params: convertMemberSchema(name, 'params', member.paramsSchema, components),\n };\n if (docs.description !== undefined) m.description = docs.description;\n if (docs.comment !== undefined) m.comment = docs.comment;\n if (docs.annotations !== undefined) m.annotations = docs.annotations;\n return m;\n}\n\nfunction validateInterfaceErrors(schema: LinkRpcInterfaceSchema | undefined): void {\n if (schema === undefined) return;\n for (const [methodName, method] of Object.entries(schema.methods)) {\n if (method.result === undefined && method.errors !== undefined) {\n throw new Error(`Notification \"${methodName}\" cannot declare application errors.`);\n }\n const seen = new Set<number>();\n for (const error of method.errors ?? []) {\n if (typeof error.message !== 'string') {\n throw new Error(`Application error message on \"${methodName}\" must be a string.`);\n }\n if (!Number.isInteger(error.code) || error.code < -2147483648 || error.code > 2147483647) {\n throw new Error(`Application error code ${error.code} on \"${methodName}\" must be a signed 32-bit integer.`);\n }\n if ((error.code >= -32768 && error.code <= -32000) || error.code === -32800) {\n throw new Error(`Application error code ${error.code} on \"${methodName}\" is reserved by JSON-RPC or LinkRPC.`);\n }\n if (seen.has(error.code)) {\n throw new Error(`Duplicate application error code ${error.code} on \"${methodName}\".`);\n }\n seen.add(error.code);\n }\n }\n}\n\nfunction convertMemberSchema(\n methodName: string,\n position: string,\n schema: Schema,\n components: Record<string, LinkRpcJsonSchema>,\n): LinkRpcJsonSchema {\n return zodToSvcJsonSchema(schema, {\n methodName,\n schemaPosition: position,\n components,\n });\n}\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 */\nexport function defineInterface<TMembers extends MemberMap>(\n info: InterfaceInfo,\n members: TMembers,\n): InterfaceDefinition<TMembers> {\n return new InterfaceDefinition(info, members);\n}\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 because recognizing a typed error must\n * never rely on its code alone.\n *\n * Methods with no `result` descriptor become notifications; methods with\n * `clientStream` / `serverStream` get pass-through stream payload\n * schemas attached.\n */\nexport function interfaceFromSchema(schema: LinkRpcInterfaceSchema): InterfaceDefinition<MemberMap> {\n const members: MemberMap = {};\n for (const [name, method] of Object.entries(schema.methods)) {\n if (method.result === undefined) {\n members[name] = new NotificationType(zAny());\n continue;\n }\n const base = new RequestType<unknown, unknown, void>(zAny(), zAny(), zVoid())\n .withErrors((method.errors ?? []).map((error) => error.data === undefined\n ? applicationError(error.code, error.message)\n : applicationError(error.code, error.message, schemaToZod(\n error.data, schema.components?.schemas,\n ))));\n members[name] = method.clientStream !== undefined || method.serverStream !== undefined ?\n base.withStream({\n client: method.clientStream !== undefined ? zAny() : undefined,\n server: method.serverStream !== undefined ? zAny() : undefined,\n }) :\n base;\n }\n const info: InterfaceInfo = { id: schema.id };\n if (schema.description !== undefined) info.description = schema.description;\n if (schema.comment !== undefined) info.comment = schema.comment;\n return new InterfaceDefinition(info, members, { frozenSchema: schema });\n}\n","/**\n * Minimal JSON-RPC 2.0 wire types — only what we need to send and receive\n * requests, notifications, and responses.\n */\n\nimport type { JsonValue } from \"./jsonValue\";\n\nexport type { JsonValue };\n\nexport type RequestId = number | string;\n\nexport interface JsonRpcRequest<TParams = JsonValue> {\n jsonrpc: \"2.0\";\n id: RequestId;\n method: string;\n params?: TParams;\n}\n\nexport interface JsonRpcNotification<TParams = JsonValue> {\n jsonrpc: \"2.0\";\n method: string;\n params?: TParams;\n}\n\nexport interface JsonRpcSuccess {\n jsonrpc: \"2.0\";\n id: RequestId | null;\n result: JsonValue;\n}\n\nexport interface JsonRpcError {\n jsonrpc: \"2.0\";\n id: RequestId | null;\n error: { code: number; message: string; data?: JsonValue };\n}\n\nexport type JsonRpcResponse = JsonRpcSuccess | JsonRpcError;\nexport type JsonRpcMessage = JsonRpcRequest | JsonRpcNotification | JsonRpcResponse;\n\nexport const ErrorCode = {\n parseError: -32700,\n invalidRequest: -32600,\n methodNotFound: -32601,\n invalidParams: -32602,\n internalError: -32603,\n /** Caller is authenticated but lacks a capability covering the call. */\n permissionRequired: -32401,\n /** The peer a request was routed to detached before it could respond. */\n peerDisconnected: -32402,\n /** The request exceeded the hub's idle timeout with no stream activity. */\n requestTimeout: -32403,\n /** The request was cancelled (by the caller, or by the hub on disconnect). */\n cancelled: -32800,\n} as const;\n\nexport function isRequest(m: JsonRpcMessage): m is JsonRpcRequest {\n return typeof (m as JsonRpcRequest).method === \"string\"\n && (m as JsonRpcRequest).id !== undefined;\n}\n\nexport function isNotification(m: JsonRpcMessage): m is JsonRpcNotification {\n return typeof (m as JsonRpcNotification).method === \"string\"\n && (m as JsonRpcRequest).id === undefined;\n}\n\nexport function isResponse(m: JsonRpcMessage): m is JsonRpcResponse {\n return typeof (m as JsonRpcRequest).method !== \"string\";\n}\n","/**\n * Identity primitives. linkrpc itself is identity-agnostic; this module\n * defines the shared types. No crypto code lives here — the crypto API is\n * `./crypto` (backed by the Web Crypto implementation in\n * `./ed25519CryptoProvider`).\n */\n\n/** Raw Ed25519 public key (32 bytes). */\nexport type PublicKey = Uint8Array;\n\n/** Raw Ed25519 private key (32 bytes — seed form). */\nexport type PrivateKey = Uint8Array;\n\n/** Raw Ed25519 signature (64 bytes). */\nexport type Signature = Uint8Array;\n\n/**\n * A **principal**: an identity's stable, opaque name. In Phase 1 every\n * principal is *perpetual* and self-describing — its genesis signing key is\n * embedded verbatim:\n *\n * principal = \"id:\" + keyId (e.g. \"id:key:<b64url(pubKey)>\")\n *\n * So the genesis check is pure string equality (`\"id:\" + keyId === principal`)\n * and no key-binding records are ever needed. Treat as opaque; construct via\n * {@link principalForPublicKey} and resolve a verifying key via\n * {@link resolveSigningKey}.\n */\nexport type PrincipalId = string;\n\n/**\n * A **keyId**: names the signing key that produced a signature. In Phase 1 the\n * only form is an *inline* key — the public key encoded verbatim:\n *\n * keyId = \"key:\" + b64url(pubKey)\n *\n * (Future forms, e.g. `\"keydoc:\" + b64url(sha256(jcs(doc)))`, are resolved\n * through bindings — see the design doc — but Phase 1 needs none.)\n */\nexport type KeyId = string;\n\nexport interface Keypair {\n readonly publicKey: PublicKey;\n readonly privateKey: PrivateKey;\n}\n\n/** Raw X25519 keypair. Both halves are 32 bytes. */\nexport interface X25519Keypair {\n readonly publicKey: Uint8Array;\n readonly privateKey: Uint8Array;\n}\n\n// ---- base64url codec (no padding) ----------------------------------------\n\nconst _b64UrlAlphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\nconst _b64UrlReverse: Record<string, number> = (() => {\n const m: Record<string, number> = {};\n for (let i = 0; i < _b64UrlAlphabet.length; i++) m[_b64UrlAlphabet[i]] = i;\n return m;\n})();\n\nexport function bytesToBase64Url(bytes: Uint8Array): string {\n let out = \"\";\n let i = 0;\n for (; i + 3 <= bytes.length; i += 3) {\n const n = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n out += _b64UrlAlphabet[(n >> 18) & 63]\n + _b64UrlAlphabet[(n >> 12) & 63]\n + _b64UrlAlphabet[(n >> 6) & 63]\n + _b64UrlAlphabet[n & 63];\n }\n const rem = bytes.length - i;\n if (rem === 1) {\n const n = bytes[i] << 16;\n out += _b64UrlAlphabet[(n >> 18) & 63] + _b64UrlAlphabet[(n >> 12) & 63];\n } else if (rem === 2) {\n const n = (bytes[i] << 16) | (bytes[i + 1] << 8);\n out += _b64UrlAlphabet[(n >> 18) & 63]\n + _b64UrlAlphabet[(n >> 12) & 63]\n + _b64UrlAlphabet[(n >> 6) & 63];\n }\n return out;\n}\n\nexport function base64UrlToBytes(s: string): Uint8Array {\n const len = s.length;\n const fullGroups = Math.floor(len / 4);\n const rem = len % 4;\n if (rem === 1) throw new Error(\"base64UrlToBytes: invalid length\");\n const outLen = fullGroups * 3 + (rem === 0 ? 0 : rem - 1);\n const out = new Uint8Array(outLen);\n let oi = 0;\n let i = 0;\n for (let g = 0; g < fullGroups; g++, i += 4) {\n const n = (_lookup(s, i) << 18) | (_lookup(s, i + 1) << 12) | (_lookup(s, i + 2) << 6) | _lookup(s, i + 3);\n out[oi++] = (n >> 16) & 0xff;\n out[oi++] = (n >> 8) & 0xff;\n out[oi++] = n & 0xff;\n }\n if (rem === 2) {\n const n = (_lookup(s, i) << 18) | (_lookup(s, i + 1) << 12);\n out[oi++] = (n >> 16) & 0xff;\n } else if (rem === 3) {\n const n = (_lookup(s, i) << 18) | (_lookup(s, i + 1) << 12) | (_lookup(s, i + 2) << 6);\n out[oi++] = (n >> 16) & 0xff;\n out[oi++] = (n >> 8) & 0xff;\n }\n return out;\n}\n\nfunction _lookup(s: string, i: number): number {\n const v = _b64UrlReverse[s[i]];\n if (v === undefined) throw new Error(`base64UrlToBytes: invalid char at ${i}`);\n return v;\n}\n\n// ---- principals & keyIds (the identity ⇄ key seam) -----------------------\n\n/** Role-tag prefix on a {@link KeyId}'s inline-key form. */\nexport const KEY_ID_PREFIX = \"key:\";\n\n/** Role-tag prefix that wraps a genesis {@link KeyId} into a {@link PrincipalId}. */\nexport const PRINCIPAL_PREFIX = \"id:\";\n\n/** The inline {@link KeyId} for a raw public key: `\"key:\" + b64url(pk)`. */\nexport function keyIdForPublicKey(pk: PublicKey): KeyId {\n return KEY_ID_PREFIX + bytesToBase64Url(pk);\n}\n\n/** The perpetual {@link PrincipalId} for a raw public key: `\"id:key:\" + b64url(pk)`. */\nexport function principalForPublicKey(pk: PublicKey): PrincipalId {\n return PRINCIPAL_PREFIX + keyIdForPublicKey(pk);\n}\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 */\nexport function keyIdForPrincipal(principal: PrincipalId): KeyId {\n if (!principal.startsWith(PRINCIPAL_PREFIX)) {\n throw new Error(`malformed principal (missing \"${PRINCIPAL_PREFIX}\" prefix): ${principal}`);\n }\n return principal.slice(PRINCIPAL_PREFIX.length);\n}\n\n/**\n * The raw public key carried inline by a `\"key:\"` {@link KeyId}. Throws on a\n * missing prefix or malformed base64url.\n */\nexport function publicKeyForKeyId(keyId: KeyId): PublicKey {\n if (!keyId.startsWith(KEY_ID_PREFIX)) {\n throw new Error(`unsupported keyId (expected \"${KEY_ID_PREFIX}\" prefix): ${keyId}`);\n }\n return base64UrlToBytes(keyId.slice(KEY_ID_PREFIX.length));\n}\n\n/** Arguments to {@link resolveSigningKey}. */\nexport interface ResolveSigningKeyArgs {\n /** The identity the signature claims to be from. */\n readonly principal: PrincipalId;\n /** Which key (per `$hubrpcSignature[domain].keyId`) is claimed to have signed. */\n readonly keyId: KeyId;\n /** Presented key-binding records. Unused in Phase 1 (perpetual ids need none). */\n readonly bindings?: Record<KeyId, unknown>;\n /** Time the signature was made (e.g. `signedAtMs`). Unused in Phase 1. */\n readonly timeMs?: number;\n}\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 */\nexport function resolveSigningKey(args: ResolveSigningKeyArgs): { publicKey: PublicKey } | undefined {\n const { principal, keyId } = args;\n if (!keyId.startsWith(KEY_ID_PREFIX)) {\n return undefined; // keydoc:/rotation — deferred\n }\n if (PRINCIPAL_PREFIX + keyId !== principal) {\n return undefined; // not this principal's genesis key\n }\n try {\n return { publicKey: base64UrlToBytes(keyId.slice(KEY_ID_PREFIX.length)) };\n } catch {\n return undefined; // malformed base64url\n }\n}\n","import {\n array,\n boolean,\n enum as zEnum,\n int,\n literal,\n nonnegative,\n number,\n object,\n optional,\n record,\n string,\n union,\n unknown,\n} from \"zod/mini\";\nimport type { output as zInfer } from \"zod/v4/core\";\nimport { defineInterface } from \"../connection/interfaceDefinition\";\nimport { requestType } from \"../schema/memberTypes\";\n\nexport const zTopologyPort = object({\n portId: string(),\n label: optional(string()),\n});\n\nexport const zParticipantDescriptor = object({\n type: optional(string()),\n label: optional(string()),\n processId: optional(number()),\n processType: optional(string()),\n nodeStatusServiceId: optional(string()),\n metadata: optional(record(string(), union([string(), number(), boolean()]))),\n});\n\nexport const zParticipantDescriptorSource = object({\n source: zEnum([\"self\", \"attacher\"]),\n descriptor: zParticipantDescriptor,\n});\n\nexport const zTopologyNode = object({\n nodeId: string(),\n kind: optional(zEnum([\"endpoint\", \"hub\"])),\n label: optional(string()),\n descriptors: optional(array(zParticipantDescriptorSource)),\n ports: array(zTopologyPort),\n});\n\nexport const zTopologyLinkEndpoint = object({\n nodeId: string(),\n portId: string(),\n});\n\nexport const zTopologyTransportEndpoint = object({\n address: optional(string()),\n port: optional(number().check(int(), nonnegative())),\n});\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 */\nexport const zTopologyTransportInfo = object({\n type: string(),\n local: optional(zTopologyTransportEndpoint),\n remote: optional(zTopologyTransportEndpoint),\n path: optional(string()),\n metadata: optional(record(string(), union([string(), number(), boolean()]))),\n});\n\nexport const zTopologyLink = object({\n from: zTopologyLinkEndpoint,\n to: zTopologyLinkEndpoint,\n label: optional(string()),\n peerState: optional(zEnum([\"identified\", \"pending\", \"unsupported\", \"error\"])),\n transport: optional(zTopologyTransportInfo),\n});\n\nexport const zRouteClaim = object({\n serviceId: string(),\n nodeId: string(),\n portId: string(),\n match: zEnum([\"exact\", \"prefix\"]),\n});\n\nexport const zTopologyGraph = object({\n observerServiceId: string(),\n entryNodeId: string(),\n nodes: array(zTopologyNode),\n links: array(zTopologyLink),\n routes: array(zRouteClaim),\n});\n\nexport type TopologyPort = zInfer<typeof zTopologyPort>;\nexport type ParticipantDescriptor = zInfer<typeof zParticipantDescriptor>;\nexport type ParticipantDescriptorSource = zInfer<typeof zParticipantDescriptorSource>;\nexport type TopologyNode = zInfer<typeof zTopologyNode>;\nexport type TopologyLinkEndpoint = zInfer<typeof zTopologyLinkEndpoint>;\nexport type TopologyTransportEndpoint = zInfer<typeof zTopologyTransportEndpoint>;\nexport type TopologyTransportInfo = zInfer<typeof zTopologyTransportInfo>;\nexport type TopologyLink = zInfer<typeof zTopologyLink>;\nexport type RouteClaim = zInfer<typeof zRouteClaim>;\nexport type TopologyGraph = zInfer<typeof zTopologyGraph>;\n\nexport const topologyInterface = defineInterface(\n {\n id: \"hubrpc.topology\",\n description:\n \"Inspect the transport graph visible from a service. A watch emits invalidation \"\n + \"ticks; consumers re-fetch getGraph after each tick.\",\n },\n {\n getGraph: requestType(object({}), zTopologyGraph).withStream({ client: object({}) }),\n watchGraph: requestType(object({}), object({})).withStream({\n server: object({}),\n }),\n },\n);\n\nexport const zTrafficTransitEndpoint = object({\n edgeId: string(),\n portId: string(),\n requestId: optional(union([number(), string()])),\n});\n\nexport const zTrafficTransitEvent = object({\n type: literal(\"transit\"),\n timeMs: number(),\n nodeId: string(),\n in: optional(zTrafficTransitEndpoint),\n out: optional(zTrafficTransitEndpoint),\n disposition: zEnum([\"forwarded\", \"consumed\", \"dropped\", \"unroutable\"]),\n kind: zEnum([\"request\", \"notification\", \"response\", \"stream\"]),\n method: optional(string()),\n params: optional(unknown()),\n result: optional(unknown()),\n error: optional(object({\n code: number(),\n message: string(),\n data: optional(unknown()),\n })),\n});\n\nexport const zTrafficOverflowEvent = object({\n type: literal(\"overflow\"),\n dropped: number().check(int(), nonnegative()),\n});\n\nexport const zTrafficEvent = union([zTrafficTransitEvent, zTrafficOverflowEvent]);\n\nexport type TrafficTransitEndpoint = zInfer<typeof zTrafficTransitEndpoint>;\nexport type TrafficTransitEvent = zInfer<typeof zTrafficTransitEvent>;\nexport type TrafficOverflowEvent = zInfer<typeof zTrafficOverflowEvent>;\nexport type TrafficEvent = zInfer<typeof zTrafficEvent>;\n\nexport const zTrafficWatchResult = object({\n delivered: number().check(int(), nonnegative()),\n dropped: number().check(int(), nonnegative()),\n});\n\nexport type TrafficWatchResult = zInfer<typeof zTrafficWatchResult>;\n\nconst zTrafficWatchParams = object({\n methodPrefix: optional(string()),\n trafficIgnoreKey: optional(string()),\n focusRequest: optional(object({\n portId: string(),\n requestId: union([number(), string()]),\n })),\n});\n\nconst zTrafficWatchWithPayloadsParams = object({\n methodPrefix: optional(string()),\n trafficIgnoreKey: optional(string()),\n focusRequest: optional(object({\n portId: string(),\n requestId: union([number(), string()]),\n })),\n maxPayloadBytes: number().check(int(), nonnegative()),\n});\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 */\nexport const trafficInterface = defineInterface(\n {\n id: \"hubrpc.traffic\",\n description:\n \"Stream raw message transits for the entire node hosting the addressed service. \"\n + \"Payload-free and explicitly payload-bearing variants keep disclosure opt-in.\",\n },\n {\n watch: requestType(zTrafficWatchParams, zTrafficWatchResult).withStream({\n server: zTrafficEvent,\n }),\n watchWithPayloads: requestType(\n zTrafficWatchWithPayloadsParams,\n zTrafficWatchResult,\n ).withStream({\n server: zTrafficEvent,\n }),\n },\n);\n","import { array, object, optional, string } from \"zod/mini\";\nimport type { output as zInfer } from \"zod/v4/core\";\nimport { defineInterface } from \"../connection/interfaceDefinition\";\nimport { requestType } from \"../schema/memberTypes\";\nimport { zParticipantDescriptorSource } from \"./inspection.interfaces\";\nimport type { ParticipantDescriptorSource } from \"./inspection.interfaces\";\n\nconst zNodeInfo = object({\n /**\n * Random identity of this connection's node. It is a topology-correlation\n * label only and must not be used for authentication or authorization.\n */\n nodeId: string(),\n /** Random identity of this connection's port on its node. */\n portId: string(),\n /** Optional diagnostic descriptors; never used for authorization. */\n descriptors: optional(array(zParticipantDescriptorSource)),\n});\n\nexport type NodeInfo = zInfer<typeof zNodeInfo>;\nexport type { ParticipantDescriptorSource };\n\n/**\n * Generates unique topology-correlation labels, not security identities.\n * Custom generators must avoid collisions across nodes and ports. Tests can\n * supply an independent deterministic sequence for each participant.\n */\nexport type TopologyIdGenerator = (kind: 'node' | 'port') => string;\n\n/**\n * Minimal root service for aligning the independently observed topologies at\n * both ends of a connection.\n */\nexport const nodeInterface = defineInterface(\n {\n id: \"hubrpc.node\",\n description:\n \"Topology bootstrap: identify the node and port at this end of the direct connection.\",\n },\n {\n getNodeId: requestType(object({}), zNodeInfo),\n },\n);\n","import { enum as zEnum, number, object, optional, string, union, unknown } from \"zod/mini\";\nimport type { output as zInfer } from \"zod/v4/core\";\nimport { defineInterface } from \"./interfaceDefinition\";\nimport { notificationType } from \"../schema/memberTypes\";\n\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 */\nexport const StreamDir = {\n /** callee → caller: progress, partial results. Routes like a response. */\n toCaller: \"toCaller\",\n /** caller → callee: input, cancellation, keepalive ping. */\n toCallee: \"toCallee\",\n} as const;\nexport type StreamDir = (typeof StreamDir)[keyof typeof StreamDir];\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 */\nexport const StreamControlType = {\n /**\n * Ask the callee to abort the in-flight request. Always {@link\n * StreamDir.toCallee}. The callee surfaces this as an `AbortSignal`\n * and is expected to settle the request (typically with a\n * `cancelled` error response).\n */\n cancel: \"cancel\",\n /**\n * Keepalive / liveness probe. Resets the hub's per-request idle timer\n * so a long-running call is not reaped, and lets either side actively\n * probe the peer. Carries a `nonce` the peer echoes in its {@link\n * StreamControlType.pong}. May travel in either direction. Emitted\n * automatically (without awaiting a pong) by the channel for streaming\n * calls; see {@link STREAM_METHOD}.\n */\n ping: \"ping\",\n /**\n * Reply to a {@link StreamControlType.ping}, echoing the ping's\n * `nonce` so the prober can correlate it. Travels opposite the ping.\n * Carries no app effect — purely a liveness acknowledgement.\n */\n pong: \"pong\",\n} as const;\nexport type StreamControlType = (typeof StreamControlType)[keyof typeof StreamControlType];\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 */\nexport const StreamControlReason = {\n /**\n * The caller's transport dropped while the request was in flight; the\n * hub cancels the callee's now-orphaned work.\n */\n clientDisconnected: \"clientDisconnected\",\n /**\n * The request exceeded the hub's idle timeout with no stream activity\n * (no ping, no stream message). See {@link STREAM_METHOD} docs.\n */\n idleTimeout: \"idleTimeout\",\n} as const;\nexport type StreamControlReason = (typeof StreamControlReason)[keyof typeof StreamControlReason];\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 */\nexport const streamInterface = defineInterface(\n {\n id: \"$stream\",\n description:\n \"Reserved sub-protocol for in-flight stream messages \"\n + \"correlated to a request by `requestId`.\",\n },\n {\n send: notificationType(\n object({\n /**\n * Id of the in-flight request the message belongs to.\n * The hub rewrites this across the forwarding boundary\n * in the same way it rewrites response ids.\n */\n requestId: union([number(), string()]),\n /**\n * Which way this message travels relative to the request.\n * Explicit so the hub can author messages (e.g. cancel on\n * disconnect) without inferring direction from arrival.\n */\n dir: zEnum([\"toCaller\", \"toCallee\"]),\n /**\n * Reserved control verb (cancel / ping / pong). Mutually\n * exclusive with `payload` in practice: a control message\n * is interpreted by the runtime, not the application.\n */\n control: optional(\n object({\n type: zEnum([\"cancel\", \"ping\", \"pong\"]),\n /** Open-set human/diagnostic reason; see {@link StreamControlReason}. */\n reason: optional(string()),\n /**\n * Correlation token. A `ping` carries a fresh nonce;\n * the matching `pong` echoes it back so the prober\n * can resolve the right outstanding probe.\n */\n nonce: optional(string()),\n })\n ),\n /** Opaque app payload — typed per call by the request's stream schema. */\n payload: optional(unknown()),\n }),\n {\n description:\n \"Emit a stream message tied to the request `requestId`.\",\n },\n ),\n },\n);\n\n/**\n * Full wire method name for stream notifications. Pulled from the\n * interface object so we have a single source of truth.\n */\nexport const STREAM_METHOD = `${streamInterface.info.id}::send` as const;\n\n/** Wire-level shape carried on `params` of {@link STREAM_METHOD}. */\nexport type StreamSendParams = zInfer<typeof streamInterface.members.send.paramsSchema>;\n\n","import type {\n TrafficTransitEndpoint,\n TrafficTransitEvent,\n} from './inspection.interfaces';\n\nexport interface TrafficRequestRef {\n readonly portId: string;\n readonly requestId: string | number;\n}\n\nexport interface TrafficFlowFilterOptions {\n readonly focus?: TrafficRequestRef;\n}\n\nexport class TrafficFlowFilter {\n private readonly _focused: CorrelatedFlow | undefined;\n\n constructor(options: TrafficFlowFilterOptions) {\n this._focused = options.focus !== undefined\n ? new CorrelatedFlow([options.focus])\n : undefined;\n }\n\n public shouldInclude(transit: TrafficTransitEvent): boolean {\n const focused = this._focused?.accept(transit).matches ?? true;\n return focused;\n }\n}\n\nexport class TrafficWatchFlowTracker {\n private readonly _active = new Set<CorrelatedFlow>();\n private readonly _unclaimed = new Map<string, CorrelatedFlow>();\n\n public accept(transit: TrafficTransitEvent): boolean {\n if (transit.kind === 'request' && isTrafficWatchMethod(transit.method)) {\n const trafficIgnoreKey = readTrafficIgnoreKey(transit.params);\n let flow = this._findFlow(transit);\n if (flow === undefined) {\n flow = new CorrelatedFlow(\n requestRefsOf(transit),\n completionRefOf(transit),\n );\n if (!isTerminal(transit)) this._active.add(flow);\n } else {\n flow.accept(transit);\n }\n if (isTerminal(transit)) {\n this._removeFlow(flow);\n return true;\n }\n if (trafficIgnoreKey !== undefined) {\n this._unclaimed.set(trafficIgnoreKey, flow);\n }\n return true;\n }\n for (const flow of this._active) {\n const match = flow.accept(transit);\n if (!match.matches) continue;\n if (match.completed) this._removeFlow(flow);\n return true;\n }\n return false;\n }\n\n private _findFlow(transit: TrafficTransitEvent): CorrelatedFlow | undefined {\n for (const flow of this._active) {\n if (flow.matches(transit)) return flow;\n }\n return undefined;\n }\n\n private _removeFlow(flow: CorrelatedFlow): void {\n this._active.delete(flow);\n for (const [key, pending] of this._unclaimed) {\n if (pending === flow) this._unclaimed.delete(key);\n }\n }\n\n public claim(trafficIgnoreKey: string): boolean {\n return this._unclaimed.delete(trafficIgnoreKey);\n }\n\n public clear(): void {\n this._active.clear();\n this._unclaimed.clear();\n }\n\n public forgetPort(portId: string): void {\n for (const flow of this._active) {\n if (flow.hasPort(portId)) this._removeFlow(flow);\n }\n }\n}\n\nclass CorrelatedFlow {\n private readonly _endpoints = new Set<string>();\n private readonly _ports = new Set<string>();\n private readonly _completionEndpoint: string | undefined;\n\n constructor(\n endpoints: readonly TrafficRequestRef[],\n completionEndpoint: TrafficRequestRef | undefined = endpoints[0],\n ) {\n for (const endpoint of endpoints) {\n this._endpoints.add(endpointKey(endpoint));\n this._ports.add(endpoint.portId);\n }\n this._completionEndpoint = completionEndpoint === undefined\n ? undefined\n : endpointKey(completionEndpoint);\n }\n\n public matches(transit: TrafficTransitEvent): boolean {\n return requestRefsOf(transit)\n .some((endpoint) => this._endpoints.has(endpointKey(endpoint)));\n }\n\n public hasPort(portId: string): boolean {\n return this._ports.has(portId);\n }\n\n public accept(transit: TrafficTransitEvent): {\n readonly matches: boolean;\n readonly completed: boolean;\n } {\n const endpoints = requestRefsOf(transit);\n if (!this.matches(transit)) {\n return { matches: false, completed: false };\n }\n for (const endpoint of endpoints) {\n this._endpoints.add(endpointKey(endpoint));\n this._ports.add(endpoint.portId);\n }\n const completed = transit.kind === 'response'\n && (\n isTerminal(transit)\n || (\n this._completionEndpoint !== undefined\n && endpoints.some((endpoint) =>\n endpointKey(endpoint) === this._completionEndpoint)\n )\n );\n if (completed) this._endpoints.clear();\n return { matches: true, completed };\n }\n\n}\n\nfunction isTerminal(transit: TrafficTransitEvent): boolean {\n return transit.disposition === 'dropped'\n || transit.disposition === 'unroutable';\n}\n\nfunction requestRefsOf(transit: TrafficTransitEvent): TrafficRequestRef[] {\n const result: TrafficRequestRef[] = [];\n if (transit.in?.requestId !== undefined) result.push(requestRef(transit.in));\n if (transit.out?.requestId !== undefined) result.push(requestRef(transit.out));\n return result;\n}\n\nfunction requestRef(endpoint: TrafficTransitEndpoint): TrafficRequestRef {\n return {\n portId: endpoint.portId,\n requestId: endpoint.requestId!,\n };\n}\n\nfunction completionRefOf(transit: TrafficTransitEvent): TrafficRequestRef | undefined {\n if (transit.in?.requestId !== undefined) return requestRef(transit.in);\n if (transit.out?.requestId !== undefined) return requestRef(transit.out);\n return undefined;\n}\n\nfunction endpointKey(endpoint: TrafficRequestRef): string {\n return JSON.stringify([\n endpoint.portId,\n typeof endpoint.requestId,\n endpoint.requestId,\n ]);\n}\n\nfunction isTrafficWatchMethod(method: string | undefined): boolean {\n return method?.endsWith('::hubrpc.traffic::watch') === true\n || method?.endsWith('::hubrpc.traffic::watchWithPayloads') === true\n || method === 'hubrpc.traffic::watch'\n || method === 'hubrpc.traffic::watchWithPayloads';\n}\n\nfunction readTrafficIgnoreKey(params: unknown): string | undefined {\n if (params === null || Array.isArray(params) || typeof params !== 'object' || !('trafficIgnoreKey' in params)) {\n return undefined;\n }\n const value = params.trafficIgnoreKey;\n return typeof value === 'string' ? value : undefined;\n}\n","import type {\n TrafficEvent,\n TrafficTransitEvent,\n TrafficWatchResult,\n} from './inspection.interfaces';\nimport type { JsonValue } from '../protocol/jsonRpc';\nimport {\n TrafficFlowFilter,\n} from './trafficFlowFilter';\nimport type { TrafficRequestRef } from './trafficFlowFilter';\n\nconst DEFAULT_QUEUE_LIMIT = 256;\n\nexport interface TrafficSubscriptionOptions {\n readonly methodPrefix?: string;\n readonly maxPayloadBytes?: number;\n readonly trafficIgnoreKey?: string;\n readonly focusRequest?: TrafficRequestRef;\n}\n\nexport interface TrafficSubscription {\n readonly closed: Promise<TrafficWatchResult>;\n dispose(): void;\n}\n\n/**\n * Applies per-subscriber filtering and payload policy while isolating traffic\n * producers from slow or failed stream consumers.\n */\nexport class BoundedTrafficSubscription implements TrafficSubscription {\n private readonly _queue: TrafficTransitEvent[] = [];\n private _active = true;\n private _pumping = false;\n private _overflowPending = 0;\n private _delivered = 0;\n private _dropped = 0;\n private readonly _resolveClosed: (result: TrafficWatchResult) => void;\n private readonly _filter: TrafficFlowFilter;\n public readonly closed: Promise<TrafficWatchResult>;\n\n constructor(\n private readonly _options: TrafficSubscriptionOptions,\n private readonly _send: (event: TrafficEvent) => Promise<void>,\n private readonly _onDispose: () => void,\n private readonly _queueLimit = DEFAULT_QUEUE_LIMIT,\n ) {\n let resolve!: (result: TrafficWatchResult) => void;\n this.closed = new Promise<TrafficWatchResult>((r) => resolve = r);\n this._resolveClosed = resolve;\n this._filter = new TrafficFlowFilter({\n focus: _options.focusRequest,\n });\n }\n\n public enqueue(transit: TrafficTransitEvent): void {\n if (!this._active) return;\n if (!this._filter.shouldInclude(transit)) return;\n if (\n this._options.methodPrefix !== undefined\n && !transit.method?.startsWith(this._options.methodPrefix)\n ) {\n return;\n }\n\n const event = this._options.maxPayloadBytes === undefined\n ? withoutPayloads(transit)\n : withCappedPayloads(transit, this._options.maxPayloadBytes);\n if (this._queue.length >= this._queueLimit) {\n this._queue.shift();\n this._dropped++;\n this._overflowPending++;\n }\n this._queue.push(event);\n if (!this._pumping) {\n this._pumping = true;\n queueMicrotask(() => void this._pump());\n }\n }\n\n public dispose(): void {\n if (!this._active) return;\n this._active = false;\n this._dropped += this._queue.length;\n this._queue.length = 0;\n this._overflowPending = 0;\n this._onDispose();\n if (!this._pumping) this._complete();\n }\n\n private async _pump(): Promise<void> {\n try {\n while (this._active) {\n if (this._overflowPending > 0) {\n const dropped = this._overflowPending;\n this._overflowPending = 0;\n await this._send({ type: 'overflow', dropped });\n continue;\n }\n const event = this._queue.shift();\n if (event === undefined) break;\n await this._send(event);\n this._delivered++;\n }\n } catch {\n this.dispose();\n } finally {\n this._pumping = false;\n if (!this._active) {\n this._complete();\n } else if (this._queue.length > 0 || this._overflowPending > 0) {\n this._pumping = true;\n queueMicrotask(() => void this._pump());\n }\n }\n }\n\n private _complete(): void {\n this._resolveClosed({\n delivered: this._delivered,\n dropped: this._dropped,\n });\n }\n}\n\nfunction withoutPayloads(transit: TrafficTransitEvent): TrafficTransitEvent {\n const { params: _params, result: _result, error, ...rest } = transit;\n if (error === undefined) return rest;\n return {\n ...rest,\n error: { code: error.code, message: error.message },\n };\n}\n\nfunction withCappedPayloads(\n transit: TrafficTransitEvent,\n maxPayloadBytes: number,\n): TrafficTransitEvent {\n return {\n ...transit,\n params: capPayload(transit.params, maxPayloadBytes),\n result: capPayload(transit.result, maxPayloadBytes),\n error: transit.error === undefined ? undefined : {\n ...transit.error,\n data: capPayload(transit.error.data, maxPayloadBytes),\n },\n };\n}\n\nfunction capPayload(value: unknown, maxBytes: number): JsonValue | undefined {\n if (value === undefined) return undefined;\n if (maxBytes === Number.POSITIVE_INFINITY) return value as JsonValue;\n const json = JSON.stringify(value);\n if (json === undefined) return undefined;\n const encoded = new TextEncoder().encode(json);\n if (encoded.byteLength <= maxBytes) return value as JsonValue;\n const encoder = new TextEncoder();\n let preview = new TextDecoder().decode(encoded.slice(0, maxBytes));\n while (encoder.encode(preview).byteLength > maxBytes) {\n preview = preview.slice(0, -1);\n }\n return preview;\n}\n","import {\n isNotification,\n isRequest,\n isResponse,\n type JsonRpcMessage,\n type RequestId,\n} from '../protocol/jsonRpc';\nimport {\n STREAM_METHOD,\n type StreamSendParams,\n} from '../connection/streaming';\nimport type { TrafficTransitEvent } from './inspection.interfaces';\nimport type { WireMessageDirection, WireMessageObserver } from '../connection/channel';\n\ninterface RequestCorrelation {\n readonly method: string;\n readonly timeMs: number;\n}\n\nconst REQUEST_CORRELATION_RETENTION_MS = 30 * 60_000;\nconst MAX_REQUEST_CORRELATIONS = 4096;\n\nexport class EndpointTrafficInspector {\n private readonly _outboundRequests = new Map<string, RequestCorrelation>();\n private readonly _inboundRequests = new Map<string, RequestCorrelation>();\n\n public readonly observe: WireMessageObserver = (direction, message) => {\n this._onMessage(direction, message);\n };\n\n constructor(\n private readonly _nodeId: string,\n private readonly _portId: string,\n private readonly _emit: (event: TrafficTransitEvent) => void,\n private readonly _isObserved: () => boolean,\n ) { }\n\n public dispose(): void {\n this._outboundRequests.clear();\n this._inboundRequests.clear();\n }\n\n private _onMessage(\n direction: WireMessageDirection,\n message: JsonRpcMessage,\n ): void {\n const now = Date.now();\n this._pruneRequestCorrelations(now);\n const publiclyObserved = this._isObserved();\n if (!publiclyObserved) this.dispose();\n let transit: TrafficTransitEvent;\n const endpoint = this._endpoint('id' in message ? message.id ?? undefined : undefined);\n const base = {\n type: 'transit' as const,\n timeMs: now,\n nodeId: this._nodeId,\n ...(direction === 'inbound' ? { in: endpoint } : { out: endpoint }),\n disposition: direction === 'inbound' ? 'consumed' as const : 'forwarded' as const,\n };\n if (isRequest(message)) {\n const correlation: RequestCorrelation = {\n method: message.method,\n timeMs: now,\n };\n if (publiclyObserved) {\n const map = this._requestMap(direction);\n const key = requestKey(message.id);\n map.delete(key);\n map.set(key, correlation);\n }\n transit = {\n ...base,\n kind: 'request',\n method: message.method,\n params: message.params,\n };\n } else if (isResponse(message)) {\n const responseMap = direction === 'inbound'\n ? this._outboundRequests\n : this._inboundRequests;\n const key = requestKey(message.id);\n const correlation = responseMap.get(key);\n responseMap.delete(key);\n transit = {\n ...base,\n kind: 'response',\n method: correlation?.method,\n result: 'result' in message ? message.result : undefined,\n error: 'error' in message ? message.error : undefined,\n };\n } else if (isNotification(message) && message.method === STREAM_METHOD) {\n const params = message.params as StreamSendParams | undefined;\n const streamEndpoint = this._endpoint(params?.requestId);\n transit = {\n ...base,\n ...(direction === 'inbound' ? { in: streamEndpoint } : { out: streamEndpoint }),\n kind: 'stream',\n method: STREAM_METHOD,\n params: message.params,\n };\n } else {\n transit = {\n ...base,\n kind: 'notification',\n method: message.method,\n params: message.params,\n };\n }\n\n function requestKey(requestId: RequestId | null): string {\n return JSON.stringify([typeof requestId, requestId]);\n }\n\n this._emit(transit);\n }\n\n private _requestMap(\n direction: WireMessageDirection,\n ): Map<string, RequestCorrelation> {\n return direction === 'outbound'\n ? this._outboundRequests\n : this._inboundRequests;\n }\n\n private _endpoint(requestId: RequestId | undefined) {\n return {\n edgeId: this._portId,\n portId: this._portId,\n ...(requestId !== undefined ? { requestId } : {}),\n } as const;\n }\n\n private _pruneRequestCorrelations(timeMs: number): void {\n this._pruneRequestMap(this._outboundRequests, timeMs);\n this._pruneRequestMap(this._inboundRequests, timeMs);\n }\n\n private _pruneRequestMap(\n map: Map<string, RequestCorrelation>,\n timeMs: number,\n ): void {\n while (map.size !== 0) {\n const first = map.entries().next().value as\n | [string, RequestCorrelation]\n | undefined;\n if (\n first === undefined\n || (\n map.size <= MAX_REQUEST_CORRELATIONS\n && timeMs - first[1].timeMs <= REQUEST_CORRELATION_RETENTION_MS\n )\n ) {\n return;\n }\n map.delete(first[0]);\n }\n }\n\n}\n","import type { LinkRpcConnection, InterfaceRegistration } from '../connection/linkRpcConnection';\nimport { EndpointTrafficInspector } from './endpointTrafficInspector';\nimport type { InspectionSource, TopologyFragment } from './inspectionHost';\nimport type { TopologyLink, TopologyNode, TrafficTransitEvent } from './inspection.interfaces';\n\nexport interface TrackConnectionOptions {\n readonly portId: string;\n readonly label?: string;\n /** Explicit peer identity; foreign protocols need not support discovery. */\n readonly peer?: {\n readonly nodeId: string;\n readonly portId: string;\n readonly label?: string;\n };\n readonly transport?: TopologyLink['transport'];\n}\n\nexport class ConnectionInspectionSource<TIn, TOut> implements InspectionSource {\n constructor(\n private readonly _connection: LinkRpcConnection<TIn, TOut>,\n private readonly _nodeId: string,\n private readonly _options: TrackConnectionOptions,\n private readonly _isObserved: () => boolean,\n ) {}\n\n public snapshotTopology(): TopologyFragment {\n const { portId, label, peer, transport } = this._options;\n const nodes: TopologyNode[] = [{\n nodeId: this._nodeId,\n ports: [{ portId, ...(label === undefined ? {} : { label }) }],\n }];\n const links: TopologyLink[] = [];\n if (peer !== undefined) {\n nodes.push({\n nodeId: peer.nodeId, kind: 'endpoint',\n ...(peer.label === undefined ? {} : { label: peer.label }),\n ports: [{ portId: peer.portId }],\n });\n links.push({\n from: { nodeId: this._nodeId, portId },\n to: { nodeId: peer.nodeId, portId: peer.portId },\n peerState: 'identified',\n ...(transport === undefined ? {} : { transport }),\n });\n }\n return { nodes, links, routes: [] };\n }\n\n public onTopologyChanged(_listener: () => void): InterfaceRegistration {\n return { dispose: () => {} };\n }\n\n public observeTraffic(listener: (event: TrafficTransitEvent) => void): InterfaceRegistration {\n const inspector = new EndpointTrafficInspector(\n this._nodeId, this._options.portId, listener, this._isObserved,\n );\n const observation = this._connection.observeWireMessages(inspector.observe);\n return { dispose: () => {\n observation.dispose();\n inspector.dispose();\n } };\n }\n}\n","import type { LinkRpcConnection, InterfaceRegistration } from '../connection/linkRpcConnection';\nimport type { StreamApi } from '../connection/interfaceDefinition';\nimport { bytesToBase64Url } from '../crypto/cryptoProvider';\nimport { nodeInterface } from './node.interfaces';\nimport {\n topologyInterface, trafficInterface,\n type ParticipantDescriptorSource, type TopologyGraph, type TopologyNode,\n type TrafficEvent, type TrafficTransitEvent, type TrafficWatchResult,\n} from './inspection.interfaces';\nimport {\n BoundedTrafficSubscription, type TrafficSubscription, type TrafficSubscriptionOptions,\n} from './boundedTrafficSubscription';\nimport { TrafficWatchFlowTracker } from './trafficFlowFilter';\nimport { EndpointTrafficInspector } from './endpointTrafficInspector';\nimport { ConnectionInspectionSource, type TrackConnectionOptions } from './connectionInspectionSource';\n\nexport interface TopologyFragment {\n readonly nodes: TopologyGraph['nodes'];\n readonly links: TopologyGraph['links'];\n readonly routes: TopologyGraph['routes'];\n}\n\nexport interface InspectionSource {\n snapshotTopology(): TopologyFragment;\n onTopologyChanged(listener: () => void): InterfaceRegistration;\n /** Includes watch control traffic so self-observation can be excluded. */\n observeTraffic(listener: (event: TrafficTransitEvent) => void): InterfaceRegistration;\n}\n\nexport interface InspectionHostOptions {\n readonly nodeId: string;\n readonly kind?: 'endpoint' | 'hub';\n readonly label?: string;\n readonly descriptors?: readonly ParticipantDescriptorSource[];\n}\n\nexport interface InspectionExposureOptions {\n readonly serviceId: string;\n readonly portId?: string;\n readonly descriptors?: readonly ParticipantDescriptorSource[];\n /** False when the source already supplies the service's route. */\n readonly includeRoute?: boolean;\n}\n\nexport interface InspectionTrafficSource {\n observe(listener: (event: TrafficTransitEvent) => void): InterfaceRegistration;\n}\n\ninterface LazyTrafficSource {\n readonly source: InspectionTrafficSource;\n observation?: InterfaceRegistration;\n}\n\n/** A shared inspection scope, independent of both routing and its RPC connections. */\nexport class InspectionHost {\n private readonly _sources = new Map<InspectionSource, InterfaceRegistration>();\n private readonly _trackedConnections = new Set<InterfaceRegistration>();\n private readonly _bindings = new Set<InspectionBinding>();\n private readonly _subscribers = new Set<BoundedTrafficSubscription>();\n private readonly _observers = new Set<(event: TrafficTransitEvent) => void>();\n private readonly _topologyListeners = new Set<() => void>();\n private readonly _trafficSources = new Set<LazyTrafficSource>();\n private readonly _trafficWatches = new TrafficWatchFlowTracker();\n private _disposed = false;\n\n public readonly nodeId: string;\n\n constructor(private readonly _options: InspectionHostOptions) {\n this.nodeId = _options.nodeId;\n }\n\n public get observerCount(): number {\n return this._subscribers.size + this._observers.size;\n }\n\n public addSource(source: InspectionSource): InterfaceRegistration {\n this._assertActive();\n if (this._sources.has(source)) throw new Error('Inspection source is already registered');\n const readPorts = () => new Set(source.snapshotTopology().nodes.flatMap(node =>\n node.ports.map(port => port.portId)));\n let ports = readPorts();\n const topology = source.onTopologyChanged(() => {\n const nextPorts = readPorts();\n const removed = [...ports].filter(port => !nextPorts.has(port));\n ports = nextPorts;\n this._forgetUnusedPorts(removed);\n this._invalidateTopology();\n });\n let traffic: InterfaceRegistration;\n try {\n traffic = source.observeTraffic(event => this.publishTransit(event));\n } catch (error) {\n topology.dispose();\n throw error;\n }\n const registration = {\n dispose: () => {\n if (this._sources.get(source) !== registration) return;\n this._sources.delete(source);\n topology.dispose();\n traffic.dispose();\n this._forgetUnusedPorts([...ports]);\n this._invalidateTopology();\n },\n };\n this._sources.set(source, registration);\n this._invalidateTopology();\n return registration;\n }\n\n public trackConnection<TIn, TOut>(\n connection: LinkRpcConnection<TIn, TOut>,\n options: TrackConnectionOptions,\n ): InterfaceRegistration {\n this._assertActive();\n if (this.getGraph('').nodes.some(node =>\n node.ports.some(port => port.portId === options.portId))) {\n throw new Error(`Inspection port \"${options.portId}\" is already registered`);\n }\n const source = new ConnectionInspectionSource(\n connection, this.nodeId, options, () => this.observerCount !== 0,\n );\n const registration = this.addSource(source);\n let close: InterfaceRegistration;\n try {\n close = connection.onDidClose(() => result.dispose());\n } catch (error) {\n registration.dispose();\n throw error;\n }\n const result = {\n dispose: () => {\n this._trackedConnections.delete(result);\n close.dispose();\n registration.dispose();\n },\n };\n this._trackedConnections.add(result);\n return result;\n }\n\n public expose<TIn, TOut>(\n connection: LinkRpcConnection<TIn, TOut>,\n options: InspectionExposureOptions,\n ): InterfaceRegistration {\n this._assertActive();\n const portId = options.portId ?? createPortId();\n const binding = new InspectionBinding(portId);\n const registrations: InterfaceRegistration[] = [];\n this._bindings.add(binding);\n const registerOptions = { serviceId: options.serviceId };\n try {\n // An exposure observes only watch-control flows, not frontend business traffic.\n const controls = new EndpointTrafficInspector(\n this.nodeId, portId, event => this._trafficWatches.accept(event), () => false,\n );\n registrations.push(connection.observeWireMessages(controls.observe));\n registrations.push({ dispose: () => controls.dispose() });\n registrations.push(connection.registerInspection(nodeInterface, {\n getNodeId: () => ({\n nodeId: this.nodeId,\n portId,\n ...((options.descriptors ?? this._options.descriptors) === undefined ? {} : {\n descriptors: [...(options.descriptors ?? this._options.descriptors ?? [])],\n }),\n }),\n }, registerOptions));\n registrations.push(connection.registerInspection(topologyInterface, {\n getGraph: () => this.getGraph(\n options.serviceId, options.includeRoute === false ? undefined : portId,\n ),\n watchGraph: (_params, _ctx, stream) => this._watchGraph(binding, stream),\n }, registerOptions));\n registrations.push(connection.registerInspection(trafficInterface, {\n watch: (params, _ctx, stream) => this._watchTraffic(binding, params, stream),\n watchWithPayloads: (params, _ctx, stream) => this._watchTraffic(binding, params, stream),\n }, registerOptions));\n } catch (error) {\n for (const registration of registrations.reverse()) registration.dispose();\n this._bindings.delete(binding);\n throw error;\n }\n binding.onDispose = () => {\n this._bindings.delete(binding);\n for (const registration of registrations.reverse()) registration.dispose();\n this._forgetUnusedPorts([portId]);\n this._invalidateTopology();\n };\n registrations.push(connection.onDidClose(() => binding.dispose()));\n this._invalidateTopology();\n return binding;\n }\n\n public getGraph(observerServiceId: string, routePortId?: string): TopologyGraph {\n this._assertActive();\n const nodes = new Map<string, TopologyNode>();\n const mergeNode = (node: TopologyNode): void => {\n const previous = nodes.get(node.nodeId);\n const ports = new Map(previous?.ports.map(port => [port.portId, port]));\n for (const port of node.ports) ports.set(port.portId, { ...ports.get(port.portId), ...port });\n nodes.set(node.nodeId, { ...previous, ...node, ports: [...ports.values()] });\n };\n mergeNode({\n nodeId: this.nodeId,\n kind: this._options.kind ?? 'endpoint',\n ...(this._options.label === undefined ? {} : { label: this._options.label }),\n ...(this._options.descriptors === undefined ? {} : { descriptors: [...this._options.descriptors] }),\n ports: [],\n });\n const links: TopologyGraph['links'] = [];\n const routes: TopologyGraph['routes'] = [];\n for (const source of this._sources.keys()) {\n const fragment = source.snapshotTopology();\n for (const node of fragment.nodes) mergeNode(node);\n links.push(...fragment.links);\n routes.push(...fragment.routes);\n }\n for (const binding of this._bindings) {\n mergeNode({ nodeId: this.nodeId, ports: [{ portId: binding.portId }] });\n }\n if (routePortId !== undefined) {\n routes.push({\n serviceId: observerServiceId, nodeId: this.nodeId,\n portId: routePortId, match: 'exact',\n });\n }\n return {\n observerServiceId, entryNodeId: this.nodeId,\n nodes: [...nodes.values()], links, routes,\n };\n }\n\n public publishTransit(event: TrafficTransitEvent): void {\n if (this._disposed || this._trafficWatches.accept(event)) return;\n for (const observer of [...this._observers]) {\n try {\n observer(event);\n } catch {\n // Diagnostic observers must not interrupt the observed connection.\n }\n }\n for (const subscriber of this._subscribers) subscriber.enqueue(event);\n }\n\n public subscribe(\n options: TrafficSubscriptionOptions,\n send: (event: TrafficEvent) => Promise<void>,\n ): TrafficSubscription {\n this._assertActive();\n if (options.trafficIgnoreKey !== undefined && !this._trafficWatches.claim(options.trafficIgnoreKey)) {\n throw new Error('Traffic watch request was not observed before subscription');\n }\n const subscriber = new BoundedTrafficSubscription(options, send, () => {\n this._subscribers.delete(subscriber);\n this._stopUnusedTrafficSources();\n });\n this._subscribers.add(subscriber);\n try {\n this._startTrafficSources();\n } catch (error) {\n subscriber.dispose();\n throw error;\n }\n return subscriber;\n }\n\n public observeTraffic(observer: (event: TrafficTransitEvent) => void): InterfaceRegistration {\n this._assertActive();\n this._observers.add(observer);\n const registration = { dispose: () => {\n this._observers.delete(observer);\n this._stopUnusedTrafficSources();\n } };\n try {\n this._startTrafficSources();\n } catch (error) {\n registration.dispose();\n throw error;\n }\n return registration;\n }\n\n public addTrafficSource(source: InspectionTrafficSource): InterfaceRegistration {\n this._assertActive();\n const entry: LazyTrafficSource = { source };\n this._trafficSources.add(entry);\n try {\n this._startTrafficSources();\n } catch (error) {\n this._trafficSources.delete(entry);\n throw error;\n }\n return { dispose: () => {\n this._trafficSources.delete(entry);\n entry.observation?.dispose();\n entry.observation = undefined;\n } };\n }\n\n public dispose(): void {\n if (this._disposed) return;\n this._disposed = true;\n for (const binding of [...this._bindings]) binding.dispose();\n for (const subscriber of [...this._subscribers]) subscriber.dispose();\n this._observers.clear();\n this._stopUnusedTrafficSources();\n this._trafficSources.clear();\n for (const connection of [...this._trackedConnections]) connection.dispose();\n for (const source of [...this._sources.values()]) source.dispose();\n this._topologyListeners.clear();\n this._trafficWatches.clear();\n }\n\n private _startTrafficSources(): void {\n if (this.observerCount === 0) return;\n for (const entry of this._trafficSources) {\n entry.observation ??= entry.source.observe(event => this.publishTransit(event));\n }\n }\n\n private _stopUnusedTrafficSources(): void {\n if (this.observerCount !== 0) return;\n for (const entry of this._trafficSources) {\n entry.observation?.dispose();\n entry.observation = undefined;\n }\n }\n\n private _invalidateTopology(): void {\n if (this._disposed) return;\n for (const listener of this._topologyListeners) listener();\n }\n\n private _forgetUnusedPorts(portIds: readonly string[]): void {\n if (this._disposed) return;\n const remaining = new Set(this.getGraph('').nodes.flatMap(node => node.ports.map(port => port.portId)));\n for (const portId of portIds) {\n if (!remaining.has(portId)) this._trafficWatches.forgetPort(portId);\n }\n }\n\n private _watchGraph<T>(\n binding: InspectionBinding,\n stream: StreamApi<T, Record<string, never>>,\n ): Promise<Record<string, never>> {\n return new Promise((resolve, reject) => {\n let pending = false;\n let active = true;\n const finish = () => {\n active = false;\n this._topologyListeners.delete(invalidate);\n stream.signal.removeEventListener('abort', finish);\n binding.abort.signal.removeEventListener('abort', finish);\n resolve({});\n };\n const invalidate = () => {\n if (pending || !active) return;\n pending = true;\n queueMicrotask(() => {\n pending = false;\n if (!active) return;\n void stream.send({}).catch(error => {\n reject(error);\n finish();\n });\n });\n };\n this._topologyListeners.add(invalidate);\n stream.signal.addEventListener('abort', finish, { once: true });\n binding.abort.signal.addEventListener('abort', finish, { once: true });\n if (stream.signal.aborted || binding.abort.signal.aborted) finish();\n });\n }\n\n private async _watchTraffic<T>(\n binding: InspectionBinding,\n options: TrafficSubscriptionOptions,\n stream: StreamApi<T, TrafficEvent>,\n ): Promise<TrafficWatchResult> {\n const subscription = this.subscribe(options, event => stream.send(event));\n const dispose = () => subscription.dispose();\n stream.signal.addEventListener('abort', dispose, { once: true });\n binding.abort.signal.addEventListener('abort', dispose, { once: true });\n if (stream.signal.aborted || binding.abort.signal.aborted) dispose();\n try {\n return await subscription.closed;\n } finally {\n stream.signal.removeEventListener('abort', dispose);\n binding.abort.signal.removeEventListener('abort', dispose);\n subscription.dispose();\n }\n }\n\n private _assertActive(): void {\n if (this._disposed) throw new Error('Inspection host is disposed');\n }\n}\n\nclass InspectionBinding implements InterfaceRegistration {\n public readonly abort = new AbortController();\n public onDispose: () => void = () => {};\n constructor(public readonly portId: string) {}\n public dispose(): void {\n if (this.abort.signal.aborted) return;\n this.abort.abort();\n this.onDispose();\n }\n}\n\nfunction createPortId(): string {\n const bytes = new Uint8Array(16);\n globalThis.crypto.getRandomValues(bytes);\n return `port:${bytesToBase64Url(bytes)}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAUA,MAAM,4BAAY,IAAI,IAAI;CACtB;CAAQ;CACR;CAAc;CAAY;CAC1B;CAAS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