@hediet/linkrpc-cli 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +370 -0
- package/dist/chunks/cli-D_-vlAa2.js +6073 -0
- package/dist/chunks/cli-D_-vlAa2.js.map +1 -0
- package/dist/chunks/runApprovalUi-BvJZdjKm.js +715 -0
- package/dist/chunks/runApprovalUi-BvJZdjKm.js.map +1 -0
- package/dist/chunks/runComplete-BkQwzPbF.js +3949 -0
- package/dist/chunks/runComplete-BkQwzPbF.js.map +1 -0
- package/dist/chunks/runUi-D-8LMU4F.js +1143 -0
- package/dist/chunks/runUi-D-8LMU4F.js.map +1 -0
- package/dist/chunks/scroll-BTzAYh4N.js +93 -0
- package/dist/chunks/scroll-BTzAYh4N.js.map +1 -0
- package/dist/hub.d.ts +1 -0
- package/dist/hub.js +8 -0
- package/dist/hub.js.map +1 -0
- package/dist/index.d.ts +381 -0
- package/dist/index.js +2 -0
- package/dist/linkrpc.d.ts +1 -0
- package/dist/linkrpc.js +8 -0
- package/dist/linkrpc.js.map +1 -0
- package/dist/rpc.d.ts +1 -0
- package/dist/rpc.js +8 -0
- package/dist/rpc.js.map +1 -0
- package/package.json +45 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli-D_-vlAa2.js","names":["fetchSchema","fetchSchema","CLAIM_METHOD","_untilSignalled","traceMessageTransport","fetchSchema","toJsonValue","participantLabel","fetchSchema","_untilSignalled","hubConnection","connectEndpoint"],"sources":["../../src/output.ts","../../src/suggest.ts","../../src/schemaLookup.ts","../../src/commands/call.ts","../../src/commands/batch.ts","../../src/commands/tunnel.ts","../../src/commands/connectionBroker.ts","../../src/commands/connectionBrokerClient.ts","../../src/commands/connectionBrokerProcess.ts","../../src/duration.ts","../../src/commands/checkCompat.ts","../../src/commands/codegen.ts","../../src/completions/shellScripts.ts","../../src/commands/completions.ts","../../src/commands/defaults.ts","../../src/commands/hash.ts","../../src/commands/internalComplete.ts","../../src/commands/displayForest.ts","../../src/commands/jsonPatch.ts","../../src/commands/stateJsonl.ts","../../src/commands/ls.ts","../../src/commands/topology.ts","../../src/commands/ping.ts","../../src/commands/participantWatch.ts","../../src/commands/schema.ts","../../src/commands/serve.ts","../../src/commands/connectAs.ts","../../src/commands/connectAsTransports.ts","../../src/commands/mcpForward.ts","../../src/commands/jsonRpcStdio.ts","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/logging/logging.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/debugLocation.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/debugName.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/observables/baseObservable.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/commonFacade/deps.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/disposables.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/observables/derivedImpl.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/observables/derived.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/reactions/createEffectImpl.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/reactions/createEffect.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/base.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/transaction.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/observables/observableValue.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/observables/observableFromEvent.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/utils/utils.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/logging/consoleObservableLogger.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/logging/debugGetDependencyGraph.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/index.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/utils/promise.js","../../src/approvalPresentation.ts","../../src/commands/approval.ts","../../src/commands/identity.ts","../../src/engine/runHub.ts","../../src/methodHelp.ts","../../src/paramFlags.ts","../../src/cli.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\n\n/**\n * Read params either from a `--params <json>` argument (treated as inline\n * JSON) or `--params -` (read from stdin). `undefined` if neither was given.\n */\nexport function readParamsArg(value: string | undefined): unknown {\n if (value === undefined) return undefined;\n const text = value === \"-\" ? readFileSync(0, \"utf8\") : value;\n const trimmed = text.trim();\n if (trimmed.length === 0) return undefined;\n try {\n return JSON.parse(trimmed);\n } catch (e) {\n throw new Error(`--params: invalid JSON (${(e as Error).message})`);\n }\n}\n\nexport function formatJson(v: unknown): string {\n if (v === undefined) return \"undefined\";\n return JSON.stringify(v, null, 2);\n}\n\n/** Stringify a value for one-line tabular output. */\nexport function oneLine(v: unknown): string {\n if (v === undefined) return \"\";\n if (typeof v === \"string\") return v;\n return JSON.stringify(v);\n}\n","/**\n * \"Did you mean…\" suggestions for failed `hub call` / `hub notify` invocations.\n *\n * Drives off a static snapshot of the hub (`HubSnapshot`) so the formatter is\n * pure-functional and exhaustively testable with literal strings. A snapshot\n * is built by walking the bus once (`HubSnapshot.load`) on the error path.\n *\n * The matrix is resolved left-to-right (serviceId, interfaceId, method): the\n * first token that doesn't resolve dictates the suggestion scope, and we never\n * propose replacements for positions to its left.\n */\nimport { MethodRefWithOptHash } from './methodRef';\nimport {\n fetchSchema,\n walkHub,\n type CliChannel,\n} from '@hediet/linkrpc-client';\n\n// ---------------------------------------------------------------------------\n// HubSnapshot\n// ---------------------------------------------------------------------------\n\nexport interface SnapshotEntry {\n /** Empty string = root. */\n readonly serviceId: string;\n readonly interfaceId: string;\n readonly hash: string;\n readonly methods: readonly string[];\n}\n\nconst _SYSTEM_PREFIX = 'hubrpc.';\n\nfunction _isSystemInterface(id: string): boolean {\n return id.startsWith(_SYSTEM_PREFIX);\n}\n\nfunction _isUserInterface(id: string): boolean {\n return !_isSystemInterface(id);\n}\n\n/**\n * Indexed view of the bus's directory + per-interface methods. Constructed\n * directly from a list of entries (tests) or by walking a live channel\n * (`HubSnapshot.load`). Read-only after construction.\n */\nexport class HubSnapshot {\n private readonly _byService = new Map<string, Map<string, SnapshotEntry>>();\n private readonly _byInterface = new Map<string, string[]>();\n private readonly _byMethodName = new Map<string, { serviceId: string; interfaceId: string; }[]>();\n\n constructor(public readonly entries: readonly SnapshotEntry[]) {\n for (const e of entries) {\n let byIface = this._byService.get(e.serviceId);\n if (!byIface) {\n byIface = new Map();\n this._byService.set(e.serviceId, byIface);\n }\n byIface.set(e.interfaceId, e);\n\n const hosts = this._byInterface.get(e.interfaceId) ?? [];\n if (!hosts.includes(e.serviceId)) hosts.push(e.serviceId);\n this._byInterface.set(e.interfaceId, hosts);\n\n for (const m of e.methods) {\n const locs = this._byMethodName.get(m) ?? [];\n locs.push({ serviceId: e.serviceId, interfaceId: e.interfaceId });\n this._byMethodName.set(m, locs);\n }\n }\n }\n\n /** All serviceIds present on the bus, in encounter order (\"\" = root). */\n services(): readonly string[] {\n return [...this._byService.keys()];\n }\n\n /** All distinct interface ids (system + user), in encounter order. */\n interfaces(): readonly string[] {\n return [...this._byInterface.keys()];\n }\n\n interfacesOnService(serviceId: string): readonly string[] {\n const m = this._byService.get(serviceId);\n return m ? [...m.keys()] : [];\n }\n\n servicesHostingInterface(interfaceId: string): readonly string[] {\n return this._byInterface.get(interfaceId) ?? [];\n }\n\n methodsOn(serviceId: string, interfaceId: string): readonly string[] {\n return this._byService.get(serviceId)?.get(interfaceId)?.methods ?? [];\n }\n\n locationsOfMethod(name: string): readonly { serviceId: string; interfaceId: string; }[] {\n return this._byMethodName.get(name) ?? [];\n }\n\n /**\n * Walk the live bus once and fetch the schema for every (service, interface)\n * pair in parallel. Failures on individual schema fetches are absorbed —\n * the affected entry just ends up with `methods: []`, so it still\n * participates in service/interface-level suggestions.\n */\n static async load(channel: CliChannel): Promise<HubSnapshot> {\n const listings = await walkHub(channel);\n const entries = await Promise.all(listings.map(async (l): Promise<SnapshotEntry> => {\n try {\n const schema = await fetchSchema(\n channel,\n l.interfaceId,\n l.hash,\n l.serviceId || undefined,\n );\n return {\n serviceId: l.serviceId,\n interfaceId: l.interfaceId,\n hash: l.hash,\n methods: Object.keys(schema.methods),\n };\n } catch {\n return {\n serviceId: l.serviceId,\n interfaceId: l.interfaceId,\n hash: l.hash,\n methods: [],\n };\n }\n }));\n return new HubSnapshot(entries);\n }\n}\n\n// ---------------------------------------------------------------------------\n// formatSuggestion (entry point)\n// ---------------------------------------------------------------------------\n\nexport interface SuggestionInput {\n readonly ref: MethodRefWithOptHash;\n readonly snapshot: HubSnapshot;\n /** Verb embedded in copy-paste lines (`hub call` vs `hub notify`). */\n readonly verb: 'call' | 'notify';\n /** CLI binary name; defaults to `hub`. */\n readonly tool?: string;\n}\n\ninterface _Ctx {\n ref: MethodRefWithOptHash;\n snapshot: HubSnapshot;\n verb: 'call' | 'notify';\n tool: string;\n}\n\n/**\n * Compose a multi-line \"Did you mean…\" message tailored to the failed ref.\n * The returned string has no trailing newline and no `linkrpc:` prefix (the\n * outer error path adds those).\n */\nexport function formatSuggestion(input: SuggestionInput): string {\n const ctx: _Ctx = {\n ref: input.ref,\n snapshot: input.snapshot,\n verb: input.verb,\n tool: input.tool ?? 'hub',\n };\n if (ctx.ref.serviceId !== undefined && ctx.ref.interfaceId !== undefined) {\n return _suggestForm3(ctx);\n }\n if (ctx.ref.interfaceId !== undefined) {\n return _suggestForm2(ctx);\n }\n return _suggestForm1(ctx);\n}\n\nfunction _qualify(ctx: _Ctx, s: string, i: string, m: string): string {\n return `${ctx.tool} ${ctx.verb} ${s}::${i}::${m}`;\n}\n\n// ---------------------------------------------------------------------------\n// Form 1: `<method>` (bare token, no preset)\n// ---------------------------------------------------------------------------\n\nfunction _suggestForm1(ctx: _Ctx): string {\n const { ref, snapshot } = ctx;\n const token = ref.methodName;\n\n // A1: token is itself a serviceId\n if (token !== '' && snapshot.services().includes(token)) {\n const samples = _sampleCallsForService(ctx, token, 3);\n const lines = [`\"${token}\" is a serviceId, not a method.`];\n lines.push(' See its interfaces:');\n lines.push(` ${ctx.tool} ls --service ${token}`);\n if (samples.length > 0) {\n lines.push(' Or call one:');\n for (const s of samples) lines.push(` ${s}`);\n }\n return lines.join('\\n');\n }\n\n // A2: token is an interfaceId\n if (snapshot.interfaces().includes(token) && _isUserInterface(token)) {\n const hosts = snapshot.servicesHostingInterface(token).filter((s) => s !== '');\n const samples = _sampleCallsForInterface(ctx, token, 3);\n const lines = [\n `\"${token}\" is an interface, not a method. It's hosted on services: ${hosts.join(', ')}.`,\n ];\n if (samples.length > 0) {\n lines.push(' Try a call:');\n for (const s of samples) lines.push(` ${s}`);\n }\n return lines.join('\\n');\n }\n\n // A3/A4: token is exactly a method name on one or more interfaces\n const locs = snapshot\n .locationsOfMethod(token)\n .filter((l) => _isUserInterface(l.interfaceId));\n if (locs.length > 0) {\n const lines = [`\"${token}\" is not callable without an interface (no preset is set).`];\n lines.push(' Did you mean:');\n for (const l of locs.slice(0, 5)) {\n lines.push(` ${_qualify(ctx, l.serviceId, l.interfaceId, token)}`);\n }\n return lines.join('\\n');\n }\n\n // A5/A6/A7: fuzzy fallback\n return _suggestForm1Fuzzy(ctx);\n}\n\nfunction _suggestForm1Fuzzy(ctx: _Ctx): string {\n const { snapshot } = ctx;\n const token = ctx.ref.methodName;\n\n const methodHits = _rankAllMethods(snapshot, token, 3);\n const ifaceHits = _rankAllInterfaces(snapshot, token, 3);\n const svcHits = _rankServices(snapshot, token, 3);\n\n const lines = [`\"${token}\" matches no known service, interface, or method.`];\n if (methodHits.length > 0) {\n lines.push(' Closest methods:');\n for (const h of methodHits) {\n lines.push(` ${_qualify(ctx, h.serviceId, h.interfaceId, h.name)}`);\n }\n }\n if (ifaceHits.length > 0) {\n lines.push(' Closest interfaces:');\n for (const id of ifaceHits) {\n const sampleSvc = snapshot\n .servicesHostingInterface(id)\n .find((s) => s !== '') ?? snapshot.servicesHostingInterface(id)[0];\n lines.push(` ${id} (try ${ctx.tool} ${ctx.verb} ${sampleSvc ?? ''}::${id}::<method>)`);\n }\n }\n if (svcHits.length > 0) {\n lines.push(' Closest services:');\n for (const s of svcHits) {\n lines.push(` ${s} (try ${ctx.tool} ls --service ${s})`);\n }\n }\n if (methodHits.length === 0 && ifaceHits.length === 0 && svcHits.length === 0) {\n lines.push(` Tip: run \\`${ctx.tool} ls\\` to see what's available.`);\n }\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Form 2: `<interface>::<method>`\n// ---------------------------------------------------------------------------\n\nfunction _suggestForm2(ctx: _Ctx): string {\n const { ref, snapshot } = ctx;\n const iface = ref.interfaceId!;\n const method = ref.methodName;\n const hostsOfIface = snapshot.servicesHostingInterface(iface);\n\n if (hostsOfIface.length === 0) {\n // Interface unknown.\n // B3: first token is actually a serviceId\n if (iface !== '' && snapshot.services().includes(iface)) {\n // B3a: the second token is an exact method name on that service\n // (e.g. `azure-cli::runCommand` → fully-qualified suggestion).\n const locs = snapshot\n .locationsOfMethod(method)\n .filter((l) => l.serviceId === iface && _isUserInterface(l.interfaceId));\n if (locs.length > 0) {\n const lines = [\n `Interface \"${method}\" not found on service \"${iface}\", `\n + `but \"${method}\" is a method name there.`,\n ];\n lines.push(' Did you mean:');\n for (const l of locs.slice(0, 3)) {\n lines.push(` ${_qualify(ctx, l.serviceId, l.interfaceId, method)}`);\n }\n return lines.join('\\n');\n }\n\n // B3b: prefix or full enumeration — list interfaces on the service.\n // Typing `vscode::vscode.` is navigation, not a typo; show what's\n // available rather than guessing methods.\n return _formatInterfaceListOnService(ctx, iface, method);\n }\n\n // B2: fuzzy interfaces, boost ones where `method` exists\n const candidates = _rankInterfacesWithMethodBoost(snapshot, iface, method, 3);\n const lines = [`Interface \"${iface}\" not found.`];\n if (candidates.length > 0) {\n lines.push(' Did you mean:');\n for (const c of candidates) {\n lines.push(` ${_qualify(ctx, c.serviceId, c.interfaceId, c.methodToTry)}`);\n }\n } else {\n lines.push(` Tip: run \\`${ctx.tool} ls\\` to see what's available.`);\n }\n return lines.join('\\n');\n }\n\n // Interface valid on >=1 service. Method missing on all of them.\n // B1/B4: fuzzy methods across hosts\n const fuzzy = _rankMethodsOnInterface(snapshot, iface, method, 3);\n if (fuzzy.length > 0) {\n const where = hostsOfIface.length === 1 ? ` (service: ${hostsOfIface[0]})` : '';\n const lines = [`Method \"${method}\" not found on interface \"${iface}\"${where}.`];\n lines.push(' Did you mean:');\n for (const f of fuzzy) {\n lines.push(` ${_qualify(ctx, f.serviceId, iface, f.methodName)}`);\n }\n return lines.join('\\n');\n }\n\n // B5: enumerate everything available under this interface\n const lines = [`Method \"${method}\" not found on interface \"${iface}\".`];\n lines.push(' Available methods:');\n let count = 0;\n for (const s of hostsOfIface) {\n for (const m of snapshot.methodsOn(s, iface)) {\n if (count >= 12) break;\n lines.push(` ${_qualify(ctx, s, iface, m)}`);\n count++;\n }\n if (count >= 12) break;\n }\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Form 3: `<svc>::<iface>::<method>`\n// ---------------------------------------------------------------------------\n\nfunction _suggestForm3(ctx: _Ctx): string {\n const { ref, snapshot } = ctx;\n const svc = ref.serviceId!;\n const iface = ref.interfaceId!;\n const method = ref.methodName;\n\n // C4/C7: service unknown\n if (!snapshot.services().includes(svc)) {\n const hits = _rankServices(snapshot, svc, 3, (cand) => {\n const ifaces = snapshot.interfacesOnService(cand);\n if (ifaces.includes(iface) && snapshot.methodsOn(cand, iface).includes(method)) {\n return 200;\n }\n if (ifaces.includes(iface)) return 100;\n return 0;\n });\n const lines = [`Service \"${svc}\" not found.`];\n if (hits.length > 0) {\n lines.push(' Did you mean:');\n for (const h of hits) {\n const ifacesOnH = snapshot.interfacesOnService(h);\n if (ifacesOnH.includes(iface) && snapshot.methodsOn(h, iface).includes(method)) {\n lines.push(` ${_qualify(ctx, h, iface, method)}`);\n } else {\n lines.push(` ${h} (try ${ctx.tool} ls --service ${h})`);\n }\n }\n } else {\n lines.push(` Tip: run \\`${ctx.tool} ls\\` to see what's available.`);\n }\n return lines.join('\\n');\n }\n\n // Service valid; check interface.\n const ifacesOnSvc = snapshot.interfacesOnService(svc);\n if (!ifacesOnSvc.includes(iface)) {\n // C2a: navigation-style input — `iface` is a prefix of one or more\n // interfaces on this service (e.g. `vscode::vscode.::login`). List the\n // matches, using `method` as the sample call when it exists on a\n // match, else the first method of each.\n const prefixMatches = _prefixMatchesOnService(snapshot, svc, iface);\n if (prefixMatches.length > 0) {\n const lines = [\n `Interface \"${iface}\" not found on service \"${svc}\". `\n + `Interfaces starting with \"${iface}\":`,\n ];\n for (const id of prefixMatches.slice(0, 10)) {\n const sampleMethod = snapshot.methodsOn(svc, id).includes(method)\n ? method\n : (snapshot.methodsOn(svc, id)[0] ?? '<method>');\n lines.push(` ${_qualify(ctx, svc, id, sampleMethod)}`);\n }\n const otherHosts = snapshot\n .servicesHostingInterface(iface)\n .filter((s) => s !== svc && s !== '');\n if (otherHosts.length > 0) {\n lines.push(` Note: \"${iface}\" also exists on service \"${otherHosts[0]}\".`);\n }\n return lines.join('\\n');\n }\n\n // C2/C3\n const lines = [`Interface \"${iface}\" not found on service \"${svc}\".`];\n\n // C2: fuzzy interfaces on THIS service, boost those hosting `method`\n const hits = _rankInterfacesOnService(snapshot, svc, iface, method, 3);\n if (hits.length > 0) {\n lines.push(' Did you mean:');\n for (const h of hits) {\n const methodOk = snapshot.methodsOn(svc, h).includes(method);\n lines.push(` ${_qualify(ctx, svc, h, methodOk ? method : '<method>')}`);\n }\n }\n\n // C3: footnote — interface exists on another service?\n const otherHosts = snapshot\n .servicesHostingInterface(iface)\n .filter((s) => s !== svc && s !== '');\n const userIfacesOnSvc = ifacesOnSvc.filter(_isUserInterface);\n if (otherHosts.length > 0) {\n if (hits.length === 0 && userIfacesOnSvc.length > 0) {\n lines.push(` Interfaces on \"${svc}\": ${userIfacesOnSvc.join(', ')}`);\n }\n const otherSvc = otherHosts[0];\n const sampleMethod = snapshot.methodsOn(otherSvc, iface).includes(method)\n ? method\n : (snapshot.methodsOn(otherSvc, iface)[0] ?? '<method>');\n lines.push(` Note: \"${iface}\" exists on service \"${otherSvc}\". Did you mean:`);\n lines.push(` ${_qualify(ctx, otherSvc, iface, sampleMethod)}`);\n } else if (hits.length === 0) {\n if (userIfacesOnSvc.length > 0) {\n lines.push(` Interfaces on \"${svc}\": ${userIfacesOnSvc.join(', ')}`);\n } else {\n lines.push(` Tip: run \\`${ctx.tool} ls --service ${svc}\\``);\n }\n }\n return lines.join('\\n');\n }\n\n // C1: svc + iface valid; method missing\n const methods = snapshot.methodsOn(svc, iface);\n const hits = _rankNames(methods, method, 3);\n const lines = [`Method \"${method}\" not found on ${svc}::${iface}.`];\n if (hits.length > 0) {\n lines.push(' Did you mean:');\n for (const h of hits) {\n lines.push(` ${_qualify(ctx, svc, iface, h)}`);\n }\n } else if (methods.length > 0) {\n lines.push(' Available methods:');\n for (const m of methods.slice(0, 12)) {\n lines.push(` ${_qualify(ctx, svc, iface, m)}`);\n }\n } else {\n lines.push(` Tip: this interface has no methods declared.`);\n }\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Ranking / fuzzy primitives\n// ---------------------------------------------------------------------------\n\nfunction _threshold(s: string): number {\n return Math.max(1, Math.ceil(s.length / 3));\n}\n\n/** Levenshtein distance between two short strings. O(m*n) time, O(n) space. */\nfunction _lev(a: string, b: string): number {\n const m = a.length, n = b.length;\n if (m === 0) return n;\n if (n === 0) return m;\n const dp = new Array<number>(n + 1);\n for (let j = 0; j <= n; j++) dp[j] = j;\n for (let i = 1; i <= m; i++) {\n let prev = dp[0];\n dp[0] = i;\n for (let j = 1; j <= n; j++) {\n const tmp = dp[j];\n dp[j] = a[i - 1] === b[j - 1] ? prev : Math.min(prev, dp[j], dp[j - 1]) + 1;\n prev = tmp;\n }\n }\n return dp[n];\n}\n\ninterface _Ranked<T> { item: T; dist: number; boost: number; }\n\nfunction _rank<T>(\n items: readonly T[],\n key: (t: T) => string,\n query: string,\n limit: number,\n boost?: (t: T) => number,\n): T[] {\n const lower = query.toLowerCase();\n const thr = _threshold(query);\n const ranked: _Ranked<T>[] = [];\n for (const it of items) {\n const k = key(it);\n const d = _lev(k.toLowerCase(), lower);\n if (d > thr) continue;\n ranked.push({ item: it, dist: d, boost: boost ? boost(it) : 0 });\n }\n ranked.sort((a, b) =>\n (a.dist - b.dist)\n || (b.boost - a.boost)\n || key(a.item).localeCompare(key(b.item))\n );\n return ranked.slice(0, limit).map((r) => r.item);\n}\n\nfunction _rankNames(\n names: readonly string[],\n query: string,\n limit: number,\n boost?: (n: string) => number,\n): string[] {\n return _rank(names, (n) => n, query, limit, boost);\n}\n\nfunction _rankServices(\n snapshot: HubSnapshot,\n query: string,\n limit: number,\n boost?: (s: string) => number,\n): string[] {\n return _rankNames(snapshot.services().filter((s) => s !== ''), query, limit, boost);\n}\n\nfunction _rankAllInterfaces(snapshot: HubSnapshot, query: string, limit: number): string[] {\n return _rankNames(snapshot.interfaces().filter(_isUserInterface), query, limit);\n}\n\nfunction _rankAllMethods(\n snapshot: HubSnapshot,\n query: string,\n limit: number,\n): readonly { name: string; serviceId: string; interfaceId: string; }[] {\n const all: { name: string; serviceId: string; interfaceId: string; }[] = [];\n for (const e of snapshot.entries) {\n if (!_isUserInterface(e.interfaceId)) continue;\n for (const m of e.methods) {\n all.push({ name: m, serviceId: e.serviceId, interfaceId: e.interfaceId });\n }\n }\n return _rank(all, (x) => x.name, query, limit);\n}\n\nfunction _rankMethodsOnInterface(\n snapshot: HubSnapshot,\n interfaceId: string,\n query: string,\n limit: number,\n): readonly { methodName: string; serviceId: string; }[] {\n const all: { methodName: string; serviceId: string; }[] = [];\n for (const s of snapshot.servicesHostingInterface(interfaceId)) {\n for (const m of snapshot.methodsOn(s, interfaceId)) {\n all.push({ methodName: m, serviceId: s });\n }\n }\n return _rank(all, (x) => x.methodName, query, limit);\n}\n\nfunction _rankInterfacesWithMethodBoost(\n snapshot: HubSnapshot,\n query: string,\n methodName: string,\n limit: number,\n): readonly { interfaceId: string; serviceId: string; methodToTry: string; }[] {\n const ifaces = snapshot.interfaces().filter(_isUserInterface);\n const ranked = _rankNames(ifaces, query, limit, (id) => {\n for (const s of snapshot.servicesHostingInterface(id)) {\n if (snapshot.methodsOn(s, id).includes(methodName)) return 100;\n }\n return 0;\n });\n return ranked.map((id) => {\n const hosts = snapshot.servicesHostingInterface(id);\n const withMethod = hosts.find(\n (s) => s !== '' && snapshot.methodsOn(s, id).includes(methodName),\n );\n const fallback = hosts.find((s) => s !== '') ?? hosts[0] ?? '';\n const svc = withMethod ?? fallback;\n const m = snapshot.methodsOn(svc, id).includes(methodName)\n ? methodName\n : (snapshot.methodsOn(svc, id)[0] ?? '<method>');\n return { interfaceId: id, serviceId: svc, methodToTry: m };\n });\n}\n\nfunction _rankInterfacesOnService(\n snapshot: HubSnapshot,\n serviceId: string,\n query: string,\n methodName: string,\n limit: number,\n): string[] {\n const ifaces = snapshot.interfacesOnService(serviceId).filter(_isUserInterface);\n return _rankNames(ifaces, query, limit, (id) =>\n snapshot.methodsOn(serviceId, id).includes(methodName) ? 100 : 0\n );\n}\n\n// ---------------------------------------------------------------------------\n// Sample call generators\n// ---------------------------------------------------------------------------\n\n/**\n * Interface ids on `serviceId` whose name starts with `prefix`\n * (case-insensitive). System interfaces (`linkrpc.*`) are excluded — they're\n * noise for navigation. Returns `[]` for an empty `prefix` so the caller can\n * distinguish \"no prefix typed\" from \"prefix had matches\".\n */\nfunction _prefixMatchesOnService(\n snapshot: HubSnapshot,\n serviceId: string,\n prefix: string,\n): string[] {\n if (prefix === '') return [];\n const lower = prefix.toLowerCase();\n return snapshot\n .interfacesOnService(serviceId)\n .filter((id) => _isUserInterface(id) && id.toLowerCase().startsWith(lower));\n}\n\n/**\n * Render an interface-list response for `serviceId`. When `prefix` is a real\n * prefix of one or more interfaces, only those are shown; otherwise all user\n * interfaces on the service are listed. Sample method per row defaults to the\n * first declared method.\n */\nfunction _formatInterfaceListOnService(\n ctx: _Ctx,\n serviceId: string,\n prefix: string,\n): string {\n const allUserIfaces = ctx.snapshot\n .interfacesOnService(serviceId)\n .filter(_isUserInterface);\n const prefixMatches = _prefixMatchesOnService(ctx.snapshot, serviceId, prefix);\n const matches = prefixMatches.length > 0 ? prefixMatches : allUserIfaces;\n\n const header = prefixMatches.length > 0\n ? `Interfaces on \"${serviceId}\" starting with \"${prefix}\":`\n : (prefix !== ''\n ? `Interface \"${prefix}\" not found on service \"${serviceId}\". `\n + `Interfaces on \"${serviceId}\":`\n : `Interfaces on \"${serviceId}\":`);\n\n const lines = [header];\n if (matches.length === 0) {\n lines.push(` Tip: run \\`${ctx.tool} ls --service ${serviceId}\\``);\n return lines.join('\\n');\n }\n for (const id of matches.slice(0, 10)) {\n const sampleMethod = ctx.snapshot.methodsOn(serviceId, id)[0] ?? '<method>';\n lines.push(` ${_qualify(ctx, serviceId, id, sampleMethod)}`);\n }\n return lines.join('\\n');\n}\n\nfunction _sampleCallsForService(ctx: _Ctx, serviceId: string, limit: number): string[] {\n const { snapshot } = ctx;\n const out: string[] = [];\n for (const iface of snapshot.interfacesOnService(serviceId)) {\n if (!_isUserInterface(iface)) continue;\n for (const m of snapshot.methodsOn(serviceId, iface)) {\n out.push(_qualify(ctx, serviceId, iface, m));\n if (out.length >= limit) return out;\n }\n }\n return out;\n}\n\nfunction _sampleCallsForInterface(ctx: _Ctx, interfaceId: string, limit: number): string[] {\n const { snapshot } = ctx;\n const out: string[] = [];\n for (const s of snapshot.servicesHostingInterface(interfaceId)) {\n if (s === '') continue;\n for (const m of snapshot.methodsOn(s, interfaceId)) {\n out.push(_qualify(ctx, s, interfaceId, m));\n if (out.length >= limit) return out;\n }\n }\n return out;\n}\n","import type { LinkRpcInterfaceSchema } from '@hediet/linkrpc';\nimport {\n type CliChannel,\n fetchDefaults,\n fetchSchema,\n} from '@hediet/linkrpc-client';\nimport type { MethodRefWithOptHash } from './methodRef';\n\n/**\n * Fetch the schema addressed by a method reference. Form-1 references use the\n * connection preset for lookup, but remain bare when sent on the wire.\n */\nexport async function fetchSchemaForMethodRef(\n channel: CliChannel,\n ref: MethodRefWithOptHash,\n): Promise<LinkRpcInterfaceSchema | undefined> {\n if (ref.interfaceId !== undefined) {\n return fetchSchema(channel, ref.interfaceId, ref.hash, ref.serviceId);\n }\n\n const defaults = await fetchDefaults(channel);\n if (defaults.interfaceId === undefined) {\n return undefined;\n }\n return fetchSchema(\n channel,\n defaults.interfaceId,\n ref.hash ?? defaults.hash,\n defaults.serviceId,\n );\n}\n","import { ErrorCode, type JsonValue, RpcError } from '@hediet/linkrpc';\nimport { MethodRefWithOptHash } from '../methodRef';\nimport { formatJson, readParamsArg } from '../output';\nimport { mergeParams } from '../paramParsing';\nimport { type CliChannel, findMethodInSchema } from '@hediet/linkrpc-client';\nimport { formatSuggestion, HubSnapshot } from '../suggest';\nimport {\n describeObjectParams,\n describeSchema,\n explainValidation,\n validateValueAgainstSchema,\n} from '../validation';\nimport type { LinkRpcInterfaceSchema as SvcInterfaceSchema, MethodSchema } from '@hediet/linkrpc';\nimport { fetchSchemaForMethodRef } from '../schemaLookup';\n\nexport interface CallCommandOptions {\n /** Full `[svc::][iface::]method[@hash]` reference. */\n readonly methodRef: string;\n /** Raw `--params <json>` value, or \"-\" for stdin. */\n readonly paramsArg?: string;\n readonly paramOverrides?: readonly string[];\n /** Skip schema-based validation. Default: validate. */\n readonly noValidate?: boolean;\n /** Schema lookup policy. `noValidate` takes precedence when set. */\n readonly validation?: 'auto' | 'required' | 'off';\n readonly json?: boolean;\n /**\n * Invoked for every server→client stream message (`$stream::send`) that\n * arrives while the call is in flight. Defaults to writing each chunk to\n * stderr (one line each) so streamed progress shows live without\n * polluting the stdout result. Pass a custom sink in tests.\n */\n readonly onStreamChunk?: (payload: JsonValue) => void;\n}\n\nexport async function callCommand(channel: CliChannel, opts: CallCommandOptions): Promise<string> {\n const ref = MethodRefWithOptHash.parseMethodRef(opts.methodRef);\n const baseParams = readParamsArg(opts.paramsArg);\n const params = mergeParams({ base: baseParams, overrides: opts.paramOverrides });\n\n const validation = opts.noValidate ? 'off' : (opts.validation ?? 'required');\n if (validation !== 'off') await validateParams(channel, ref, params, 'call', validation);\n const onStreamChunk = opts.onStreamChunk ?? writeChunkToStderr;\n try {\n // Always use the streaming send path: it behaves identically to a plain\n // request when no stream messages arrive, and surfaces them live when\n // the method does stream (e.g. an interactive `login` device-code\n // prompt). The final result is the request's response.\n const call = channel.sendRequestWithStream(ref.getMethodOnWire(), params as never, {\n onStreamMessage: onStreamChunk,\n });\n const result = await call.result;\n return opts.json !== false ? formatJson(result) : String(result);\n } catch (e) {\n if (e instanceof RpcError && e.code === ErrorCode.methodNotFound) {\n await _failWithSuggestion(channel, ref, 'call');\n }\n if (e instanceof RpcError) throw formatRpcError(e);\n throw e;\n }\n}\n\n/**\n * Default stream sink: one line per chunk on stderr. Strings pass through\n * verbatim; structured payloads are JSON-encoded. stderr (not stdout) keeps\n * `call … | jq` clean while still showing live progress.\n */\nfunction writeChunkToStderr(payload: JsonValue): void {\n const text = typeof payload === 'string' ? payload : JSON.stringify(payload);\n process.stderr.write(text + '\\n');\n}\n\nexport interface NotifyCommandOptions extends CallCommandOptions { }\n\nexport async function notifyCommand(channel: CliChannel, opts: NotifyCommandOptions): Promise<string> {\n const ref = MethodRefWithOptHash.parseMethodRef(opts.methodRef);\n const baseParams = readParamsArg(opts.paramsArg);\n const params = mergeParams({ base: baseParams, overrides: opts.paramOverrides });\n const validation = opts.noValidate ? 'off' : (opts.validation ?? 'required');\n if (validation !== 'off') await validateParams(channel, ref, params, 'notify', validation);\n await channel.sendNotification(ref.getMethodOnWire(), params as never);\n return '(notification sent)';\n}\n\nasync function validateParams(\n channel: CliChannel,\n ref: MethodRefWithOptHash,\n params: unknown,\n verb: 'call' | 'notify',\n validation: 'auto' | 'required',\n): Promise<void> {\n let schema: SvcInterfaceSchema | undefined;\n try {\n schema = await fetchSchemaForMethodRef(channel, ref);\n } catch (e) {\n // Server side says the interface (or its host route) is unknown.\n // ErrorCode.methodNotFound covers both \"no such interface\" and \"no\n // such route\" — in either case the bus-wide suggestion is what the\n // user wants. Any other RpcError (e.g. permission) is propagated.\n if (e instanceof RpcError && e.code === ErrorCode.methodNotFound) {\n if (validation === 'auto') return;\n await _failWithSuggestion(channel, ref, verb);\n }\n throw e;\n }\n if (schema === undefined) {\n if (validation === 'auto') return;\n await _failWithSuggestion(channel, ref, verb);\n }\n const method = findMethodInSchema(schema, ref.methodName);\n if (!method) {\n await _failWithSuggestion(channel, ref, verb);\n }\n if (verb === 'call' && method!.result === undefined) {\n throw new Error(\n `${ref.getMethodOnWire()} is a notification member; use \\`notify\\` instead of \\`call\\`.`,\n );\n }\n if (verb === 'notify' && method!.result !== undefined) {\n throw new Error(\n `${ref.getMethodOnWire()} is a request member; use \\`call\\` instead of \\`notify\\`.`,\n );\n }\n const paramsSchema = method!.params;\n const reason = validateValueAgainstSchema(params, paramsSchema, schema.components?.schemas ?? {});\n if (reason !== undefined) {\n throw new Error(_formatParamValidationError(ref, schema, method!, params, reason));\n }\n}\n\nfunction _formatParamValidationError(\n ref: MethodRefWithOptHash,\n schema: SvcInterfaceSchema,\n method: MethodSchema,\n params: unknown,\n fallback: string,\n): string {\n const components = schema.components?.schemas ?? {};\n const paramsSchema = method.params;\n const lines: string[] = [];\n lines.push(`Param validation failed for ${ref.getMethodOnWire()}:`);\n const issues = explainValidation(params, paramsSchema, components);\n if (issues.length > 0) {\n for (const i of issues) {\n const where = i.path === '' ? '(root)' : i.path;\n lines.push(` ${where}: ${i.reason}`);\n }\n } else {\n lines.push(` ${fallback}`);\n }\n if (paramsSchema !== undefined) {\n const table = describeObjectParams(paramsSchema, components);\n if (table !== undefined) {\n lines.push('Expected params:');\n lines.push(table);\n } else {\n lines.push(`Expected: ${describeSchema(paramsSchema, components)}`);\n }\n }\n return lines.join('\\n');\n}\n\n/**\n * Walk the bus once, build a snapshot, and throw an Error whose message is a\n * focused \"did you mean…\" block tailored to `ref`. Always throws — return\n * type is `Promise<never>`. Snapshot load failures fall back to an empty\n * snapshot so we still produce *some* output.\n */\nasync function _failWithSuggestion(\n channel: CliChannel,\n ref: MethodRefWithOptHash,\n verb: 'call' | 'notify',\n): Promise<never> {\n let snapshot: HubSnapshot;\n try {\n snapshot = await HubSnapshot.load(channel);\n } catch {\n snapshot = new HubSnapshot([]);\n }\n throw new Error(formatSuggestion({ ref, snapshot, verb }));\n}\n\nfunction formatRpcError(e: RpcError): Error {\n if (e.code === ErrorCode.permissionRequired) {\n return new Error(_formatPermissionRequired(e));\n }\n const dataStr = e.data === undefined ? '' : ` ${JSON.stringify(e.data)}`;\n return new Error(`RPC error ${e.code}: ${e.message}${dataStr}`);\n}\n\n/**\n * Friendly explanation for `permissionRequired` (-32401). Typical when the\n * CLI couldn't acquire a capability via `hubAccess::requestAccess` and the\n * target service gates on caps. The earlier `capability negotiation\n * skipped` warning explains *why* we couldn't get one; this footer tells\n * the user what to do.\n */\nfunction _formatPermissionRequired(e: RpcError): string {\n return [\n `Permission required: ${e.message}`,\n ' The hub gates this call on a capability, and none was acquired.',\n ' If your hub uses an access handler, accept the consent prompt and retry.',\n ' Otherwise, the hub admin has to issue a capability to this CLI identity',\n ` (\\`hub logout\\` then retry to mint a fresh identity).`,\n ].join('\\n');\n}\n","import type { JsonValue } from \"@hediet/linkrpc\";\nimport type { CallCommandOptions, NotifyCommandOptions } from \"./call\";\n\nexport interface BatchOperation {\n readonly kind: \"call\" | \"notify\";\n readonly methodRef: string;\n readonly paramsArg?: string;\n readonly paramOverrides: readonly string[];\n readonly noValidate: boolean;\n}\n\nexport interface BatchPlan {\n readonly operations: readonly BatchOperation[];\n readonly continueOnError: boolean;\n}\n\nexport interface BatchExecutor {\n readonly call: (options: CallCommandOptions) => Promise<string>;\n readonly notify: (options: NotifyCommandOptions) => Promise<string>;\n}\n\nexport type BatchResult =\n | {\n readonly index: number;\n readonly kind: BatchOperation[\"kind\"];\n readonly method: string;\n readonly ok: true;\n readonly result?: JsonValue;\n }\n | {\n readonly index: number;\n readonly kind: BatchOperation[\"kind\"];\n readonly method: string;\n readonly ok: false;\n readonly error: string;\n };\n\nexport interface ExecuteBatchOptions {\n readonly validation?: 'auto' | 'required' | 'off';\n readonly onStreamChunk?: (event: {\n readonly index: number;\n readonly method: string;\n readonly payload: JsonValue;\n }) => void;\n}\n\nexport function parseBatchArgs(args: readonly string[]): BatchPlan {\n const operations: MutableBatchOperation[] = [];\n let current: MutableBatchOperation | undefined;\n let continueOnError = false;\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n switch (arg) {\n case \"--call\":\n case \"--notify\": {\n const methodRef = readOptionValue(args, ++i, arg, \"method\");\n current = {\n kind: arg === \"--call\" ? \"call\" : \"notify\",\n methodRef,\n paramOverrides: [],\n noValidate: false,\n };\n operations.push(current);\n break;\n }\n case \"--params\": {\n requireOperation(current, arg);\n if (current.paramsArg !== undefined) {\n throw new Error(\"--params may be specified only once per batch operation\");\n }\n current.paramsArg = readOptionValue(args, ++i, arg);\n break;\n }\n case \"--param\": {\n requireOperation(current, arg);\n current.paramOverrides.push(readOptionValue(args, ++i, arg));\n break;\n }\n case \"--no-validate\":\n requireOperation(current, arg);\n current.noValidate = true;\n break;\n case \"--continue-on-error\":\n continueOnError = true;\n break;\n default:\n if (arg.startsWith(\"-\")) {\n throw new Error(`Unknown batch option: ${arg}`);\n }\n throw new Error(`Unexpected batch argument: ${arg}`);\n }\n }\n\n if (operations.length === 0) {\n throw new Error(\"Batch requires at least one --call or --notify operation\");\n }\n\n return { operations, continueOnError };\n}\n\nexport async function executeBatch(\n plan: BatchPlan,\n executor: BatchExecutor,\n options: ExecuteBatchOptions = {},\n): Promise<BatchResult[]> {\n const results: BatchResult[] = [];\n\n for (let index = 0; index < plan.operations.length; index++) {\n const operation = plan.operations[index];\n const commandOptions: CallCommandOptions = {\n methodRef: operation.methodRef,\n paramsArg: operation.paramsArg,\n paramOverrides: operation.paramOverrides,\n noValidate: operation.noValidate,\n validation: options.validation,\n json: true,\n onStreamChunk: (payload) => options.onStreamChunk?.({\n index,\n method: operation.methodRef,\n payload,\n }),\n };\n\n try {\n if (operation.kind === \"notify\") {\n await executor.notify(commandOptions);\n results.push(toSuccessResult(index, operation));\n } else {\n const output = await executor.call(commandOptions);\n const result: JsonValue = JSON.parse(output);\n results.push(toSuccessResult(index, operation, result));\n }\n } catch (error) {\n if (!plan.continueOnError) {\n throw error;\n }\n results.push({\n index,\n kind: operation.kind,\n method: operation.methodRef,\n ok: false,\n error: getErrorMessage(error),\n });\n }\n }\n\n return results;\n}\n\ninterface MutableBatchOperation {\n kind: BatchOperation[\"kind\"];\n methodRef: string;\n paramsArg?: string;\n paramOverrides: string[];\n noValidate: boolean;\n}\n\nfunction readOptionValue(\n args: readonly string[],\n index: number,\n option: string,\n valueName = \"value\",\n): string {\n const value = args[index];\n if (value === undefined || value.startsWith(\"--\")) {\n throw new Error(`${option} requires a ${valueName}`);\n }\n return value;\n}\n\nfunction requireOperation(\n operation: MutableBatchOperation | undefined,\n option: string,\n): asserts operation is MutableBatchOperation {\n if (operation === undefined) {\n throw new Error(`${option} must follow --call or --notify`);\n }\n}\n\nfunction toSuccessResult(\n index: number,\n operation: BatchOperation,\n result?: JsonValue,\n): BatchResult {\n return {\n index,\n kind: operation.kind,\n method: operation.methodRef,\n ok: true,\n ...(result === undefined ? {} : { result }),\n };\n}\n\nfunction getErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","import { ErrorCode, type IncomingCall, type IRequestHandler, type JsonValue, RpcError } from '@hediet/linkrpc';\nimport { hubGrantedServiceIdInterface } from '@hediet/linkrpc/hub/common';\nimport { hubServiceIdRegistryInterface } from '@hediet/linkrpc/hub/common';\nimport type { CliConnection } from '@hediet/linkrpc-client';\n\n/**\n * The wire method for the provenance claim front door. Mirrors\n * `Hub.registerServiceIdNamespace`, which calls\n * `connection.get(hubGrantedServiceIdInterface).register({ serviceId })`\n * with no serviceId prefix — i.e. interface-form\n * `hubGrantedServiceId::register`. The claimed serviceId must be\n * within the connection's granted namespace.\n */\nconst CLAIM_METHOD = `${hubGrantedServiceIdInterface.info.id}::register`;\nconst GET_CLAIM_NAMESPACE_METHOD = `${hubGrantedServiceIdInterface.info.id}::get`;\nconst GET_HUB_SERVICE_ID_METHOD = `${hubGrantedServiceIdInterface.info.id}::getHubServiceId`;\n\nexport interface TunnelOptions {\n readonly serviceId: string;\n /** Live connection to the hub we claim `serviceId` on and receive requests from. */\n readonly local: CliConnection;\n /** Live connection to the endpoint we forward every received request to. */\n readonly remote: CliConnection;\n /**\n * When set, also forward every request/notification the {@link remote}\n * endpoint emits back to {@link local} (the hub), exposing the hub to the\n * endpoint. Forwards everything verbatim (unsigned).\n */\n readonly bidi?: boolean;\n /**\n * Resolves to stop the tunnel (e.g. on SIGINT). When omitted, the tunnel\n * runs until the process is signalled (`SIGINT` / `SIGTERM`).\n */\n readonly stop?: Promise<void>;\n /** Sink for human-readable status lines (defaults to stderr). */\n readonly log?: (line: string) => void;\n}\n\n/**\n * Run a transparent service tunnel until stopped.\n *\n * Claims `serviceId` on {@link TunnelOptions.local} via the hub claim\n * interface, then forwards every inbound request/notification verbatim onto\n * {@link TunnelOptions.remote} and pipes the response back. Forwarding is\n * signature-preserving: the original caller's `$hubrpc` envelope rides inside\n * `params`, so the remote send is issued unsigned (`signerOverride: null`) to\n * avoid re-wrapping it. The streaming sub-protocol is bridged both ways, so\n * long-running / streaming calls forward their in-flight stream messages and\n * cancellation, not just the final response.\n *\n * When {@link TunnelOptions.bidi} is set, the mirror forwarder is also bound on\n * {@link TunnelOptions.remote}, so every request/notification the endpoint\n * emits is forwarded verbatim back to the hub.\n *\n * Resolves when {@link TunnelOptions.stop} resolves (or on `SIGINT`/`SIGTERM`).\n */\nexport async function tunnelCommand(opts: TunnelOptions): Promise<void> {\n const log = opts.log ?? ((line) => process.stderr.write(line + '\\n'));\n\n // Bind the catch-all forwarder BEFORE claiming so no request can race in\n // between the claim landing and the handler being installed.\n opts.local.setRequestHandler(createForwardingHandler(opts.remote));\n\n // When bidirectional, mirror the forwarder on the remote so every request\n // and notification the endpoint emits is routed back to the source hub.\n if (opts.bidi) {\n opts.remote.setRequestHandler(createForwardingHandler(opts.local));\n }\n\n // Claim via root namespace when in-namespace, otherwise via the hub-level\n // service id registry.\n await _claimServiceId(opts.local, opts.serviceId);\n log(\n opts.bidi\n ? `tunnel: claimed '${opts.serviceId}' — forwarding requests to remote (bidirectional)`\n : `tunnel: claimed '${opts.serviceId}' — forwarding requests to remote`,\n );\n\n await (opts.stop ?? _untilSignalled());\n log('tunnel: stopping');\n}\n\n/**\n * Build the inbound handler that forwards every request/notification received\n * on one connection onto `to`, bridging the streaming sub-protocol both ways\n * (see {@link _forwardRequest}). Used for the source→target direction and, in\n * bidirectional mode, the mirror.\n */\nexport function createForwardingHandler(to: CliConnection): IRequestHandler {\n return {\n handleRequest: (call) => _forwardRequest(to, call),\n handleNotification: (call) => _forwardNotification(to, call),\n };\n}\n\nasync function _claimServiceId(local: CliConnection, serviceId: string): Promise<void> {\n const namespaceRes = await local.channel.sendRequest(GET_CLAIM_NAMESPACE_METHOD, {});\n const grantedNamespace =\n typeof namespaceRes === 'object'\n && namespaceRes !== null\n && 'grantedServiceIdNamespace' in namespaceRes\n && typeof (namespaceRes as { grantedServiceIdNamespace?: unknown; }).grantedServiceIdNamespace === 'string'\n ? (namespaceRes as { grantedServiceIdNamespace: string; }).grantedServiceIdNamespace\n : '';\n\n if (_isServiceIdUnder(serviceId, grantedNamespace)) {\n await local.channel.sendRequest(CLAIM_METHOD, { serviceId });\n return;\n }\n\n const hubIdRes = await local.channel.sendRequest(GET_HUB_SERVICE_ID_METHOD, {});\n const hubServiceId =\n typeof hubIdRes === 'object'\n && hubIdRes !== null\n && 'hubServiceId' in hubIdRes\n && typeof (hubIdRes as { hubServiceId?: unknown; }).hubServiceId === 'string'\n ? (hubIdRes as { hubServiceId: string; }).hubServiceId\n : undefined;\n if (!hubServiceId) {\n throw new Error('tunnel: failed to resolve hub service id for out-of-namespace claim');\n }\n\n const registerMethod = `${hubServiceId}::${hubServiceIdRegistryInterface.info.id}::registerServiceId`;\n await local.channel.sendRequest(registerMethod, { requestedPrefix: serviceId });\n}\n\nfunction _isServiceIdUnder(serviceId: string, namespace: string): boolean {\n if (namespace === '') return false;\n return serviceId === namespace || serviceId.startsWith(`${namespace}/`);\n}\n\n/** Resolve on the next `SIGINT` / `SIGTERM`. */\nfunction _untilSignalled(): Promise<void> {\n return new Promise<void>((resolve) => {\n const done = (): void => {\n process.removeListener('SIGINT', done);\n process.removeListener('SIGTERM', done);\n resolve();\n };\n process.once('SIGINT', done);\n process.once('SIGTERM', done);\n });\n}\n\nasync function _forwardRequest(\n remote: CliConnection,\n call: IncomingCall,\n): Promise<{ result: JsonValue; } | { error: { code: number; message: string; data?: JsonValue; }; }> {\n // Bridge the streaming sub-protocol both ways so long-running / streaming\n // calls forward transparently, not just their final response:\n // - callee → caller progress: relayed via `onStreamMessage` → `call.stream.send`\n // - caller → callee input: relayed via `call.stream.onMessage` → `rc.send`\n // - caller cancellation (disconnect / idle / explicit): via `call.signal` → `rc.cancel`\n // `signerOverride: null` forwards verbatim: the inbound `$hubrpc` envelope\n // (if any) is preserved instead of being re-signed.\n const rc = remote.channel.sendRequestWithStream(call.method, call.params, {\n ctx: { signerOverride: null },\n onStreamMessage: (payload) => { void call.stream.send(payload); },\n });\n call.stream.onMessage((payload) => rc.send(payload));\n const cancelRemote = (): void => rc.cancel((call.signal.reason as Error | undefined)?.message);\n if (call.signal.aborted) {\n cancelRemote();\n } else {\n call.signal.addEventListener('abort', cancelRemote, { once: true });\n }\n try {\n const result = await rc.result;\n return { result };\n } catch (err) {\n if (err instanceof RpcError) {\n return { error: { code: err.code, message: err.message, data: err.data } };\n }\n return {\n error: { code: ErrorCode.internalError, message: (err as Error).message },\n };\n }\n}\n\nfunction _forwardNotification(remote: CliConnection, call: IncomingCall): void {\n void remote.channel\n .sendNotification(call.method, call.params, { ctx: { signerOverride: null } })\n .catch(() => { /* notifications are fire-and-forget */ });\n}","import {\n ErrorCode,\n type IncomingCall,\n type IRequestHandler,\n type JsonValue,\n} from \"@hediet/linkrpc\";\nimport type { CliConnection } from \"@hediet/linkrpc-client\";\nimport type { StaticHubSchema } from \"../staticHubSchema\";\nimport { StaticHubReflection } from \"./staticHubReflection\";\nimport { createForwardingHandler } from \"./tunnel\";\n\nexport const BROKER_INTERFACE_ID = \"hubrpc.connectionBroker\";\nexport const BROKER_STATUS_METHOD = `${BROKER_INTERFACE_ID}::status`;\nexport const BROKER_READ_NOTIFICATIONS_METHOD = `${BROKER_INTERFACE_ID}::readNotifications`;\nexport const BROKER_DISCONNECT_METHOD = `${BROKER_INTERFACE_ID}::disconnect`;\n\nexport interface ConnectionBrokerOptions {\n readonly id: string;\n readonly remoteEndpoint: string;\n readonly mode: \"linkrpc\" | \"raw\";\n readonly startedAt: number;\n readonly timeoutMs: number;\n readonly ttlMs: number;\n readonly notificationLimit?: number;\n readonly now?: () => number;\n readonly onStop?: (reason: BrokerStopReason) => void;\n readonly staticHubSchema?: StaticHubSchema;\n}\n\nexport type BrokerStopReason = \"disconnect\" | \"timeout\" | \"ttl\" | \"disposed\";\n\nexport interface BufferedNotification {\n readonly sequence: number;\n readonly receivedAt: number;\n readonly method: string;\n readonly params?: JsonValue;\n}\n\ninterface NotificationReadResult {\n readonly notifications: readonly BufferedNotification[];\n readonly next: number;\n readonly droppedBefore: number;\n}\n\ninterface NotificationWaiter {\n readonly after: number;\n readonly resolve: (result: NotificationReadResult) => void;\n readonly timer: ReturnType<typeof setTimeout>;\n readonly signal: AbortSignal;\n readonly onAbort: () => void;\n}\n\nexport class ConnectionBroker {\n private readonly _now: () => number;\n private readonly _notificationLimit: number;\n private readonly _notifications: BufferedNotification[] = [];\n private readonly _waiters = new Set<NotificationWaiter>();\n private readonly _remoteForwarder: IRequestHandler;\n private readonly _staticReflection: StaticHubReflection | undefined;\n private readonly _startedAt: number;\n private _nextNotificationSequence = 1;\n private readonly _locals = new Set<CliConnection>();\n private _timeoutTimer: ReturnType<typeof setTimeout> | undefined;\n private _ttlTimer: ReturnType<typeof setTimeout> | undefined;\n private _lastActivityAt: number;\n private _resolveStopped!: (reason: BrokerStopReason) => void;\n private _disposed = false;\n\n public readonly stopped = new Promise<BrokerStopReason>((resolve) => {\n this._resolveStopped = resolve;\n });\n public stoppedReason: BrokerStopReason | undefined;\n\n constructor(\n private readonly _remote: CliConnection,\n private readonly _options: ConnectionBrokerOptions,\n ) {\n this._now = _options.now ?? Date.now;\n this._notificationLimit = _options.notificationLimit ?? 1_000;\n this._startedAt = _options.startedAt;\n this._lastActivityAt = _options.startedAt;\n this._remoteForwarder = createForwardingHandler(_remote);\n this._staticReflection = _options.staticHubSchema === undefined\n ? undefined\n : new StaticHubReflection(_options.staticHubSchema);\n this._remote.setRequestHandler({\n handleRequest: (call) => this._handleRemoteRequest(call),\n handleNotification: (call) => this._bufferNotification(call),\n });\n this._resetTimeout();\n this._ttlTimer = setTimeout(\n () => this._stop(\"ttl\"),\n Math.max(0, this._options.ttlMs - (this._now() - this._startedAt)),\n );\n this._ttlTimer.unref?.();\n }\n\n public attach(local: CliConnection): void {\n if (this._disposed) {\n throw new Error(\"connection broker is stopped\");\n }\n this._locals.add(local);\n local.setRequestHandler({\n handleRequest: (call) => this._handleLocalRequest(call),\n handleNotification: (call) => this._handleLocalNotification(call),\n });\n this.recordActivity();\n }\n\n public detach(local: CliConnection): void {\n if (!this._locals.delete(local)) return;\n local.setRequestHandler(undefined);\n }\n\n public recordActivity(): void {\n if (this._disposed) return;\n this._lastActivityAt = this._now();\n this._resetTimeout();\n }\n\n public dispose(): void {\n this._stop(\"disposed\");\n }\n\n private async _handleLocalRequest(call: IncomingCall) {\n this.recordActivity();\n switch (call.method) {\n case BROKER_STATUS_METHOD:\n return { result: this._status() as unknown as JsonValue };\n case BROKER_READ_NOTIFICATIONS_METHOD:\n return {\n result: await this._readNotifications(call.params, call.signal) as unknown as JsonValue,\n };\n case BROKER_DISCONNECT_METHOD:\n setTimeout(() => this._stop(\"disconnect\"), 0);\n return { result: { disconnected: true } };\n default:\n if (call.method.startsWith(`${BROKER_INTERFACE_ID}::`)) {\n return {\n error: {\n code: ErrorCode.methodNotFound,\n message: `Unknown connection broker method: ${call.method}`,\n },\n };\n }\n const reflected = this._staticReflection?.tryHandleRequest(call);\n if (reflected !== undefined) {\n return reflected;\n }\n return this._remoteForwarder.handleRequest(call);\n }\n }\n\n private _handleLocalNotification(call: IncomingCall): void {\n this.recordActivity();\n if (call.method.startsWith(`${BROKER_INTERFACE_ID}::`)) {\n return;\n }\n this._remoteForwarder.handleNotification(call);\n }\n\n private _handleRemoteRequest(call: IncomingCall) {\n this.recordActivity();\n if (this._locals.size !== 1) {\n return Promise.resolve({\n error: {\n code: ErrorCode.peerDisconnected,\n message: this._locals.size === 0\n ? \"No local broker client is attached\"\n : \"Cannot route a reverse request while multiple local broker clients are attached\",\n },\n });\n }\n const local = this._locals.values().next().value!;\n return createForwardingHandler(local).handleRequest(call);\n }\n\n private _bufferNotification(call: IncomingCall): void {\n this.recordActivity();\n const notification: BufferedNotification = {\n sequence: this._nextNotificationSequence++,\n receivedAt: this._now(),\n method: call.method,\n ...(call.params === undefined ? {} : { params: call.params }),\n };\n this._notifications.push(notification);\n if (this._notifications.length > this._notificationLimit) {\n this._notifications.splice(0, this._notifications.length - this._notificationLimit);\n }\n this._settleReadyWaiters();\n }\n\n private _status(): JsonValue {\n return {\n id: this._options.id,\n mode: this._options.mode,\n remoteEndpoint: this._options.remoteEndpoint,\n startedAt: this._startedAt,\n lastActivityAt: this._lastActivityAt,\n timeoutMs: this._options.timeoutMs,\n ttlMs: this._options.ttlMs,\n notificationCount: this._notifications.length,\n nextNotificationSequence: this._nextNotificationSequence,\n localClientCount: this._locals.size,\n };\n }\n\n private _readNotifications(\n params: JsonValue | undefined,\n signal: AbortSignal,\n ): Promise<NotificationReadResult> {\n const parsed = parseReadParams(params);\n const immediate = this._collectNotifications(parsed.after);\n if (immediate.notifications.length > 0 || parsed.waitMs === 0) {\n return Promise.resolve(immediate);\n }\n return new Promise<NotificationReadResult>((resolve) => {\n const waiter: NotificationWaiter = {\n after: parsed.after,\n resolve,\n timer: setTimeout(() => this._settleWaiter(waiter), parsed.waitMs),\n signal,\n onAbort: () => this._settleWaiter(waiter),\n };\n waiter.timer.unref?.();\n signal.addEventListener(\"abort\", waiter.onAbort, { once: true });\n this._waiters.add(waiter);\n });\n }\n\n private _collectNotifications(after: number): NotificationReadResult {\n const notifications = this._notifications.filter((item) => item.sequence > after);\n const next = notifications.at(-1)?.sequence ?? after;\n return {\n notifications,\n next,\n droppedBefore: this._notifications[0]?.sequence ?? this._nextNotificationSequence,\n };\n }\n\n private _settleReadyWaiters(): void {\n for (const waiter of [...this._waiters]) {\n if (this._notifications.some((item) => item.sequence > waiter.after)) {\n this._settleWaiter(waiter);\n }\n }\n }\n\n private _settleWaiter(waiter: NotificationWaiter): void {\n if (!this._waiters.delete(waiter)) return;\n clearTimeout(waiter.timer);\n waiter.signal.removeEventListener(\"abort\", waiter.onAbort);\n waiter.resolve(this._collectNotifications(waiter.after));\n }\n\n private _resetTimeout(): void {\n if (this._timeoutTimer !== undefined) {\n clearTimeout(this._timeoutTimer);\n }\n this._timeoutTimer = setTimeout(() => this._stop(\"timeout\"), this._options.timeoutMs);\n this._timeoutTimer.unref?.();\n }\n\n private _stop(reason: BrokerStopReason): void {\n if (this._disposed) return;\n this._disposed = true;\n this.stoppedReason = reason;\n if (this._timeoutTimer !== undefined) clearTimeout(this._timeoutTimer);\n if (this._ttlTimer !== undefined) clearTimeout(this._ttlTimer);\n for (const waiter of [...this._waiters]) {\n this._settleWaiter(waiter);\n }\n for (const local of this._locals) {\n local.close();\n }\n this._locals.clear();\n this._remote.close();\n this._resolveStopped(reason);\n this._options.onStop?.(reason);\n }\n}\n\nfunction parseReadParams(params: JsonValue | undefined): { after: number; waitMs: number; } {\n if (params === undefined) return { after: 0, waitMs: 0 };\n if (typeof params !== \"object\" || params === null || Array.isArray(params)) {\n throw new Error(\"readNotifications params must be an object\");\n }\n const after = \"after\" in params ? params.after : 0;\n const waitMs = \"waitMs\" in params ? params.waitMs : 0;\n if (typeof after !== \"number\" || !Number.isSafeInteger(after) || after < 0) {\n throw new Error(\"readNotifications after must be a non-negative integer\");\n }\n if (\n typeof waitMs !== \"number\"\n || !Number.isSafeInteger(waitMs)\n || waitMs < 0\n || waitMs > 30_000\n ) {\n throw new Error(\"readNotifications waitMs must be an integer between 0 and 30000\");\n }\n return { after, waitMs };\n}\n","import type { JsonValue } from \"@hediet/linkrpc\";\nimport type { CliChannel } from \"@hediet/linkrpc-client\";\nimport {\n BROKER_DISCONNECT_METHOD,\n BROKER_READ_NOTIFICATIONS_METHOD,\n BROKER_STATUS_METHOD,\n type BufferedNotification,\n} from \"./connectionBroker\";\n\nexport interface ReadBrokerNotificationsOptions {\n readonly after?: number;\n readonly waitMs?: number;\n}\n\nexport interface BrokerNotificationBatch {\n readonly notifications: readonly BufferedNotification[];\n readonly next: number;\n readonly droppedBefore: number;\n}\n\nexport function getBrokerStatus(channel: CliChannel): Promise<JsonValue> {\n return channel.sendRequest(BROKER_STATUS_METHOD, {});\n}\n\nexport async function disconnectBroker(channel: CliChannel): Promise<void> {\n await channel.sendRequest(BROKER_DISCONNECT_METHOD, {});\n}\n\nexport async function readBrokerNotifications(\n channel: CliChannel,\n options: ReadBrokerNotificationsOptions = {},\n): Promise<BrokerNotificationBatch> {\n const value = await channel.sendRequest(BROKER_READ_NOTIFICATIONS_METHOD, {\n after: options.after ?? 0,\n waitMs: options.waitMs ?? 0,\n });\n if (!isRecord(value) || !Array.isArray(value.notifications)) {\n throw new Error(\"connection broker returned an invalid notification batch\");\n }\n const next = value.next;\n const droppedBefore = value.droppedBefore;\n if (\n typeof next !== \"number\"\n || !Number.isSafeInteger(next)\n || typeof droppedBefore !== \"number\"\n || !Number.isSafeInteger(droppedBefore)\n ) {\n throw new Error(\"connection broker returned invalid notification sequence metadata\");\n }\n const notifications = value.notifications.map(parseNotification);\n return { notifications, next, droppedBefore };\n}\n\nfunction parseNotification(value: unknown): BufferedNotification {\n if (\n !isRecord(value)\n || typeof value.sequence !== \"number\"\n || !Number.isSafeInteger(value.sequence)\n || typeof value.receivedAt !== \"number\"\n || !Number.isSafeInteger(value.receivedAt)\n || typeof value.method !== \"string\"\n ) {\n throw new Error(\"connection broker returned an invalid notification\");\n }\n return {\n sequence: value.sequence,\n receivedAt: value.receivedAt,\n method: value.method,\n ...(\"params\" in value ? { params: value.params as JsonValue } : {}),\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import { randomUUID } from \"node:crypto\";\nimport { spawn } from \"node:child_process\";\nimport {\n formatEndpointUri,\n traceMessageTransport,\n type ResolvedEndpoint,\n} from \"@hediet/linkrpc/node\";\nimport { SocketServer } from \"@hediet/linkrpc-hub/hub/server/node\";\nimport {\n connect,\n connectViaTransport,\n} from \"@hediet/linkrpc-client\";\nimport type { StaticHubSchema } from \"../staticHubSchema\";\nimport { ConnectionBroker, type BrokerStopReason } from \"./connectionBroker\";\n\nexport interface RunConnectionBrokerOptions {\n readonly remote: ResolvedEndpoint;\n readonly timeoutMs: number;\n readonly ttlMs: number;\n readonly notificationLimit?: number;\n readonly staticHubSchema?: StaticHubSchema;\n}\n\nexport interface RunningConnectionBroker {\n readonly endpoint: string;\n readonly stopped: Promise<BrokerStopReason>;\n dispose(): void;\n}\n\nexport async function runConnectionBroker(\n options: RunConnectionBrokerOptions,\n): Promise<RunningConnectionBroker> {\n const startedAt = Date.now();\n let broker: ConnectionBroker | undefined;\n const remote = await connect(options.remote, {\n trace: () => broker?.recordActivity(),\n });\n const token = randomUUID();\n const server = await SocketServer.start({\n isTokenAccepted: async (candidate) => candidate === token,\n });\n const mode = options.remote.kind === \"ws-no-init\" ? \"raw\" : \"linkrpc\";\n\n try {\n broker = new ConnectionBroker(remote, {\n id: randomUUID(),\n remoteEndpoint: formatRemoteEndpointForStatus(options.remote),\n mode,\n startedAt,\n timeoutMs: options.timeoutMs,\n ttlMs: options.ttlMs,\n ...(options.notificationLimit === undefined\n ? {}\n : { notificationLimit: options.notificationLimit }),\n ...(options.staticHubSchema === undefined\n ? {}\n : { staticHubSchema: options.staticHubSchema }),\n onStop: () => server.dispose(),\n });\n server.setConnectionHandler((transport) => {\n broker!.recordActivity();\n const traced = traceMessageTransport(transport, () => broker!.recordActivity());\n const local = connectViaTransport(traced);\n try {\n broker!.attach(local);\n } catch {\n local.close();\n return;\n }\n\n transport.onDidClose(() => broker!.detach(local));\n });\n } catch (error) {\n server.dispose();\n remote.close();\n throw error;\n }\n\n const endpoint = formatEndpointUri({\n kind: \"socket\",\n path: server.endpoint,\n token,\n brokerMode: mode,\n }, { revealToken: true });\n return {\n endpoint,\n stopped: broker.stopped,\n dispose: () => broker!.dispose(),\n };\n}\n\nfunction formatRemoteEndpointForStatus(endpoint: ResolvedEndpoint): string {\n if (endpoint.kind === \"ws-no-init\") {\n const url = new URL(endpoint.url);\n for (const key of [...url.searchParams.keys()]) {\n url.searchParams.set(key, \"***\");\n }\n return url.toString().replace(/^ws:/i, \"ws-no-init:\");\n }\n if (endpoint.kind === \"cmd-env\" || endpoint.kind === \"cmd-stdio\") {\n return `${endpoint.kind}:<redacted>`;\n }\n return formatEndpointUri(endpoint);\n}\n\nexport interface SpawnConnectionBrokerOptions {\n readonly remote: ResolvedEndpoint;\n readonly timeoutMs: number;\n readonly ttlMs: number;\n readonly notificationLimit?: number;\n readonly readyTimeoutMs?: number;\n readonly schemaSource?: string;\n}\n\nexport async function spawnConnectionBroker(\n options: SpawnConnectionBrokerOptions,\n): Promise<string> {\n const cliPath = process.argv[1];\n if (cliPath === undefined) {\n throw new Error(\"cannot locate the linkrpc CLI entry point\");\n }\n const args = [\n ...process.execArgv,\n cliPath,\n \"_connection-broker\",\n \"--remote-endpoint\",\n formatEndpointUri(options.remote, { revealToken: true }),\n \"--timeout-ms\",\n String(options.timeoutMs),\n \"--ttl-ms\",\n String(options.ttlMs),\n ];\n if (options.notificationLimit !== undefined) {\n args.push(\"--notification-limit\", String(options.notificationLimit));\n }\n if (options.schemaSource !== undefined) {\n args.push(\"--schema\", options.schemaSource);\n }\n\n const child = spawn(process.execPath, args, {\n detached: true,\n windowsHide: true,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n });\n const stdout = child.stdout;\n if (stdout === null) {\n child.kill();\n throw new Error(\"connection broker child exposes no stdout\");\n }\n\n try {\n const endpoint = await readReadyEndpoint(\n child,\n stdout,\n options.readyTimeoutMs ?? 15_000,\n );\n stdout.destroy();\n child.unref();\n return endpoint;\n } catch (error) {\n child.kill();\n throw error;\n }\n}\n\nfunction readReadyEndpoint(\n child: ReturnType<typeof spawn>,\n stdout: NodeJS.ReadableStream,\n timeoutMs: number,\n): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n let buffer = \"\";\n const timer = setTimeout(() => {\n cleanup();\n reject(new Error(\"connection broker did not become ready before the timeout\"));\n }, timeoutMs);\n const onData = (chunk: Buffer | string) => {\n buffer += chunk.toString();\n const newline = buffer.indexOf(\"\\n\");\n if (newline < 0) return;\n const endpoint = buffer.slice(0, newline).trim();\n cleanup();\n try {\n const parsed = new URL(endpoint);\n if (parsed.protocol !== \"unix:\" && parsed.protocol !== \"npipe:\") {\n throw new Error(`unexpected broker endpoint '${endpoint}'`);\n }\n resolve(endpoint);\n } catch (error) {\n reject(error);\n }\n };\n const onError = (error: Error) => {\n cleanup();\n reject(error);\n };\n const onExit = (code: number | null) => {\n cleanup();\n reject(new Error(`connection broker exited before becoming ready (code ${code ?? \"unknown\"})`));\n };\n const cleanup = () => {\n clearTimeout(timer);\n stdout.removeListener(\"data\", onData);\n child.removeListener(\"error\", onError);\n child.removeListener(\"exit\", onExit);\n };\n stdout.on(\"data\", onData);\n child.once(\"error\", onError);\n child.once(\"exit\", onExit);\n });\n}\n","const DURATION_PATTERN = /^(\\d+)(ms|s|m|min|h)$/;\n\nconst UNIT_MS: Readonly<Record<string, number>> = {\n ms: 1,\n s: 1_000,\n m: 60_000,\n min: 60_000,\n h: 3_600_000,\n};\n\nexport function parseDuration(value: string): number {\n const match = DURATION_PATTERN.exec(value.trim());\n if (match === null) {\n throw new Error(`invalid duration '${value}' (expected e.g. 250ms, 30s, 5min, or 2h)`);\n }\n const amount = Number.parseInt(match[1], 10);\n const durationMs = amount * UNIT_MS[match[2]];\n if (!Number.isSafeInteger(durationMs) || durationMs <= 0) {\n throw new Error(`invalid duration '${value}' (must be greater than zero)`);\n }\n return durationMs;\n}\n","import { readFileSync } from \"node:fs\";\nimport {\n isAssignable,\n type LinkRpcInterfaceSchema as SvcInterfaceSchema,\n type LinkRpcJsonSchema as SvcJsonSchema,\n} from \"@hediet/linkrpc\";\nimport { type CliChannel, fetchSchema } from \"@hediet/linkrpc-client\";\n\nexport interface CheckCompatOptions {\n readonly interfaceId: string;\n /** Path to a local SvcInterfaceSchema JSON file. */\n readonly localPath: string;\n}\n\nexport type CompatVerdict =\n | { kind: \"identical\"; hash: string }\n | { kind: \"compatible-subset\"; localHash: string; remoteHash: string; details: string }\n | { kind: \"incompatible\"; localHash: string; remoteHash: string; details: string };\n\nexport async function checkCompatCommand(channel: CliChannel, opts: CheckCompatOptions): Promise<CompatVerdict> {\n const local = JSON.parse(readFileSync(opts.localPath, \"utf8\")) as SvcInterfaceSchema;\n const remote = await fetchSchema(channel, opts.interfaceId, undefined);\n return diffSchemas(local, remote);\n}\n\nexport function diffSchemas(\n local: SvcInterfaceSchema,\n remote: SvcInterfaceSchema,\n): CompatVerdict {\n if (local.hash === remote.hash) return { kind: \"identical\", hash: local.hash };\n\n const localComponents = local.components?.schemas ?? {};\n const remoteComponents = remote.components?.schemas ?? {};\n const issues: string[] = [];\n\n // Direction: a client speaking `local` calls a server speaking `remote`.\n // For that to work, local params must be assignable to remote params\n // (server accepts what client sends) and remote result must be assignable\n // to local result (client accepts what server returns).\n for (const [name, lm] of Object.entries(local.methods)) {\n const rm = remote.methods[name];\n if (!rm) {\n issues.push(`method \"${name}\" missing on remote`);\n continue;\n }\n if (!safeAssignable(lm.params, rm.params, mergeComponents(localComponents, remoteComponents))) {\n issues.push(`method \"${name}\": params not assignable (local → remote)`);\n }\n if (lm.result && rm.result) {\n if (!safeAssignable(rm.result, lm.result, mergeComponents(localComponents, remoteComponents))) {\n issues.push(`method \"${name}\": result not assignable (remote → local)`);\n }\n } else if (lm.result && !rm.result) {\n issues.push(`method \"${name}\": local expects a result, remote is notification-only`);\n }\n }\n\n if (issues.length === 0) {\n return {\n kind: \"compatible-subset\",\n localHash: local.hash,\n remoteHash: remote.hash,\n details: \"all local methods are structurally assignable against remote\",\n };\n }\n return {\n kind: \"incompatible\",\n localHash: local.hash,\n remoteHash: remote.hash,\n details: issues.join(\"; \"),\n };\n}\n\nfunction safeAssignable(\n a: SvcJsonSchema,\n b: SvcJsonSchema,\n components: Record<string, SvcJsonSchema>,\n): boolean {\n try { return isAssignable(a, b, components); } catch { return false; }\n}\n\nfunction mergeComponents(\n a: Record<string, SvcJsonSchema>,\n b: Record<string, SvcJsonSchema>,\n): Record<string, SvcJsonSchema> {\n return { ...a, ...b };\n}\n\nexport function formatVerdict(v: CompatVerdict): string {\n switch (v.kind) {\n case \"identical\":\n return `identical (${v.hash})`;\n case \"compatible-subset\":\n return `compatible-subset\\n local: ${v.localHash}\\n remote: ${v.remoteHash}\\n ${v.details}`;\n case \"incompatible\":\n return `incompatible\\n local: ${v.localHash}\\n remote: ${v.remoteHash}\\n ${v.details}`;\n }\n}\n","import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { generateTsInterface } from '@hediet/linkrpc';\nimport { loadStaticHubSchema } from '../staticHubSchema';\n\nexport interface CodegenCommandOptions {\n readonly input: string;\n readonly interfaceId: string;\n readonly name: string;\n readonly output: string;\n readonly preserveWireSchema?: boolean;\n readonly check?: boolean;\n}\n\nexport async function codegenCommand(options: CodegenCommandOptions): Promise<void> {\n if (/^https?:\\/\\//i.test(options.input)) {\n throw new Error('codegen --input must be a local offline bundle');\n }\n if (!/^[$A-Z_a-z][$\\w]*$/.test(options.name)) {\n throw new Error(`codegen --name must be a valid TypeScript identifier, got '${options.name}'`);\n }\n\n const bundle = await loadStaticHubSchema(options.input);\n const matches = bundle.interfaceSchemas.filter((schema) => schema.id === options.interfaceId);\n if (matches.length === 0) {\n throw new Error(\n `Interface '${options.interfaceId}' was not found in bundle '${options.input}'`,\n );\n }\n if (matches.length > 1) {\n throw new Error(\n `Interface '${options.interfaceId}' is ambiguous in bundle '${options.input}' `\n + `(${matches.length} schema versions)`,\n );\n }\n\n const generated = generateTsInterface(matches[0]!, {\n exportName: options.name,\n preserveWireSchema: options.preserveWireSchema === true,\n });\n if (options.check === true) {\n let current: string;\n try {\n current = await readFile(options.output, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`Generated output is missing: ${options.output}`);\n }\n throw error;\n }\n if (current !== generated) {\n throw new Error(`Generated output is stale: ${options.output}`);\n }\n return;\n }\n\n await mkdir(dirname(options.output), { recursive: true });\n await writeFile(options.output, generated, 'utf8');\n}\n","/**\n * Emit shell-completion scripts. Currently PowerShell only; the entry point\n * is structured so adding bash / zsh later just plugs in another renderer.\n *\n * The scripts shell out to `hub _complete --line <line> --point <cursor>`,\n * which prints one candidate per line in the format `text\\ttooltip`. PS\n * turns each line into a `CompletionResult`.\n */\n\nexport type SupportedShell = 'powershell';\n\nconst SUPPORTED: ReadonlySet<SupportedShell> = new Set(['powershell']);\n\nexport function isSupportedShell(name: string): name is SupportedShell {\n return SUPPORTED.has(name as SupportedShell);\n}\n\nexport function emitCompletionScript(shell: SupportedShell): string {\n if (shell === 'powershell') return POWERSHELL_SCRIPT;\n throw new Error(`unsupported shell: ${shell}`);\n}\n\n/**\n * The PowerShell registration script. Self-contained — `Invoke-Expression`\n * of this string registers a native completer for `hub`, `linkrpc`, and `rpc`.\n *\n * Notes:\n * - `$commandAst.Extent.Text` is the entire pipeline element text (the\n * part PS treats as one command); `$cursorPosition` is absolute, so we\n * subtract `$commandAst.Extent.StartOffset` to get a position relative\n * to the line we're handing to the CLI.\n * - We invoke whichever binary the user is actually typing\n * (`$commandAst.CommandElements[0]`) so a local `hub.exe` and a global\n * one both work transparently.\n * - All errors are silently swallowed — a broken completer must never\n * break the user's prompt.\n */\nconst POWERSHELL_SCRIPT = `\n# linkrpc completion for PowerShell — auto-generated by \\`hub completions powershell\\`.\n# Install once with: hub completions powershell | Out-String | Invoke-Expression\n# Persist with: hub completions powershell >> $PROFILE\nRegister-ArgumentCompleter -Native -CommandName hub,linkrpc,rpc -ScriptBlock {\n param($wordToComplete, $commandAst, $cursorPosition)\n\n try {\n $line = $commandAst.Extent.Text\n $point = $cursorPosition - $commandAst.Extent.StartOffset\n if ($point -lt 0) { $point = 0 }\n if ($point -gt $line.Length) { $point = $line.Length }\n\n $binElement = $commandAst.CommandElements[0]\n $bin = if ($binElement.Value) { $binElement.Value } else { $binElement.Extent.Text }\n\n # The completer must never write to the user's prompt. Redirect stderr.\n $raw = & $bin _complete --line $line --point $point 2>$null\n if (-not $raw) { return }\n\n foreach ($entry in ($raw -split \"\\`r?\\`n\")) {\n if (-not $entry) { continue }\n $parts = $entry -split \"\\`t\", 2\n $text = $parts[0]\n $tooltip = if ($parts.Length -ge 2 -and $parts[1]) { $parts[1] } else { $text }\n [System.Management.Automation.CompletionResult]::new(\n $text,\n $text,\n [System.Management.Automation.CompletionResultType]::ParameterValue,\n $tooltip\n )\n }\n } catch {\n # Silent: a broken completer must not break the prompt.\n }\n}\n`.trimStart();\n","/**\n * `hub completions <shell>` — print the shell-completion registration script\n * for the requested shell.\n *\n * No connection required. Currently supports `powershell` only.\n */\nimport { emitCompletionScript, isSupportedShell } from '../completions/shellScripts';\n\nexport interface CompletionsCommandOptions {\n readonly shell: string;\n}\n\nexport function completionsCommand(opts: CompletionsCommandOptions): string {\n if (!isSupportedShell(opts.shell)) {\n throw new Error(\n `unsupported shell \"${opts.shell}\". Supported: powershell.`,\n );\n }\n return emitCompletionScript(opts.shell);\n}\n","import { type CliChannel, fetchDefaults } from \"@hediet/linkrpc-client\";\nimport { formatJson } from \"../output\";\n\nexport interface DefaultsCommandOptions {\n readonly json?: boolean;\n}\n\nexport async function defaultsCommand(channel: CliChannel, opts: DefaultsCommandOptions = {}): Promise<string> {\n const d = await fetchDefaults(channel);\n if (opts.json) return formatJson(d);\n if (!d.interfaceId && !d.serviceId) return \"(no preset)\";\n const lines: string[] = [];\n if (d.serviceId) lines.push(`service: ${d.serviceId}`);\n lines.push(`interface: ${d.interfaceId ?? \"(none)\"}`);\n if (d.hash) lines.push(`hash: ${d.hash}`);\n return lines.join(\"\\n\");\n}\n","import { readFileSync } from \"node:fs\";\nimport { computeInterfaceHash, type LinkRpcInterfaceSchema as SvcInterfaceSchema } from \"@hediet/linkrpc\";\n\nexport interface HashCommandOptions {\n readonly schemaPath: string;\n}\n\nexport function hashCommand(opts: HashCommandOptions): string {\n const text = readFileSync(opts.schemaPath, \"utf8\");\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (e) {\n throw new Error(`${opts.schemaPath}: invalid JSON (${(e as Error).message})`);\n }\n if (!isInterfaceSchema(parsed)) {\n throw new Error(`${opts.schemaPath}: not a SvcInterfaceSchema (missing id / methods)`);\n }\n return computeInterfaceHash(parsed);\n}\n\nfunction isInterfaceSchema(v: unknown): v is SvcInterfaceSchema {\n if (!v || typeof v !== \"object\") return false;\n const o = v as Record<string, unknown>;\n return typeof o.id === \"string\"\n && typeof o.methods === \"object\"\n && o.methods !== null\n && !Array.isArray(o.methods);\n}\n","/**\n * `hub _complete --line <line> --point <cursor>` — internal completion\n * resolver invoked by the shell scripts emitted by `hub completions`.\n *\n * Reads the line + cursor, optionally connects to whatever endpoint the line\n * already names (via `--endpoint*` flags or `LINKRPC_ENDPOINT`), and prints\n * one candidate per line as `text\\ttooltip`. Empty output on any error —\n * the completer that invokes us must never disturb the user's prompt.\n *\n * The actual resolution lives in `../completions/runComplete.ts`; this command\n * just formats the structured result for stdout.\n */\nimport { type Completion } from '../completions/complete';\nimport { completeForLine, type CompleteForLineOptions } from '../completions/runComplete';\nimport { type DirectorySource } from '../completions/directorySource';\n\nexport interface InternalCompleteOptions {\n readonly line: string;\n readonly point: number;\n /** Override the directory source (tests). */\n readonly directoryOverride?: DirectorySource;\n /** Suppress the connect attempt entirely (tests). */\n readonly skipConnect?: boolean;\n}\n\n/**\n * Compute completions and return them as a `\\n`-joined `text\\ttooltip` string\n * ready for stdout. Returns `''` when there are no candidates so callers can\n * unconditionally write the result.\n */\nexport async function internalCompleteCommand(opts: InternalCompleteOptions): Promise<string> {\n const runOpts: CompleteForLineOptions = {\n line: opts.line,\n point: opts.point,\n ...(opts.directoryOverride !== undefined ? { directoryOverride: opts.directoryOverride } : {}),\n ...(opts.skipConnect !== undefined ? { skipConnect: opts.skipConnect } : {}),\n };\n const result = await completeForLine(runOpts);\n return _formatCandidates(result.candidates);\n}\n\nfunction _formatCandidates(candidates: readonly Completion[]): string {\n return candidates\n .map((c) => (c.tooltip ? `${c.text}\\t${c.tooltip}` : c.text))\n .join('\\n');\n}\n","export interface DisplayForestNode<TNode, TEdge> {\n readonly node: TNode;\n readonly parentEdge?: TEdge;\n readonly children: readonly DisplayForestNode<TNode, TEdge>[];\n}\n\nexport interface DisplayForest<TNode, TEdge> {\n readonly roots: readonly DisplayForestNode<TNode, TEdge>[];\n readonly crossEdges: readonly TEdge[];\n}\n\nexport interface DisplayGraph<TNode, TEdge> {\n readonly nodes: readonly TNode[];\n readonly edges: readonly TEdge[];\n readonly rootIds: readonly string[];\n nodeId(node: TNode): string;\n edgeKey(edge: TEdge): string;\n edgeEndpoints(edge: TEdge): readonly [string, string];\n readonly directed?: boolean;\n}\n\n/**\n * Projects a graph into a deterministic shortest-path forest. Every node is\n * rendered once; non-tree edges remain available as explicit cross-links.\n */\nexport function createDisplayForest<TNode, TEdge>(\n graph: DisplayGraph<TNode, TEdge>,\n): DisplayForest<TNode, TEdge> {\n const nodes = new Map(graph.nodes.map((node) => [graph.nodeId(node), node]));\n const edges = [...graph.edges].sort((a, b) => graph.edgeKey(a).localeCompare(graph.edgeKey(b)));\n const adjacency = new Map<string, Array<{ edge: TEdge; next: string }>>();\n for (const edge of edges) {\n const [from, to] = graph.edgeEndpoints(edge);\n if (nodes.has(from) && nodes.has(to)) {\n addAdjacent(adjacency, from, edge, to);\n if (graph.directed !== true) addAdjacent(adjacency, to, edge, from);\n }\n }\n for (const entries of adjacency.values()) {\n entries.sort((a, b) =>\n a.next.localeCompare(b.next)\n || graph.edgeKey(a.edge).localeCompare(graph.edgeKey(b.edge)));\n }\n\n const parent = new Map<string, { parentId: string; edge: TEdge }>();\n const visited = new Set<string>();\n const roots: string[] = [];\n const walk = (rootId: string): void => {\n if (visited.has(rootId) || !nodes.has(rootId)) return;\n roots.push(rootId);\n visited.add(rootId);\n const queue = [rootId];\n for (let index = 0; index < queue.length; index++) {\n const current = queue[index];\n for (const entry of adjacency.get(current) ?? []) {\n if (visited.has(entry.next)) continue;\n visited.add(entry.next);\n parent.set(entry.next, { parentId: current, edge: entry.edge });\n queue.push(entry.next);\n }\n }\n };\n\n for (const rootId of [...new Set(graph.rootIds)].sort()) walk(rootId);\n for (const nodeId of [...nodes.keys()].sort()) walk(nodeId);\n\n const children = new Map<string, string[]>();\n for (const [nodeId, value] of parent) {\n const entries = children.get(value.parentId) ?? [];\n entries.push(nodeId);\n children.set(value.parentId, entries);\n }\n for (const entries of children.values()) entries.sort();\n\n const build = (nodeId: string): DisplayForestNode<TNode, TEdge> => ({\n node: nodes.get(nodeId)!,\n ...(parent.get(nodeId) !== undefined ? { parentEdge: parent.get(nodeId)!.edge } : {}),\n children: (children.get(nodeId) ?? []).map(build),\n });\n const treeEdgeKeys = new Set([...parent.values()].map((value) => graph.edgeKey(value.edge)));\n return {\n roots: roots.map(build),\n crossEdges: edges.filter((edge) => !treeEdgeKeys.has(graph.edgeKey(edge))),\n };\n}\n\nfunction addAdjacent<TEdge>(\n adjacency: Map<string, Array<{ edge: TEdge; next: string }>>,\n from: string,\n edge: TEdge,\n next: string,\n): void {\n const entries = adjacency.get(from) ?? [];\n entries.push({ edge, next });\n adjacency.set(from, entries);\n}\n","export type JsonValue =\n | null\n | boolean\n | number\n | string\n | JsonValue[]\n | { [key: string]: JsonValue };\n\nexport type JsonPatchOperation =\n | { readonly op: \"add\" | \"replace\"; readonly path: string; readonly value: JsonValue }\n | { readonly op: \"remove\"; readonly path: string };\n\nexport function createJsonPatch(\n before: JsonValue,\n after: JsonValue,\n path = \"\",\n): JsonPatchOperation[] {\n if (Object.is(before, after)) {\n return [];\n }\n if (isJsonObject(before) && isJsonObject(after)) {\n const operations: JsonPatchOperation[] = [];\n const beforeKeys = Object.keys(before).sort();\n const afterKeys = Object.keys(after).sort();\n const afterKeySet = new Set(afterKeys);\n for (const key of beforeKeys) {\n if (!afterKeySet.has(key)) {\n operations.push({ op: \"remove\", path: appendPath(path, key) });\n }\n }\n const beforeKeySet = new Set(beforeKeys);\n for (const key of afterKeys) {\n const childPath = appendPath(path, key);\n if (!beforeKeySet.has(key)) {\n operations.push({ op: \"add\", path: childPath, value: after[key] });\n } else {\n operations.push(...createJsonPatch(before[key], after[key], childPath));\n }\n }\n return operations;\n }\n return [{ op: \"replace\", path, value: after }];\n}\n\nexport function applyJsonPatch(\n value: JsonValue,\n operations: readonly JsonPatchOperation[],\n): JsonValue {\n let result = structuredClone(value);\n for (const operation of operations) {\n if (operation.path === \"\") {\n if (operation.op === \"remove\") {\n throw new Error(\"Cannot remove the JSON document root\");\n }\n result = structuredClone(operation.value);\n continue;\n }\n const segments = operation.path\n .slice(1)\n .split(\"/\")\n .map((segment) => segment.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\"));\n let target = result;\n for (const segment of segments.slice(0, -1)) {\n if (typeof target !== \"object\" || target === null || Array.isArray(target)) {\n throw new Error(`JSON patch path does not address an object: ${operation.path}`);\n }\n target = target[segment];\n }\n if (typeof target !== \"object\" || target === null || Array.isArray(target)) {\n throw new Error(`JSON patch path does not address an object: ${operation.path}`);\n }\n const key = segments.at(-1)!;\n if (operation.op === \"remove\") {\n delete target[key];\n } else {\n target[key] = structuredClone(operation.value);\n }\n }\n return result;\n}\n\nfunction appendPath(path: string, key: string): string {\n return `${path}/${key.replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\")}`;\n}\n\nfunction isJsonObject(value: JsonValue): value is { [key: string]: JsonValue } {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import {\n createJsonPatch,\n type JsonPatchOperation,\n type JsonValue,\n} from \"./jsonPatch\";\n\nexport type StateJsonlLine =\n | {\n readonly type: \"snapshot\";\n readonly revision: number;\n readonly value: JsonValue;\n }\n | {\n readonly type: \"patch\";\n readonly revision: number;\n readonly patch: readonly JsonPatchOperation[];\n };\n\n/**\n * Serializes changing state as one initial value followed by atomic RFC 6902\n * patches. Await {@link whenIdle} before closing the destination.\n */\nexport class StateJsonlWriter {\n private _current: JsonValue | undefined;\n private _queue = Promise.resolve();\n\n public constructor(\n private readonly _emitLine: (line: string) => void | Promise<void>,\n ) {}\n\n public write(value: unknown, revision: number): void {\n const next = toJsonValue(value);\n this._queue = this._queue.then(async () => {\n if (this._current === undefined) {\n const line: StateJsonlLine = { type: \"snapshot\", revision, value: next };\n this._current = next;\n await this._emitLine(JSON.stringify(line));\n return;\n }\n const patch = createJsonPatch(this._current, next);\n this._current = next;\n if (patch.length === 0) return;\n const line: StateJsonlLine = { type: \"patch\", revision, patch };\n await this._emitLine(JSON.stringify(line));\n });\n }\n\n public async whenIdle(): Promise<void> {\n await this._queue;\n }\n}\n\nexport function toJsonValue(value: unknown): JsonValue {\n return JSON.parse(JSON.stringify(value)) as JsonValue;\n}\n","import { mkdir, open, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { LinkRpcInterfaceSchema } from \"@hediet/linkrpc\";\nimport {\n DEFAULT_WALK_DEPTH,\n HubDirectoryExplorer,\n fetchSchema,\n type DiscoveredListing,\n type HubDirectoryGraphEvent,\n type HubDirectoryGraphSnapshot,\n type HubDirectoryNodeReport,\n type HubDirectoryGraphTarget,\n type InaccessibleDirectory,\n type ServiceListing,\n type WalkHubOptions,\n} from \"@hediet/linkrpc/hub/common\";\nimport type { CliChannel } from \"@hediet/linkrpc-client\";\nimport { formatJson } from \"../output\";\nimport { createDisplayForest, type DisplayForestNode } from \"./displayForest\";\nimport { createJsonPatch, type JsonValue } from \"./jsonPatch\";\nimport { StateJsonlWriter } from \"./stateJsonl\";\n\nexport type LsFormat = \"pretty\" | \"json\" | \"jsonl\";\n\nexport interface LsOptions {\n readonly interfaceId?: string;\n readonly interfacePrefix?: string;\n readonly serviceId?: string;\n readonly servicePrefix?: string;\n readonly search?: string;\n readonly json?: boolean;\n readonly format?: LsFormat;\n readonly withMembers?: boolean;\n /** Write a complete topology and schema fixture instead of rendering the listing. */\n readonly dumpPath?: string;\n /** Write one RFC 6902 operation per line as exploration progresses. `-` writes to stdout. */\n readonly dumpPatchesPath?: string;\n /** Emit an initial value and subsequent RFC 6902 patches as a patch-log JSONL stream. */\n readonly stream?: boolean;\n /** Keep the explorer watches active until `stop` resolves. Implies `stream`. */\n readonly watch?: boolean;\n /** Destination for stdout-oriented streaming modes. */\n readonly emitLine?: (line: string) => void | Promise<void>;\n /** Destination for a complete repainting terminal frame. */\n readonly emitFrame?: (frame: string) => void | Promise<void>;\n /** Receives each reconstructable state before it is rendered or serialized. */\n readonly onState?: (state: LsState) => void;\n /** Resolves when a watched stream should stop. */\n readonly stop?: Promise<void>;\n /**\n * When listing the whole bus, how many `hubrpc.directory` follow-ups\n * to perform. Defaults to 5. Ignored when `serviceId` is set (then we\n * just list that one service).\n */\n readonly maxDepth?: number;\n /** Hard deadline for each directory request. Defaults to 5 seconds. */\n readonly timeoutMs?: number;\n}\n\nexport interface LsState {\n readonly kind: \"directory\";\n readonly revision: number;\n readonly complete: boolean;\n readonly root: HubDirectoryNodeReport;\n readonly directories: readonly HubDirectoryNodeReport[];\n readonly listings: readonly DiscoveredListing[];\n readonly inaccessible: readonly InaccessibleDirectory[];\n}\n\n/**\n * Recursive bus walk: list the connection's directory, then for each\n * `hubrpc.directory` entry it surfaces on a service we haven't queried\n * yet, recurse. Bounded by `maxDepth`. Duplicates (same\n * `serviceId+interfaceId+hash`) are dropped.\n */\nexport async function lsCommand(channel: CliChannel, opts: LsOptions = {}): Promise<string> {\n validateLsOptions(opts);\n const legacyOutput = opts.format === undefined;\n if (opts.dumpPath !== undefined) {\n const dump = await createHubDump(channel, { maxDepth: opts.maxDepth });\n const dumpPath = path.resolve(opts.dumpPath);\n await mkdir(path.dirname(dumpPath), { recursive: true });\n await writeFile(dumpPath, `${formatJson(dump)}\\n`, \"utf8\");\n return dumpSummary(\"Wrote\", dumpPath, dump);\n }\n if (opts.dumpPatchesPath !== undefined) {\n return runStreamingLs(channel, opts);\n }\n if (legacyOutput && (opts.stream === true || opts.watch === true)) {\n return runStreamingLs(channel, opts);\n }\n const format = resolveLsFormat(opts);\n if (opts.format !== undefined || opts.watch === true) {\n return runStateLs(channel, opts, format);\n }\n\n const explorer = new HubDirectoryExplorer(channel, explorerOptions(opts));\n await explorer.explore();\n const state = createLsState(explorer.graphSnapshot, opts);\n explorer.dispose();\n const all = state.listings;\n const output = opts.withMembers\n ? await addMembers(channel, all, (listing) => listing.discoveredFrom)\n : all;\n if (format === \"json\") return formatJson(legacyOutput ? output : state);\n return renderTree(output, opts.interfaceId);\n}\n\nfunction validateLsOptions(opts: LsOptions): void {\n validateSearchExpression(opts.search, \"ls\");\n if (opts.format !== undefined && opts.withMembers === true) {\n throw new Error(\"--format cannot be combined with --with-members\");\n }\n if (opts.dumpPath !== undefined) {\n if (\n opts.interfaceId !== undefined\n || opts.interfacePrefix !== undefined\n || opts.serviceId !== undefined\n || opts.servicePrefix !== undefined\n || opts.search !== undefined\n || opts.json === true\n || opts.format !== undefined\n || opts.withMembers === true\n || opts.stream === true\n || opts.watch === true\n || opts.dumpPatchesPath !== undefined\n ) {\n throw new Error(\n \"--dump cannot be combined with filters, --with-members, --json, --format, \"\n + \"--stream, --watch, or --dump-patches\",\n );\n }\n\n }\n if (opts.dumpPatchesPath !== undefined && (\n opts.interfaceId !== undefined\n || opts.interfacePrefix !== undefined\n || opts.serviceId !== undefined\n || opts.servicePrefix !== undefined\n || opts.search !== undefined\n || opts.json === true\n || opts.format !== undefined\n || opts.withMembers === true\n || opts.stream === true\n )) {\n throw new Error(\n \"--dump-patches cannot be combined with filters, --with-members, --json, \"\n + \"--format, or --stream\",\n );\n }\n if (\n opts.format === undefined\n && (opts.stream === true || opts.watch === true)\n && opts.withMembers === true\n ) {\n throw new Error(\"--stream/--watch already emit JSON and cannot include schema members\");\n }\n if (opts.format === \"jsonl\" && opts.dumpPatchesPath === undefined) {\n if (opts.emitLine === undefined) {\n throw new Error(\"JSONL ls output requires an output sink\");\n }\n }\n if (\n opts.watch === true\n && opts.format === \"pretty\"\n && opts.emitFrame === undefined\n ) {\n throw new Error(\"pretty ls watch requires a frame output sink\");\n }\n if (opts.watch === true && opts.stop === undefined) {\n throw new Error(\"--watch requires a stop signal\");\n }\n}\n\nfunction validateSearchExpression(search: string | undefined, command: string): void {\n if (search === undefined) return;\n try {\n new RegExp(search, \"i\");\n } catch (error) {\n throw new Error(\n `Invalid ${command} search regexp: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n}\n\nfunction explorerOptions(opts: LsOptions): WalkHubOptions {\n return {\n maxDepth: opts.serviceId === undefined\n ? opts.maxDepth ?? DEFAULT_WALK_DEPTH\n : 0,\n ...(opts.interfaceId !== undefined ? { interfaceId: opts.interfaceId } : {}),\n ...(opts.interfacePrefix !== undefined\n ? { interfaceIdPrefix: opts.interfacePrefix }\n : {}),\n ...(opts.serviceId !== undefined\n ? { rootTarget: opts.serviceId, serviceId: opts.serviceId }\n : {}),\n ...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}),\n };\n}\n\nfunction resolveLsFormat(opts: LsOptions): LsFormat {\n if (opts.format !== undefined) return opts.format;\n if (opts.stream === true) return \"jsonl\";\n if (opts.json === true) return \"json\";\n return \"pretty\";\n}\n\nasync function runStateLs(\n channel: CliChannel,\n opts: LsOptions,\n format: LsFormat,\n): Promise<string> {\n const explorer = new HubDirectoryExplorer(channel, explorerOptions(opts));\n const writer = format === \"jsonl\" ? new StateJsonlWriter(opts.emitLine!) : undefined;\n let state = createLsState(explorer.graphSnapshot, opts);\n let outputQueue = Promise.resolve();\n const emitState = (snapshot: HubDirectoryGraphSnapshot): void => {\n state = createLsState(snapshot, opts);\n opts.onState?.(state);\n if (writer !== undefined) {\n writer.write(state, state.revision);\n } else if (opts.watch === true && format === \"pretty\") {\n const frame = renderLsState(state, opts);\n outputQueue = outputQueue.then(() => opts.emitFrame!(frame));\n }\n };\n const unsubscribe = explorer.subscribe((event) => emitState(event.snapshot));\n let stopWatch: (() => void) | undefined;\n try {\n if (opts.watch === true) {\n stopWatch = await explorer.watch(() => {});\n await opts.stop;\n stopWatch();\n stopWatch = undefined;\n await explorer.whenIdle();\n emitState(explorer.graphSnapshot);\n } else {\n await explorer.explore();\n emitState(explorer.graphSnapshot);\n }\n await outputQueue;\n await writer?.whenIdle();\n if (format === \"json\") return formatJson(state);\n if (format === \"pretty\") return opts.watch === true ? \"\" : renderLsState(state, opts);\n return \"\";\n } finally {\n stopWatch?.();\n unsubscribe();\n explorer.dispose();\n await outputQueue;\n await writer?.whenIdle();\n }\n}\n\nexport function createLsState(\n snapshot: HubDirectoryGraphSnapshot,\n opts: Pick<\n LsOptions,\n \"interfaceId\" | \"interfacePrefix\" | \"serviceId\" | \"servicePrefix\" | \"search\"\n > = {},\n): LsState {\n const matches = createListingFilter(opts);\n const mapNode = (node: HubDirectoryNodeReport): HubDirectoryNodeReport => ({\n ...node,\n nativeListings: node.nativeListings.filter(matches),\n });\n return {\n kind: \"directory\",\n revision: snapshot.revision,\n complete: snapshot.complete,\n root: mapNode(snapshot.root),\n directories: snapshot.directories.map(mapNode),\n listings: snapshot.result.listings.filter(matches),\n inaccessible: snapshot.result.inaccessible,\n };\n}\n\nfunction createListingFilter(\n opts: Pick<\n LsOptions,\n \"interfaceId\" | \"interfacePrefix\" | \"serviceId\" | \"servicePrefix\" | \"search\"\n >,\n): (listing: ServiceListing) => boolean {\n let search: RegExp | undefined;\n if (opts.search !== undefined) {\n try {\n search = new RegExp(opts.search, \"i\");\n } catch (error) {\n throw new Error(\n `Invalid ls search regexp: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n return (listing) =>\n (opts.interfaceId === undefined || listing.interfaceId === opts.interfaceId)\n && (opts.interfacePrefix === undefined\n || listing.interfaceId.startsWith(opts.interfacePrefix))\n && (opts.serviceId === undefined || listing.serviceId === opts.serviceId)\n && (opts.servicePrefix === undefined\n || listing.serviceId.startsWith(opts.servicePrefix))\n && (search === undefined || search.test(JSON.stringify(listing)));\n}\n\nfunction renderLsState(state: LsState, opts: Pick<LsOptions, \"interfaceId\">): string {\n const status = state.complete ? \"complete\" : \"loading\";\n const nodes = [state.root, ...state.directories];\n const edges: DirectoryDisplayEdge[] = [];\n for (const node of nodes) {\n for (const parent of node.parents) {\n edges.push({\n from: directoryTargetKey(parent.target),\n to: directoryTargetKey(node.target),\n scopes: parent.scopes.map((scope) =>\n \"exact\" in scope ? `=${scope.exact}` : `${scope.prefix}*`),\n });\n }\n }\n const forest = createDisplayForest({\n nodes,\n edges,\n rootIds: [directoryTargetKey(state.root.target)],\n nodeId: (node) => directoryTargetKey(node.target),\n edgeKey: (edge) => `${edge.from}\\0${edge.to}\\0${edge.scopes.join(\"\\0\")}`,\n edgeEndpoints: (edge) => [edge.from, edge.to],\n directed: true,\n });\n const body: string[] = [];\n for (const root of forest.roots) renderDirectoryNode(root, body, \"\");\n if (forest.crossEdges.length > 0) {\n body.push(\"\", \"Additional referrals\");\n for (const edge of forest.crossEdges) {\n body.push(` ${edge.from} → ${edge.to}${formatScopes(edge.scopes)}`);\n }\n }\n if (state.inaccessible.length > 0) {\n body.push(\"\", \"Inaccessible\");\n for (const item of state.inaccessible) {\n body.push(` ${item.serviceId}: ${item.reason}`);\n }\n }\n return [\n `LinkRPC directory (${status}, revision ${state.revision})`,\n \"\",\n ...(body.length > 0 ? body : [\"(empty)\"]),\n ].join(\"\\n\");\n}\n\ninterface DirectoryDisplayEdge {\n readonly from: string;\n readonly to: string;\n readonly scopes: readonly string[];\n}\n\nfunction renderDirectoryNode(\n item: DisplayForestNode<HubDirectoryNodeReport, DirectoryDisplayEdge>,\n lines: string[],\n prefix: string,\n): void {\n const watch = item.node.watching ? \", watching\" : \"\";\n lines.push(\n `${prefix}${directoryTargetLabel(item.node.target)} [${item.node.state}${watch}]`\n + (item.parentEdge === undefined ? \"\" : formatScopes(item.parentEdge.scopes)),\n );\n for (const listing of item.node.nativeListings) {\n const service = listing.serviceId === \"\" ? \"(root)\" : listing.serviceId;\n lines.push(`${prefix} ${service} → ${listing.interfaceId} @ ${listing.hash}`);\n }\n if (item.node.inaccessibleReason !== undefined) {\n lines.push(`${prefix} ! ${item.node.inaccessibleReason}`);\n }\n for (let index = 0; index < item.children.length; index++) {\n const child = item.children[index];\n const last = index === item.children.length - 1;\n const childPrefix = prefix + (last ? \" \" : \"│ \");\n const childLines: string[] = [];\n renderDirectoryNode(child, childLines, childPrefix);\n childLines[0] = `${prefix}${last ? \"└─ \" : \"├─ \"}${childLines[0].slice(childPrefix.length)}`;\n lines.push(...childLines);\n }\n}\n\nfunction directoryTargetKey(target: HubDirectoryGraphTarget): string {\n return target.kind === \"root\"\n ? `root:${target.serviceId ?? \"\"}`\n : `service:${target.serviceId}`;\n}\n\nfunction directoryTargetLabel(target: HubDirectoryGraphTarget): string {\n if (target.kind === \"addressed\") return target.serviceId;\n return target.serviceId === undefined || target.serviceId === \"\"\n ? \"(connection root)\"\n : `(root listing for ${target.serviceId})`;\n}\n\nfunction formatScopes(scopes: readonly string[]): string {\n return scopes.length === 0 ? \"\" : ` via ${scopes.join(\", \")}`;\n}\n\ninterface LsMember {\n readonly name: string;\n readonly kind: \"request\" | \"notification\";\n}\n\ninterface LsListing extends ServiceListing {\n readonly members?: readonly LsMember[];\n}\n\nasync function addMembers<T extends ServiceListing>(\n channel: CliChannel,\n listings: readonly T[],\n getTarget: (listing: T) => string | undefined,\n): Promise<LsListing[]> {\n const cache = new Map<string, Promise<readonly LsMember[]>>();\n return Promise.all(listings.map(async (listing) => {\n const target = getTarget(listing);\n const cacheKey = `${target ?? \"\"}\\0${listing.interfaceId}\\0${listing.hash}`;\n let members = cache.get(cacheKey);\n if (members === undefined) {\n members = fetchSchema(\n channel,\n listing.interfaceId,\n listing.hash,\n target === \"\" ? undefined : target,\n ).then((schema) =>\n Object.entries(schema.methods)\n .map(([name, method]): LsMember => ({\n name,\n kind: method.result === undefined ? \"notification\" : \"request\",\n }))\n .sort((a, b) => a.name.localeCompare(b.name))\n );\n cache.set(cacheKey, members);\n }\n return { ...listing, members: await members };\n }));\n}\n\nexport interface HubDumpSchemaError {\n readonly interfaceIds: readonly string[];\n readonly attempts: readonly {\n readonly reportedBy: string;\n readonly interfaceId: string;\n readonly error: string;\n }[];\n}\n\nexport interface HubDump {\n readonly format: \"linkrpc-hub-dump\";\n readonly version: 2;\n readonly revision: number;\n readonly complete: boolean;\n readonly schemasComplete: boolean;\n readonly root: HubDirectoryNodeReport;\n readonly directories: Readonly<Record<string, HubDirectoryNodeReport>>;\n readonly listings: readonly DiscoveredListing[];\n readonly inaccessible: readonly InaccessibleDirectory[];\n /** Complete reflected interface schemas, deduplicated by interface hash. */\n readonly schemas: Readonly<Record<string, LinkRpcInterfaceSchema>>;\n /** Hashes advertised by a directory but not retrievable from any reporter. */\n readonly schemaErrors: Readonly<Record<string, HubDumpSchemaError>>;\n}\n\nexport function createInitialHubDump(): HubDump {\n return {\n format: \"linkrpc-hub-dump\",\n version: 2,\n revision: 0,\n complete: false,\n schemasComplete: false,\n root: {\n target: { kind: \"root\" },\n state: \"unexplored\",\n effectiveScopes: [{ prefix: \"\" }],\n depth: 0,\n parents: [],\n nativeListings: [],\n watching: false,\n },\n directories: {},\n listings: [],\n inaccessible: [],\n schemas: {},\n schemaErrors: {},\n };\n}\n\nexport async function createHubDump(\n channel: CliChannel,\n opts: Pick<LsOptions, \"maxDepth\"> = {},\n): Promise<HubDump> {\n const explorer = new HubDirectoryExplorer(channel, {\n maxDepth: opts.maxDepth ?? DEFAULT_WALK_DEPTH,\n });\n await explorer.explore();\n const cache = await fetchDumpSchemas(channel, explorer.graphSnapshot);\n const dump = buildHubDump(explorer.graphSnapshot, cache, true);\n explorer.dispose();\n return dump;\n}\n\ninterface SchemaCandidate {\n readonly reportedBy: string;\n readonly target: string | undefined;\n readonly interfaceId: string;\n}\n\ninterface DumpSchemaCache {\n readonly schemas: Map<string, LinkRpcInterfaceSchema>;\n readonly errors: Map<string, HubDumpSchemaError>;\n}\n\nasync function fetchDumpSchemas(\n channel: CliChannel,\n snapshot: HubDirectoryGraphSnapshot,\n cache: DumpSchemaCache = { schemas: new Map(), errors: new Map() },\n): Promise<DumpSchemaCache> {\n const candidatesByHash = collectSchemaCandidates(snapshot);\n for (const [hash, candidates] of candidatesByHash) {\n if (cache.schemas.has(hash)) continue;\n cache.errors.delete(hash);\n const attempts: { reportedBy: string; interfaceId: string; error: string; }[] = [];\n for (const candidate of candidates) {\n try {\n const schema = await fetchSchema(\n channel,\n candidate.interfaceId,\n hash,\n candidate.target,\n );\n cache.schemas.set(hash, schema);\n break;\n } catch (error) {\n attempts.push({\n reportedBy: candidate.reportedBy,\n interfaceId: candidate.interfaceId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n if (!cache.schemas.has(hash)) {\n cache.errors.set(hash, {\n interfaceIds: [...new Set(candidates.map((candidate) => candidate.interfaceId))],\n attempts,\n });\n }\n }\n return cache;\n}\n\nfunction buildHubDump(\n snapshot: HubDirectoryGraphSnapshot,\n cache: DumpSchemaCache,\n schemasComplete: boolean,\n): HubDump {\n const directories = Object.fromEntries(snapshot.directories.map((directory) => [\n directory.target.kind === \"addressed\" ? directory.target.serviceId : \"\",\n directory,\n ]));\n const activeHashes = new Set(collectSchemaCandidates(snapshot).keys());\n for (const hash of [...cache.schemas.keys()]) {\n if (!activeHashes.has(hash)) cache.schemas.delete(hash);\n }\n for (const hash of [...cache.errors.keys()]) {\n if (!activeHashes.has(hash)) cache.errors.delete(hash);\n }\n return {\n format: \"linkrpc-hub-dump\",\n version: 2,\n revision: snapshot.revision,\n complete: snapshot.complete,\n schemasComplete,\n root: snapshot.root,\n directories,\n listings: snapshot.result.listings,\n inaccessible: snapshot.result.inaccessible,\n schemas: Object.fromEntries(cache.schemas),\n schemaErrors: Object.fromEntries(cache.errors),\n };\n}\n\nfunction collectSchemaCandidates(\n snapshot: HubDirectoryGraphSnapshot,\n): Map<string, SchemaCandidate[]> {\n const result = new Map<string, SchemaCandidate[]>();\n for (const report of [snapshot.root, ...snapshot.directories]) {\n const target = report.target.serviceId;\n const reportedBy = target ?? \"\";\n for (const listing of report.nativeListings) {\n const candidates = result.get(listing.hash) ?? [];\n if (!candidates.some((candidate) =>\n candidate.reportedBy === reportedBy\n && candidate.interfaceId === listing.interfaceId\n )) {\n candidates.push({ reportedBy, target, interfaceId: listing.interfaceId });\n result.set(listing.hash, candidates);\n }\n }\n }\n return result;\n}\n\nasync function runStreamingLs(channel: CliChannel, opts: LsOptions): Promise<string> {\n const explorer = new HubDirectoryExplorer(channel, explorerOptions(opts));\n const patchMode = opts.dumpPatchesPath !== undefined;\n const patchPath = patchMode && opts.dumpPatchesPath !== \"-\"\n ? path.resolve(opts.dumpPatchesPath)\n : undefined;\n if (patchPath !== undefined) await mkdir(path.dirname(patchPath), { recursive: true });\n const file = patchPath !== undefined ? await open(patchPath, \"w\") : undefined;\n const writeLine = file !== undefined\n ? async (line: string) => { await file.write(`${line}\\n`); }\n : opts.emitLine;\n if (writeLine === undefined) {\n explorer.dispose();\n throw new Error(\"--dump-patches - requires an output sink\");\n }\n\n let currentDump = createInitialHubDump();\n let previousListings: readonly DiscoveredListing[] = [];\n let previousStreamValue: LsStreamEvent | undefined;\n const schemaCache: DumpSchemaCache = { schemas: new Map(), errors: new Map() };\n let queue = Promise.resolve();\n const unsubscribe = explorer.subscribe((event) => {\n queue = queue.then(async () => {\n if (patchMode) {\n if (event.type === \"settled\") {\n await fetchDumpSchemas(channel, event.snapshot, schemaCache);\n }\n const schemasComplete = event.snapshot.complete\n && [...collectSchemaCandidates(event.snapshot).keys()].every((hash) =>\n schemaCache.schemas.has(hash) || schemaCache.errors.has(hash));\n const next = buildHubDump(event.snapshot, schemaCache, schemasComplete);\n for (const operation of createJsonPatch(\n toJsonValue(currentDump),\n toJsonValue(next),\n )) {\n await writeLine(JSON.stringify(operation));\n }\n currentDump = next;\n } else {\n const nextStreamValue = createLsStreamEvent(event, previousListings);\n await writeLine(JSON.stringify(createPatchLogLine(event, previousStreamValue, nextStreamValue)));\n previousListings = event.snapshot.result.listings;\n previousStreamValue = nextStreamValue;\n }\n });\n });\n\n let stopWatch: (() => void) | undefined;\n try {\n if (opts.watch === true) {\n stopWatch = await explorer.watch(() => {});\n } else {\n await explorer.explore();\n }\n await queue;\n if (opts.watch === true) {\n await opts.stop;\n stopWatch();\n stopWatch = undefined;\n await explorer.whenIdle();\n await queue;\n }\n } finally {\n stopWatch?.();\n unsubscribe();\n explorer.dispose();\n try {\n await queue;\n } finally {\n await file?.close();\n }\n }\n\n if (patchPath !== undefined) {\n return dumpSummary(\"Wrote patches to\", patchPath, currentDump);\n }\n return \"\";\n}\n\ninterface LsStreamEvent {\n readonly type: HubDirectoryGraphEvent[\"type\"];\n readonly reason?: string;\n readonly revision: number;\n readonly complete: boolean;\n readonly target?: HubDirectoryNodeReport[\"target\"];\n readonly state?: HubDirectoryNodeReport[\"state\"];\n readonly added: readonly DiscoveredListing[];\n readonly removed: readonly DiscoveredListing[];\n readonly listings: readonly DiscoveredListing[];\n readonly inaccessible: readonly InaccessibleDirectory[];\n}\n\ntype LsPatchLogLine =\n | {\n readonly message: string;\n readonly time: number;\n readonly value: LsStreamEvent;\n }\n | {\n readonly message: string;\n readonly time: number;\n readonly patch: ReturnType<typeof createJsonPatch>;\n };\n\nfunction createPatchLogLine(\n event: HubDirectoryGraphEvent,\n previous: LsStreamEvent | undefined,\n next: LsStreamEvent,\n): LsPatchLogLine {\n const metadata = {\n message: describeLsStreamEvent(event),\n time: Date.now(),\n };\n if (previous === undefined) {\n return { ...metadata, value: next };\n }\n return {\n ...metadata,\n patch: createJsonPatch(toJsonValue(previous), toJsonValue(next)),\n };\n}\n\nfunction describeLsStreamEvent(event: HubDirectoryGraphEvent): string {\n if (event.type === \"settled\") return \"Directory exploration settled\";\n const subject = event.type === \"snapshot\"\n ? \"Directory snapshot\"\n : event.type === \"node-added\"\n ? \"Directory node added\"\n : event.type === \"node-updated\"\n ? \"Directory node updated\"\n : \"Directory node removed\";\n return `${subject}: ${event.reason}`;\n}\n\nfunction createLsStreamEvent(\n event: HubDirectoryGraphEvent,\n previousListings: readonly DiscoveredListing[],\n): LsStreamEvent {\n const current = event.snapshot.result.listings;\n const previousByKey = new Map(previousListings.map((listing) => [listingKey(listing), listing]));\n const currentByKey = new Map(current.map((listing) => [listingKey(listing), listing]));\n const node = \"node\" in event ? event.node : undefined;\n return {\n type: event.type,\n ...(\"reason\" in event ? { reason: event.reason } : {}),\n revision: event.snapshot.revision,\n complete: event.snapshot.complete,\n ...(node !== undefined ? { target: node.target, state: node.state } : {}),\n added: current.filter((listing) => !previousByKey.has(listingKey(listing))),\n removed: previousListings.filter((listing) => !currentByKey.has(listingKey(listing))),\n listings: current,\n inaccessible: event.snapshot.result.inaccessible,\n };\n}\n\nfunction listingKey(listing: ServiceListing): string {\n return `${listing.serviceId}\\0${listing.interfaceId}\\0${listing.hash}`;\n}\n\nfunction toJsonValue(value: unknown): JsonValue {\n return JSON.parse(JSON.stringify(value)) as JsonValue;\n}\n\nfunction dumpSummary(prefix: string, destination: string, dump: HubDump): string {\n return `${prefix} ${destination} (${Object.keys(dump.directories).length + 1} directories, `\n + `${Object.keys(dump.schemas).length} schemas)`;\n}\n\nfunction renderTree(\n listings: readonly LsListing[],\n interfaceFilter: string | undefined,\n): string {\n if (listings.length === 0) {\n return interfaceFilter\n ? `(no interfaces matching \"${interfaceFilter}\")`\n : \"(no services)\";\n }\n\n const byService = new Map<string, LsListing[]>();\n for (const l of listings) {\n const bucket = byService.get(l.serviceId) ?? [];\n bucket.push(l);\n byService.set(l.serviceId, bucket);\n }\n const serviceIds = [...byService.keys()].sort((a, b) => {\n // Root first, then lexical.\n if (a === b) return 0;\n if (a === \"\") return -1;\n if (b === \"\") return 1;\n return a < b ? -1 : 1;\n });\n\n const lines: string[] = [];\n for (const sid of serviceIds) {\n lines.push(sid === \"\" ? \"(root)\" : sid);\n const ifaces = (byService.get(sid) ?? [])\n .slice()\n .sort((a, b) => (a.interfaceId < b.interfaceId ? -1 : a.interfaceId > b.interfaceId ? 1 : 0));\n for (let i = 0; i < ifaces.length; i++) {\n const isLast = i === ifaces.length - 1;\n const branch = isLast ? \"└── \" : \"├── \";\n const path = ifaces[i].path ? ` [${ifaces[i].path}]` : \"\";\n lines.push(`${branch}${ifaces[i].interfaceId} @ ${ifaces[i].hash}${path}`);\n const members = ifaces[i].members ?? [];\n for (let j = 0; j < members.length; j++) {\n const memberPrefix = isLast ? \" \" : \"│ \";\n const memberBranch = j === members.length - 1 ? \"└── \" : \"├── \";\n lines.push(\n `${memberPrefix}${memberBranch}${members[j].kind.padEnd(12)} ${members[j].name}`,\n );\n }\n }\n }\n return lines.join(\"\\n\");\n}\n","import { LinkRpcConnection } from \"@hediet/linkrpc\";\nimport type {\n NetworkTopologyGraph,\n SourcedTopologyLink,\n SourcedTopologyNode,\n TopologyNetworkSnapshot,\n} from \"@hediet/linkrpc-infra/inspection\";\nimport { TopologyNetworkClient } from \"@hediet/linkrpc-infra/inspection\";\nimport type { CliChannel } from \"@hediet/linkrpc-client\";\nimport { formatJson } from \"../output\";\nimport { createDisplayForest, type DisplayForestNode } from \"./displayForest\";\nimport { StateJsonlWriter } from \"./stateJsonl\";\n\nexport type TopologyFormat = \"pretty\" | \"json\" | \"jsonl\";\n\nexport interface TopologyCommandOptions {\n readonly sources?: readonly string[];\n readonly maxDepth?: number;\n readonly timeoutMs?: number;\n readonly watch?: boolean;\n readonly format?: TopologyFormat;\n readonly nodeId?: string;\n readonly serviceId?: string;\n readonly kind?: \"hub\" | \"endpoint\";\n readonly search?: string;\n readonly emitLine?: (line: string) => void | Promise<void>;\n readonly emitFrame?: (frame: string) => void | Promise<void>;\n readonly onState?: (state: TopologyNetworkSnapshot) => void;\n readonly stop?: Promise<void>;\n}\n\nexport async function topologyCommand(\n channel: CliChannel,\n options: TopologyCommandOptions = {},\n): Promise<string> {\n const format = options.format ?? \"pretty\";\n compileTopologySearch(options.search);\n if (format === \"jsonl\" && options.emitLine === undefined) {\n throw new Error(\"JSONL topology output requires an output sink\");\n }\n if (options.watch === true && options.stop === undefined) {\n throw new Error(\"topology watch requires a stop signal\");\n }\n if (options.watch === true && format === \"pretty\" && options.emitFrame === undefined) {\n throw new Error(\"pretty topology watch requires a frame output sink\");\n }\n\n const connection = new LinkRpcConnection(channel);\n const client = new TopologyNetworkClient(connection);\n const writer = format === \"jsonl\" ? new StateJsonlWriter(options.emitLine!) : undefined;\n let latest: TopologyNetworkSnapshot | undefined;\n let outputQueue = Promise.resolve();\n const consume = (snapshot: TopologyNetworkSnapshot): void => {\n latest = filterTopologySnapshot(snapshot, options);\n options.onState?.(latest);\n if (writer !== undefined) {\n writer.write(latest, latest.revision);\n } else if (options.watch === true && format === \"pretty\") {\n const frame = renderTopology(latest);\n outputQueue = outputQueue.then(() => options.emitFrame!(frame));\n }\n };\n const sourceOptions = {\n ...(options.sources !== undefined ? { sourceServiceIds: options.sources } : {}),\n ...(options.maxDepth !== undefined ? { maxDepth: options.maxDepth } : {}),\n ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n };\n\n if (options.watch === true) {\n const watch = client.watch(sourceOptions);\n const unsubscribe = watch.subscribe(consume);\n try {\n await options.stop;\n } finally {\n await watch.cancel(\"topology CLI stopped\");\n unsubscribe();\n }\n } else {\n latest = await client.query(sourceOptions, { onSnapshot: consume });\n latest = filterTopologySnapshot(latest, options);\n }\n\n await outputQueue;\n await writer?.whenIdle();\n const snapshot = latest ?? filterTopologySnapshot(\n await client.query(sourceOptions),\n options,\n );\n if (format === \"json\") return formatJson(snapshot);\n if (format === \"pretty\") return options.watch === true ? \"\" : renderTopology(snapshot);\n return \"\";\n}\n\nexport function filterTopologySnapshot(\n snapshot: TopologyNetworkSnapshot,\n options: Pick<TopologyCommandOptions, \"nodeId\" | \"serviceId\" | \"kind\" | \"search\">,\n): TopologyNetworkSnapshot {\n const hasFilter = options.nodeId !== undefined\n || options.serviceId !== undefined\n || options.kind !== undefined\n || options.search !== undefined;\n if (!hasFilter) return snapshot;\n const search = compileTopologySearch(options.search);\n const graph = snapshot.graph;\n const routesByNode = new Map<string, NetworkTopologyGraph[\"routes\"]>();\n for (const route of graph.routes) {\n const routes = routesByNode.get(route.nodeId) ?? [];\n routesByNode.set(route.nodeId, [...routes, route]);\n }\n const matchingNodeIds = new Set(graph.nodes\n .filter((node) => {\n const routes = routesByNode.get(node.nodeId) ?? [];\n return (options.nodeId === undefined || node.nodeId === options.nodeId)\n && (options.kind === undefined || node.kind === options.kind)\n && (options.serviceId === undefined\n || routes.some((route) => route.serviceId === options.serviceId))\n && (search === undefined || search.test(JSON.stringify({\n node,\n routes,\n })));\n })\n .map((node) => node.nodeId));\n const nodes = graph.nodes.filter((node) => matchingNodeIds.has(node.nodeId));\n const nodeIds = new Set(nodes.map((node) => node.nodeId));\n return {\n ...snapshot,\n graph: {\n ...graph,\n nodes,\n links: graph.links.filter((link) =>\n nodeIds.has(link.from.nodeId) && nodeIds.has(link.to.nodeId)),\n routes: graph.routes.filter((route) =>\n nodeIds.has(route.nodeId)\n && (options.serviceId === undefined || route.serviceId === options.serviceId)),\n },\n };\n}\n\nfunction compileTopologySearch(search: string | undefined): RegExp | undefined {\n if (search === undefined) return undefined;\n try {\n return new RegExp(search, \"i\");\n } catch (error) {\n throw new Error(\n `Invalid topology search regexp: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n}\n\nexport function renderTopology(snapshot: TopologyNetworkSnapshot): string {\n const sourceLines = snapshot.sources.map((source) => {\n const marker = source.state === \"ready\" ? \"✓\" : source.state === \"loading\" ? \"…\" : \"!\";\n return ` ${marker} ${source.serviceId}${source.error ? ` — ${source.error}` : \"\"}`;\n });\n const forest = createDisplayForest({\n nodes: snapshot.graph.nodes,\n edges: snapshot.graph.links,\n rootIds: snapshot.graph.sources.map((source) => source.entryNodeId),\n nodeId: (node) => node.nodeId,\n edgeKey: topologyLinkKey,\n edgeEndpoints: (link) => [link.from.nodeId, link.to.nodeId],\n });\n const routeMap = new Map<string, NetworkTopologyGraph[\"routes\"]>();\n for (const route of snapshot.graph.routes) {\n const routes = routeMap.get(route.nodeId) ?? [];\n routeMap.set(route.nodeId, [...routes, route]);\n }\n const treeLines: string[] = [];\n for (const root of forest.roots) renderTopologyNode(root, routeMap, treeLines, \"\");\n if (forest.crossEdges.length > 0) {\n treeLines.push(\"\", \"Additional links\");\n for (const link of forest.crossEdges) {\n treeLines.push(` ${formatEndpoint(link.from)} ↔ ${formatEndpoint(link.to)}`);\n }\n }\n const status = snapshot.complete ? \"complete\" : \"loading\";\n return [\n `LinkRPC topology (${status}, revision ${snapshot.revision})`,\n \"\",\n \"Sources\",\n ...(sourceLines.length > 0 ? sourceLines : [\" (none)\"]),\n \"\",\n \"Network\",\n ...(treeLines.length > 0 ? treeLines : [\" (empty)\"]),\n ].join(\"\\n\");\n}\n\nfunction renderTopologyNode(\n item: DisplayForestNode<SourcedTopologyNode, SourcedTopologyLink>,\n routes: ReadonlyMap<string, NetworkTopologyGraph[\"routes\"]>,\n lines: string[],\n prefix: string,\n): void {\n const label = participantLabel(item.node);\n lines.push(`${prefix}${label} [${item.node.kind ?? \"unknown\"}]`);\n for (const route of routes.get(item.node.nodeId) ?? []) {\n lines.push(`${prefix} ${route.match.padEnd(6)} ${route.serviceId} → ${route.portId}`);\n }\n for (let index = 0; index < item.children.length; index++) {\n const child = item.children[index];\n const last = index === item.children.length - 1;\n const branch = last ? \"└─ \" : \"├─ \";\n const childPrefix = prefix + (last ? \" \" : \"│ \");\n const childLines: string[] = [];\n renderTopologyNode(child, routes, childLines, childPrefix);\n childLines[0] = `${prefix}${branch}${childLines[0].slice(childPrefix.length)}`;\n lines.push(...childLines);\n }\n}\n\nfunction participantLabel(node: SourcedTopologyNode): string {\n for (const source of node.descriptors ?? []) {\n if (source.descriptor.label !== undefined) return source.descriptor.label;\n }\n return node.label ?? node.nodeId;\n}\n\nfunction topologyLinkKey(link: SourcedTopologyLink): string {\n const endpoints = [formatEndpoint(link.from), formatEndpoint(link.to)].sort();\n return `${endpoints[0]}\\0${endpoints[1]}`;\n}\n\nfunction formatEndpoint(endpoint: { readonly nodeId: string; readonly portId: string }): string {\n return `${endpoint.nodeId}:${endpoint.portId}`;\n}\n","import type { CliChannel } from \"@hediet/linkrpc-client\";\n\nexport async function pingCommand(channel: CliChannel): Promise<string> {\n const start = performance.now();\n await channel.sendRequest(\"hubrpc.defaults::get\", {});\n const latencyMs = performance.now() - start;\n return `pong ${latencyMs.toFixed(1)}ms`;\n}\n","import { createInterface } from 'node:readline/promises';\nimport { stdin as input, stdout as output } from 'node:process';\nimport {\n LinkRpcConnection,\n type TopologyGraph,\n type TrafficEvent,\n type TrafficTransitEvent,\n} from '@hediet/linkrpc';\nimport {\n HubDirectoryExplorer,\n} from '@hediet/linkrpc/hub/common';\nimport type {\n ParticipantDescriptorSource,\n RouteClaim,\n} from '@hediet/linkrpc';\nimport {\n formatFlowSummary,\n TrafficFlowAggregator,\n} from '@hediet/linkrpc-hub';\nimport { TopologyClient, TrafficClient } from '@hediet/linkrpc-infra/inspection';\nimport type { CliChannel } from '@hediet/linkrpc-client';\nimport { formatJson } from '../output';\n\nexport interface ParticipantWatchOptions {\n readonly search?: string;\n readonly nodeId?: string;\n readonly format?: 'pretty' | 'plain' | 'jsonl';\n readonly methodPrefix?: string;\n readonly payloadBytes?: number;\n readonly resume?: string | true;\n readonly stop: Promise<void>;\n readonly emit?: (line: string) => void;\n}\n\nexport interface ParticipantSummary {\n readonly nodeId: string;\n readonly descriptors: readonly ParticipantDescriptorSource[];\n readonly routeClaims: readonly RouteClaim[];\n readonly serviceIds: readonly string[];\n readonly sourceServices: readonly string[];\n}\n\ninterface InspectionSource {\n readonly serviceId: string;\n readonly graph: TopologyGraph;\n}\n\nconst TOPOLOGY_INTERFACE = 'hubrpc.topology';\n\nexport async function topologyParticipantsCommand(\n channel: CliChannel,\n search?: string,\n): Promise<string> {\n const participants = await discoverParticipants(channel);\n const filtered = filterParticipants(participants, search);\n return formatJson(filtered);\n}\n\nexport async function trafficWatchCommand(\n channel: CliChannel,\n options: ParticipantWatchOptions,\n): Promise<void> {\n const emit = options.emit ?? ((line: string) => process.stdout.write(line + '\\n'));\n const connection = new LinkRpcConnection(channel);\n const sources = await discoverTopologySources(channel, connection);\n let participants = summarizeParticipants(sources);\n let search = options.search;\n let nodeId = options.nodeId;\n let methodPrefix = options.methodPrefix;\n let payloadBytes = options.payloadBytes;\n let format = options.format;\n\n if (options.resume !== undefined) {\n const resumed = await readResume(options.resume);\n search ??= resumed.search;\n nodeId ??= resumed.nodeId;\n methodPrefix ??= resumed.methodPrefix;\n payloadBytes ??= resumed.payloadBytes;\n format ??= resumed.format;\n }\n\n let selected = selectParticipant(filterParticipants(participants, search), nodeId);\n if (selected === undefined && options.nodeId === undefined && search !== undefined) {\n selected = selectParticipant(filterParticipants(participants, search), undefined);\n }\n if (selected === undefined && process.stdin.isTTY && process.stdout.isTTY) {\n const prompted = await promptForParticipant(participants, search);\n selected = prompted?.participant;\n search = prompted?.search ?? search;\n }\n if (selected === undefined) {\n throw new Error(\n 'No participant matched. Use --search <regexp> or --node <nodeId>; '\n + 'interactive selection requires a TTY.',\n );\n }\n\n const serviceId = serviceForParticipant(sources, selected.nodeId);\n if (serviceId === undefined) {\n throw new Error(`Participant ${selected.nodeId} has no addressable service route.`);\n }\n\n await writeResume(options.resume, {\n search,\n nodeId: selected.nodeId,\n methodPrefix,\n format,\n payloadBytes,\n });\n\n format ??= process.stdout.isTTY ? 'pretty' : 'plain';\n const session = {\n type: 'session',\n version: 1,\n nodeId: selected.nodeId,\n serviceId,\n search,\n format,\n methodPrefix,\n payloadBytes,\n };\n if (format === 'jsonl') emit(JSON.stringify(session));\n else emit(`Watching participant ${selected.nodeId} via ${serviceId}`);\n\n let aggregator: TrafficFlowAggregator | undefined;\n if (format === 'pretty') {\n aggregator = new TrafficFlowAggregator({\n onFlow: (flow) => emit(formatFlowSummary(flow)),\n });\n }\n\n const traffic = new TrafficClient(connection, serviceId);\n const callbacks = {\n onTransit: (event: TrafficTransitEvent) => {\n if (aggregator !== undefined) {\n aggregator.add(event);\n } else if (format === 'jsonl') {\n emit(JSON.stringify({ type: 'transit', event }));\n } else {\n emit(formatTransit(event));\n }\n },\n onOverflow: (event: Extract<TrafficEvent, { type: 'overflow' }>) => {\n emit(format === 'jsonl'\n ? JSON.stringify({ type: 'overflow', event })\n : `traffic overflow: dropped ${event.dropped} events`);\n },\n onError: (error: unknown) => {\n emit(`traffic watch failed: ${error instanceof Error ? error.message : String(error)}`);\n },\n };\n const watch = payloadBytes === undefined\n ? traffic.watch(\n { methodPrefix },\n callbacks,\n )\n : traffic.watchWithPayloads(\n { methodPrefix, maxPayloadBytes: payloadBytes },\n callbacks,\n );\n\n try {\n await Promise.race([watch.done, options.stop]);\n } finally {\n await watch.cancel('cli-watch-ended');\n aggregator?.flush();\n aggregator?.dispose();\n if (format === 'jsonl') {\n emit(JSON.stringify({ type: 'end', reason: 'stopped' }));\n }\n }\n}\n\nasync function discoverTopologySources(\n channel: CliChannel,\n connection: LinkRpcConnection,\n): Promise<readonly InspectionSource[]> {\n const explorer = new HubDirectoryExplorer(channel, { maxDepth: 5 });\n const result = await explorer.explore();\n const serviceIds = unique(\n result.listings\n .filter((listing) => listing.interfaceId === TOPOLOGY_INTERFACE)\n .map((listing) => listing.serviceId),\n );\n const sources: InspectionSource[] = [];\n for (const serviceId of serviceIds) {\n const graph = await new TopologyClient(connection, serviceId).getGraph();\n sources.push({ serviceId, graph });\n }\n explorer.dispose();\n return sources;\n}\n\nasync function discoverParticipants(channel: CliChannel): Promise<readonly ParticipantSummary[]> {\n return summarizeParticipants(await discoverTopologySources(channel, new LinkRpcConnection(channel)));\n}\n\nfunction summarizeParticipants(sources: readonly InspectionSource[]): ParticipantSummary[] {\n const byNode = new Map<string, {\n descriptors: unknown[];\n routeClaims: unknown[];\n serviceIds: Set<string>;\n sourceServices: Set<string>;\n }>();\n for (const source of sources) {\n for (const node of source.graph.nodes) {\n const current = byNode.get(node.nodeId) ?? {\n descriptors: [],\n routeClaims: [],\n serviceIds: new Set<string>(),\n sourceServices: new Set<string>(),\n };\n current.descriptors.push(...(node.descriptors ?? []));\n byNode.set(node.nodeId, current);\n current.sourceServices.add(source.serviceId);\n }\n for (const route of source.graph.routes) {\n const current = byNode.get(route.nodeId) ?? {\n descriptors: [],\n routeClaims: [],\n serviceIds: new Set<string>(),\n sourceServices: new Set<string>(),\n };\n current.routeClaims.push(route);\n current.serviceIds.add(route.serviceId);\n byNode.set(route.nodeId, current);\n }\n }\n return [...byNode].map(([nodeId, value]) => ({\n nodeId,\n descriptors: value.descriptors,\n routeClaims: value.routeClaims,\n serviceIds: [...value.serviceIds].sort(),\n sourceServices: [...value.sourceServices].sort(),\n }));\n}\n\nfunction filterParticipants(\n participants: readonly ParticipantSummary[],\n search: string | undefined,\n): ParticipantSummary[] {\n if (search === undefined || search.length === 0) return [...participants];\n let expression: RegExp;\n try {\n expression = new RegExp(search, 'i');\n } catch (error) {\n throw new Error(`Invalid participant search regexp: ${error instanceof Error ? error.message : String(error)}`);\n }\n return participants.filter((participant) => expression.test(JSON.stringify(participant)));\n}\n\nfunction selectParticipant(\n participants: readonly ParticipantSummary[],\n nodeId: string | undefined,\n): ParticipantSummary | undefined {\n if (nodeId !== undefined) {\n return participants.find((participant) => participant.nodeId === nodeId);\n }\n return participants.length === 1 ? participants[0] : undefined;\n}\n\nasync function promptForParticipant(\n participants: readonly ParticipantSummary[],\n search: string | undefined,\n): Promise<{ participant: ParticipantSummary; search: string } | undefined> {\n const readline = createInterface({ input, output });\n try {\n const query = search ?? await readline.question('Search participants (regexp): ');\n const matches = filterParticipants(participants, query);\n if (matches.length === 0) return undefined;\n for (let i = 0; i < matches.length; i++) {\n output.write(`${i + 1}. ${participantLabel(matches[i])}\\n`);\n }\n const answer = await readline.question('Select participant: ');\n const index = Number.parseInt(answer, 10) - 1;\n return Number.isInteger(index) && index >= 0 && matches[index] !== undefined\n ? { participant: matches[index], search: query }\n : undefined;\n } finally {\n readline.close();\n }\n}\n\nfunction participantLabel(participant: ParticipantSummary): string {\n const labels = participant.descriptors\n .flatMap((value) => {\n if (typeof value !== 'object' || value === null) return [];\n const descriptor = (value as { descriptor?: { label?: unknown } }).descriptor;\n return typeof descriptor?.label === 'string' ? [descriptor.label] : [];\n });\n return `${labels[0] ?? participant.nodeId} (${participant.serviceIds.join(', ') || 'no routes'})`;\n}\n\nfunction serviceForParticipant(\n sources: readonly InspectionSource[],\n nodeId: string,\n): string | undefined {\n for (const source of sources) {\n const route = source.graph.routes.find((candidate) => candidate.nodeId === nodeId);\n if (route !== undefined) return route.serviceId;\n if (source.graph.entryNodeId === nodeId) return source.serviceId;\n }\n return undefined;\n}\n\nfunction formatTransit(event: TrafficTransitEvent): string {\n const direction = event.in !== undefined && event.out !== undefined\n ? 'forward'\n : event.in !== undefined ? 'in' : 'out';\n return `${event.ts} ${direction} ${event.kind} ${event.method ?? '(unknown)'}`;\n}\n\ninterface ResumeState {\n readonly search?: string;\n readonly nodeId?: string;\n readonly methodPrefix?: string;\n readonly format?: 'pretty' | 'plain' | 'jsonl';\n readonly payloadBytes?: number;\n}\n\nasync function readResume(value: string | true): Promise<ResumeState> {\n const { readFile } = await import('node:fs/promises');\n const path = value === true ? '.linkrpc-watch.json' : value;\n try {\n return JSON.parse(await readFile(path, 'utf8')) as ResumeState;\n } catch (error) {\n throw new Error(`Cannot resume from ${path}: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\nasync function writeResume(value: string | true | undefined, state: ResumeState): Promise<void> {\n if (value === undefined) return;\n const { writeFile } = await import('node:fs/promises');\n const path = value === true ? '.linkrpc-watch.json' : value;\n await writeFile(path, `${JSON.stringify(state, null, 2)}\\n`, 'utf8');\n}\n\nfunction unique(values: readonly string[]): string[] {\n return [...new Set(values)];\n}\n","import type { MethodSchema, LinkRpcInterfaceSchema as SvcInterfaceSchema } from \"@hediet/linkrpc\";\nimport { type CliChannel, fetchSchema, findMethodInSchema } from \"@hediet/linkrpc-client\";\nimport { formatJson } from \"../output\";\n\nexport interface SchemaCommandOptions {\n readonly interfaceId: string;\n readonly hash?: string;\n readonly method?: string;\n readonly json?: boolean;\n /**\n * Route the schema request to a specific service (form-3). Needed when\n * the interface lives behind a hub participant — the CLI's default\n * (form-2) target is the hub itself.\n */\n readonly serviceId?: string;\n}\n\nexport async function schemaCommand(channel: CliChannel, opts: SchemaCommandOptions): Promise<string> {\n const schema = await fetchSchema(channel, opts.interfaceId, opts.hash, opts.serviceId);\n if (opts.method !== undefined) {\n const m = findMethodInSchema(schema, opts.method);\n if (!m) throw new Error(`Method \"${opts.method}\" not found in ${schema.id}@${schema.hash}`);\n if (opts.json) return formatJson(m);\n return renderMethod(m);\n }\n if (opts.json) return formatJson(schema);\n return renderSchema(schema);\n}\n\nfunction renderSchema(schema: SvcInterfaceSchema): string {\n const lines: string[] = [];\n lines.push(`${schema.id}@${schema.hash}`);\n if (schema.description) lines.push(` ${schema.description}`);\n lines.push(\"\");\n for (const [name, method] of Object.entries(schema.methods)) {\n lines.push(renderMethod(name, method));\n lines.push(\"\");\n }\n return lines.join(\"\\n\").trimEnd();\n}\n\nfunction renderMethod(name: string, m: MethodSchema): string {\n const kind = m.result === undefined ? \"notify\" : \"request\";\n const lines: string[] = [];\n lines.push(` ${kind} ${name}`);\n if (m.summary) lines.push(` ${m.summary}`);\n if (m.description) lines.push(` ${m.description}`);\n lines.push(` params: ${shortSchema(m.params)}`);\n if (m.result) {\n lines.push(` result: ${shortSchema(m.result)}`);\n }\n return lines.join(\"\\n\");\n}\n\nfunction shortSchema(s: unknown): string {\n const str = JSON.stringify(s);\n if (str.length <= 120) return str;\n return str.slice(0, 117) + \"...\";\n}\n","/**\n * `linkrpc serve <config>` — run a hub from a declarative `HubConfig` file and\n * block until interrupted. Thin CLI face over the shared `@hediet/linkrpc-hub`\n * engine, so one config format drives the CLI hub, the server hub, and the\n * VS Code extension.\n */\nimport { loadHubConfig, printHubConfigSchema } from '@hediet/linkrpc-hub/config-file';\n\nexport { loadHubConfig, printHubConfigSchema };\n\nexport interface ServeOptions {\n /** Path to the JSON config file. */\n readonly configPath: string;\n /** Forward this process's stdin to the single cmd endpoint, if any. */\n readonly cmdInteractive?: boolean;\n /** Log every JSON-RPC message routed through the hub to stderr. */\n readonly logMessages?: boolean;\n}\n\n/** Run a hub from `configPath` and resolve only when interrupted (SIGINT/SIGTERM). */\nexport async function serveCommand(opts: ServeOptions): Promise<void> {\n const { serveHub } = await import('@hediet/linkrpc-hub/serve');\n await serveHub({\n configPath: opts.configPath,\n cmdInteractive: opts.cmdInteractive,\n logMessages: opts.logMessages,\n log: (line) => process.stderr.write(`linkrpc: ${line}\\n`),\n });\n}\n","import { connectTransports, type IMessageTransport } from '@hediet/linkrpc';\n\n/**\n * A live transport plus the seams to observe and tear down its underlying\n * resource. `IMessageTransport` itself exposes no close event, so `onClose`\n * bridges the raw socket / child-process lifecycle (mirrors how the docker\n * provenance proxy drives its splice teardown).\n */\nexport interface TransportHandle {\n readonly transport: IMessageTransport;\n /** Register a callback fired when the underlying resource closes. */\n onClose(cb: () => void): void;\n /** Tear down the transport and its underlying resource. */\n dispose(): void;\n}\n\nexport interface ConnectAsDeps {\n /**\n * Mint a single-use `hubrpc::initialize` token bound to the target's slot\n * (identity + granted namespace), via a `connectionTokenBinder` service.\n */\n mintToken(): Promise<string>;\n /**\n * Open the **hub-facing** transport, presenting `token` in its initialize\n * handshake so the hub's `{ token: \"bound\" }` handler redeems it — binding\n * this connection to the slot's identity + granted namespace.\n */\n openHubTransport(token: string): Promise<TransportHandle>;\n /**\n * Open the **target-facing** transport. Either a dial (ws / socket / uri /\n * cmd-stdio) or an accept-one (cmd-env: spawn the child and take the\n * connection it dials back).\n */\n openTargetTransport(): Promise<TransportHandle>;\n /**\n * Optional tap wrapping the target-facing transport so every spliced\n * message is logged. Tapping one edge captures the full bidirectional flow\n * (each message crosses it exactly once), so this is applied to a single\n * side to avoid double-logging.\n */\n tapTarget?(transport: IMessageTransport): IMessageTransport;\n /** Human-readable status sink. */\n log?(line: string): void;\n /** Resolves to stop the proxy (e.g. on SIGINT). */\n stop?: Promise<void>;\n}\n\n/**\n * Run a **connect-as** proxy until either side closes (or {@link\n * ConnectAsDeps.stop} resolves).\n *\n * Mints a bound token for a slot, opens the target-facing transport and the\n * hub-facing transport (which redeems the token → this connection *is* the slot\n * on the hub), and splices them message-for-message. The target thereby joins\n * the hub as a first-class participant with the slot's managed identity +\n * granted namespace, without running a local hub and without the target needing\n * to perform the hub handshake itself.\n *\n * Because all traffic crosses the CLI's splice point, {@link\n * ConnectAsDeps.tapTarget} yields complete `--log-messages` observability.\n */\nexport async function connectAs(deps: ConnectAsDeps): Promise<void> {\n const token = await deps.mintToken();\n\n const target = await deps.openTargetTransport();\n let hub: TransportHandle;\n try {\n hub = await deps.openHubTransport(token);\n } catch (e) {\n target.dispose();\n throw e;\n }\n\n const targetTransport = deps.tapTarget\n ? deps.tapTarget(target.transport)\n : target.transport;\n const pipe = connectTransports(targetTransport, hub.transport);\n\n deps.log?.('connect-as: bridged target ⟷ hub');\n\n await new Promise<void>((resolve) => {\n let done = false;\n const teardown = (): void => {\n if (done) return;\n done = true;\n pipe.dispose();\n try { target.dispose(); } catch { /* best effort */ }\n try { hub.dispose(); } catch { /* best effort */ }\n resolve();\n };\n target.onClose(teardown);\n hub.onClose(teardown);\n void deps.stop?.then(teardown);\n });\n\n deps.log?.('connect-as: closed');\n}\n","import {\n connectNdjson,\n type EndpointCommand,\n openWebSocket,\n runInitializeHandshake,\n WebSocketTransport,\n} from '@hediet/linkrpc/node';\nimport { SocketServer, type NodeSocketTransport } from '@hediet/linkrpc-hub/hub/server/node';\nimport { spawnCommand } from '@hediet/linkrpc-hub/spawn';\nimport { randomBytes } from 'node:crypto';\nimport * as fs from 'node:fs';\nimport * as net from 'node:net';\nimport type { ResolvedEndpoint } from '@hediet/linkrpc-client';\nimport type { TransportHandle } from './connectAs';\n\n/** A ws / socket endpoint the CLI can dial (the only dial-able hub-facing kinds). */\nexport type DialEndpoint = Extract<ResolvedEndpoint, { kind: 'ws' | 'socket'; }>;\n\n/**\n * Dial a ws / socket endpoint as a client, presenting `token` in the\n * `hubrpc::initialize` handshake. Used for the hub-facing side (with the minted\n * bound token) and for ws / socket / uri targets (with the target's own token).\n */\nexport async function openDialTransport(spec: DialEndpoint, token: string): Promise<TransportHandle> {\n if (spec.kind === 'ws') {\n const ws = await openWebSocket(spec.url);\n const closeWs = (): void => { try { ws.close(); } catch { /* ignore */ } };\n const transport = new WebSocketTransport(ws, closeWs);\n try {\n await runInitializeHandshake(transport, { kind: 'client', token });\n } catch (err) {\n transport.dispose();\n closeWs();\n throw err;\n }\n return {\n transport,\n onClose: (cb) => ws.addEventListener('close', () => cb()),\n dispose: () => { transport.dispose(); closeWs(); },\n };\n }\n const socket = net.createConnection(spec.path);\n const { transport } = await connectNdjson({\n input: socket,\n output: socket,\n onClose: () => socket.destroy(),\n initialize: { kind: 'client', token },\n });\n return {\n transport,\n onClose: (cb) => socket.on('close', cb),\n dispose: () => socket.destroy(),\n };\n}\n\n/** Forward a child stream's lines to `log`, prefixed with `label`. */\nfunction _pipeLines(\n stream: NodeJS.ReadableStream | null,\n label: string,\n log: (line: string) => void,\n): void {\n if (!stream) return;\n stream.setEncoding('utf8');\n stream.on('data', (chunk: string) => {\n for (const line of chunk.split(/\\r?\\n/)) {\n if (line.length > 0) log(`[${label}] ${line}`);\n }\n });\n}\n\n/** Spawn a `cmd-stdio` target and talk linkrpc over its stdin/stdout. */\nexport async function openStdioTransport(\n command: EndpointCommand,\n env: Readonly<Record<string, string>> | undefined,\n cwd: string | undefined,\n log?: (line: string) => void,\n): Promise<TransportHandle> {\n const child = spawnCommand(command, {\n stdio: ['pipe', 'pipe', 'pipe'],\n ...(env !== undefined ? { env: { ...process.env, ...env } } : {}),\n ...(cwd !== undefined ? { cwd } : {}),\n });\n if (!child.stdin || !child.stdout) {\n throw new Error('connect-as: cmd-stdio child exposes no stdio');\n }\n // stdout carries the linkrpc protocol; only stderr can be logged.\n if (log) _pipeLines(child.stderr, 'target', log);\n const { transport } = await connectNdjson({\n input: child.stdout,\n output: child.stdin,\n onClose: () => { if (!child.killed) child.kill(); },\n });\n return {\n transport,\n onClose: (cb) => child.once('exit', cb),\n dispose: () => { transport.dispose(); if (!child.killed) child.kill(); },\n };\n}\n\n/**\n * Spawn a `cmd-env` target against a private socket the CLI listens on, and\n * take the single connection it dials back. This is the sole role-inverted\n * case: the target dials the CLI, so we accept rather than dial. No hub /\n * acceptor is needed — just the raw post-handshake transport to splice.\n */\nexport async function openAcceptOneTransport(\n command: EndpointCommand,\n env: Readonly<Record<string, string>> | undefined,\n cwd: string | undefined,\n log?: (line: string) => void,\n): Promise<TransportHandle> {\n const socketPath = SocketServer.allocSocketPath();\n const token = randomBytes(16).toString('hex');\n const server = await SocketServer.start({ endpoint: socketPath });\n\n const accepted = new Promise<NodeSocketTransport>((resolve) => {\n server.setConnectionHandler((t) => resolve(t));\n });\n const child = spawnCommand(command, {\n stdio: ['ignore', 'pipe', 'pipe'],\n env: { ...process.env, ...env, LINKRPC_ENDPOINT: socketPath, LINKRPC_TOKEN: token },\n ...(cwd !== undefined ? { cwd } : {}),\n });\n // The child talks to the CLI over the socket, so both its stdout and stderr\n // are free to surface (crucial for diagnosing a child that exits before\n // dialing back).\n if (log) {\n _pipeLines(child.stdout, 'target', log);\n _pipeLines(child.stderr, 'target', log);\n }\n\n let exited = false;\n child.once('exit', () => { exited = true; });\n\n const transport = await Promise.race([\n accepted,\n new Promise<never>((_resolve, reject) => {\n child.once('exit', (code) =>\n reject(new Error(`connect-as: cmd-env child exited (code ${code ?? '?'}) before connecting`)),\n );\n }),\n ]).catch((err: unknown) => {\n server.dispose();\n _unlink(socketPath);\n if (!child.killed) child.kill();\n throw err;\n });\n\n const dispose = (): void => {\n transport.dispose();\n server.dispose();\n _unlink(socketPath);\n if (!exited && !child.killed) child.kill();\n };\n return {\n transport,\n onClose: (cb) => { transport.onDidClose(cb); child.once('exit', cb); },\n dispose,\n };\n}\n\n/** Open the target-facing transport for any resolved endpoint kind. */\nexport function openTargetTransport(\n endpoint: ResolvedEndpoint,\n log?: (line: string) => void,\n): Promise<TransportHandle> {\n switch (endpoint.kind) {\n case 'cmd-env':\n return openAcceptOneTransport(endpoint.command, endpoint.env, endpoint.cwd, log);\n case 'cmd-stdio':\n return openStdioTransport(endpoint.command, endpoint.env, endpoint.cwd, log);\n case 'ws':\n case 'socket':\n return openDialTransport(endpoint, endpoint.token ?? '');\n }\n}\n\nfunction _unlink(socketPath: string): void {\n if (process.platform === 'win32') return;\n try { fs.unlinkSync(socketPath); } catch { /* ignore */ }\n}\n","import { LinkRpcConnection } from '@hediet/linkrpc';\nimport { hubGrantedServiceIdInterface } from '@hediet/linkrpc/hub/common';\nimport { type EndpointCommand } from '@hediet/linkrpc/node';\nimport { spawnCommand } from '@hediet/linkrpc-hub/spawn';\nimport * as readline from 'node:readline';\nimport type { CliConnection } from '@hediet/linkrpc-client';\nimport { mcpForwardInterface } from '../mcpForward.interface';\n\n/**\n * Front door for claiming a serviceId within the connection's granted\n * namespace — interface-form `hubGrantedServiceId::register`. Same claim the\n * `tunnel` command uses.\n */\nconst CLAIM_METHOD = `${hubGrantedServiceIdInterface.info.id}::register`;\n\n/** Read-only connection facts — `hubGrantedServiceId::get`. */\nconst INFO_METHOD = `${hubGrantedServiceIdInterface.info.id}::get`;\n\nexport interface McpForwardOptions {\n /**\n * Prefix to claim on the hub; the MCP server is reached as\n * `<serviceId>::vscode.mcp-forward::connect`. When omitted, the connection's\n * granted serviceId namespace (`hubGrantedServiceId::get`) is claimed as-is.\n */\n readonly serviceId?: string;\n /** Live, signed connection to the hub we claim `serviceId` on and serve from. */\n readonly local: CliConnection;\n /** The MCP server child to spawn (one fresh child per `connect` leg). */\n readonly command: EndpointCommand;\n /** Extra env merged on top of `process.env` for the spawned child. */\n readonly env?: Readonly<Record<string, string>>;\n /** Resolves to stop the forwarder (e.g. on SIGINT). Defaults to first SIGINT/SIGTERM. */\n readonly stop?: Promise<void>;\n /** Sink for human-readable status lines (defaults to stderr). */\n readonly log?: (line: string) => void;\n}\n\n/**\n * Run a transparent MCP forwarder until stopped.\n *\n * Serves {@link mcpForwardInterface} under `serviceId` on the hub: each inbound\n * `connect` request spawns a fresh MCP server child and shuttles raw JSON-RPC\n * frames between the child's stdio (newline-delimited JSON, the MCP stdio\n * transport framing) and the request's duplex stream. The forwarder never\n * parses MCP semantics — it only splits/joins NDJSON lines so each line becomes\n * one opaque `frame`. {@link LinkRpcConnection.enableReflection} is enabled so\n * the hub's directory can discover the service.\n *\n * Resolves when {@link McpForwardOptions.stop} resolves (or on SIGINT/SIGTERM).\n */\nexport async function mcpForwardCommand(opts: McpForwardOptions): Promise<void> {\n const log = opts.log ?? ((line) => process.stderr.write(line + '\\n'));\n\n // Default the prefix to the connection's granted serviceId namespace, so a\n // forwarder run without an explicit `--serviceId` claims exactly what it is\n // already entitled to.\n const serviceId = opts.serviceId ?? await _resolveGrantedServiceId(opts.local);\n\n // A typed connection that SERVES the forward interface over the hub link.\n // Constructing it binds the inbound handler, so do this BEFORE claiming so\n // no `connect` can race in between the claim landing and the handler being\n // installed.\n const conn = new LinkRpcConnection(opts.local.rpcChannel);\n conn.register(\n mcpForwardInterface,\n {\n connect: (_params, _ctx, stream) => _runLeg(opts.command, opts.env, stream, log),\n },\n { serviceId },\n );\n // Advertise reflection (directory + schemas) under the same serviceId so the\n // hub's referral-only directory fan-out can discover and surface this leg.\n conn.enableReflection({ serviceId });\n\n // Claim the prefix via the granted-namespace front door. The local\n // connection's signing layer signs this where the hub requires it.\n await opts.local.channel.sendRequest(CLAIM_METHOD, { serviceId });\n log(`mcp-forward: claimed '${serviceId}' — forwarding MCP stdio to ${_describe(opts.command)}`);\n\n await (opts.stop ?? _untilSignalled());\n log('mcp-forward: stopping');\n}\n\n/**\n * Resolve the connection's granted serviceId namespace\n * (`hubGrantedServiceId::get`) to use as the default forward prefix. Throws if\n * the namespace is empty (\"claim nothing freely\") — the caller must then pass an\n * explicit `--serviceId`.\n */\nasync function _resolveGrantedServiceId(local: CliConnection): Promise<string> {\n const info = await local.channel.sendRequest(INFO_METHOD, {}) as {\n grantedServiceIdNamespace?: string;\n } | null | undefined;\n const granted = info?.grantedServiceIdNamespace ?? '';\n if (granted.length === 0) {\n throw new Error(\n 'mcp-forward: this connection has no granted serviceId namespace to claim; '\n + 'pass an explicit --serviceId.',\n );\n }\n return granted;\n}\n\n/**\n * One MCP session leg: spawn the child, bridge stdio<->stream, and resolve when\n * the child exits or the caller cancels (killing the child).\n */\nfunction _runLeg(\n command: EndpointCommand,\n env: Readonly<Record<string, string>> | undefined,\n stream: { send(p: { frame: unknown; }): void; onMessage(l: (p: { frame: unknown; }) => void): void; readonly signal: AbortSignal; },\n log: (line: string) => void,\n): Promise<{ serverInfo?: { name: string; version: string; }; }> {\n return new Promise((resolve) => {\n const child = spawnCommand(command, {\n stdio: ['pipe', 'pipe', 'inherit'],\n ...(env !== undefined ? { env: { ...process.env, ...env } } : {}),\n });\n if (!child.stdin || !child.stdout) {\n log('mcp-forward: child exposes no stdio');\n if (!child.killed) child.kill();\n resolve({});\n return;\n }\n\n let settled = false;\n const rl = readline.createInterface({ input: child.stdout });\n const finish = (): void => {\n if (settled) return;\n settled = true;\n rl.close();\n if (!child.killed) child.kill();\n resolve({});\n };\n\n // child stdout (NDJSON) → stream: each line becomes one opaque frame.\n rl.on('line', (line) => {\n const trimmed = line.trim();\n if (trimmed.length === 0) return;\n let frame: unknown;\n try {\n frame = JSON.parse(trimmed);\n } catch {\n // MCP stdio servers must emit JSON-only on stdout; skip stray\n // non-JSON lines defensively instead of corrupting the stream.\n return;\n }\n if (stream.signal.aborted) return;\n stream.send({ frame });\n });\n\n // stream → child stdin: re-serialize each frame as one NDJSON line.\n stream.onMessage(({ frame }) => {\n if (!child.stdin || child.stdin.destroyed) return;\n child.stdin.write(JSON.stringify(frame) + '\\n');\n });\n\n // Caller cancelled / disconnected → kill the child and settle.\n if (stream.signal.aborted) {\n finish();\n return;\n }\n stream.signal.addEventListener('abort', finish, { once: true });\n\n // Child exited → settle so the consumer drops its client.\n child.on('exit', finish);\n child.on('error', (err) => {\n log(`mcp-forward: child error: ${String(err)}`);\n finish();\n });\n });\n}\n\n/** Resolve on the next `SIGINT` / `SIGTERM`. */\nfunction _untilSignalled(): Promise<void> {\n return new Promise<void>((resolve) => {\n const done = (): void => {\n process.removeListener('SIGINT', done);\n process.removeListener('SIGTERM', done);\n resolve();\n };\n process.once('SIGINT', done);\n process.once('SIGTERM', done);\n });\n}\n\n/** One-line description of the spawned command for logs. */\nfunction _describe(command: EndpointCommand): string {\n return 'argv' in command ? command.argv.join(' ') : command.command;\n}\n","import { LinkRpcConnection, type JsonValue } from '@hediet/linkrpc';\nimport {\n connectJsonRpcTransports,\n connectRawJsonRpcTransport,\n createNdjsonJsonRpcTransport,\n jsonRpcConnectionInterface,\n} from '@hediet/linkrpc-infra/json-rpc';\nimport type { CliConnection } from '@hediet/linkrpc-client';\n\nexport interface JsonRpcStdioOptions {\n readonly local: CliConnection;\n readonly serviceId: string;\n readonly params?: JsonValue;\n readonly input?: NodeJS.ReadableStream;\n readonly output?: NodeJS.WritableStream;\n}\n\n/** Expose a remote `jsonRpcConnection` service as an NDJSON stdio endpoint. */\nexport async function jsonRpcStdioCommand(options: JsonRpcStdioOptions): Promise<void> {\n const connection = new LinkRpcConnection(options.local.rpcChannel);\n const client = connection.service(options.serviceId).get(jsonRpcConnectionInterface);\n const remote = await connectRawJsonRpcTransport(client, options.params);\n const stdio = createNdjsonJsonRpcTransport({\n input: options.input ?? process.stdin,\n output: options.output ?? process.stdout,\n });\n const bridge = connectJsonRpcTransports(remote, stdio);\n\n await new Promise<void>((resolve) => {\n let settled = false;\n const finish = (): void => {\n if (settled) return;\n settled = true;\n resolve();\n };\n remote.onClose(finish);\n stdio.onClose(finish);\n });\n bridge.dispose();\n remote.close('closed');\n stdio.close('closed');\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nlet globalObservableLogger;\nfunction addLogger(logger) {\n if (!globalObservableLogger) {\n globalObservableLogger = logger;\n }\n else if (globalObservableLogger instanceof ComposedLogger) {\n globalObservableLogger.loggers.push(logger);\n }\n else {\n globalObservableLogger = new ComposedLogger([globalObservableLogger, logger]);\n }\n}\nfunction getLogger() {\n return globalObservableLogger;\n}\nlet globalObservableLoggerFn = undefined;\nfunction setLogObservableFn(fn) {\n globalObservableLoggerFn = fn;\n}\nfunction logObservable(obs) {\n if (globalObservableLoggerFn) {\n globalObservableLoggerFn(obs);\n }\n}\nclass ComposedLogger {\n constructor(loggers) {\n this.loggers = loggers;\n }\n handleObservableCreated(observable, location) {\n for (const logger of this.loggers) {\n logger.handleObservableCreated(observable, location);\n }\n }\n handleOnListenerCountChanged(observable, newCount) {\n for (const logger of this.loggers) {\n logger.handleOnListenerCountChanged(observable, newCount);\n }\n }\n handleObservableUpdated(observable, info) {\n for (const logger of this.loggers) {\n logger.handleObservableUpdated(observable, info);\n }\n }\n handleAutorunCreated(autorun, location) {\n for (const logger of this.loggers) {\n logger.handleAutorunCreated(autorun, location);\n }\n }\n handleAutorunDisposed(autorun) {\n for (const logger of this.loggers) {\n logger.handleAutorunDisposed(autorun);\n }\n }\n handleAutorunDependencyChanged(autorun, observable, change) {\n for (const logger of this.loggers) {\n logger.handleAutorunDependencyChanged(autorun, observable, change);\n }\n }\n handleAutorunStarted(autorun) {\n for (const logger of this.loggers) {\n logger.handleAutorunStarted(autorun);\n }\n }\n handleAutorunFinished(autorun) {\n for (const logger of this.loggers) {\n logger.handleAutorunFinished(autorun);\n }\n }\n handleDerivedDependencyChanged(derived, observable, change) {\n for (const logger of this.loggers) {\n logger.handleDerivedDependencyChanged(derived, observable, change);\n }\n }\n handleDerivedCleared(observable) {\n for (const logger of this.loggers) {\n logger.handleDerivedCleared(observable);\n }\n }\n handleBeginTransaction(transaction) {\n for (const logger of this.loggers) {\n logger.handleBeginTransaction(transaction);\n }\n }\n handleEndTransaction(transaction) {\n for (const logger of this.loggers) {\n logger.handleEndTransaction(transaction);\n }\n }\n}\n\nexport { addLogger, getLogger, logObservable, setLogObservableFn };\n//# sourceMappingURL=logging.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar DebugLocation;\n(function (DebugLocation) {\n let enabled = false;\n function enable() {\n enabled = true;\n }\n DebugLocation.enable = enable;\n function ofCaller() {\n return ofNthCaller(1);\n }\n DebugLocation.ofCaller = ofCaller;\n function ofNthCaller(n) {\n if (!enabled) {\n return undefined;\n }\n const Err = Error; // For the monaco editor checks, which don't have the nodejs types.\n const l = Err.stackTraceLimit;\n Err.stackTraceLimit = 3;\n const stack = new Error().stack;\n Err.stackTraceLimit = l;\n return DebugLocationImpl.fromStack(stack, n + 1);\n }\n DebugLocation.ofNthCaller = ofNthCaller;\n})(DebugLocation || (DebugLocation = {}));\nclass DebugLocationImpl {\n static fromStack(stack, parentIdx) {\n const lines = stack.split('\\n');\n const location = parseLine(lines[parentIdx + 1]);\n if (location) {\n return new DebugLocationImpl(location.fileName, location.line, location.column, location.id);\n }\n else {\n return undefined;\n }\n }\n constructor(fileName, line, column, id) {\n this.fileName = fileName;\n this.line = line;\n this.column = column;\n this.id = id;\n }\n}\nfunction parseLine(stackLine) {\n if (!stackLine) {\n return undefined;\n }\n const match = stackLine.match(/\\((.*):(\\d+):(\\d+)\\)/);\n if (match) {\n return {\n fileName: match[1],\n line: parseInt(match[2]),\n column: parseInt(match[3]),\n id: stackLine,\n };\n }\n const match2 = stackLine.match(/at ([^\\(\\)]*):(\\d+):(\\d+)/);\n if (match2) {\n return {\n fileName: match2[1],\n line: parseInt(match2[2]),\n column: parseInt(match2[3]),\n id: stackLine,\n };\n }\n return undefined;\n}\n\nexport { DebugLocation };\n//# sourceMappingURL=debugLocation.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nclass DebugNameData {\n constructor(owner, debugNameSource, referenceFn) {\n this.owner = owner;\n this.debugNameSource = debugNameSource;\n this.referenceFn = referenceFn;\n }\n getDebugName(target) {\n return getDebugName(target, this);\n }\n}\nconst countPerName = new Map();\nconst cachedDebugName = new WeakMap();\nfunction getDebugName(target, data) {\n const cached = cachedDebugName.get(target);\n if (cached) {\n return cached;\n }\n const dbgName = computeDebugName(target, data);\n if (dbgName) {\n let count = countPerName.get(dbgName) ?? 0;\n count++;\n countPerName.set(dbgName, count);\n const result = count === 1 ? dbgName : `${dbgName}#${count}`;\n cachedDebugName.set(target, result);\n return result;\n }\n return undefined;\n}\nfunction computeDebugName(self, data) {\n const cached = cachedDebugName.get(self);\n if (cached) {\n return cached;\n }\n const ownerStr = data.owner ? formatOwner(data.owner) + `.` : '';\n let result;\n const debugNameSource = data.debugNameSource;\n if (debugNameSource !== undefined) {\n if (typeof debugNameSource === 'function') {\n result = debugNameSource();\n if (result !== undefined) {\n return ownerStr + result;\n }\n }\n else {\n return ownerStr + debugNameSource;\n }\n }\n const referenceFn = data.referenceFn;\n if (referenceFn !== undefined) {\n result = getFunctionName(referenceFn);\n if (result !== undefined) {\n return ownerStr + result;\n }\n }\n if (data.owner !== undefined) {\n const key = findKey(data.owner, self);\n if (key !== undefined) {\n return ownerStr + key;\n }\n }\n return undefined;\n}\nfunction findKey(obj, value) {\n for (const key in obj) {\n if (obj[key] === value) {\n return key;\n }\n }\n return undefined;\n}\nconst countPerClassName = new Map();\nconst ownerId = new WeakMap();\nfunction formatOwner(owner) {\n const id = ownerId.get(owner);\n if (id) {\n return id;\n }\n const className = getClassName(owner) ?? 'Object';\n let count = countPerClassName.get(className) ?? 0;\n count++;\n countPerClassName.set(className, count);\n const result = count === 1 ? className : `${className}#${count}`;\n ownerId.set(owner, result);\n return result;\n}\nfunction getClassName(obj) {\n const ctor = obj.constructor;\n if (ctor) {\n if (ctor.name === 'Object') {\n return undefined;\n }\n return ctor.name;\n }\n return undefined;\n}\nfunction getFunctionName(fn) {\n const fnSrc = fn.toString();\n // Pattern: /** @description ... */\n const regexp = /\\/\\*\\*\\s*@description\\s*([^*]*)\\*\\//;\n const match = regexp.exec(fnSrc);\n const result = match ? match[1] : undefined;\n return result?.trim();\n}\n\nexport { DebugNameData, getClassName, getDebugName, getFunctionName };\n//# sourceMappingURL=debugName.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { DebugLocation } from '../debugLocation.js';\nimport { getFunctionName } from '../debugName.js';\nimport { logObservable, getLogger } from '../logging/logging.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nlet _derived;\n/**\n * @internal\n * This is to allow splitting files.\n*/\nfunction _setDerivedOpts(derived) {\n _derived = derived;\n}\nlet _recomputeInitiallyAndOnChange;\nfunction _setRecomputeInitiallyAndOnChange(recomputeInitiallyAndOnChange) {\n _recomputeInitiallyAndOnChange = recomputeInitiallyAndOnChange;\n}\nlet _keepObserved;\nfunction _setKeepObserved(keepObserved) {\n _keepObserved = keepObserved;\n}\nlet _debugGetDependencyGraph;\nfunction _setDebugGetDependencyGraph(debugGetDependencyGraph) {\n _debugGetDependencyGraph = debugGetDependencyGraph;\n}\nclass ConvenientObservable {\n get TChange() { return null; }\n reportChanges() {\n this.get();\n }\n /** @sealed */\n read(reader) {\n if (reader) {\n return reader.readObservable(this);\n }\n else {\n return this.get();\n }\n }\n map(fnOrOwner, fnOrUndefined, debugLocation = DebugLocation.ofCaller()) {\n const owner = fnOrUndefined === undefined ? undefined : fnOrOwner;\n const fn = fnOrUndefined === undefined ? fnOrOwner : fnOrUndefined;\n return _derived({\n owner,\n debugName: () => {\n const name = getFunctionName(fn);\n if (name !== undefined) {\n return name;\n }\n // regexp to match `x => x.y` or `x => x?.y` where x and y can be arbitrary identifiers (uses backref):\n const regexp = /^\\s*\\(?\\s*([a-zA-Z_$][a-zA-Z_$0-9]*)\\s*\\)?\\s*=>\\s*\\1(?:\\??)\\.([a-zA-Z_$][a-zA-Z_$0-9]*)\\s*$/;\n const match = regexp.exec(fn.toString());\n if (match) {\n return `${this.debugName}.${match[2]}`;\n }\n if (!owner) {\n return `${this.debugName} (mapped)`;\n }\n return undefined;\n },\n debugReferenceFn: fn,\n }, (reader) => fn(this.read(reader), reader), debugLocation);\n }\n /**\n * @sealed\n * Converts an observable of an observable value into a direct observable of the value.\n */\n flatten() {\n return _derived({\n owner: undefined,\n debugName: () => `${this.debugName} (flattened)`,\n }, (reader) => this.read(reader).read(reader));\n }\n recomputeInitiallyAndOnChange(store, handleValue) {\n store.add(_recomputeInitiallyAndOnChange(this, handleValue));\n return this;\n }\n /**\n * Ensures that this observable is observed. This keeps the cache alive.\n * However, in case of deriveds, it does not force eager evaluation (only when the value is read/get).\n * Use `recomputeInitiallyAndOnChange` for eager evaluation.\n */\n keepObserved(store) {\n store.add(_keepObserved(this));\n return this;\n }\n get debugValue() {\n return this.get();\n }\n debugGetDependencyGraph() {\n return _debugGetDependencyGraph(this);\n }\n}\nclass BaseObservable extends ConvenientObservable {\n constructor(debugLocation) {\n super();\n this._observers = new Set();\n getLogger()?.handleObservableCreated(this, debugLocation);\n }\n addObserver(observer) {\n const len = this._observers.size;\n this._observers.add(observer);\n if (len === 0) {\n this.onFirstObserverAdded();\n }\n if (len !== this._observers.size) {\n getLogger()?.handleOnListenerCountChanged(this, this._observers.size);\n }\n }\n removeObserver(observer) {\n const deleted = this._observers.delete(observer);\n if (deleted && this._observers.size === 0) {\n this.onLastObserverRemoved();\n }\n if (deleted) {\n getLogger()?.handleOnListenerCountChanged(this, this._observers.size);\n }\n }\n onFirstObserverAdded() { }\n onLastObserverRemoved() { }\n log() {\n const hadLogger = !!getLogger();\n logObservable(this);\n if (!hadLogger) {\n getLogger()?.handleObservableCreated(this, DebugLocation.ofCaller());\n }\n return this;\n }\n debugGetObservers() {\n return this._observers;\n }\n}\n\nexport { BaseObservable, ConvenientObservable, _setDebugGetDependencyGraph, _setDerivedOpts, _setKeepObserved, _setRecomputeInitiallyAndOnChange };\n//# sourceMappingURL=baseObservable.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction toDisposable(fn) {\n return {\n dispose: fn\n };\n}\nclass BugIndicatingError extends Error {\n constructor(message) {\n super(message || 'An unexpected bug occurred.');\n Object.setPrototypeOf(this, BugIndicatingError.prototype);\n // Because we know for sure only buggy code throws this,\n // we definitely want to break here and fix the bug.\n // eslint-disable-next-line no-debugger\n // debugger;\n }\n}\nfunction onBugIndicatingError(error) {\n // debugger;\n throw error;\n}\nfunction onUnexpectedError(error) {\n console.error('Unexpected error:', error);\n}\n/**\n * Compares two items for equality using strict equality.\n*/\nconst strictEquals = (a, b) => a === b;\n\nexport { BugIndicatingError, onBugIndicatingError, onUnexpectedError, strictEquals, toDisposable };\n//# sourceMappingURL=deps.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nclass DisposableStore {\n constructor() {\n this.disposables = [];\n this._isDisposed = false;\n }\n get isDisposed() { return this._isDisposed; }\n dispose() {\n this.clear();\n this._isDisposed = true;\n }\n add(disposable) {\n if (disposable) {\n this.disposables.push(disposable);\n }\n return disposable;\n }\n remove(disposable) {\n if (!disposable) {\n return disposable;\n }\n const index = this.disposables.indexOf(disposable);\n if (index !== -1) {\n this.disposables.splice(index, 1);\n }\n return disposable;\n }\n clear() {\n for (const disposable of this.disposables) {\n disposable.dispose();\n }\n this.disposables = [];\n }\n leakItems() {\n this.disposables = [];\n }\n}\nclass Disposable {\n constructor() {\n this._store = new DisposableStore();\n }\n dispose() {\n this._store.dispose();\n }\n _register(t) {\n this._store.add(t);\n return t;\n }\n _registerOrDispose(t) {\n if (t) {\n if (this._store.isDisposed) {\n t.dispose();\n }\n else {\n this._store.add(t);\n }\n }\n return t;\n }\n}\n\nexport { Disposable, DisposableStore };\n//# sourceMappingURL=disposables.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { BaseObservable } from './baseObservable.js';\nimport { BugIndicatingError, onBugIndicatingError } from '../commonFacade/deps.js';\nimport { getLogger } from '../logging/logging.js';\nimport { DisposableStore } from '../../disposables.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction derivedStateToString(state) {\n switch (state) {\n case 0 /* DerivedState.initial */: return 'initial';\n case 1 /* DerivedState.dependenciesMightHaveChanged */: return 'dependenciesMightHaveChanged';\n case 2 /* DerivedState.stale */: return 'stale';\n case 3 /* DerivedState.upToDate */: return 'upToDate';\n default: return '<unknown>';\n }\n}\nclass Derived extends BaseObservable {\n get debugName() {\n return this._debugNameData.getDebugName(this) ?? '(anonymous)';\n }\n constructor(_debugNameData, _computeFn, _changeTracker, _handleLastObserverRemoved = undefined, _equalityComparator, debugLocation) {\n super(debugLocation);\n this._debugNameData = _debugNameData;\n this._computeFn = _computeFn;\n this._changeTracker = _changeTracker;\n this._handleLastObserverRemoved = _handleLastObserverRemoved;\n this._equalityComparator = _equalityComparator;\n this._state = 0 /* DerivedState.initial */;\n this._value = undefined;\n this._updateCount = 0;\n this._dependencies = new Set();\n this._dependenciesToBeRemoved = new Set();\n this._changeSummary = undefined;\n this._isUpdating = false;\n this._isComputing = false;\n this._didReportChange = false;\n this._isInBeforeUpdate = false;\n this._isReaderValid = false;\n this._store = undefined;\n this._delayedStore = undefined;\n this._removedObserverToCallEndUpdateOn = null;\n this._changeSummary = this._changeTracker?.createChangeSummary(undefined);\n }\n onLastObserverRemoved() {\n /**\n * We are not tracking changes anymore, thus we have to assume\n * that our cache is invalid.\n */\n this._state = 0 /* DerivedState.initial */;\n this._value = undefined;\n getLogger()?.handleDerivedCleared(this);\n for (const d of this._dependencies) {\n d.removeObserver(this);\n }\n this._dependencies.clear();\n if (this._store !== undefined) {\n this._store.dispose();\n this._store = undefined;\n }\n if (this._delayedStore !== undefined) {\n this._delayedStore.dispose();\n this._delayedStore = undefined;\n }\n this._handleLastObserverRemoved?.();\n }\n get() {\n const checkEnabled = false; // TODO set to true\n if (this._isComputing && checkEnabled) {\n // investigate why this fails in the diff editor!\n throw new BugIndicatingError('Cyclic deriveds are not supported yet!');\n }\n if (this._observers.size === 0) {\n let result;\n // Without observers, we don't know when to clean up stuff.\n // Thus, we don't cache anything to prevent memory leaks.\n try {\n this._isReaderValid = true;\n let changeSummary = undefined;\n if (this._changeTracker) {\n changeSummary = this._changeTracker.createChangeSummary(undefined);\n this._changeTracker.beforeUpdate?.(this, changeSummary);\n }\n result = this._computeFn(this, changeSummary);\n }\n finally {\n this._isReaderValid = false;\n }\n // Clear new dependencies\n this.onLastObserverRemoved();\n return result;\n }\n else {\n do {\n // We might not get a notification for a dependency that changed while it is updating,\n // thus we also have to ask all our depedencies if they changed in this case.\n if (this._state === 1 /* DerivedState.dependenciesMightHaveChanged */) {\n for (const d of this._dependencies) {\n /** might call {@link handleChange} indirectly, which could make us stale */\n d.reportChanges();\n if (this._state === 2 /* DerivedState.stale */) {\n // The other dependencies will refresh on demand, so early break\n break;\n }\n }\n }\n // We called report changes of all dependencies.\n // If we are still not stale, we can assume to be up to date again.\n if (this._state === 1 /* DerivedState.dependenciesMightHaveChanged */) {\n this._state = 3 /* DerivedState.upToDate */;\n }\n if (this._state !== 3 /* DerivedState.upToDate */) {\n this._recompute();\n }\n // In case recomputation changed one of our dependencies, we need to recompute again.\n } while (this._state !== 3 /* DerivedState.upToDate */);\n return this._value;\n }\n }\n _recompute() {\n let didChange = false;\n this._isComputing = true;\n this._didReportChange = false;\n const emptySet = this._dependenciesToBeRemoved;\n this._dependenciesToBeRemoved = this._dependencies;\n this._dependencies = emptySet;\n try {\n const changeSummary = this._changeSummary;\n this._isReaderValid = true;\n if (this._changeTracker) {\n this._isInBeforeUpdate = true;\n this._changeTracker.beforeUpdate?.(this, changeSummary);\n this._isInBeforeUpdate = false;\n this._changeSummary = this._changeTracker?.createChangeSummary(changeSummary);\n }\n const hadValue = this._state !== 0 /* DerivedState.initial */;\n const oldValue = this._value;\n this._state = 3 /* DerivedState.upToDate */;\n const delayedStore = this._delayedStore;\n if (delayedStore !== undefined) {\n this._delayedStore = undefined;\n }\n try {\n if (this._store !== undefined) {\n this._store.dispose();\n this._store = undefined;\n }\n /** might call {@link handleChange} indirectly, which could invalidate us */\n this._value = this._computeFn(this, changeSummary);\n }\n finally {\n this._isReaderValid = false;\n // We don't want our observed observables to think that they are (not even temporarily) not being observed.\n // Thus, we only unsubscribe from observables that are definitely not read anymore.\n for (const o of this._dependenciesToBeRemoved) {\n o.removeObserver(this);\n }\n this._dependenciesToBeRemoved.clear();\n if (delayedStore !== undefined) {\n delayedStore.dispose();\n }\n }\n didChange = this._didReportChange || (hadValue && !(this._equalityComparator(oldValue, this._value)));\n getLogger()?.handleObservableUpdated(this, {\n oldValue,\n newValue: this._value,\n change: undefined,\n didChange,\n hadValue,\n });\n }\n catch (e) {\n onBugIndicatingError(e);\n }\n this._isComputing = false;\n if (!this._didReportChange && didChange) {\n for (const r of this._observers) {\n r.handleChange(this, undefined);\n }\n }\n else {\n this._didReportChange = false;\n }\n }\n toString() {\n return `LazyDerived<${this.debugName}>`;\n }\n // IObserver Implementation\n beginUpdate(_observable) {\n if (this._isUpdating) {\n throw new BugIndicatingError('Cyclic deriveds are not supported yet!');\n }\n this._updateCount++;\n this._isUpdating = true;\n try {\n const propagateBeginUpdate = this._updateCount === 1;\n if (this._state === 3 /* DerivedState.upToDate */) {\n this._state = 1 /* DerivedState.dependenciesMightHaveChanged */;\n // If we propagate begin update, that will already signal a possible change.\n if (!propagateBeginUpdate) {\n for (const r of this._observers) {\n r.handlePossibleChange(this);\n }\n }\n }\n if (propagateBeginUpdate) {\n for (const r of this._observers) {\n r.beginUpdate(this); // This signals a possible change\n }\n }\n }\n finally {\n this._isUpdating = false;\n }\n }\n endUpdate(_observable) {\n this._updateCount--;\n if (this._updateCount === 0) {\n // End update could change the observer list.\n const observers = [...this._observers];\n for (const r of observers) {\n r.endUpdate(this);\n }\n if (this._removedObserverToCallEndUpdateOn) {\n const observers = [...this._removedObserverToCallEndUpdateOn];\n this._removedObserverToCallEndUpdateOn = null;\n for (const r of observers) {\n r.endUpdate(this);\n }\n }\n }\n }\n handlePossibleChange(observable) {\n // In all other states, observers already know that we might have changed.\n if (this._state === 3 /* DerivedState.upToDate */ && this._dependencies.has(observable) && !this._dependenciesToBeRemoved.has(observable)) {\n this._state = 1 /* DerivedState.dependenciesMightHaveChanged */;\n for (const r of this._observers) {\n r.handlePossibleChange(this);\n }\n }\n }\n handleChange(observable, change) {\n if (this._dependencies.has(observable) && !this._dependenciesToBeRemoved.has(observable) || this._isInBeforeUpdate) {\n getLogger()?.handleDerivedDependencyChanged(this, observable, change);\n let shouldReact = false;\n try {\n shouldReact = this._changeTracker ? this._changeTracker.handleChange({\n changedObservable: observable,\n change,\n didChange: (o) => o === observable,\n }, this._changeSummary) : true;\n }\n catch (e) {\n onBugIndicatingError(e);\n }\n const wasUpToDate = this._state === 3 /* DerivedState.upToDate */;\n if (shouldReact && (this._state === 1 /* DerivedState.dependenciesMightHaveChanged */ || wasUpToDate)) {\n this._state = 2 /* DerivedState.stale */;\n if (wasUpToDate) {\n for (const r of this._observers) {\n r.handlePossibleChange(this);\n }\n }\n }\n }\n }\n // IReader Implementation\n _ensureReaderValid() {\n if (!this._isReaderValid) {\n throw new BugIndicatingError('The reader object cannot be used outside its compute function!');\n }\n }\n readObservable(observable) {\n this._ensureReaderValid();\n // Subscribe before getting the value to enable caching\n observable.addObserver(this);\n /** This might call {@link handleChange} indirectly, which could invalidate us */\n const value = observable.get();\n // Which is why we only add the observable to the dependencies now.\n this._dependencies.add(observable);\n this._dependenciesToBeRemoved.delete(observable);\n return value;\n }\n reportChange(change) {\n this._ensureReaderValid();\n this._didReportChange = true;\n // TODO add logging\n for (const r of this._observers) {\n r.handleChange(this, change);\n }\n }\n get store() {\n this._ensureReaderValid();\n if (this._store === undefined) {\n this._store = new DisposableStore();\n }\n return this._store;\n }\n get delayedStore() {\n this._ensureReaderValid();\n if (this._delayedStore === undefined) {\n this._delayedStore = new DisposableStore();\n }\n return this._delayedStore;\n }\n addObserver(observer) {\n const shouldCallBeginUpdate = !this._observers.has(observer) && this._updateCount > 0;\n super.addObserver(observer);\n if (shouldCallBeginUpdate) {\n if (this._removedObserverToCallEndUpdateOn && this._removedObserverToCallEndUpdateOn.has(observer)) {\n this._removedObserverToCallEndUpdateOn.delete(observer);\n }\n else {\n observer.beginUpdate(this);\n }\n }\n }\n removeObserver(observer) {\n if (this._observers.has(observer) && this._updateCount > 0) {\n if (!this._removedObserverToCallEndUpdateOn) {\n this._removedObserverToCallEndUpdateOn = new Set();\n }\n this._removedObserverToCallEndUpdateOn.add(observer);\n }\n super.removeObserver(observer);\n }\n debugGetState() {\n return {\n state: this._state,\n stateStr: derivedStateToString(this._state),\n updateCount: this._updateCount,\n isComputing: this._isComputing,\n dependencies: this._dependencies,\n value: this._value,\n };\n }\n debugSetValue(newValue) {\n this._value = newValue;\n }\n debugRecompute() {\n if (!this._isComputing) {\n this._recompute();\n }\n else {\n this._state = 2 /* DerivedState.stale */;\n }\n }\n setValue(newValue, tx, change) {\n this._value = newValue;\n const observers = this._observers;\n tx.updateObserver(this, this);\n for (const d of observers) {\n d.handleChange(this, change);\n }\n }\n}\nclass DerivedWithSetter extends Derived {\n constructor(debugNameData, computeFn, changeTracker, handleLastObserverRemoved = undefined, equalityComparator, set, debugLocation) {\n super(debugNameData, computeFn, changeTracker, handleLastObserverRemoved, equalityComparator, debugLocation);\n this.set = set;\n }\n}\n\nexport { Derived, DerivedWithSetter };\n//# sourceMappingURL=derivedImpl.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { strictEquals } from '../commonFacade/deps.js';\nimport { DebugLocation } from '../debugLocation.js';\nimport { DebugNameData } from '../debugName.js';\nimport { _setDerivedOpts } from './baseObservable.js';\nimport { Derived, DerivedWithSetter } from './derivedImpl.js';\nimport { DisposableStore } from '../../disposables.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction derived(computeFnOrOwner, computeFn, debugLocation = DebugLocation.ofCaller()) {\n if (computeFn !== undefined) {\n return new Derived(new DebugNameData(computeFnOrOwner, undefined, computeFn), computeFn, undefined, undefined, strictEquals, debugLocation);\n }\n return new Derived(new DebugNameData(undefined, undefined, computeFnOrOwner), computeFnOrOwner, undefined, undefined, strictEquals, debugLocation);\n}\nfunction derivedWithSetter(owner, computeFn, setter, debugLocation = DebugLocation.ofCaller()) {\n return new DerivedWithSetter(new DebugNameData(owner, undefined, computeFn), computeFn, undefined, undefined, strictEquals, setter, debugLocation);\n}\nfunction derivedOpts(options, computeFn, debugLocation = DebugLocation.ofCaller()) {\n return new Derived(new DebugNameData(options.owner, options.debugName, options.debugReferenceFn), computeFn, undefined, options.onLastObserverRemoved, options.equalsFn ?? strictEquals, debugLocation);\n}\n_setDerivedOpts(derivedOpts);\n/**\n * Represents an observable that is derived from other observables.\n * The value is only recomputed when absolutely needed.\n *\n * {@link computeFn} should start with a JS Doc using `@description` to name the derived.\n *\n * Use `createEmptyChangeSummary` to create a \"change summary\" that can collect the changes.\n * Use `handleChange` to add a reported change to the change summary.\n * The compute function is given the last change summary.\n * The change summary is discarded after the compute function was called.\n *\n * @see derived\n */\nfunction derivedHandleChanges(options, computeFn, debugLocation = DebugLocation.ofCaller()) {\n return new Derived(new DebugNameData(options.owner, options.debugName, undefined), computeFn, options.changeTracker, undefined, options.equalityComparer ?? strictEquals, debugLocation);\n}\nfunction derivedWithStore(computeFnOrOwner, computeFnOrUndefined, debugLocation = DebugLocation.ofCaller()) {\n let computeFn;\n let owner;\n if (computeFnOrUndefined === undefined) {\n computeFn = computeFnOrOwner;\n owner = undefined;\n }\n else {\n owner = computeFnOrOwner;\n computeFn = computeFnOrUndefined;\n }\n // Intentionally re-assigned in case an inactive observable is re-used later\n // eslint-disable-next-line local/code-no-potentially-unsafe-disposables\n let store = new DisposableStore();\n return new Derived(new DebugNameData(owner, undefined, computeFn), r => {\n if (store.isDisposed) {\n store = new DisposableStore();\n }\n else {\n store.clear();\n }\n return computeFn(r, store);\n }, undefined, () => store.dispose(), strictEquals, debugLocation);\n}\nfunction derivedDisposable(computeFnOrOwner, computeFnOrUndefined, debugLocation = DebugLocation.ofCaller()) {\n let computeFn;\n let owner;\n if (computeFnOrUndefined === undefined) {\n computeFn = computeFnOrOwner;\n owner = undefined;\n }\n else {\n owner = computeFnOrOwner;\n computeFn = computeFnOrUndefined;\n }\n let store = undefined;\n return new Derived(new DebugNameData(owner, undefined, computeFn), r => {\n if (!store) {\n store = new DisposableStore();\n }\n else {\n store.clear();\n }\n const result = computeFn(r);\n if (result) {\n store.add(result);\n }\n return result;\n }, undefined, () => {\n if (store) {\n store.dispose();\n store = undefined;\n }\n }, strictEquals, debugLocation);\n}\n\nexport { derived, derivedDisposable, derivedHandleChanges, derivedOpts, derivedWithSetter, derivedWithStore };\n//# sourceMappingURL=derived.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { onBugIndicatingError, BugIndicatingError } from '../commonFacade/deps.js';\nimport { getLogger } from '../logging/logging.js';\nimport { DisposableStore } from '../../disposables.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction autorunStateToString(state) {\n switch (state) {\n case 1 /* AutorunState.dependenciesMightHaveChanged */: return 'dependenciesMightHaveChanged';\n case 2 /* AutorunState.stale */: return 'stale';\n case 3 /* AutorunState.upToDate */: return 'upToDate';\n default: return '<unknown>';\n }\n}\nclass AutorunObserver {\n get debugName() {\n return this._debugNameData.getDebugName(this) ?? '(anonymous)';\n }\n constructor(_debugNameData, _runFn, _changeTracker, debugLocation) {\n this._debugNameData = _debugNameData;\n this._runFn = _runFn;\n this._changeTracker = _changeTracker;\n this._state = 2 /* AutorunState.stale */;\n this._updateCount = 0;\n this._disposed = false;\n this._dependencies = new Set();\n this._dependenciesToBeRemoved = new Set();\n this._isRunning = false;\n this._store = undefined;\n this._delayedStore = undefined;\n this._changeSummary = this._changeTracker?.createChangeSummary(undefined);\n getLogger()?.handleAutorunCreated(this, debugLocation);\n this._run();\n }\n dispose() {\n if (this._disposed) {\n return;\n }\n this._disposed = true;\n for (const o of this._dependencies) {\n o.removeObserver(this); // Warning: external call!\n }\n this._dependencies.clear();\n if (this._store !== undefined) {\n this._store.dispose();\n }\n if (this._delayedStore !== undefined) {\n this._delayedStore.dispose();\n }\n getLogger()?.handleAutorunDisposed(this);\n }\n _run() {\n const emptySet = this._dependenciesToBeRemoved;\n this._dependenciesToBeRemoved = this._dependencies;\n this._dependencies = emptySet;\n this._state = 3 /* AutorunState.upToDate */;\n try {\n if (!this._disposed) {\n getLogger()?.handleAutorunStarted(this);\n const changeSummary = this._changeSummary;\n const delayedStore = this._delayedStore;\n if (delayedStore !== undefined) {\n this._delayedStore = undefined;\n }\n try {\n this._isRunning = true;\n if (this._changeTracker) {\n this._changeTracker.beforeUpdate?.(this, changeSummary);\n this._changeSummary = this._changeTracker.createChangeSummary(changeSummary); // Warning: external call!\n }\n if (this._store !== undefined) {\n this._store.dispose();\n this._store = undefined;\n }\n this._runFn(this, changeSummary); // Warning: external call!\n }\n catch (e) {\n onBugIndicatingError(e);\n }\n finally {\n this._isRunning = false;\n if (delayedStore !== undefined) {\n delayedStore.dispose();\n }\n }\n }\n }\n finally {\n if (!this._disposed) {\n getLogger()?.handleAutorunFinished(this);\n }\n // We don't want our observed observables to think that they are (not even temporarily) not being observed.\n // Thus, we only unsubscribe from observables that are definitely not read anymore.\n for (const o of this._dependenciesToBeRemoved) {\n o.removeObserver(this); // Warning: external call!\n }\n this._dependenciesToBeRemoved.clear();\n }\n }\n toString() {\n return `Autorun<${this.debugName}>`;\n }\n // IObserver implementation\n beginUpdate(_observable) {\n if (this._state === 3 /* AutorunState.upToDate */) {\n this._state = 1 /* AutorunState.dependenciesMightHaveChanged */;\n }\n this._updateCount++;\n }\n endUpdate(_observable) {\n try {\n if (this._updateCount === 1) {\n do {\n if (this._state === 1 /* AutorunState.dependenciesMightHaveChanged */) {\n this._state = 3 /* AutorunState.upToDate */;\n for (const d of this._dependencies) {\n d.reportChanges(); // Warning: external call!\n if (this._state === 2 /* AutorunState.stale */) {\n // The other dependencies will refresh on demand\n break;\n }\n }\n }\n if (this._state !== 3 /* AutorunState.upToDate */) {\n this._run(); // Warning: indirect external call!\n }\n } while (this._state !== 3 /* AutorunState.upToDate */);\n }\n }\n finally {\n this._updateCount--;\n }\n }\n handlePossibleChange(observable) {\n if (this._state === 3 /* AutorunState.upToDate */ && this._isDependency(observable)) {\n this._state = 1 /* AutorunState.dependenciesMightHaveChanged */;\n }\n }\n handleChange(observable, change) {\n if (this._isDependency(observable)) {\n getLogger()?.handleAutorunDependencyChanged(this, observable, change);\n try {\n // Warning: external call!\n const shouldReact = this._changeTracker ? this._changeTracker.handleChange({\n changedObservable: observable,\n change,\n didChange: (o) => o === observable,\n }, this._changeSummary) : true;\n if (shouldReact) {\n this._state = 2 /* AutorunState.stale */;\n }\n }\n catch (e) {\n onBugIndicatingError(e);\n }\n }\n }\n _isDependency(observable) {\n return this._dependencies.has(observable) && !this._dependenciesToBeRemoved.has(observable);\n }\n // IReader implementation\n _ensureNoRunning() {\n if (!this._isRunning) {\n throw new BugIndicatingError('The reader object cannot be used outside its compute function!');\n }\n }\n readObservable(observable) {\n this._ensureNoRunning();\n // In case the run action disposes the autorun\n if (this._disposed) {\n return observable.get(); // warning: external call!\n }\n observable.addObserver(this); // warning: external call!\n const value = observable.get(); // warning: external call!\n this._dependencies.add(observable);\n this._dependenciesToBeRemoved.delete(observable);\n return value;\n }\n get store() {\n this._ensureNoRunning();\n if (this._disposed) {\n throw new BugIndicatingError('Cannot access store after dispose');\n }\n if (this._store === undefined) {\n this._store = new DisposableStore();\n }\n return this._store;\n }\n get delayedStore() {\n this._ensureNoRunning();\n if (this._disposed) {\n throw new BugIndicatingError('Cannot access store after dispose');\n }\n if (this._delayedStore === undefined) {\n this._delayedStore = new DisposableStore();\n }\n return this._delayedStore;\n }\n debugGetState() {\n return {\n isRunning: this._isRunning,\n updateCount: this._updateCount,\n dependencies: this._dependencies,\n state: this._state,\n stateStr: autorunStateToString(this._state),\n };\n }\n debugRerun() {\n if (!this._isRunning) {\n this._run();\n }\n else {\n this._state = 2 /* AutorunState.stale */;\n }\n }\n}\n\nexport { AutorunObserver };\n//# sourceMappingURL=createEffectImpl.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { toDisposable } from '../commonFacade/deps.js';\nimport { DebugNameData } from '../debugName.js';\nimport { AutorunObserver } from './createEffectImpl.js';\nimport { DebugLocation } from '../debugLocation.js';\nimport { DisposableStore } from '../../disposables.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/**\n * Runs immediately and whenever a transaction ends and an observed observable changed.\n * {@link fn} should start with a JS Doc using `@description` to name the effect.\n */\nfunction createEffect(fn, debugLocation = DebugLocation.ofCaller()) {\n return new AutorunObserver(new DebugNameData(undefined, undefined, fn), fn, undefined, debugLocation);\n}\n/**\n * @deprecated Use {@link createEffect} instead.\n */\nconst autorun = createEffect;\n/**\n * Runs immediately and whenever a transaction ends and an observed observable changed.\n * {@link fn} should start with a JS Doc using `@description` to name the autorun.\n */\nfunction createEffectOpts(options, fn, debugLocation = DebugLocation.ofCaller()) {\n return new AutorunObserver(new DebugNameData(options.owner, options.debugName, options.debugReferenceFn ?? fn), fn, undefined, debugLocation);\n}\n/**\n * @deprecated Use {@link createEffectOpts} instead.\n */\nconst autorunOpts = createEffectOpts;\n/**\n * Runs immediately and whenever a transaction ends and an observed observable changed.\n * {@link fn} should start with a JS Doc using `@description` to name the autorun.\n *\n * Use `changeTracker.createChangeSummary` to create a \"change summary\" that can collect the changes.\n * Use `changeTracker.handleChange` to add a reported change to the change summary.\n * The run function is given the last change summary.\n * The change summary is discarded after the run function was called.\n *\n * @see autorun\n */\nfunction autorunHandleChanges(options, fn, debugLocation = DebugLocation.ofCaller()) {\n return new AutorunObserver(new DebugNameData(options.owner, options.debugName, options.debugReferenceFn ?? fn), fn, options.changeTracker, debugLocation);\n}\n/**\n * @see autorunHandleChanges (but with a disposable store that is cleared before the next run or on dispose)\n */\nfunction autorunWithStoreHandleChanges(options, fn) {\n const store = new DisposableStore();\n const disposable = autorunHandleChanges({\n owner: options.owner,\n debugName: options.debugName,\n debugReferenceFn: options.debugReferenceFn ?? fn,\n changeTracker: options.changeTracker,\n }, (reader, changeSummary) => {\n store.clear();\n fn(reader, changeSummary, store);\n });\n return toDisposable(() => {\n disposable.dispose();\n store.dispose();\n });\n}\n/**\n * @see autorun (but with a disposable store that is cleared before the next run or on dispose)\n *\n * @deprecated Use `autorun(reader => { reader.store.add(...) })` instead!\n */\nfunction autorunWithStore(fn) {\n const store = new DisposableStore();\n const disposable = createEffectOpts({\n owner: undefined,\n debugName: undefined,\n debugReferenceFn: fn,\n }, reader => {\n store.clear();\n fn(reader, store);\n });\n return toDisposable(() => {\n disposable.dispose();\n store.dispose();\n });\n}\nfunction autorunDelta(observable, handler) {\n let _lastValue;\n return createEffectOpts({ debugReferenceFn: handler }, (reader) => {\n const newValue = observable.read(reader);\n const lastValue = _lastValue;\n _lastValue = newValue;\n handler({ lastValue, newValue });\n });\n}\nfunction autorunIterableDelta(getValue, handler, getUniqueIdentifier = v => v) {\n const lastValues = new Map();\n return createEffectOpts({ debugReferenceFn: getValue }, (reader) => {\n const newValues = new Map();\n const removedValues = new Map(lastValues);\n for (const value of getValue(reader)) {\n const id = getUniqueIdentifier(value);\n if (lastValues.has(id)) {\n removedValues.delete(id);\n }\n else {\n newValues.set(id, value);\n lastValues.set(id, value);\n }\n }\n for (const id of removedValues.keys()) {\n lastValues.delete(id);\n }\n if (newValues.size || removedValues.size) {\n handler({ addedValues: [...newValues.values()], removedValues: [...removedValues.values()] });\n }\n });\n}\n/**\n * An autorun with a `dispose()` method on its `reader` which cancels the autorun.\n * It it safe to call `dispose()` synchronously.\n */\nfunction autorunSelfDisposable(fn, debugLocation = DebugLocation.ofCaller()) {\n let ar;\n let disposed = false;\n // eslint-disable-next-line prefer-const\n ar = createEffect(reader => {\n fn({\n delayedStore: reader.delayedStore,\n store: reader.store,\n readObservable: reader.readObservable.bind(reader),\n dispose: () => {\n ar?.dispose();\n disposed = true;\n }\n });\n }, debugLocation);\n if (disposed) {\n ar.dispose();\n }\n return ar;\n}\n\nexport { autorun, autorunDelta, autorunHandleChanges, autorunIterableDelta, autorunOpts, autorunSelfDisposable, autorunWithStore, autorunWithStoreHandleChanges, createEffect, createEffectOpts };\n//# sourceMappingURL=createEffect.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { onUnexpectedError } from './commonFacade/deps.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/**\n * This function is used to indicate that the caller recovered from an error that indicates a bug.\n*/\nfunction handleBugIndicatingErrorRecovery(message) {\n const err = new Error('BugIndicatingErrorRecovery: ' + message);\n onUnexpectedError(err);\n console.error('recovered from an error that indicates a bug', err);\n}\n\nexport { handleBugIndicatingErrorRecovery };\n//# sourceMappingURL=base.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { handleBugIndicatingErrorRecovery } from './base.js';\nimport { getFunctionName } from './debugName.js';\nimport { getLogger } from './logging/logging.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/**\n * Starts a transaction in which many observables can be changed at once.\n * {@link fn} should start with a JS Doc using `@description` to give the transaction a debug name.\n * Reaction run on demand or when the transaction ends.\n */\nfunction transaction(fn, getDebugName) {\n const tx = new TransactionImpl(fn, getDebugName);\n try {\n fn(tx);\n }\n finally {\n tx.finish();\n }\n}\nlet _globalTransaction = undefined;\nfunction globalTransaction(fn) {\n if (_globalTransaction) {\n fn(_globalTransaction);\n }\n else {\n const tx = new TransactionImpl(fn, undefined);\n _globalTransaction = tx;\n try {\n fn(tx);\n }\n finally {\n tx.finish(); // During finish, more actions might be added to the transaction.\n // Which is why we only clear the global transaction after finish.\n _globalTransaction = undefined;\n }\n }\n}\n/** @deprecated */\nasync function asyncTransaction(fn, getDebugName) {\n const tx = new TransactionImpl(fn, getDebugName);\n try {\n await fn(tx);\n }\n finally {\n tx.finish();\n }\n}\n/**\n * Allows to chain transactions.\n */\nfunction subtransaction(tx, fn, getDebugName) {\n if (!tx) {\n transaction(fn, getDebugName);\n }\n else {\n fn(tx);\n }\n}\nclass TransactionImpl {\n constructor(_fn, _getDebugName) {\n this._fn = _fn;\n this._getDebugName = _getDebugName;\n this._updatingObservers = [];\n getLogger()?.handleBeginTransaction(this);\n }\n getDebugName() {\n if (this._getDebugName) {\n return this._getDebugName();\n }\n return getFunctionName(this._fn);\n }\n updateObserver(observer, observable) {\n if (!this._updatingObservers) {\n // This happens when a transaction is used in a callback or async function.\n // If an async transaction is used, make sure the promise awaits all users of the transaction (e.g. no race).\n handleBugIndicatingErrorRecovery('Transaction already finished!');\n // Error recovery\n transaction(tx => {\n tx.updateObserver(observer, observable);\n });\n return;\n }\n // When this gets called while finish is active, they will still get considered\n this._updatingObservers.push({ observer, observable });\n observer.beginUpdate(observable);\n }\n finish() {\n const updatingObservers = this._updatingObservers;\n if (!updatingObservers) {\n handleBugIndicatingErrorRecovery('transaction.finish() has already been called!');\n return;\n }\n for (let i = 0; i < updatingObservers.length; i++) {\n const { observer, observable } = updatingObservers[i];\n observer.endUpdate(observable);\n }\n // Prevent anyone from updating observers from now on.\n this._updatingObservers = null;\n getLogger()?.handleEndTransaction(this);\n }\n debugGetUpdatingObservers() {\n return this._updatingObservers;\n }\n}\n\nexport { TransactionImpl, asyncTransaction, globalTransaction, subtransaction, transaction };\n//# sourceMappingURL=transaction.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { TransactionImpl } from '../transaction.js';\nimport { BaseObservable } from './baseObservable.js';\nimport { strictEquals } from '../commonFacade/deps.js';\nimport { DebugNameData } from '../debugName.js';\nimport { getLogger } from '../logging/logging.js';\nimport { DebugLocation } from '../debugLocation.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction observableValue(nameOrOwner, initialValue, debugLocation = DebugLocation.ofCaller()) {\n let debugNameData;\n if (typeof nameOrOwner === 'string') {\n debugNameData = new DebugNameData(undefined, nameOrOwner, undefined);\n }\n else {\n debugNameData = new DebugNameData(nameOrOwner, undefined, undefined);\n }\n return new ObservableValue(debugNameData, initialValue, strictEquals, debugLocation);\n}\nclass ObservableValue extends BaseObservable {\n get debugName() {\n return this._debugNameData.getDebugName(this) ?? 'ObservableValue';\n }\n constructor(_debugNameData, initialValue, _equalityComparator, debugLocation) {\n super(debugLocation);\n this._debugNameData = _debugNameData;\n this._equalityComparator = _equalityComparator;\n this._value = initialValue;\n getLogger()?.handleObservableUpdated(this, { hadValue: false, newValue: initialValue, change: undefined, didChange: true, oldValue: undefined });\n }\n get() {\n return this._value;\n }\n set(value, tx, change) {\n if (change === undefined && this._equalityComparator(this._value, value)) {\n return;\n }\n let _tx;\n if (!tx) {\n tx = _tx = new TransactionImpl(() => { }, () => `Setting ${this.debugName}`);\n }\n try {\n const oldValue = this._value;\n this._setValue(value);\n getLogger()?.handleObservableUpdated(this, { oldValue, newValue: value, change, didChange: true, hadValue: true });\n for (const observer of this._observers) {\n tx.updateObserver(observer, this);\n observer.handleChange(this, change);\n }\n }\n finally {\n if (_tx) {\n _tx.finish();\n }\n }\n }\n toString() {\n return `${this.debugName}: ${this._value}`;\n }\n _setValue(newValue) {\n this._value = newValue;\n }\n debugGetState() {\n return {\n value: this._value,\n };\n }\n debugSetValue(value) {\n this._value = value;\n }\n}\n/**\n * A disposable observable. When disposed, its value is also disposed.\n * When a new value is set, the previous value is disposed.\n */\nfunction disposableObservableValue(nameOrOwner, initialValue, debugLocation = DebugLocation.ofCaller()) {\n let debugNameData;\n if (typeof nameOrOwner === 'string') {\n debugNameData = new DebugNameData(undefined, nameOrOwner, undefined);\n }\n else {\n debugNameData = new DebugNameData(nameOrOwner, undefined, undefined);\n }\n return new DisposableObservableValue(debugNameData, initialValue, strictEquals, debugLocation);\n}\nclass DisposableObservableValue extends ObservableValue {\n _setValue(newValue) {\n if (this._value === newValue) {\n return;\n }\n if (this._value) {\n this._value.dispose();\n }\n this._value = newValue;\n }\n dispose() {\n this._value?.dispose();\n }\n}\n\nexport { DisposableObservableValue, ObservableValue, disposableObservableValue, observableValue };\n//# sourceMappingURL=observableValue.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { subtransaction } from '../transaction.js';\nimport { strictEquals } from '../commonFacade/deps.js';\nimport { DebugNameData } from '../debugName.js';\nimport { getLogger } from '../logging/logging.js';\nimport { BaseObservable } from './baseObservable.js';\nimport { DebugLocation } from '../debugLocation.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction observableFromEvent(...args) {\n let owner;\n let event;\n let getValue;\n let debugLocation;\n if (args.length === 2) {\n [event, getValue] = args;\n }\n else {\n [owner, event, getValue, debugLocation] = args;\n }\n return new FromEventObservable(new DebugNameData(owner, undefined, getValue), event, getValue, () => FromEventObservable.globalTransaction, strictEquals, debugLocation ?? DebugLocation.ofCaller());\n}\nfunction observableFromEventOpts(options, event, getValue, debugLocation = DebugLocation.ofCaller()) {\n return new FromEventObservable(new DebugNameData(options.owner, options.debugName, options.debugReferenceFn ?? getValue), event, getValue, () => FromEventObservable.globalTransaction, options.equalsFn ?? strictEquals, debugLocation);\n}\nclass FromEventObservable extends BaseObservable {\n constructor(_debugNameData, event, _getValue, _getTransaction, _equalityComparator, debugLocation) {\n super(debugLocation);\n this._debugNameData = _debugNameData;\n this.event = event;\n this._getValue = _getValue;\n this._getTransaction = _getTransaction;\n this._equalityComparator = _equalityComparator;\n this._hasValue = false;\n this.handleEvent = (args) => {\n const newValue = this._getValue(args);\n const oldValue = this._value;\n const didChange = !this._hasValue || !(this._equalityComparator(oldValue, newValue));\n let didRunTransaction = false;\n if (didChange) {\n this._value = newValue;\n if (this._hasValue) {\n didRunTransaction = true;\n subtransaction(this._getTransaction(), (tx) => {\n getLogger()?.handleObservableUpdated(this, { oldValue, newValue, change: undefined, didChange, hadValue: this._hasValue });\n for (const o of this._observers) {\n tx.updateObserver(o, this);\n o.handleChange(this, undefined);\n }\n }, () => {\n const name = this.getDebugName();\n return 'Event fired' + (name ? `: ${name}` : '');\n });\n }\n this._hasValue = true;\n }\n if (!didRunTransaction) {\n getLogger()?.handleObservableUpdated(this, { oldValue, newValue, change: undefined, didChange, hadValue: this._hasValue });\n }\n };\n }\n getDebugName() {\n return this._debugNameData.getDebugName(this);\n }\n get debugName() {\n const name = this.getDebugName();\n return 'From Event' + (name ? `: ${name}` : '');\n }\n onFirstObserverAdded() {\n this._subscription = this.event(this.handleEvent);\n }\n onLastObserverRemoved() {\n this._subscription.dispose();\n this._subscription = undefined;\n this._hasValue = false;\n this._value = undefined;\n }\n get() {\n if (this._subscription) {\n if (!this._hasValue) {\n this.handleEvent(undefined);\n }\n return this._value;\n }\n else {\n // no cache, as there are no subscribers to keep it updated\n const value = this._getValue(undefined);\n return value;\n }\n }\n debugSetValue(value) {\n this._value = value;\n }\n debugGetState() {\n return { value: this._value, hasValue: this._hasValue };\n }\n}\n(function (observableFromEvent) {\n observableFromEvent.Observer = FromEventObservable;\n function batchEventsGlobally(tx, fn) {\n let didSet = false;\n if (FromEventObservable.globalTransaction === undefined) {\n FromEventObservable.globalTransaction = tx;\n didSet = true;\n }\n try {\n fn();\n }\n finally {\n if (didSet) {\n FromEventObservable.globalTransaction = undefined;\n }\n }\n }\n observableFromEvent.batchEventsGlobally = batchEventsGlobally;\n})(observableFromEvent || (observableFromEvent = {}));\n\nexport { FromEventObservable, observableFromEvent, observableFromEventOpts };\n//# sourceMappingURL=observableFromEvent.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { createEffect } from '../reactions/createEffect.js';\nimport { transaction } from '../transaction.js';\nimport { observableValue } from '../observables/observableValue.js';\nimport { toDisposable } from '../commonFacade/deps.js';\nimport { derivedOpts, derived } from '../observables/derived.js';\nimport { observableFromEvent } from '../observables/observableFromEvent.js';\nimport { observableSignal } from '../observables/observableSignal.js';\nimport { _setKeepObserved, _setRecomputeInitiallyAndOnChange } from '../observables/baseObservable.js';\nimport { DisposableStore } from '../../disposables.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction observableFromPromise(promise) {\n const observable = observableValue('promiseValue', {});\n promise.then((value) => {\n observable.set({ value }, undefined);\n });\n return observable;\n}\nfunction signalFromObservable(owner, observable) {\n return derivedOpts({\n owner,\n equalsFn: () => false,\n }, reader => {\n observable.read(reader);\n });\n}\n/**\n * @deprecated Use `debouncedObservable` instead.\n */\nfunction debouncedObservableDeprecated(observable, debounceMs, disposableStore) {\n const debouncedObservable = observableValue('debounced', undefined);\n let timeout = undefined;\n disposableStore.add(createEffect(reader => {\n /** @description debounce */\n const value = observable.read(reader);\n if (timeout) {\n clearTimeout(timeout);\n }\n timeout = setTimeout(() => {\n transaction(tx => {\n debouncedObservable.set(value, tx);\n });\n }, debounceMs);\n }));\n return debouncedObservable;\n}\n/**\n * Creates an observable that debounces the input observable.\n */\nfunction debouncedObservable(observable, debounceMs) {\n let hasValue = false;\n let lastValue;\n let timeout = undefined;\n return observableFromEvent(cb => {\n const d = createEffect(reader => {\n const value = observable.read(reader);\n if (!hasValue) {\n hasValue = true;\n lastValue = value;\n }\n else {\n if (timeout) {\n clearTimeout(timeout);\n }\n timeout = setTimeout(() => {\n lastValue = value;\n cb();\n }, debounceMs);\n }\n });\n return {\n dispose() {\n d.dispose();\n hasValue = false;\n lastValue = undefined;\n },\n };\n }, () => {\n if (hasValue) {\n return lastValue;\n }\n else {\n return observable.get();\n }\n });\n}\nfunction wasEventTriggeredRecently(event, timeoutMs, disposableStore) {\n const observable = observableValue('triggeredRecently', false);\n let timeout = undefined;\n disposableStore.add(event(() => {\n observable.set(true, undefined);\n if (timeout) {\n clearTimeout(timeout);\n }\n timeout = setTimeout(() => {\n observable.set(false, undefined);\n }, timeoutMs);\n }));\n return observable;\n}\n/**\n * This makes sure the observable is being observed and keeps its cache alive.\n */\nfunction keepObserved(observable) {\n const o = new KeepAliveObserver(false, undefined);\n observable.addObserver(o);\n return toDisposable(() => {\n observable.removeObserver(o);\n });\n}\n_setKeepObserved(keepObserved);\n/**\n * This converts the given observable into an autorun.\n */\nfunction recomputeInitiallyAndOnChange(observable, handleValue) {\n const o = new KeepAliveObserver(true, handleValue);\n observable.addObserver(o);\n try {\n o.beginUpdate(observable);\n }\n finally {\n o.endUpdate(observable);\n }\n return toDisposable(() => {\n observable.removeObserver(o);\n });\n}\n_setRecomputeInitiallyAndOnChange(recomputeInitiallyAndOnChange);\nclass KeepAliveObserver {\n constructor(_forceRecompute, _handleValue) {\n this._forceRecompute = _forceRecompute;\n this._handleValue = _handleValue;\n this._counter = 0;\n }\n beginUpdate(observable) {\n this._counter++;\n }\n endUpdate(observable) {\n if (this._counter === 1 && this._forceRecompute) {\n if (this._handleValue) {\n this._handleValue(observable.get());\n }\n else {\n observable.reportChanges();\n }\n }\n this._counter--;\n }\n handlePossibleChange(observable) {\n // NO OP\n }\n handleChange(observable, change) {\n // NO OP\n }\n}\nfunction derivedObservableWithCache(owner, computeFn) {\n let lastValue = undefined;\n const observable = derivedOpts({ owner, debugReferenceFn: computeFn }, reader => {\n lastValue = computeFn(reader, lastValue);\n return lastValue;\n });\n return observable;\n}\nfunction derivedObservableWithWritableCache(owner, computeFn) {\n let lastValue = undefined;\n const onChange = observableSignal('derivedObservableWithWritableCache');\n const observable = derived(owner, reader => {\n onChange.read(reader);\n lastValue = computeFn(reader, lastValue);\n return lastValue;\n });\n return Object.assign(observable, {\n clearCache: (tx) => {\n lastValue = undefined;\n onChange.trigger(tx);\n },\n setCache: (newValue, tx) => {\n lastValue = newValue;\n onChange.trigger(tx);\n }\n });\n}\n/**\n * When the items array changes, referential equal items are not mapped again.\n */\nfunction mapObservableArrayCached(owner, items, map, keySelector) {\n let m = new ArrayMap(map, keySelector);\n const self = derivedOpts({\n debugReferenceFn: map,\n owner,\n onLastObserverRemoved: () => {\n m.dispose();\n m = new ArrayMap(map);\n }\n }, (reader) => {\n m.setItems(items.read(reader));\n return m.getItems();\n });\n return self;\n}\nclass ArrayMap {\n constructor(_map, _keySelector) {\n this._map = _map;\n this._keySelector = _keySelector;\n this._cache = new Map();\n this._items = [];\n }\n dispose() {\n this._cache.forEach(entry => entry.store.dispose());\n this._cache.clear();\n }\n setItems(items) {\n const newItems = [];\n const itemsToRemove = new Set(this._cache.keys());\n for (const item of items) {\n const key = this._keySelector ? this._keySelector(item) : item;\n let entry = this._cache.get(key);\n if (!entry) {\n const store = new DisposableStore();\n const out = this._map(item, store);\n entry = { out, store };\n this._cache.set(key, entry);\n }\n else {\n itemsToRemove.delete(key);\n }\n newItems.push(entry.out);\n }\n for (const item of itemsToRemove) {\n const entry = this._cache.get(item);\n entry.store.dispose();\n this._cache.delete(item);\n }\n this._items = newItems;\n }\n getItems() {\n return this._items;\n }\n}\n\nexport { KeepAliveObserver, debouncedObservable, debouncedObservableDeprecated, derivedObservableWithCache, derivedObservableWithWritableCache, keepObserved, mapObservableArrayCached, observableFromPromise, recomputeInitiallyAndOnChange, signalFromObservable, wasEventTriggeredRecently };\n//# sourceMappingURL=utils.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { addLogger } from './logging.js';\nimport { getClassName } from '../debugName.js';\nimport { Derived } from '../observables/derivedImpl.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nlet consoleObservableLogger;\nfunction logObservableToConsole(obs) {\n if (!consoleObservableLogger) {\n consoleObservableLogger = new ConsoleObservableLogger();\n addLogger(consoleObservableLogger);\n }\n consoleObservableLogger.addFilteredObj(obs);\n}\nclass ConsoleObservableLogger {\n constructor() {\n this.indentation = 0;\n this.changedObservablesSets = new WeakMap();\n }\n addFilteredObj(obj) {\n if (!this._filteredObjects) {\n this._filteredObjects = new Set();\n }\n this._filteredObjects.add(obj);\n }\n _isIncluded(obj) {\n return this._filteredObjects?.has(obj) ?? true;\n }\n textToConsoleArgs(text) {\n return consoleTextToArgs([\n normalText(repeat('| ', this.indentation)),\n text,\n ]);\n }\n formatInfo(info) {\n if (!info.hadValue) {\n return [\n normalText(` `),\n styled(formatValue(info.newValue, 60), {\n color: 'green',\n }),\n normalText(` (initial)`),\n ];\n }\n return info.didChange\n ? [\n normalText(` `),\n styled(formatValue(info.oldValue, 70), {\n color: 'red',\n strikeThrough: true,\n }),\n normalText(` `),\n styled(formatValue(info.newValue, 60), {\n color: 'green',\n }),\n ]\n : [normalText(` (unchanged)`)];\n }\n handleObservableCreated(observable) {\n if (observable instanceof Derived) {\n const derived = observable;\n this.changedObservablesSets.set(derived, new Set());\n }\n }\n handleOnListenerCountChanged(observable, newCount) {\n }\n handleObservableUpdated(observable, info) {\n if (!this._isIncluded(observable)) {\n return;\n }\n if (observable instanceof Derived) {\n this._handleDerivedRecomputed(observable, info);\n return;\n }\n console.log(...this.textToConsoleArgs([\n formatKind('observable value changed'),\n styled(observable.debugName, { color: 'BlueViolet' }),\n ...this.formatInfo(info),\n ]));\n }\n formatChanges(changes) {\n if (changes.size === 0) {\n return undefined;\n }\n return styled(' (changed deps: ' +\n [...changes].map((o) => o.debugName).join(', ') +\n ')', { color: 'gray' });\n }\n handleDerivedDependencyChanged(derived, observable, change) {\n if (!this._isIncluded(derived)) {\n return;\n }\n this.changedObservablesSets.get(derived)?.add(observable);\n }\n _handleDerivedRecomputed(derived, info) {\n if (!this._isIncluded(derived)) {\n return;\n }\n const changedObservables = this.changedObservablesSets.get(derived);\n if (!changedObservables) {\n return;\n }\n console.log(...this.textToConsoleArgs([\n formatKind('derived recomputed'),\n styled(derived.debugName, { color: 'BlueViolet' }),\n ...this.formatInfo(info),\n this.formatChanges(changedObservables),\n { data: [{ fn: derived._debugNameData.referenceFn ?? derived._computeFn }] }\n ]));\n changedObservables.clear();\n }\n handleDerivedCleared(derived) {\n if (!this._isIncluded(derived)) {\n return;\n }\n console.log(...this.textToConsoleArgs([\n formatKind('derived cleared'),\n styled(derived.debugName, { color: 'BlueViolet' }),\n ]));\n }\n handleFromEventObservableTriggered(observable, info) {\n if (!this._isIncluded(observable)) {\n return;\n }\n console.log(...this.textToConsoleArgs([\n formatKind('observable from event triggered'),\n styled(observable.debugName, { color: 'BlueViolet' }),\n ...this.formatInfo(info),\n { data: [{ fn: observable._getValue }] }\n ]));\n }\n handleAutorunCreated(autorun) {\n if (!this._isIncluded(autorun)) {\n return;\n }\n this.changedObservablesSets.set(autorun, new Set());\n }\n handleAutorunDisposed(autorun) {\n }\n handleAutorunDependencyChanged(autorun, observable, change) {\n if (!this._isIncluded(autorun)) {\n return;\n }\n this.changedObservablesSets.get(autorun).add(observable);\n }\n handleAutorunStarted(autorun) {\n const changedObservables = this.changedObservablesSets.get(autorun);\n if (!changedObservables) {\n return;\n }\n if (this._isIncluded(autorun)) {\n console.log(...this.textToConsoleArgs([\n formatKind('autorun'),\n styled(autorun.debugName, { color: 'BlueViolet' }),\n this.formatChanges(changedObservables),\n { data: [{ fn: autorun._debugNameData.referenceFn ?? autorun._runFn }] }\n ]));\n }\n changedObservables.clear();\n this.indentation++;\n }\n handleAutorunFinished(autorun) {\n this.indentation--;\n }\n handleBeginTransaction(transaction) {\n let transactionName = transaction.getDebugName();\n if (transactionName === undefined) {\n transactionName = '';\n }\n if (this._isIncluded(transaction)) {\n console.log(...this.textToConsoleArgs([\n formatKind('transaction'),\n styled(transactionName, { color: 'BlueViolet' }),\n { data: [{ fn: transaction._fn }] }\n ]));\n }\n this.indentation++;\n }\n handleEndTransaction() {\n this.indentation--;\n }\n}\nfunction consoleTextToArgs(text) {\n const styles = new Array();\n const data = [];\n let firstArg = '';\n function process(t) {\n if ('length' in t) {\n for (const item of t) {\n if (item) {\n process(item);\n }\n }\n }\n else if ('text' in t) {\n firstArg += `%c${t.text}`;\n styles.push(t.style);\n if (t.data) {\n data.push(...t.data);\n }\n }\n else if ('data' in t) {\n data.push(...t.data);\n }\n }\n process(text);\n const result = [firstArg, ...styles];\n result.push(...data);\n return result;\n}\nfunction normalText(text) {\n return styled(text, { color: 'black' });\n}\nfunction formatKind(kind) {\n return styled(padStr(`${kind}: `, 10), { color: 'black', bold: true });\n}\nfunction styled(text, options = {\n color: 'black',\n}) {\n function objToCss(styleObj) {\n return Object.entries(styleObj).reduce((styleString, [propName, propValue]) => {\n return `${styleString}${propName}:${propValue};`;\n }, '');\n }\n const style = {\n color: options.color,\n };\n if (options.strikeThrough) {\n style['text-decoration'] = 'line-through';\n }\n if (options.bold) {\n style['font-weight'] = 'bold';\n }\n return {\n text,\n style: objToCss(style),\n };\n}\nfunction formatValue(value, availableLen) {\n try {\n return formatValueUnsafe(value, availableLen);\n }\n catch {\n // Value could not be formatted (e.g., a Proxy that throws on coercion)\n return '[[???]]';\n }\n}\nfunction formatValueUnsafe(value, availableLen) {\n switch (typeof value) {\n case 'number':\n return '' + value;\n case 'string':\n if (value.length + 2 <= availableLen) {\n return `\"${value}\"`;\n }\n return `\"${value.substr(0, availableLen - 7)}\"+...`;\n case 'boolean':\n return value ? 'true' : 'false';\n case 'undefined':\n return 'undefined';\n case 'object':\n if (value === null) {\n return 'null';\n }\n if (Array.isArray(value)) {\n return formatArray(value, availableLen);\n }\n return formatObject(value, availableLen);\n case 'symbol':\n return value.toString();\n case 'function':\n return `[[Function${value.name ? ' ' + value.name : ''}]]`;\n default:\n return '' + value;\n }\n}\nfunction formatArray(value, availableLen) {\n let result = '[ ';\n let first = true;\n for (const val of value) {\n if (!first) {\n result += ', ';\n }\n if (result.length - 5 > availableLen) {\n result += '...';\n break;\n }\n first = false;\n result += `${formatValue(val, availableLen - result.length)}`;\n }\n result += ' ]';\n return result;\n}\nfunction formatObject(value, availableLen) {\n // Avoid drilling into Proxies - wrap operations that could trigger traps\n try {\n if (typeof value.toString === 'function' && value.toString !== Object.prototype.toString) {\n const val = value.toString();\n if (val.length <= availableLen) {\n return val;\n }\n return val.substring(0, availableLen - 3) + '...';\n }\n }\n catch {\n // toString triggered a Proxy trap or threw - bail out\n return '[[Object]]';\n }\n const className = getClassName(value);\n let result = className ? className + '(' : '{ ';\n let first = true;\n let entries;\n try {\n entries = Object.entries(value);\n }\n catch {\n // Object.entries triggered a Proxy trap - bail out\n return className ? `${className}(...)` : '[[Object]]';\n }\n for (const [key, val] of entries) {\n if (!first) {\n result += ', ';\n }\n if (result.length - 5 > availableLen) {\n result += '...';\n break;\n }\n first = false;\n result += `${key}: ${formatValue(val, availableLen - result.length)}`;\n }\n result += className ? ')' : ' }';\n return result;\n}\nfunction repeat(str, count) {\n let result = '';\n for (let i = 1; i <= count; i++) {\n result += str;\n }\n return result;\n}\nfunction padStr(str, length) {\n while (str.length < length) {\n str += ' ';\n }\n return str;\n}\n\nexport { ConsoleObservableLogger, formatValue, logObservableToConsole };\n//# sourceMappingURL=consoleObservableLogger.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { Derived } from '../observables/derivedImpl.js';\nimport { FromEventObservable } from '../observables/observableFromEvent.js';\nimport { ObservableValue } from '../observables/observableValue.js';\nimport { AutorunObserver } from '../reactions/createEffectImpl.js';\nimport { formatValue } from './consoleObservableLogger.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction debugGetDependencyGraph(obs, options) {\n const debugNamePostProcessor = options?.debugNamePostProcessor ?? ((str) => str);\n const info = Info.from(obs, debugNamePostProcessor);\n if (!info) {\n return '';\n }\n const alreadyListed = new Set();\n return formatObservableInfo(info, 0, alreadyListed).trim();\n}\nfunction formatObservableInfo(info, indentLevel, alreadyListed) {\n const indent = '\\t\\t'.repeat(indentLevel);\n const lines = [];\n const isAlreadyListed = alreadyListed.has(info.sourceObj);\n if (isAlreadyListed) {\n lines.push(`${indent}* ${info.type} ${info.name} (already listed)`);\n return lines.join('\\n');\n }\n alreadyListed.add(info.sourceObj);\n lines.push(`${indent}* ${info.type} ${info.name}:`);\n lines.push(`${indent} value: ${formatValue(info.value, 50)}`);\n lines.push(`${indent} state: ${info.state}`);\n if (info.dependencies.length > 0) {\n lines.push(`${indent} dependencies:`);\n for (const dep of info.dependencies) {\n lines.push(formatObservableInfo(dep, indentLevel + 1, alreadyListed));\n }\n }\n return lines.join('\\n');\n}\nclass Info {\n static from(obs, debugNamePostProcessor) {\n if (obs instanceof AutorunObserver) {\n const state = obs.debugGetState();\n return new Info(obs, debugNamePostProcessor(obs.debugName), 'autorun', undefined, state.stateStr, Array.from(state.dependencies).map(dep => Info.from(dep, debugNamePostProcessor) || Info.unknown(dep)));\n }\n else if (obs instanceof Derived) {\n const state = obs.debugGetState();\n return new Info(obs, debugNamePostProcessor(obs.debugName), 'derived', state.value, state.stateStr, Array.from(state.dependencies).map(dep => Info.from(dep, debugNamePostProcessor) || Info.unknown(dep)));\n }\n else if (obs instanceof ObservableValue) {\n const state = obs.debugGetState();\n return new Info(obs, debugNamePostProcessor(obs.debugName), 'observableValue', state.value, 'upToDate', []);\n }\n else if (obs instanceof FromEventObservable) {\n const state = obs.debugGetState();\n return new Info(obs, debugNamePostProcessor(obs.debugName), 'fromEvent', state.value, state.hasValue ? 'upToDate' : 'initial', []);\n }\n return undefined;\n }\n static unknown(obs) {\n return new Info(obs, '(unknown)', 'unknown', undefined, 'unknown', []);\n }\n constructor(sourceObj, name, type, value, state, dependencies) {\n this.sourceObj = sourceObj;\n this.name = name;\n this.type = type;\n this.value = value;\n this.state = state;\n this.dependencies = dependencies;\n }\n}\n\nexport { debugGetDependencyGraph };\n//# sourceMappingURL=debugGetDependencyGraph.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { setLogObservableFn } from './logging/logging.js';\nimport { _setDebugGetDependencyGraph } from './observables/baseObservable.js';\nexport { DebugLocation } from './debugLocation.js';\nexport { derived, derivedDisposable, derivedHandleChanges, derivedOpts, derivedWithSetter, derivedWithStore } from './observables/derived.js';\nexport { debouncedObservable, debouncedObservableDeprecated, derivedObservableWithCache, derivedObservableWithWritableCache, keepObserved, mapObservableArrayCached, observableFromPromise, recomputeInitiallyAndOnChange, signalFromObservable, wasEventTriggeredRecently } from './utils/utils.js';\nexport { observableFromEvent, observableFromEventOpts } from './observables/observableFromEvent.js';\nimport { logObservableToConsole } from './logging/consoleObservableLogger.js';\nimport { debugGetDependencyGraph } from './logging/debugGetDependencyGraph.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n// This is a facade for the observable implementation. Only import from here!\n_setDebugGetDependencyGraph(debugGetDependencyGraph);\nsetLogObservableFn(logObservableToConsole);\n//# sourceMappingURL=index.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { transaction } from '../transaction.js';\nimport { derived } from '../observables/derived.js';\nimport { observableValue } from '../observables/observableValue.js';\n\nclass ObservableLazy {\n /**\n * The cached value.\n * Does not force a computation of the value.\n */\n get cachedValue() { return this._value; }\n constructor(_computeValue) {\n this._computeValue = _computeValue;\n this._value = observableValue(this, undefined);\n }\n /**\n * Returns the cached value.\n * Computes the value if the value has not been cached yet.\n */\n getValue() {\n let v = this._value.get();\n if (!v) {\n v = this._computeValue();\n this._value.set(v, undefined);\n }\n return v;\n }\n}\n/**\n * A promise whose state is observable.\n */\nclass ObservablePromise {\n static fromFn(fn) {\n return new ObservablePromise(fn());\n }\n constructor(promise) {\n this._value = observableValue(this, undefined);\n /**\n * The current state of the promise.\n * Is `undefined` if the promise didn't resolve yet.\n */\n this.promiseResult = this._value;\n this.resolvedValue = derived(this, reader => {\n const result = this.promiseResult.read(reader);\n if (!result) {\n return undefined;\n }\n return result.getDataOrThrow();\n });\n this.promise = promise.then(value => {\n transaction(tx => {\n /** @description onPromiseResolved */\n this._value.set(new PromiseResult(value, undefined), tx);\n });\n return value;\n }, error => {\n transaction(tx => {\n /** @description onPromiseRejected */\n this._value.set(new PromiseResult(undefined, error), tx);\n });\n throw error;\n });\n }\n}\nclass PromiseResult {\n constructor(\n /**\n * The value of the resolved promise.\n * Undefined if the promise rejected.\n */\n data, \n /**\n * The error in case of a rejected promise.\n * Undefined if the promise resolved.\n */\n error) {\n this.data = data;\n this.error = error;\n }\n /**\n * Returns the value if the promise resolved, otherwise throws the error.\n */\n getDataOrThrow() {\n if (this.error) {\n throw this.error;\n }\n return this.data;\n }\n}\n/**\n * A lazy promise whose state is observable.\n */\nclass ObservableLazyPromise {\n constructor(_computePromise) {\n this._computePromise = _computePromise;\n this._lazyValue = new ObservableLazy(() => new ObservablePromise(this._computePromise()));\n /**\n * Does not enforce evaluation of the promise compute function.\n * Is undefined if the promise has not been computed yet.\n */\n this.cachedPromiseResult = derived(this, reader => this._lazyValue.cachedValue.read(reader)?.promiseResult.read(reader));\n }\n getPromise() {\n return this._lazyValue.getValue().promise;\n }\n}\n\nexport { ObservableLazy, ObservableLazyPromise, ObservablePromise, PromiseResult };\n//# sourceMappingURL=promise.js.map\n","import { jcsCanonicalize, type Pattern, type Permission } from '@hediet/linkrpc';\nimport type { HubAccessManifestRequest } from '@hediet/linkrpc/hub/common';\nimport type { AccessDirectPermission } from '@hediet/linkrpc-hub/hub/server';\n\nexport interface ApprovalPresentationLine {\n readonly label?: string;\n readonly text: string;\n readonly tone?: 'normal' | 'muted' | 'warning';\n}\n\nexport interface ApprovalPresentationRequest {\n readonly id: string;\n readonly request: HubAccessManifestRequest;\n readonly sourceServiceId?: string;\n}\n\nexport interface PreparedApprovalPresentation {\n readonly pending: ApprovalPresentationRequest;\n readonly permissions: readonly Permission[];\n readonly resolvedSlot?: {\n readonly serviceId: string;\n readonly satisfiedInterfaces: readonly string[];\n };\n}\n\nexport interface ApprovalPresentation {\n readonly heading: string;\n readonly details: readonly ApprovalPresentationLine[];\n}\n\nexport function createApprovalPresentation(\n item: ApprovalPresentationRequest,\n prepared?: PreparedApprovalPresentation,\n): ApprovalPresentation {\n const request = item.request;\n const details: ApprovalPresentationLine[] = [\n { label: 'Consumer', text: request.consumer.name },\n { label: 'Principal', text: request.consumer.principal, tone: 'muted' },\n ...(request.consumer.origin !== undefined\n ? [{ label: 'Origin', text: request.consumer.origin } satisfies ApprovalPresentationLine]\n : []),\n ...(request.consumer.purpose !== undefined\n ? [{ label: 'Purpose', text: request.consumer.purpose } satisfies ApprovalPresentationLine]\n : []),\n ...(request.reason !== undefined\n ? [{ label: 'Reason', text: request.reason } satisfies ApprovalPresentationLine]\n : []),\n ...(item.sourceServiceId === undefined\n ? []\n : [{\n label: 'Manifest source',\n text: item.sourceServiceId.length === 0 ? '<root>' : item.sourceServiceId,\n } satisfies ApprovalPresentationLine]),\n {\n label: 'Duration',\n text: request.duration ?? 'unspecified',\n tone: durationTone(request.duration),\n },\n { label: 'Request ID', text: item.id, tone: 'muted' },\n ...(prepared?.resolvedSlot === undefined\n ? []\n : [\n {\n label: 'Resolved service',\n text: prepared.resolvedSlot.serviceId,\n tone: 'warning',\n } satisfies ApprovalPresentationLine,\n {\n label: 'Satisfied interfaces',\n text: prepared.resolvedSlot.satisfiedInterfaces.join(', '),\n } satisfies ApprovalPresentationLine,\n ]),\n {\n text: prepared !== undefined\n ? 'Exact authority to be signed'\n : request.kind === 'direct' ? 'Requested authority' : 'Required service shape',\n tone: 'muted',\n },\n ];\n\n const reviewedPermissions = prepared?.pending.request.kind === 'direct'\n ? prepared.pending.request.permissions\n : undefined;\n details.push(...(\n prepared === undefined\n ? authorityLines(request)\n : permissionLines(prepared.permissions, reviewedPermissions)\n ));\n return {\n heading: `${item.id} ${request.kind} ${request.consumer.name}`,\n details,\n };\n}\n\nexport function approvalDetailLines(\n item: ApprovalPresentationRequest,\n prepared?: PreparedApprovalPresentation,\n): readonly ApprovalPresentationLine[] {\n return createApprovalPresentation(item, prepared).details;\n}\n\nfunction authorityLines(\n request: HubAccessManifestRequest,\n): readonly ApprovalPresentationLine[] {\n if (request.kind === 'direct') {\n return permissionLines(request.permissions);\n }\n return [\n ...request.interfaces.map((item) => ({\n text: `• interface ${item.id}${item.required === false ? ' (optional)' : ''}`,\n } satisfies ApprovalPresentationLine)),\n ...request.members.map((item) => ({\n text: `• member ${item.interfaceId}::${patternText(item.member)}`\n + `${item.required === false ? ' (optional)' : ''}`,\n } satisfies ApprovalPresentationLine)),\n ];\n}\n\nfunction permissionLines(\n permissions: readonly Permission[],\n reviewedPermissions?: readonly AccessDirectPermission[],\n): readonly ApprovalPresentationLine[] {\n return permissions.flatMap((permission, index) => {\n const service = patternText(permission.target.serviceId);\n const iface = patternText(permission.target.interfaceId);\n const members = permission.target.members.map(patternText).join(', ');\n const actions = [\n ...(permission.canInvoke === true ? ['invoke'] : []),\n ...(permission.canDelegate === true ? ['delegate'] : []),\n ].join(' + ') || 'none';\n const callIntent = reviewedPermissions?.[index]?.callIntent;\n return [\n {\n text: `• ${service}::${iface} {${members}}`,\n tone: [\n permission.target.serviceId,\n permission.target.interfaceId,\n ...permission.target.members,\n ].some(isBroadPattern)\n ? 'warning' as const\n : 'normal' as const,\n },\n {\n label: ` Actions ${index + 1}`,\n text: actions,\n tone: permission.canDelegate ? 'warning' : 'normal',\n } satisfies ApprovalPresentationLine,\n ...(permission.target.interfaceHash === undefined\n ? []\n : [{\n label: ' Interface hash',\n text: permission.target.interfaceHash,\n } satisfies ApprovalPresentationLine]),\n ...(permission.params === undefined\n ? [{\n label: ' Parameters',\n text: 'any',\n tone: 'warning',\n } satisfies ApprovalPresentationLine]\n : [{\n label: ' Parameters',\n text: jcsCanonicalize(permission.params),\n } satisfies ApprovalPresentationLine]),\n ...(permission.callBind === undefined\n ? []\n : [{\n label: ' Exact-call binding',\n text: jcsCanonicalize(permission.callBind),\n } satisfies ApprovalPresentationLine]),\n ...(callIntent === undefined\n ? []\n : [\n ...(callIntent.summary === undefined\n ? []\n : [{\n label: ' Call summary',\n text: callIntent.summary,\n } satisfies ApprovalPresentationLine]),\n {\n label: ' Call method',\n text: callIntent.method,\n } satisfies ApprovalPresentationLine,\n {\n label: ' Call parameters',\n text: callIntent.params === undefined\n ? '{}'\n : jcsCanonicalize(callIntent.params),\n } satisfies ApprovalPresentationLine,\n ...(callIntent.interfaceHash === undefined\n ? []\n : [{\n label: ' Call interface hash',\n text: callIntent.interfaceHash,\n } satisfies ApprovalPresentationLine]),\n ]),\n ];\n });\n}\n\nfunction patternText(pattern: Pattern | undefined): string {\n if (pattern === undefined) return 'any';\n if ('exact' in pattern) return `exact(${JSON.stringify(pattern.exact)})`;\n if ('prefix' in pattern) return `prefix(${JSON.stringify(pattern.prefix)})`;\n return 'any';\n}\n\nfunction isBroadPattern(pattern: Pattern | undefined): boolean {\n return pattern === undefined || 'prefix' in pattern;\n}\n\nfunction durationTone(\n duration: string | undefined,\n): ApprovalPresentationLine['tone'] {\n return duration === 'persistent' || duration === undefined ? 'warning' : 'normal';\n}\n","import {\n LinkRpcConnection,\n jcsCanonicalize,\n type Permission,\n type Principal,\n type SignedCapability,\n TransportPair,\n type SigningCallCtx,\n type SigningIdentity,\n} from '@hediet/linkrpc';\nimport {\n HubDirectoryExplorer,\n hubAccessManifestInterface,\n type HubAccessManifestDecision,\n type HubAccessManifestRequest,\n type IHubAccessManifest,\n} from '@hediet/linkrpc/hub/common';\nimport {\n AggregatingHubAccessManifest,\n ApproveClient,\n buildSlotPermissions,\n registerAggregatingManifest,\n runManifestApprover,\n toSignedPermissions,\n type AggregatorSource,\n type ConsentPrompt,\n} from '@hediet/linkrpc-hub';\nimport {\n CapabilityProposalIssuer,\n candidatesForSlot,\n durationToExp,\n type AccessDirectPermission,\n type AccessDurationName,\n type AccessSlotRequest,\n type DirectoryEntry,\n} from '@hediet/linkrpc-hub/hub/server';\nimport { autorun } from '@vscode/observables';\nimport { createApprovalPresentation } from '../approvalPresentation';\nimport { formatJson } from '../output';\n\n/**\n * The only authority an approval command needs for inspecting and updating\n * manifests across a federated Hub.\n */\nexport const approvalCommandPermissions: readonly Permission[] = [\n {\n target: {\n serviceId: { prefix: '' },\n interfaceId: { exact: 'hubAccessManifest' },\n members: [{ prefix: '' }],\n },\n canInvoke: true,\n },\n {\n target: {\n serviceId: { prefix: '' },\n interfaceId: { exact: 'hubrpc.directory' },\n members: [{ prefix: '' }],\n },\n canInvoke: true,\n },\n];\n\nconst approvalCommandPermissionsJson = jcsCanonicalize(approvalCommandPermissions);\n\n/**\n * Installs the root identity's narrowly scoped self-capability used by the\n * approval scanner. Reusing the non-expiring exact grant prevents repeated\n * commands from growing the principal's durable capability bag.\n */\nexport async function bootstrapApprovalCommandCapability(\n principal: Principal,\n): Promise<SignedCapability> {\n const existing = principal.capBag.capabilities.find((capability) =>\n capability.issuer === principal.id\n && capability.audience === principal.id\n && capability.expiresAtMs === undefined\n && capability.parentHash === undefined\n && jcsCanonicalize(capability.permissions) === approvalCommandPermissionsJson\n );\n if (existing) {\n return existing;\n }\n\n const issuer = new CapabilityProposalIssuer(principal.identity);\n const capability = await issuer.mint({\n audience: principal.id,\n permissions: approvalCommandPermissions,\n });\n await principal.capBag.add(capability);\n return capability;\n}\n\nconst MANIFEST_INTERFACE_ID = hubAccessManifestInterface.info.id;\nconst AGGREGATE_SERVICE_ID = 'linkrpc-cli.approvals';\nconst EXTERNAL_ID_PREFIX = 'ar1_';\n\nexport interface PendingApprovalRequest {\n readonly id: string;\n readonly request: HubAccessManifestRequest;\n /** Manifest revision containing the request rendered to the operator. */\n readonly revision: number;\n /** Service ID of the hubAccessManifest that supplied this request. */\n readonly sourceServiceId?: string;\n}\n\nexport type ApprovalDecisionOutcome = 'applied' | 'still-pending';\n\nexport interface PreparedApproval {\n readonly pending: PendingApprovalRequest;\n /** Exact permissions that will be signed, including one-shot call binding. */\n readonly permissions: readonly Permission[];\n readonly resolvedSlot?: {\n readonly serviceId: string;\n readonly satisfiedInterfaces: readonly string[];\n };\n}\n\nexport interface ApprovalSnapshot {\n readonly state: 'connecting' | 'live' | 'stale';\n readonly requests: readonly PendingApprovalRequest[];\n readonly error?: string;\n}\n\nexport interface ApprovalSubscription {\n dispose(): void;\n}\n\nexport interface ApprovalCommandClientOptions {\n readonly manifest: IHubAccessManifest;\n readonly identity: SigningIdentity;\n readonly fetchDirectory?: () => Promise<readonly DirectoryEntry[]>;\n readonly log?: (line: string) => void;\n readonly dispose?: () => void;\n readonly timeoutMs?: number;\n}\n\n/**\n * CLI-facing approval operations over the hub's shared manifest frontend.\n * The underlying {@link ApproveClient} remains authoritative for snapshots and\n * acknowledgement. One-shot commands mint before calling its acknowledged\n * decision path; {@link runManifestApprover} drives the interactive UI.\n */\nexport class ApprovalCommandClient {\n private readonly _principalId: string;\n private readonly _manifest: IHubAccessManifest;\n private readonly _client: ApproveClient;\n private readonly _issuer: CapabilityProposalIssuer;\n private readonly _fetchDirectory: ApprovalCommandClientOptions['fetchDirectory'];\n private readonly _log: (line: string) => void;\n private readonly _disposeExtra: (() => void) | undefined;\n private _lastClientError: string | undefined;\n private _disposed = false;\n\n constructor(options: ApprovalCommandClientOptions) {\n this._principalId = options.identity.publicSigningIdentity.principal;\n this._manifest = options.manifest;\n this._issuer = new CapabilityProposalIssuer(options.identity);\n this._fetchDirectory = options.fetchDirectory;\n this._log = options.log ?? (() => { /* quiet */ });\n this._disposeExtra = options.dispose;\n this._client = new ApproveClient({\n manifest: this._manifest,\n ownPrincipalId: this._principalId,\n timeoutMs: options.timeoutMs,\n log: (line) => {\n this._lastClientError = line;\n this._log(line);\n },\n });\n }\n\n public get principalId(): string {\n return this._principalId;\n }\n\n public async requests(): Promise<readonly PendingApprovalRequest[]> {\n return this._toPendingRequests(await this._currentRequests());\n }\n\n /**\n * Subscribe to the authoritative manifest snapshot. The callback is invoked\n * immediately and whenever the watch reconnects or the request set changes.\n */\n public watch(listener: (snapshot: ApprovalSnapshot) => void): ApprovalSubscription {\n return autorun((reader) => {\n const state = this._client.state.read(reader);\n const requests = this._toPendingRequests(this._client.requests.read(reader));\n listener({\n state,\n requests,\n ...(state === 'stale' && this._lastClientError !== undefined\n ? { error: this._lastClientError }\n : {}),\n });\n });\n }\n\n /** Force an immediate manifest reconciliation. */\n public async refresh(): Promise<void> {\n await this._currentRequests();\n }\n\n public async deny(\n externalId: string,\n reason?: string,\n expected?: PendingApprovalRequest,\n ): Promise<ApprovalDecisionOutcome> {\n const internalId = decodeApprovalRequestId(externalId);\n const pending = await this._requirePending(internalId, externalId);\n if (expected !== undefined) this._requireUnchanged(pending, expected);\n const result = await this._client.decide(internalId, {\n status: 'denied',\n ...(reason !== undefined ? { reason } : {}),\n });\n if (result === 'gone') {\n throw new Error(`approval request '${externalId}' is no longer pending`);\n }\n return result;\n }\n\n public async approve(externalId: string): Promise<ApprovalDecisionOutcome> {\n return this.approvePrepared(await this.prepareApproval(externalId));\n }\n\n /**\n * Resolve the exact authority that an approval will mint. Interactive\n * surfaces render this result before asking for confirmation.\n */\n public async prepareApproval(externalId: string): Promise<PreparedApproval> {\n const internalId = decodeApprovalRequestId(externalId);\n const pending = await this._requirePending(internalId, externalId);\n const resolved = await this._resolveRequest(pending.request);\n if ('denied' in resolved) {\n throw new Error(`approval request '${externalId}' cannot be granted: ${resolved.denied}`);\n }\n const sourceServiceId = approvalRequestSource(internalId);\n return {\n pending: {\n id: externalId,\n request: pending.request,\n revision: pending.revision,\n ...(sourceServiceId === undefined ? {} : { sourceServiceId }),\n },\n permissions: await toSignedPermissions(\n resolved.permissions,\n pending.request.consumer.principal,\n pending.request.duration,\n ),\n ...(resolved.resolvedSlot === undefined ? {} : { resolvedSlot: resolved.resolvedSlot }),\n };\n }\n\n /** Approve only if the request is still exactly the one that was reviewed. */\n public async approvePrepared(prepared: PreparedApproval): Promise<ApprovalDecisionOutcome> {\n const externalId = prepared.pending.id;\n const internalId = decodeApprovalRequestId(externalId);\n const pending = await this._requirePending(internalId, externalId);\n this._requireUnchanged(pending, prepared.pending);\n const decision = await this._grantDecision(prepared);\n // Await the authoritative post-write snapshot before the CLI prints success.\n const result = await this._client.decide(internalId, decision);\n if (result === 'gone') {\n throw new Error(`approval request '${externalId}' is no longer pending`);\n }\n if (decision.status !== 'granted') {\n throw new Error(\n `approval request '${externalId}' could not be granted`\n + (decision.reason !== undefined ? `: ${decision.reason}` : ''),\n );\n }\n return result;\n }\n\n public async runInteractive(signal: AbortSignal, prompt?: ConsentPrompt): Promise<void> {\n await this._currentRequests();\n const approver = runManifestApprover({\n manifest: this._manifest,\n issuer: this._issuer,\n ownPrincipalId: this._principalId,\n ...(this._fetchDirectory !== undefined ? { fetchDirectory: this._fetchDirectory } : {}),\n ...(prompt !== undefined ? { prompt } : {}),\n log: this._log,\n });\n try {\n await waitForAbort(signal);\n } finally {\n approver.dispose();\n }\n }\n\n public dispose(): void {\n if (this._disposed) return;\n this._disposed = true;\n this._client.dispose();\n this._disposeExtra?.();\n }\n\n private async _currentRequests() {\n await this._client.refresh();\n if (this._client.state.get() === 'stale') {\n throw new Error(this._lastClientError ?? 'could not read pending approval requests');\n }\n return this._client.requests.get();\n }\n\n private _toPendingRequests(\n requests: readonly {\n readonly id: string;\n readonly request: HubAccessManifestRequest;\n readonly revision: number;\n }[],\n ): readonly PendingApprovalRequest[] {\n return requests\n .map(({ id, request, revision }) => {\n const sourceServiceId = approvalRequestSource(id);\n return {\n id: encodeApprovalRequestId(id),\n request,\n revision,\n ...(sourceServiceId === undefined ? {} : { sourceServiceId }),\n };\n })\n .sort((a, b) => a.id.localeCompare(b.id));\n }\n\n private async _requirePending(\n internalId: string,\n externalId: string,\n ): Promise<{ readonly id: string; readonly request: HubAccessManifestRequest; readonly revision: number; }> {\n const requests = await this._currentRequests();\n const pending = requests.find((request) => request.id === internalId);\n if (!pending) {\n throw new Error(\n `approval request '${externalId}' is not pending for principal '${this._principalId}'`,\n );\n }\n return pending;\n }\n\n private _requireUnchanged(\n actual: { readonly request: HubAccessManifestRequest; readonly revision: number; },\n expected: PendingApprovalRequest,\n ): void {\n if (jcsCanonicalize(actual.request) !== jcsCanonicalize(expected.request)) {\n throw new Error(\n `approval request '${expected.id}' changed after it was reviewed; review it again`,\n );\n }\n }\n\n private async _resolveRequest(\n request: HubAccessManifestRequest,\n ): Promise<\n | {\n readonly permissions: readonly AccessDirectPermission[];\n readonly resolvedSlot?: {\n readonly serviceId: string;\n readonly satisfiedInterfaces: readonly string[];\n };\n }\n | { readonly denied: string; }\n > {\n let permissions: readonly AccessDirectPermission[];\n let resolvedSlot:\n | { readonly serviceId: string; readonly satisfiedInterfaces: readonly string[]; }\n | undefined;\n if (request.kind === 'direct') {\n permissions = request.permissions as readonly AccessDirectPermission[];\n } else {\n if (this._fetchDirectory === undefined) {\n return { denied: 'no directory available to resolve discover candidates' };\n }\n const slot: AccessSlotRequest = {\n interfaces: request.interfaces.map((item) => ({\n id: item.id,\n required: item.required !== false,\n ...(item.hash !== undefined ? { hash: item.hash } : {}),\n })),\n members: request.members.map((item) => ({\n interfaceId: item.interfaceId,\n member: item.member,\n required: item.required !== false,\n })),\n };\n const candidate = candidatesForSlot(slot, await this._fetchDirectory())[0];\n if (!candidate) {\n return { denied: 'no candidate service satisfies the requested interfaces' };\n }\n const present = new Set(candidate.satisfiedInterfaces.map((item) => item.id));\n permissions = buildSlotPermissions(\n candidate.serviceId,\n slot.interfaces,\n slot.members,\n present,\n ) as AccessDirectPermission[];\n resolvedSlot = {\n serviceId: candidate.serviceId,\n satisfiedInterfaces: candidate.satisfiedInterfaces.map((item) => item.id),\n };\n }\n return {\n permissions,\n ...(resolvedSlot === undefined ? {} : { resolvedSlot }),\n };\n }\n\n private async _grantDecision(prepared: PreparedApproval): Promise<HubAccessManifestDecision> {\n const request = prepared.pending.request;\n const capability = await this._issuer.mint({\n audience: request.consumer.principal,\n permissions: prepared.permissions,\n expiresAtMs: durationToExp(request.duration as AccessDurationName | undefined),\n });\n return {\n status: 'granted',\n granted: prepared.resolvedSlot === undefined\n ? { kind: 'direct', capabilities: [capability] }\n : {\n kind: 'discover',\n serviceId: prepared.resolvedSlot.serviceId,\n satisfiedInterfaces: [...prepared.resolvedSlot.satisfiedInterfaces],\n capabilities: [capability],\n },\n };\n }\n}\n\n/**\n * Discover every manifest in the connected hub and expose it through one\n * validated, namespaced aggregate. This is the same discovery/validation path\n * used by the hub's approval UI.\n */\nexport function createHubApprovalCommandClient(\n connection: LinkRpcConnection<unknown, SigningCallCtx>,\n identity: SigningIdentity,\n log?: (line: string) => void,\n): ApprovalCommandClient {\n const hubConnection = connection as unknown as LinkRpcConnection;\n const explorer = new HubDirectoryExplorer(hubConnection.channel);\n const sourceCache = new Map<string, AggregatorSource>();\n let directoryChanged: (() => void) | undefined;\n const watchStarted = explorer.watch(() => directoryChanged?.());\n const fetchDirectory = async (): Promise<readonly DirectoryEntry[]> => {\n await watchStarted;\n return explorer.result.listings.map((entry) => ({\n serviceId: entry.serviceId,\n interfaceId: entry.interfaceId,\n hash: entry.hash,\n ...(entry.serviceDescription === undefined\n ? {}\n : { serviceDescription: entry.serviceDescription }),\n ...(entry.rootPrincipalSets === undefined\n ? {}\n : { rootPrincipalSets: entry.rootPrincipalSets }),\n }));\n };\n const resolveSources = async () => {\n const directory = await fetchDirectory();\n const serviceIds = [...new Set(\n directory\n .filter((entry) => entry.interfaceId === MANIFEST_INTERFACE_ID)\n .map((entry) => entry.serviceId),\n )].sort();\n log?.(\n `approval: discovered ${serviceIds.length} manifest source`\n + `${serviceIds.length === 1 ? '' : 's'}`\n + `${serviceIds.length > 0 ? `: ${serviceIds.join(', ')}` : ''}`,\n );\n const active = new Set(serviceIds);\n for (const serviceId of sourceCache.keys()) {\n if (!active.has(serviceId)) sourceCache.delete(serviceId);\n }\n return serviceIds.map((serviceId) => {\n const cached = sourceCache.get(serviceId);\n if (cached !== undefined) return cached;\n const manifest = serviceId === ''\n ? connection.get(hubAccessManifestInterface)\n : connection.service(serviceId).get(hubAccessManifestInterface);\n const source: AggregatorSource = {\n tag: serviceId,\n manifest: withApprovalSourceLogging(manifest, serviceId, log),\n preserveOrigin: false,\n };\n sourceCache.set(serviceId, source);\n return source;\n });\n };\n\n const aggregate = new AggregatingHubAccessManifest({\n resolveSources,\n watchSources: (onChange) => {\n directoryChanged = onChange;\n return () => {\n if (directoryChanged === onChange) directoryChanged = undefined;\n };\n },\n log,\n });\n const pair = new TransportPair();\n const aggregateServer = LinkRpcConnection.fromTransport(pair.a);\n const aggregateClient = LinkRpcConnection.fromTransport(pair.b);\n registerAggregatingManifest(aggregateServer, aggregate, { serviceId: AGGREGATE_SERVICE_ID });\n\n return new ApprovalCommandClient({\n manifest: aggregateClient.service(AGGREGATE_SERVICE_ID).get(hubAccessManifestInterface),\n identity,\n fetchDirectory,\n log,\n dispose: () => {\n aggregate.dispose();\n void watchStarted.then((stop) => stop(), () => undefined);\n explorer.dispose();\n aggregateClient.close();\n aggregateServer.close();\n },\n });\n}\n\nfunction withApprovalSourceLogging(\n manifest: IHubAccessManifest,\n serviceId: string,\n log: ((line: string) => void) | undefined,\n): IHubAccessManifest {\n if (!log) return manifest;\n const getDesired = manifest.getDesired.bind(manifest);\n return new Proxy(manifest, {\n get: (target, property, receiver) => {\n if (property !== 'getDesired') return Reflect.get(target, property, receiver);\n return async (...args: Parameters<typeof getDesired>) => {\n const result = await getDesired(...args);\n const count = Object.keys(result.requested).length;\n log(\n `approval: source '${serviceId || '<root>'}' has ${count} pending request`\n + (count === 1 ? '' : 's'),\n );\n return result;\n };\n },\n });\n}\n\nexport function encodeApprovalRequestId(internalId: string): string {\n if (internalId.length === 0) throw new Error('cannot encode an empty approval request id');\n return `${EXTERNAL_ID_PREFIX}${Buffer.from(internalId, 'utf8').toString('base64url')}`;\n}\n\nexport function decodeApprovalRequestId(externalId: string): string {\n if (!new RegExp(`^${EXTERNAL_ID_PREFIX}[A-Za-z0-9_-]+$`).test(externalId)) {\n throw new Error(`invalid approval request id '${externalId}'`);\n }\n\n const encoded = externalId.slice(EXTERNAL_ID_PREFIX.length);\n const decoded = Buffer.from(encoded, 'base64url').toString('utf8');\n if (decoded.length === 0 || encodeApprovalRequestId(decoded) !== externalId) {\n throw new Error(`invalid approval request id '${externalId}'`);\n }\n return decoded;\n}\n\nfunction approvalRequestSource(internalId: string): string | undefined {\n const separator = internalId.indexOf('\\u0000');\n return separator < 0 ? undefined : internalId.slice(0, separator);\n}\n\nexport function formatApprovalRequests(\n requests: readonly PendingApprovalRequest[],\n principalId: string,\n json = false,\n): string {\n if (json) {\n return formatJson({\n version: 1,\n principal: principalId,\n requests: requests.map(({ id, request }) => ({ id, request })),\n });\n }\n if (requests.length === 0) {\n return `No pending approval requests for ${principalId}.`;\n }\n const lines: string[] = [];\n for (const request of requests) {\n const presentation = createApprovalPresentation(request);\n lines.push(presentation.heading);\n for (const detail of presentation.details) {\n lines.push(` ${detail.label === undefined ? '' : `${detail.label}: `}${detail.text}`);\n }\n }\n return lines.join('\\n');\n}\n\nexport function formatApprovalDecision(\n action: 'approved' | 'denied',\n id: string,\n principalId: string,\n json = false,\n outcome: ApprovalDecisionOutcome = 'applied',\n): string {\n if (json) {\n return formatJson({\n version: 1,\n action,\n id,\n principal: principalId,\n ...(outcome === 'still-pending' ? { requestStillPending: true } : {}),\n });\n }\n return outcome === 'applied'\n ? `${action === 'approved' ? 'Approved' : 'Denied'} ${id}.`\n : `${action === 'approved' ? 'Approval' : 'Denial'} decision accepted for ${id}, `\n + 'but a matching request is still pending; the consumer may have retried.';\n}\n\nfunction waitForAbort(signal: AbortSignal): Promise<void> {\n if (signal.aborted) return Promise.resolve();\n return new Promise((resolve) => signal.addEventListener('abort', () => resolve(), { once: true }));\n}\n","import type { PrincipalSource, SigningSession } from '@hediet/linkrpc-client';\nimport { formatPrincipalSource } from '@hediet/linkrpc-client';\nimport { formatJson } from '../output';\n\nexport interface CliIdentity {\n readonly principal: string;\n readonly source: PrincipalSource;\n}\n\nexport function cliIdentity(session: SigningSession): CliIdentity {\n return {\n principal: session.principal.id,\n source: session.principalSource,\n };\n}\n\nexport function formatCliIdentity(identity: CliIdentity, json = false): string {\n if (json) {\n return formatJson({\n version: 1,\n principal: identity.principal,\n source: identity.source,\n });\n }\n return [\n formatPrincipalSource(identity.source, identity.principal),\n `principal: ${identity.principal}`,\n ].join('\\n');\n}\n","/**\n * The hub engine now lives in `@hediet/linkrpc-hub` (shared by the CLI, the\n * standalone `linkrpc-hub` server, and the VS Code extension). This module\n * re-exports it for the CLI's existing `./engine/runHub` import sites.\n */\nimport type {\n ListenerInfo,\n RunHubOptions,\n RunningHub,\n} from '@hediet/linkrpc-hub/engine/runHub';\n\nexport type { ListenerInfo, RunHubOptions, RunningHub };\n\nexport async function runHub(options: RunHubOptions): Promise<RunningHub> {\n const engine = await import('@hediet/linkrpc-hub/engine/runHub');\n return engine.runHub(options);\n}\n","/**\n * Render the dynamic \"Method parameters\" block appended to `hub call --help`\n * and `hub notify --help`. Pure: takes a `MethodSchema` (already fetched by\n * the caller) plus the live interface schema for ref resolution, and returns\n * the formatted block. The caller concatenates it after commander's\n * static help text.\n *\n * Param names show up as `--p:<name>`; the type / required-ness / one-line\n * description is derived from the params object's `properties` map.\n *\n * If the method's params schema isn't a plain object schema (e.g. a\n * union, or a top-level array), we render a coarse fallback instead of\n * pretending each branch is its own `--p:` flag.\n */\nimport type {\n MethodSchema,\n LinkRpcInterfaceSchema as SvcInterfaceSchema,\n LinkRpcJsonSchema as SvcJsonSchema,\n} from '@hediet/linkrpc';\n\nexport interface RenderedParamHelp {\n /** Multi-line block, or empty when the method takes no params. */\n readonly text: string;\n /**\n * Param names suitable for completion. Empty when the params descriptor\n * isn't a plain object (no `--p:<name>` flag-name to suggest).\n */\n readonly paramNames: readonly string[];\n}\n\nexport function renderMethodParamHelp(\n method: MethodSchema,\n schema: SvcInterfaceSchema,\n): RenderedParamHelp {\n const resolved = _resolve(method.params, schema.components?.schemas ?? {});\n if (!_isObjectSchema(resolved)) {\n return {\n text:\n `Method parameters (${schema.id}@${schema.hash}):\\n`\n + ` (params is not a plain object — pass with --params <json>)\\n`,\n paramNames: [],\n };\n }\n\n const props = resolved.properties ?? {};\n const required = new Set<string>(resolved.required ?? []);\n const names = Object.keys(props);\n if (names.length === 0) {\n return {\n text:\n `Method parameters (${schema.id}@${schema.hash}):\\n`\n + ` (no parameters)\\n`,\n paramNames: [],\n };\n }\n\n const rows: string[][] = [];\n for (const name of names) {\n const propSchema = _resolve(props[name], schema.components?.schemas ?? {});\n const flag = `--p:${name} <${_typeLabel(propSchema)}>`;\n const reqMark = required.has(name) ? 'required' : 'optional';\n const desc = _oneLineDescription(propSchema);\n rows.push([flag, reqMark, desc]);\n }\n\n const flagCol = Math.max(...rows.map((r) => r[0].length));\n const reqCol = Math.max(...rows.map((r) => r[1].length));\n\n const lines = [`Method parameters (${schema.id}@${schema.hash}):`];\n for (const [flag, req, desc] of rows) {\n const padded = ` ${flag.padEnd(flagCol)} ${req.padEnd(reqCol)}${desc ? ' ' + desc : ''}`;\n lines.push(padded.trimEnd());\n }\n return { text: lines.join('\\n') + '\\n', paramNames: names };\n}\n\nfunction _isObjectSchema(\n s: SvcJsonSchema,\n): s is Extract<SvcJsonSchema, { type: 'object' }> {\n return typeof s === 'object' && s !== null && (s as { type?: string }).type === 'object';\n}\n\nfunction _resolve(\n s: SvcJsonSchema,\n components: Record<string, SvcJsonSchema>,\n): SvcJsonSchema {\n if (typeof s === 'object' && s !== null && '$ref' in s) {\n const ref = (s as { $ref: string }).$ref;\n const m = /^#\\/components\\/schemas\\/(.+)$/.exec(ref);\n if (m) {\n const target = components[m[1]];\n if (target !== undefined) return target;\n }\n }\n return s;\n}\n\nfunction _typeLabel(s: SvcJsonSchema): string {\n if (s === true) return 'any';\n if (s === false) return 'never';\n const obj = s as unknown as Record<string, unknown>;\n\n if (typeof obj.type === 'string') {\n if (obj.type === 'array') {\n const items = obj.items as SvcJsonSchema | undefined;\n if (items !== undefined) return `${_typeLabel(items)}[]`;\n return 'array';\n }\n const fmt = obj.format !== undefined ? `:${obj.format}` : '';\n return `${obj.type as string}${fmt}`;\n }\n if (Array.isArray(obj.enum)) {\n return `enum(${obj.enum.map((v) => JSON.stringify(v)).join('|')})`;\n }\n if ('const' in obj) {\n return JSON.stringify(obj.const);\n }\n if (Array.isArray(obj.oneOf) || Array.isArray(obj.anyOf)) {\n return 'union';\n }\n if ('$ref' in obj) {\n const ref = obj.$ref as string;\n const m = /^#\\/components\\/schemas\\/(.+)$/.exec(ref);\n return m ? m[1] : 'ref';\n }\n return 'value';\n}\n\nfunction _oneLineDescription(propSchema: SvcJsonSchema): string {\n const obj = propSchema as unknown as Record<string, unknown>;\n const raw = (obj.description as string | undefined) ?? (obj.title as string | undefined) ?? '';\n if (!raw) return '';\n const firstLine = raw.split(/\\r?\\n/, 1)[0];\n return firstLine.length > 80 ? firstLine.slice(0, 77) + '…' : firstLine;\n}\n","/**\n * Pre-processor for `--p:<name>[=<value>]` shortcuts on the CLI. Rewrites\n * them to commander-friendly `--param <name>=<value>` pairs *before*\n * commander sees the argv, so we don't have to teach commander about them\n * (which is awkward given they're dynamic per-method).\n *\n * Forms accepted:\n * --p:to=a@b.c single token, kept verbatim → `--param to=a@b.c`\n * --p:to a@b.c two tokens, joined → `--param to=a@b.c`\n * --p:dryRun boolean shortcut (no value) → `--param dryRun=true`\n *\n * Nested keys keep working through the existing `mergeParams` dot-path\n * support: `--p:user.name=alice` → `--param user.name=alice`.\n *\n * Anything past a literal `--` token is left alone (POSIX end-of-options).\n * Tokens that look like the start of the next flag (e.g. `--p:dryRun\n * --verbose`) are treated as the \"no value\" form so `--verbose` keeps its\n * intended role.\n */\n\nconst FLAG_PREFIX = '--p:';\n\n/**\n * Transform `argv`, expanding every `--p:<name>` token to `--param key=value`.\n * Non-matching tokens pass through unchanged. Returns a new array; never\n * mutates the input.\n */\nexport function rewriteParamShortcuts(argv: readonly string[]): string[] {\n const out: string[] = [];\n let stopExpanding = false;\n\n for (let i = 0; i < argv.length; i++) {\n const tok = argv[i];\n\n if (!stopExpanding && tok === '--') {\n stopExpanding = true;\n out.push(tok);\n continue;\n }\n if (stopExpanding || !tok.startsWith(FLAG_PREFIX)) {\n out.push(tok);\n continue;\n }\n\n const rest = tok.slice(FLAG_PREFIX.length);\n if (rest.length === 0) {\n // Bare `--p:` is meaningless; leave it for commander to error on.\n out.push(tok);\n continue;\n }\n\n const eq = rest.indexOf('=');\n if (eq >= 0) {\n const name = rest.slice(0, eq);\n const value = rest.slice(eq + 1);\n if (name.length === 0) {\n out.push(tok); // malformed `--p:=value`; let commander complain\n continue;\n }\n out.push('--param', `${name}=${value}`);\n continue;\n }\n\n // `--p:name` with no inline value. Use the next token unless it looks\n // like another flag (then assume boolean shortcut).\n const name = rest;\n const peek = argv[i + 1];\n if (peek === undefined || peek.startsWith('-')) {\n out.push('--param', `${name}=true`);\n continue;\n }\n out.push('--param', `${name}=${peek}`);\n i += 1;\n }\n return out;\n}\n","import { Command, InvalidArgumentError } from 'commander';\nimport { LinkRpcConnection, type JsonValue } from '@hediet/linkrpc';\nimport { formatEndpointUri, isHubEndpoint, parseEndpointUri } from '@hediet/linkrpc/node';\nimport { connectionTokenBinderInterface } from '@hediet/linkrpc-hub/hub/server/connection-token-binder';\nimport { tapTransport } from '@hediet/linkrpc-hub/hub/server/transit';\nimport { callCommand, notifyCommand } from './commands/call';\nimport { executeBatch, parseBatchArgs } from './commands/batch';\nimport {\n disconnectBroker,\n getBrokerStatus,\n readBrokerNotifications,\n} from './commands/connectionBrokerClient';\nimport {\n runConnectionBroker,\n spawnConnectionBroker,\n} from './commands/connectionBrokerProcess';\nimport { parseDuration } from './duration';\nimport { checkCompatCommand, formatVerdict } from './commands/checkCompat';\nimport { codegenCommand } from './commands/codegen';\nimport { completionsCommand } from './commands/completions';\nimport { defaultsCommand } from './commands/defaults';\nimport { hashCommand } from './commands/hash';\nimport { internalCompleteCommand } from './commands/internalComplete';\nimport { lsCommand } from './commands/ls';\nimport { topologyCommand, type TopologyFormat } from './commands/topology';\nimport { pingCommand } from './commands/ping';\nimport {\n topologyParticipantsCommand,\n trafficWatchCommand,\n} from './commands/participantWatch';\nimport { schemaCommand } from './commands/schema';\nimport { loadHubConfig, printHubConfigSchema, serveCommand } from './commands/serve';\nimport { tunnelCommand } from './commands/tunnel';\nimport { connectAs } from './commands/connectAs';\nimport { openDialTransport, openTargetTransport, type DialEndpoint } from './commands/connectAsTransports';\nimport { mcpForwardCommand } from './commands/mcpForward';\nimport { jsonRpcStdioCommand } from './commands/jsonRpcStdio';\nimport {\n bootstrapApprovalCommandCapability,\n createHubApprovalCommandClient,\n formatApprovalDecision,\n formatApprovalRequests,\n type ApprovalCommandClient,\n} from './commands/approval';\nimport { cliIdentity, formatCliIdentity } from './commands/identity';\nimport {\n connect as connectEndpoint,\n connectViaRootOverlay,\n type CliConnection,\n type ConnectLogOptions,\n} from '@hediet/linkrpc-client';\nimport { type HubConfig } from '@hediet/linkrpc-client';\nimport { runHub, type RunningHub } from './engine/runHub';\nimport {\n type ResolvedEndpoint,\n resolveTargetEndpoint,\n resolvedEndpointToConfig,\n} from '@hediet/linkrpc-client';\nimport {\n type SigningSession,\n setupSigning,\n requestReflectionAccess,\n requestTopologyAccess,\n} from '@hediet/linkrpc-client';\nimport { logoutCliIdentity } from '@hediet/linkrpc-client';\nimport { MethodRefWithOptHash } from './methodRef';\nimport { renderMethodParamHelp } from './methodHelp';\nimport { rewriteParamShortcuts } from './paramFlags';\nimport { formatPrincipalSource, parsePrincipalSpec, type PrincipalSpec } from '@hediet/linkrpc-client';\nimport { findMethodInSchema } from '@hediet/linkrpc-client';\nimport { fetchSchemaForMethodRef } from './schemaLookup';\nimport {\n loadStaticHubSchema,\n resolveStaticHubSchemaSource,\n} from './staticHubSchema';\nimport {\n ContextStore,\n type ContextReference,\n type ContextValues,\n type ValidationMode,\n formatContextReference,\n} from './contexts';\nimport {\n type CliProfile,\n type ResolvedInvocationContext,\n mutationReference,\n resolveInvocationContext,\n resolveInvocationEndpoint,\n validationDefault,\n} from './invocationContext';\nimport { resolveCliInvocation } from './cliInvocation';\nimport { withStaticHubReflection } from './commands/staticHubReflection';\n\nexport async function main(\n rawArgv: readonly string[],\n executableName: 'linkrpc' | 'rpc' | 'hub' = 'linkrpc',\n): Promise<void> {\n const cliInvocation = resolveCliInvocation(rawArgv, executableName);\n const profile = cliInvocation.profile;\n const program = new Command();\n program.configureHelp({ showGlobalOptions: true });\n program\n .name(cliInvocation.programName)\n .description(\n profile === 'hub'\n ? 'CLI / TUI for LinkRPC hubs. Shared RPC commands use hub initialization, signing, '\n + 'capability negotiation, and required schema validation by default.'\n : 'CLI / TUI for JSON-RPC and LinkRPC endpoints. Shared commands use the RPC profile '\n + 'with automatic schema validation and no endpoint environment override by default.',\n )\n .option(\n '--endpoint <uri>',\n 'endpoint URI (unix:/path?token=…, npipe://./pipe/…, ws[s]://host?token=…, ' +\n 'ws-no-init://host?…, ' +\n 'cmd:?command=… or cmd-stdio:?command=…)',\n )\n .option('--endpoint-cmd <command>', 'spawn a server, connect via an injected env socket')\n .option('--endpoint-cmd-stdio <command>', 'spawn a child and talk over its stdio')\n .option(\n '--endpoint-cmd-env <key=value>',\n 'env var for the --endpoint-cmd / --endpoint-cmd-stdio child (repeatable)',\n (val: string, acc: Record<string, string> | undefined) => {\n const eq = val.indexOf('=');\n if (eq === -1) {\n throw new InvalidArgumentError(`expected key=value, got '${val}'`);\n }\n const next = acc ?? {};\n next[val.slice(0, eq)] = val.slice(eq + 1);\n return next;\n },\n )\n .option(\n '--endpoint-token <token>',\n 'fill the exact token=% placeholder in --endpoint (or a context endpoint)',\n )\n .option(\n '--endpoint-cmd-cwd <dir>',\n 'working directory for the --endpoint-cmd / --endpoint-cmd-stdio child',\n )\n .option(\n '--context <selector>',\n 'use an exact folder, id:<name>, :root, or :empty context; otherwise look up from cwd',\n )\n .option(\n '--context-set',\n 'persist context-capable overrides supplied on this command to the active context',\n )\n .option(\n '--new-context <selector>',\n 'create a new context from the effective command values; fails if it already exists',\n )\n .option('--schema <path-or-url>', 'static schema catalog used for discovery and validation')\n .option(\n '--validation <mode>',\n 'schema validation mode: auto, required, or off',\n parseValidationMode,\n )\n .option('--use-env', 'allow LINKRPC_* / legacy HUBRPC_* endpoint variables to override context')\n .option('--no-use-env', 'ignore LINKRPC_* / legacy HUBRPC_* endpoint variables')\n .option(\n '--provision-identity',\n 'with --endpoint-cmd: provision & reuse a persistent identity (slot derived from cwd + command)',\n )\n .option(\n '--provision-identity-slot <slot>',\n 'with --endpoint-cmd: provision & reuse a persistent identity under this explicit slot id',\n )\n .option(\n '--principal <spec>',\n 'identity to sign calls with: \"managed\" (default, falls back to user:hubrpc-cli), ' +\n '\"user:<id>\" (per-user data dir), or \"file:<path>\"',\n (v) => {\n try {\n parsePrincipalSpec(v);\n } catch (e) {\n throw new InvalidArgumentError((e as Error).message);\n }\n return v;\n },\n )\n .option(\n '--log-messages',\n profile === 'hub'\n ? 'log every JSON-RPC message to stderr, one coalesced flow per line (like the ' +\n 'VS Code \"linkrpc Flows\" channel). For `serve` / `-c, --config` this is the ' +\n 'in-process hub\\'s routed traffic; for a direct `--endpoint` connection it taps ' +\n 'the client transport. Ignored by `ui`.'\n : 'log every JSON-RPC message on a direct endpoint connection to stderr, one ' +\n 'coalesced flow per line (like the VS Code \"linkrpc Flows\" channel). Ignored by `ui`.',\n )\n .option(\n '--log-transport',\n 'log every raw JSON-RPC message sent and received to stderr, including transport initialization; '\n + 'may expose tokens and other sensitive payloads',\n )\n .showHelpAfterError();\n if (profile === 'hub') {\n program.option(\n '-c, --config <file>',\n 'run an in-process hub from this declarative config file and target it (see `serve --print-schema`)',\n );\n }\n /** Parse the effective context/flag principal once the pre-action hook has resolved it. */\n const getPrincipalSpec = (): PrincipalSpec =>\n parsePrincipalSpec(g_invocation?.values.principal);\n\n // Resolved once per command after inherited options, context defaults, and\n // the profile-specific environment policy have been merged.\n let endpoint: ResolvedEndpoint | undefined;\n let pendingContextSet:\n | {\n readonly store: ContextStore;\n readonly reference: Exclude<ContextReference, { readonly kind: 'empty'; }>;\n readonly values: ContextValues;\n }\n | undefined;\n let pendingNewContext:\n | {\n readonly store: ContextStore;\n readonly reference: Exclude<ContextReference, { readonly kind: 'empty'; }>;\n readonly values: ContextValues;\n }\n | undefined;\n let preparedNewContext:\n | {\n readonly store: ContextStore;\n readonly reference: Exclude<ContextReference, { readonly kind: 'empty'; }>;\n }\n | undefined;\n program.hook('preAction', async (_thisCommand, actionCommand) => {\n const commandPath = getCommandPath(actionCommand);\n const allowMissingContext = commandPath === 'context set';\n const store = new ContextStore();\n const cliOverrides = collectContextOverrides(program, actionCommand);\n const selector = explicitOption<string>(program, 'context');\n const useEnvironment = explicitOption<boolean>(program, 'useEnv');\n g_contextStore = store;\n g_invocation = await resolveInvocationContext({\n profile,\n store,\n ...(selector !== undefined ? { selector } : {}),\n cliOverrides,\n ...(useEnvironment !== undefined ? { useEnvironment } : {}),\n allowMissingContext,\n });\n if (profile === 'rpc' && g_invocation.values.config !== undefined) {\n throw new Error('--config is only available in the hub profile');\n }\n\n if (program.opts().contextSet === true) {\n if (program.opts().newContext !== undefined) {\n throw new Error('--context-set cannot be combined with --new-context');\n }\n if (Object.keys(cliOverrides).length === 0) {\n throw new Error('--context-set requires at least one context-capable override');\n }\n pendingContextSet = {\n store,\n reference: await mutationReference(store, g_invocation.selected),\n values: cliOverrides,\n };\n }\n\n if (program.opts().newContext !== undefined) {\n const reference = mutableReference(\n await store.resolveReference(program.opts().newContext as string),\n );\n await store.assertCanCreate(reference);\n preparedNewContext = { store, reference };\n }\n if (preparedNewContext !== undefined && commandPath !== 'connection create') {\n pendingNewContext = {\n store,\n reference: preparedNewContext.reference,\n values: g_invocation.values,\n };\n }\n\n endpoint = commandUsesEndpoint(commandPath) || hasEndpointOverrides(cliOverrides)\n ? resolveInvocationEndpoint(g_invocation, actionCommand.name() === 'tunnel')\n : undefined;\n g_hubConfigPath = g_invocation.values.config;\n // Message logging goes to stderr, which would corrupt the full-screen\n // TUI — so it applies to every command except `ui`.\n g_logMessages = program.opts().logMessages === true\n && actionCommand.name() !== 'ui';\n g_logTransport = program.opts().logTransport === true\n && actionCommand.name() !== 'ui';\n });\n program.hook('postAction', async () => {\n if (pendingContextSet !== undefined) {\n await pendingContextSet.store.set(\n pendingContextSet.reference,\n pendingContextSet.values,\n );\n process.stderr.write(\n `linkrpc: updated context ${formatContextReference(pendingContextSet.reference)}.\\n`,\n );\n pendingContextSet = undefined;\n }\n if (pendingNewContext !== undefined) {\n await createContextFromInvocation(\n pendingNewContext.store,\n pendingNewContext.reference,\n pendingNewContext.values,\n );\n pendingNewContext = undefined;\n }\n });\n\n program\n .command('ls')\n .description(\n 'List services and interfaces. Walks the bus recursively, following `hubrpc.directory` references.',\n )\n .option('--interface <id>', 'filter by interfaceId')\n .option('--interface-prefix <prefix>', 'filter by interfaceId prefix')\n .option('--service <id>', 'list a single service (no recursion)')\n .option('--service-prefix <prefix>', 'filter by serviceId prefix')\n .option('--search <regexp>', 'case-insensitive regexp over listings')\n .option('--depth <n>', 'max recursion depth (default 5)', (v) => Number.parseInt(v, 10))\n .option('--with-members', 'include request and notification members from interface schemas')\n .option('--json', 'legacy flat listing JSON; use --format json for graph state')\n .option('--format <format>', 'pretty, json, or jsonl')\n .option('--dump <file>', 'write topology and all schemas to one JSON fixture file')\n .option(\n '--dump-patches <file>',\n 'write progressive RFC 6902 operations as JSON Lines; use - for stdout',\n )\n .option('--stream', 'legacy patch-log JSONL; use --format jsonl for reconstructable graph state')\n .option('--watch', 'continue observing directory changes until interrupted')\n .action(async (opts) => {\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const format = resolveGraphFormat(opts.format, {\n json: opts.json === true,\n stream: opts.stream === true,\n watch: opts.watch === true,\n });\n const legacyOutput = opts.format === undefined && opts.watch !== true;\n const out = await lsCommand(channel, {\n interfaceId: opts.interface,\n interfacePrefix: opts.interfacePrefix,\n serviceId: opts.service,\n servicePrefix: opts.servicePrefix,\n search: opts.search,\n withMembers: !!opts.withMembers,\n json: !!opts.json,\n format: legacyOutput ? undefined : format,\n dumpPath: opts.dump,\n dumpPatchesPath: opts.dumpPatches,\n stream: !!opts.stream,\n watch: !!opts.watch,\n emitLine: (line) => { process.stdout.write(line + '\\n'); },\n emitFrame: (frame) => { repaintTerminal(frame); },\n stop: opts.watch ? _untilSignalled() : undefined,\n maxDepth: typeof opts.depth === 'number' && !Number.isNaN(opts.depth) ?\n opts.depth :\n undefined,\n });\n if (out.length > 0) process.stdout.write(out + '\\n');\n });\n });\n\n if (profile === 'hub') {\n const topology = program\n .command('topology')\n .description('Inspect and optionally watch the merged transport topology.')\n .option(\n '--source <serviceId>',\n 'topology provider serviceId; repeat for multiple fixed sources',\n collectOption,\n )\n .option('--depth <n>', 'directory discovery depth (default 5)', (v) => Number.parseInt(v, 10))\n .option('--node <nodeId>', 'filter by exact node id')\n .option('--service <serviceId>', 'filter route claims by exact service id')\n .option('--kind <kind>', 'filter nodes by hub or endpoint')\n .option('--search <regexp>', 'case-insensitive regexp over node metadata and routes')\n .option('--format <format>', 'pretty, json, or jsonl')\n .option('--json', 'alias for --format json')\n .option('--stream', 'alias for --format jsonl')\n .option('--watch', 'continue observing directory and topology changes')\n .action(async (opts) => {\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const format = resolveGraphFormat(opts.format, {\n json: opts.json === true,\n stream: opts.stream === true,\n watch: opts.watch === true,\n });\n const kind = opts.kind === undefined ? undefined : String(opts.kind);\n if (kind !== undefined && kind !== 'hub' && kind !== 'endpoint') {\n throw new InvalidArgumentError(\"--kind must be 'hub' or 'endpoint'\");\n }\n const out = await topologyCommand(channel, {\n sources: opts.source,\n maxDepth: typeof opts.depth === 'number' && !Number.isNaN(opts.depth)\n ? opts.depth\n : undefined,\n nodeId: opts.node,\n serviceId: opts.service,\n kind,\n search: opts.search,\n format,\n watch: opts.watch === true,\n emitLine: (line) => { process.stdout.write(line + '\\n'); },\n emitFrame: (frame) => { repaintTerminal(frame); },\n stop: opts.watch ? _untilSignalled() : undefined,\n });\n if (out.length > 0) process.stdout.write(out + '\\n');\n }, {\n requestReflectionAccess: false,\n requestTopologyAccess: { sourceServiceIds: opts.source },\n });\n });\n\n topology\n .command('participants')\n .description('List participant nodes; --search accepts a case-insensitive regexp.')\n .option('--search <regexp>', 'full-text regexp over participant metadata and routes')\n .option('--json', 'raw JSON output')\n .action(async (opts) => {\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const out = await topologyParticipantsCommand(channel, opts.search);\n process.stdout.write(opts.json ? out + '\\n' : out + '\\n');\n }, {\n requestReflectionAccess: false,\n requestTopologyAccess: {},\n });\n });\n\n program\n .command('traffic')\n .description('Observe participant traffic.')\n .command('watch')\n .description('Watch node-wide traffic for a selected participant.')\n .option('--search <regexp>', 'participant metadata search regexp')\n .option('--node <nodeId>', 'select an exact topology node id')\n .option('--method <prefix>', 'only methods beginning with this prefix')\n .option('--payloads <bytes>', 'include payloads up to this many bytes', (v) => Number.parseInt(v, 10))\n .option('--format <format>', 'pretty, plain, or jsonl')\n .option('--resume [file]', 'restore the previous participant/filter selection')\n .action(async (opts) => {\n const format = opts.format as 'pretty' | 'plain' | 'jsonl';\n if (!['pretty', 'plain', 'jsonl'].includes(format)) {\n throw new InvalidArgumentError('--format must be pretty, plain, or jsonl');\n }\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n await trafficWatchCommand(channel, {\n search: opts.search,\n nodeId: opts.node,\n methodPrefix: opts.method,\n payloadBytes: opts.payloads,\n format,\n resume: opts.resume,\n stop: _untilSignalled(),\n });\n }, { requestReflectionAccess: true });\n });\n }\n\n program\n .command('defaults')\n .description('Print the preset service / interface for form-1 calls.')\n .option('--json', 'raw JSON output')\n .action(async (opts) => {\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const out = await defaultsCommand(channel, { json: !!opts.json });\n process.stdout.write(out + '\\n');\n });\n });\n\n program\n .command('codegen')\n .description('Generate a TypeScript interface definition from an offline schema bundle.')\n .requiredOption('--input <bundle>', 'local static hub schema bundle')\n .requiredOption('--interface <id>', 'interface id to generate')\n .requiredOption('--name <name>', 'exported TypeScript const name')\n .requiredOption('--output <file>', 'generated TypeScript output file')\n .option(\n '--preserve-wire-schema',\n 'freeze the canonical input schema verbatim in the generated definition',\n )\n .option('--check', 'fail if the output is missing or stale without overwriting it')\n .action(async (opts) => {\n await codegenCommand({\n input: opts.input,\n interfaceId: opts.interface,\n name: opts.name,\n output: opts.output,\n preserveWireSchema: opts.preserveWireSchema === true,\n check: opts.check === true,\n });\n });\n\n const schema = program\n .command('schema')\n .description('Inspect, hash, and compare LinkRPC interface schemas.');\n\n schema\n .command('show <interfaceRef>')\n .description('Print an interface schema. `<interfaceRef>` is `id[@hash]`.')\n .option('--method <name>', 'show only this method')\n .option('--service <id>', 'route the lookup to this service (form-3); needed behind a hub')\n .option('--json', 'raw JSON output')\n .action(async (interfaceRef: string, opts) => {\n const { id, hash } = parseInterfaceRef(interfaceRef);\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const out = await schemaCommand(channel, {\n interfaceId: id,\n hash,\n method: opts.method,\n serviceId: opts.service,\n json: !!opts.json,\n });\n process.stdout.write(out + '\\n');\n });\n });\n\n schema\n .command('hash <schema>')\n .description('Compute the hash of a local LinkRpcInterfaceSchema JSON file.')\n .action((schemaPath: string) => {\n const out = hashCommand({ schemaPath });\n process.stdout.write(out + '\\n');\n });\n\n schema\n .command('check-compat <interfaceId> <local>')\n .description('Compare a local schema against the live interface schema.')\n .action(async (interfaceId: string, local: string) => {\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const verdict = await checkCompatCommand(channel, { interfaceId, localPath: local });\n process.stdout.write(formatVerdict(verdict) + '\\n');\n if (verdict.kind === 'incompatible') process.exitCode = 1;\n });\n });\n\n /**\n * Render `commander`'s static help for the given command, then (if a\n * methodRef is provided and an endpoint is reachable) fetch the live\n * schema and append a \"Method parameters\" block describing the\n * supported `--p:<name>` shortcuts.\n *\n * Best-effort: schema fetch failures degrade to static help with an\n * inline note instead of erroring out.\n */\n const _printCallHelp = async (cmd: Command, methodRef: string): Promise<void> => {\n process.stdout.write(cmd.helpInformation());\n if (methodRef.length === 0) {\n process.stdout.write(\n '\\n(Pass a methodRef to see method-specific --p:<name> flags, e.g.\\n'\n + ' hub call acme.email::send --help)\\n',\n );\n return;\n }\n if (endpoint === undefined) {\n process.stdout.write(\n '\\n(No endpoint configured: pass --endpoint / --endpoint-cmd or set LINKRPC_ENDPOINT\\n'\n + 'to see method-specific --p:<name> flags here.)\\n',\n );\n return;\n }\n let ref: MethodRefWithOptHash;\n try {\n ref = MethodRefWithOptHash.parseMethodRef(methodRef);\n } catch (e) {\n process.stdout.write(`\\n(Could not parse method reference: ${(e as Error).message})\\n`);\n return;\n }\n try {\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const schema = await fetchSchemaForMethodRef(channel, ref);\n if (schema === undefined) {\n process.stdout.write(\n '\\n(Bare-method refs (form 1) need a preset interface to look up the schema.)\\n',\n );\n return;\n }\n const method = findMethodInSchema(schema, ref.methodName);\n if (method === undefined) {\n process.stdout.write(\n `\\n(Method \"${ref.methodName}\" not found on interface ${schema.id}@${schema.hash}.)\\n`,\n );\n return;\n }\n const rendered = renderMethodParamHelp(method, schema);\n if (rendered.text.length > 0) {\n process.stdout.write('\\n' + rendered.text);\n }\n });\n } catch (e) {\n process.stdout.write(`\\n(Could not fetch method schema: ${(e as Error).message})\\n`);\n }\n };\n\n program\n .command('call [methodRef]')\n .description(\n 'Invoke a request. `<methodRef>` is `[svc::][iface::]method[@hash]`. '\n + 'Use `--p:<name> <value>` (or `--p:<name>=<value>`) as a shortcut for '\n + '`--param <name>=<value>`. Run `hub call <methodRef> --help` to see the '\n + 'method-specific `--p:` flags derived from the live schema.',\n )\n .option('--params <json>', 'inline params JSON, or \"-\" to read stdin')\n .option('--param <kv...>', 'param override, key=value (JSON or string)')\n .option('--no-validate', 'skip schema-based param validation')\n // Disable commander's built-in --help so we can intercept it and\n // append the dynamic \"Method parameters\" block.\n .helpOption(false)\n .option('-h, --help', 'show help (includes method params when reachable)')\n .action(async (methodRef: string | undefined, opts, cmd: Command) => {\n if (opts.help) {\n await _printCallHelp(cmd, methodRef ?? '');\n return;\n }\n if (methodRef === undefined) {\n process.stderr.write(\"linkrpc: missing required argument 'methodRef'.\\n\");\n process.stderr.write(cmd.helpInformation());\n process.exit(2);\n }\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const validation = opts.validate === false\n ? 'off'\n : effectiveValidation(profile);\n const out = await callCommand(channel, {\n methodRef,\n paramsArg: opts.params,\n paramOverrides: opts.param,\n validation,\n });\n process.stdout.write(out + '\\n');\n }, { requestReflectionAccess: effectiveValidation(profile) !== 'off' });\n });\n\n program\n .command('notify [methodRef]')\n .description(\n 'Fire a notification (no response). Same `--p:<name>` shortcuts as `call`.',\n )\n .option('--params <json>', 'inline params JSON, or \"-\" to read stdin')\n .option('--param <kv...>', 'param override, key=value')\n .option('--no-validate', 'skip schema-based param validation')\n .helpOption(false)\n .option('-h, --help', 'show help (includes method params when reachable)')\n .action(async (methodRef: string | undefined, opts, cmd: Command) => {\n if (opts.help) {\n await _printCallHelp(cmd, methodRef ?? '');\n return;\n }\n if (methodRef === undefined) {\n process.stderr.write(\"linkrpc: missing required argument 'methodRef'.\\n\");\n process.stderr.write(cmd.helpInformation());\n process.exit(2);\n }\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const validation = opts.validate === false\n ? 'off'\n : effectiveValidation(profile);\n const out = await notifyCommand(channel, {\n methodRef,\n paramsArg: opts.params,\n paramOverrides: opts.param,\n validation,\n });\n process.stdout.write(out + '\\n');\n }, { requestReflectionAccess: effectiveValidation(profile) !== 'off' });\n });\n\n program\n .command('batch [batchArgs...]')\n .description(\n 'Run sequential calls and notifications on one connection. Start each operation with '\n + '`--call <method>` or `--notify <method>`; following `--params`, `--param`, and '\n + '`--no-validate` flags apply to that operation.',\n )\n .allowUnknownOption()\n .addHelpText('after', `\nBatch options:\n --call <method> start a request operation\n --notify <method> start a notification operation\n --params <json> set inline JSON params for the preceding operation\n --param <key=value> add a param override to the preceding operation (repeatable)\n --no-validate skip validation for the preceding operation\n --continue-on-error record an error and continue with later operations\n`)\n .action(async (batchArgs: string[]) => {\n const plan = parseBatchArgs(batchArgs);\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const results = await executeBatch(plan, {\n call: (options) => callCommand(channel, options),\n notify: (options) => notifyCommand(channel, options),\n }, {\n validation: effectiveValidation(profile),\n onStreamChunk: ({ index, method, payload }) => {\n const text = typeof payload === 'string'\n ? payload\n : JSON.stringify(payload);\n process.stderr.write(`[${index + 1} ${method}] ${text}\\n`);\n },\n });\n process.stdout.write(JSON.stringify(results, undefined, 2) + '\\n');\n }, {\n requestReflectionAccess: effectiveValidation(profile) !== 'off'\n && plan.operations.some((operation) => !operation.noValidate),\n });\n });\n\n const connection = program\n .command('connection')\n .description('Create, inspect, consume, and destroy persistent RPC connections.');\n\n connection\n .command('create')\n .description('Create a detached persistent connection and print its local endpoint.')\n .option('--timeout <duration>', 'exit after this much transport inactivity')\n .option('--ttl <duration>', 'hard maximum broker lifetime')\n .option(\n '--notification-limit <count>',\n 'maximum buffered incoming notifications',\n (value) => parsePositiveInteger(value, '--notification-limit'),\n )\n .action(async (opts: {\n timeout?: string;\n ttl?: string;\n notificationLimit?: number;\n }) => {\n if (g_hubConfigPath !== undefined) {\n throw new Error('connection create does not support --config; use an endpoint URI or command endpoint');\n }\n const schemaSource = g_invocation?.values.schema === undefined\n ? undefined\n : resolveStaticHubSchemaSource(g_invocation.values.schema);\n if (schemaSource !== undefined) {\n await loadStaticHubSchema(schemaSource);\n }\n const timeout = opts.timeout ?? g_invocation?.values.connectionTimeout ?? '30s';\n const ttl = opts.ttl ?? g_invocation?.values.connectionTtl ?? '5min';\n const notificationLimit = opts.notificationLimit\n ?? g_invocation?.values.notificationLimit\n ?? 1_000;\n const brokerEndpoint = await spawnConnectionBroker({\n remote: needEndpoint(endpoint),\n timeoutMs: parseDuration(timeout),\n ttlMs: parseDuration(ttl),\n notificationLimit,\n schemaSource,\n });\n if (preparedNewContext !== undefined) {\n if (g_invocation === undefined) {\n throw new Error('context resolver is unavailable');\n }\n try {\n await createConnectionContext(\n preparedNewContext.store,\n preparedNewContext.reference,\n g_invocation.values,\n brokerEndpoint,\n );\n } catch (error) {\n try {\n await stopConnectionBroker(brokerEndpoint);\n } catch (cleanupError) {\n throw new AggregateError(\n [error, cleanupError],\n 'failed to create the context and stop the new connection broker',\n );\n }\n throw error;\n }\n }\n process.stdout.write(brokerEndpoint + '\\n');\n });\n\n connection\n .command('status')\n .description('Read status from the connection broker at the configured endpoint.')\n .action(async () => {\n await withRawConnection(endpoint, async (channel) => {\n process.stdout.write(JSON.stringify(await getBrokerStatus(channel), undefined, 2) + '\\n');\n });\n });\n\n connection\n .command('destroy')\n .description('Stop the connection broker at the configured endpoint.')\n .action(async () => {\n await withRawConnection(endpoint, async (channel) => {\n await disconnectBroker(channel);\n });\n });\n\n connection\n .command('notifications')\n .description(\n 'Read server notifications buffered by the persistent connection; --follow emits JSON Lines.',\n )\n .option('--after <sequence>', 'read notifications after this sequence', (value) =>\n parseNonNegativeInteger(value, '--after'), 0)\n .option('--wait <duration>', 'wait for a notification before returning')\n .option('--follow', 'continue waiting and print notifications as JSON lines')\n .action(async (opts: { after: number; wait?: string; follow?: boolean; }) => {\n const waitMs = opts.wait === undefined\n ? (opts.follow ? 25_000 : 0)\n : Math.min(parseDuration(opts.wait), 30_000);\n await withRawConnection(endpoint, async (channel) => {\n let after = opts.after;\n do {\n const batch = await readBrokerNotifications(channel, { after, waitMs });\n if (opts.follow) {\n for (const notification of batch.notifications) {\n process.stdout.write(JSON.stringify(notification) + '\\n');\n }\n } else {\n process.stdout.write(JSON.stringify(batch, undefined, 2) + '\\n');\n }\n after = batch.next;\n } while (opts.follow);\n });\n });\n\n const context = program\n .command('context')\n .description('Show how the active context resolves, or explicitly modify shared context defaults.')\n .action(() => {\n printSelectedContext(true);\n });\n\n context\n .command('show')\n .description('Show only the selected context and its stored defaults.')\n .action(() => {\n printSelectedContext(false);\n });\n\n context\n .command('list')\n .description('List every path, named, and root context in the global store.')\n .action(async () => {\n if (g_contextStore === undefined) throw new Error('context store is unavailable');\n for (const item of await g_contextStore.list()) {\n process.stdout.write(`${formatContextReference(item.reference)}\\n`);\n }\n });\n\n context\n .command('set')\n .description(\n 'Set explicit context-capable flags on the active context; creates a cwd context when none exists.',\n )\n .option('--unset <key...>', 'remove one or more stored context values')\n .action(async (opts: { unset?: string[] }) => {\n if (g_contextStore === undefined || g_invocation === undefined) {\n throw new Error('context resolver is unavailable');\n }\n const target = explicitOption<string>(program, 'context') !== undefined\n ? mutableReference(g_invocation.selected.reference)\n : await mutationReference(g_contextStore, g_invocation.selected);\n const overrides = g_invocation.cliOverrides;\n const unset = (opts.unset ?? []).map(parseContextValueKey);\n if (Object.keys(overrides).length === 0 && unset.length === 0) {\n throw new Error('context set requires at least one context-capable flag or --unset');\n }\n let result = Object.keys(overrides).length === 0\n ? g_invocation.selected.context\n : await g_contextStore.set(target, overrides);\n if (unset.length > 0) {\n result = await g_contextStore.unset(target, unset);\n }\n process.stdout.write(`Updated context ${formatContextReference(target)}.\\n`);\n if (result !== undefined) printContextValues(result.values, false);\n });\n\n context\n .command('remove')\n .description('Remove the selected context from the global store.')\n .action(async () => {\n if (g_contextStore === undefined || g_invocation === undefined) {\n throw new Error('context resolver is unavailable');\n }\n const reference = g_invocation.selected.reference;\n if (\n reference.kind === 'empty'\n || (reference.kind === 'root' && explicitOption<string>(program, 'context') === undefined)\n ) {\n throw new Error('select the context to remove explicitly with --context');\n }\n const removed = await g_contextStore.remove(reference);\n if (!removed) throw new Error(`context ${formatContextReference(reference)} does not exist`);\n process.stdout.write(`Removed context ${formatContextReference(reference)}.\\n`);\n });\n\n program\n .command('_connection-broker')\n .description('(internal) Run a persistent connection broker.')\n .requiredOption('--remote-endpoint <uri>')\n .requiredOption('--timeout-ms <milliseconds>', '', (value) =>\n parsePositiveInteger(value, '--timeout-ms'))\n .requiredOption('--ttl-ms <milliseconds>', '', (value) =>\n parsePositiveInteger(value, '--ttl-ms'))\n .option('--notification-limit <count>', '', (value) =>\n parsePositiveInteger(value, '--notification-limit'), 1_000)\n .option('--schema <path-or-url>')\n .action(async (opts: {\n remoteEndpoint: string;\n timeoutMs: number;\n ttlMs: number;\n notificationLimit: number;\n schema?: string;\n }) => {\n const running = await runConnectionBroker({\n remote: parseEndpointUri(opts.remoteEndpoint),\n timeoutMs: opts.timeoutMs,\n ttlMs: opts.ttlMs,\n notificationLimit: opts.notificationLimit,\n ...(opts.schema === undefined\n ? {}\n : { staticHubSchema: await loadStaticHubSchema(opts.schema) }),\n });\n process.stdout.write(running.endpoint + '\\n');\n await running.stopped;\n });\n\n program\n .command('ping')\n .description('One reflection round-trip; prints latency.')\n .action(async () => {\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const out = await pingCommand(channel);\n process.stdout.write(out + '\\n');\n });\n });\n if (profile === 'hub') {\n program\n .command('json-rpc-stdio <serviceId>')\n .description(\n 'Expose <serviceId>::jsonRpcConnection::connectRaw as a newline-delimited '\n + \"JSON-RPC endpoint on this process's stdin/stdout.\",\n )\n .option('--params <json>', 'JSON value passed to the remote transport factory')\n .action(async (serviceId: string, opts: { params?: string; }) => {\n const localEp = needEndpoint(endpoint);\n let params: JsonValue | undefined;\n if (opts.params !== undefined) {\n try {\n params = JSON.parse(opts.params) as JsonValue;\n } catch (error) {\n throw new InvalidArgumentError(\n `invalid --params JSON: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n const local = await connectEndpoint(localEp, wireLog('hub'));\n try {\n const session = await setupSigning(local.channel, local.signing, getPrincipalSpec(), {\n negotiateHubCaps: isHubEndpoint(localEp),\n });\n reportIdentity(session);\n await jsonRpcStdioCommand({\n local,\n serviceId,\n ...(params === undefined ? {} : { params }),\n });\n } finally {\n local.close();\n }\n });\n\n program\n .command('serve [config]')\n .description(\n 'Run a hub from a declarative config file and block until interrupted. '\n + 'The same config format drives the CLI hub, the server hub, and the VS Code extension.',\n )\n .option('--print-schema', 'print the config JSON Schema and exit')\n .option('--cmd-interactive', 'forward stdin to the single cmd endpoint (errors if more than one)')\n .action(async (config: string | undefined, opts: { printSchema?: boolean; cmdInteractive?: boolean; }) => {\n if (opts.printSchema) {\n process.stdout.write(printHubConfigSchema() + '\\n');\n return;\n }\n if (config === undefined) {\n process.stderr.write('linkrpc: serve requires a <config> file (or --print-schema).\\n');\n process.exit(2);\n }\n await serveCommand({\n configPath: config,\n cmdInteractive: opts.cmdInteractive,\n logMessages: g_logMessages,\n });\n });\n\n program\n .command('tunnel <serviceId>')\n .description(\n 'Claim <serviceId> on the source hub (--endpoint*) and forward every request it ' +\n 'routes here to a target endpoint over a second connection. The target endpoint ' +\n 'is set via --target-endpoint / --target-endpoint-cmd / --target-endpoint-cmd-stdio; ' +\n 'when it is --target-endpoint-cmd, the spawned child sees ' +\n \"`hubGrantedServiceId::get().grantedServiceIdNamespace` = <serviceId> from its local hub, \" +\n 'and global --provision-identity[-slot] applies to it. With `-c, --config`, the ' +\n 'source hub is instead appended to the config as an endpoint claiming <serviceId>, ' +\n 'and the in-process hub serves it (the config provides the target). Runs until Ctrl-C.',\n )\n .option(\n '--target-endpoint <uri>',\n 'target endpoint URI (unix:/path?token=…, npipe://./pipe/…, ws[s]://host?token=…, ' +\n 'cmd:?command=… or cmd-stdio:?command=…)',\n )\n .option(\n '--target-endpoint-cmd <command>',\n 'spawn the target as a server, connect via an injected env socket; the child sees ' +\n 'grantedServiceIdNamespace = <serviceId> via hubGrantedServiceId::get',\n )\n .option(\n '--target-endpoint-cmd-stdio <command>',\n 'spawn the target and talk linkrpc over its stdio',\n )\n .option(\n '--target-endpoint-cmd-env <key=value>',\n 'env var for the --target-endpoint-cmd / --target-endpoint-cmd-stdio child (repeatable)',\n (val: string, acc: Record<string, string> | undefined) => {\n const eq = val.indexOf('=');\n if (eq === -1) {\n throw new InvalidArgumentError(`expected key=value, got '${val}'`);\n }\n const next = acc ?? {};\n next[val.slice(0, eq)] = val.slice(eq + 1);\n return next;\n },\n )\n .option(\n '--target-endpoint-token <token>',\n 'token overriding the target URI token (no env fallback for the target)',\n )\n .option(\n '--target-endpoint-cmd-cwd <dir>',\n 'working directory for the --target-endpoint-cmd / --target-endpoint-cmd-stdio child',\n )\n .option(\n '--bidi',\n 'also forward every request/notification the target endpoint emits back to the ' +\n 'source hub, exposing the hub to the endpoint (forwards everything, unsigned)',\n )\n .action(async (serviceId: string, cmdOpts: {\n targetEndpoint?: string;\n targetEndpointCmd?: string;\n targetEndpointCmdStdio?: string;\n targetEndpointCmdEnv?: Record<string, string>;\n targetEndpointToken?: string;\n targetEndpointCmdCwd?: string;\n bidi?: boolean;\n }) => {\n const localEp = needEndpoint(endpoint);\n\n // Config mode: append the source hub to the loaded config as an\n // endpoint claiming <serviceId>, then run that in-process hub. The\n // config itself provides the target that serves the service id, so\n // the manual two-connection forward path is not used.\n if (g_hubConfigPath !== undefined) {\n const baseConfig = loadHubConfig(g_hubConfigPath);\n const claimEndpoint = resolvedEndpointToConfig(localEp, {\n claimServiceIds: [serviceId],\n });\n const config: HubConfig = {\n ...baseConfig,\n // The in-process hub serves <serviceId> and claims it on the\n // source, so it must mount its own services under <serviceId>\n // (not the default 'hub') for the claim and routing to line up.\n hubServiceId: serviceId,\n endpoints: [...baseConfig.endpoints, claimEndpoint],\n };\n const running = await runHub({ config, logMessages: g_logMessages });\n process.stderr.write(\n `linkrpc: tunnel: claimed '${serviceId}' on source via config hub. Ctrl-C to stop.\\n`,\n );\n await new Promise<void>((resolve) => {\n const stop = (): void => {\n running.dispose();\n resolve();\n };\n process.once('SIGINT', stop);\n process.once('SIGTERM', stop);\n });\n return;\n }\n\n const globalOpts = program.opts();\n const targetRes = resolveTargetEndpoint({\n targetEndpoint: cmdOpts.targetEndpoint,\n targetEndpointCmd: cmdOpts.targetEndpointCmd,\n targetEndpointCmdStdio: cmdOpts.targetEndpointCmdStdio,\n targetEndpointCmdEnv: cmdOpts.targetEndpointCmdEnv,\n targetEndpointToken: cmdOpts.targetEndpointToken,\n targetEndpointCmdCwd: cmdOpts.targetEndpointCmdCwd,\n provisionIdentity: globalOpts.provisionIdentity as boolean | undefined,\n provisionIdentitySlot: globalOpts.provisionIdentitySlot as string | undefined,\n });\n if (targetRes.error) {\n process.stderr.write(`linkrpc: ${targetRes.error}\\n`);\n process.exit(2);\n }\n if (!targetRes.endpoint) {\n process.stderr.write(\n 'linkrpc: tunnel requires --target-endpoint / --target-endpoint-cmd / --target-endpoint-cmd-stdio.\\n',\n );\n process.exit(2);\n }\n const targetEp = targetRes.endpoint;\n // Honor the legacy LINKRPC_REMOTE_ENDPOINT_TOKEN env var as a fallback\n // for token-bearing target URIs.\n const remoteTok = process.env.LINKRPC_REMOTE_ENDPOINT_TOKEN;\n const targetEpWithToken: ResolvedEndpoint =\n remoteTok !== undefined && (targetEp.kind === 'socket' || targetEp.kind === 'ws')\n && targetEp.token === undefined\n ? { ...targetEp, token: remoteTok }\n : targetEp;\n\n const local = await connectEndpoint(localEp, wireLog('source'));\n // Connect straight to the target endpoint — no routing hub. For a\n // spawned cmd-env child we front it with a RootOverlay: its root-form\n // calls (identity::*, hubGrantedServiceId::*, reflection, hubAccess)\n // are served locally while every claimed request the tunnel forwards\n // is relayed to the child through the overlay splitter. This keeps\n // --provision-identity working (identity::* is served) without the\n // 'hub' service id / claim-wait dance a full local hub imposes.\n let remote: CliConnection;\n if (targetEpWithToken.kind === 'cmd-env') {\n remote = await connectViaRootOverlay({\n command: targetEpWithToken.command,\n provisionSlot: targetEpWithToken.provisionSlot,\n env: targetEpWithToken.env,\n ...(targetEpWithToken.cwd !== undefined ? { cwd: targetEpWithToken.cwd } : {}),\n grantedNamespace: serviceId,\n log: wireLog('target'),\n });\n } else {\n remote = await connectEndpoint(targetEpWithToken, wireLog('target'));\n }\n try {\n // Sign the claim where the source hub requires it (managed\n // identity with local-keypair fallback). The remote side is\n // left unsigned so requests forward verbatim.\n const session = await setupSigning(local.channel, local.signing, getPrincipalSpec(), {\n negotiateHubCaps: isHubEndpoint(localEp),\n });\n reportIdentity(session);\n await tunnelCommand({ serviceId, local, remote, bidi: cmdOpts.bidi });\n } finally {\n remote.close();\n local.close();\n }\n });\n\n program\n .command('connect-as <binderServiceId> <slot>')\n .description(\n 'Mint a single-use identity token for <slot> from the <binderServiceId> ' +\n '(a service implementing connectionTokenBinder, typically the hub service id), ' +\n 'then splice a target endpoint onto the hub as a first-class participant with that ' +\n 'slot\\'s managed identity and a granted serviceId namespace (--granted-service-id, ' +\n 'defaulting to <slot>). No local hub is started: the CLI ' +\n 'proxies the connection (target ⟷ CLI ⟷ hub), so it works with every target kind and ' +\n '--log-messages taps the full flow. The hub-facing bound-token listener is ' +\n '--hub-endpoint (defaults to --endpoint when that is a ws/socket). Runs until Ctrl-C.',\n )\n .option(\n '--hub-endpoint <uri>',\n 'ws/socket bound-token listener to splice the target onto (default: --endpoint)',\n )\n .option('--target-endpoint <uri>', 'target endpoint URI (unix:/…, ws[s]://…)')\n .option('--target-endpoint-cmd <command>', 'spawn the target as a server; it dials the CLI back')\n .option('--target-endpoint-cmd-stdio <command>', 'spawn the target and talk linkrpc over its stdio')\n .option(\n '--target-endpoint-cmd-env <key=value>',\n 'env var for the --target-endpoint-cmd / --target-endpoint-cmd-stdio child (repeatable)',\n (val: string, acc: Record<string, string> | undefined) => {\n const eq = val.indexOf('=');\n if (eq === -1) {\n throw new InvalidArgumentError(`expected key=value, got '${val}'`);\n }\n const next = acc ?? {};\n next[val.slice(0, eq)] = val.slice(eq + 1);\n return next;\n },\n )\n .option('--target-endpoint-token <token>', 'token overriding the target URI token')\n .option(\n '--target-endpoint-cmd-cwd <dir>',\n 'working directory for the --target-endpoint-cmd / --target-endpoint-cmd-stdio child',\n )\n .option(\n '--granted-service-id <serviceId>',\n 'serviceId namespace to grant the target (default: <slot>)',\n )\n .action(async (binderServiceId: string, slot: string, cmdOpts: {\n hubEndpoint?: string;\n targetEndpoint?: string;\n targetEndpointCmd?: string;\n targetEndpointCmdStdio?: string;\n targetEndpointCmdEnv?: Record<string, string>;\n targetEndpointToken?: string;\n targetEndpointCmdCwd?: string;\n grantedServiceId?: string;\n }) => {\n const localEp = needEndpoint(endpoint);\n\n // Resolve the hub-facing (bound-token) listener the target is spliced\n // onto. Defaults to --endpoint when that is itself a dial-able ws/socket.\n let hubEp: DialEndpoint;\n try {\n hubEp = _resolveDialEndpoint(cmdOpts.hubEndpoint, localEp);\n } catch (e) {\n process.stderr.write(`linkrpc: ${(e as Error).message}\\n`);\n process.exit(2);\n }\n\n const targetRes = resolveTargetEndpoint({\n targetEndpoint: cmdOpts.targetEndpoint,\n targetEndpointCmd: cmdOpts.targetEndpointCmd,\n targetEndpointCmdStdio: cmdOpts.targetEndpointCmdStdio,\n targetEndpointCmdEnv: cmdOpts.targetEndpointCmdEnv,\n targetEndpointToken: cmdOpts.targetEndpointToken,\n targetEndpointCmdCwd: cmdOpts.targetEndpointCmdCwd,\n });\n if (targetRes.error) {\n process.stderr.write(`linkrpc: ${targetRes.error}\\n`);\n process.exit(2);\n }\n if (!targetRes.endpoint) {\n process.stderr.write(\n 'linkrpc: connect-as requires --target-endpoint / --target-endpoint-cmd / --target-endpoint-cmd-stdio.\\n',\n );\n process.exit(2);\n }\n const targetEp = targetRes.endpoint;\n\n // Broker connection: sign the mint call where the hub requires it.\n const broker = await connectEndpoint(localEp, wireLog('broker'));\n try {\n const session = await setupSigning(broker.channel, broker.signing, getPrincipalSpec(), {\n negotiateHubCaps: isHubEndpoint(localEp),\n });\n reportIdentity(session);\n\n const brokerConn = new LinkRpcConnection(broker.rpcChannel);\n const binder = brokerConn.service(binderServiceId).get(connectionTokenBinderInterface);\n\n const logLine = (line: string): void => { process.stderr.write(`linkrpc: ${line}\\n`); };\n const serviceIdNamespace = cmdOpts.grantedServiceId ?? slot;\n await connectAs({\n mintToken: async () => {\n const { token } = await binder.bindConnectionToken({\n identitySlot: slot,\n serviceIdNamespace,\n });\n logLine(\n `connect-as: minted token for identity slot '${slot}'` +\n `${serviceIdNamespace !== slot ? `, granted serviceId '${serviceIdNamespace}'` : ''}` +\n ` via ${binderServiceId}`,\n );\n return token;\n },\n openHubTransport: (token) => openDialTransport(hubEp, token),\n openTargetTransport: () => openTargetTransport(targetEp, logLine),\n ...(g_logMessages\n ? {\n tapTarget: (t) => tapTransport(t, {\n log: logLine,\n localLabel: 'cli',\n remoteLabel: 'target',\n }),\n }\n : {}),\n log: logLine,\n stop: _untilSignalled(),\n });\n } finally {\n broker.close();\n }\n });\n\n program\n .command('mcp-forward [mcpCommand...]')\n .description(\n 'Expose an MCP server through the hub (--endpoint*) as a transparent forwarder. ' +\n 'By default it claims this connection\\'s granted serviceId namespace; pass ' +\n '--serviceId to claim a specific prefix. The MCP server command follows `--`, e.g. ' +\n '`linkrpc mcp-forward -- npx -y @modelcontextprotocol/server-everything` or ' +\n '`linkrpc mcp-forward --serviceId my-mcp -- npx -y @modelcontextprotocol/server-everything`. ' +\n 'Each consumer that opens `<serviceId>::vscode.mcp-forward::connect` spawns a fresh child ' +\n 'and gets its MCP stdio bridged raw over the stream. Runs until Ctrl-C.',\n )\n .option(\n '--serviceId <serviceId>',\n 'serviceId prefix to claim (default: the connection\\'s granted serviceId namespace)',\n )\n .option(\n '--env <key=value>',\n 'env var for the spawned MCP server child (repeatable)',\n (val: string, acc: Record<string, string> | undefined) => {\n const eq = val.indexOf('=');\n if (eq === -1) {\n throw new InvalidArgumentError(`expected key=value, got '${val}'`);\n }\n const next = acc ?? {};\n next[val.slice(0, eq)] = val.slice(eq + 1);\n return next;\n },\n )\n .action(async (mcpCommand: string[] | undefined, cmdOpts: {\n serviceId?: string;\n env?: Record<string, string>;\n }) => {\n const localEp = needEndpoint(endpoint);\n if (!mcpCommand || mcpCommand.length === 0) {\n process.stderr.write(\n 'linkrpc: mcp-forward requires an MCP server command after `--`, e.g. ' +\n '`mcp-forward -- npx -y @modelcontextprotocol/server-everything`.\\n',\n );\n process.exit(2);\n }\n const local = await connectEndpoint(localEp, wireLog('hub'));\n try {\n const session = await setupSigning(local.channel, local.signing, getPrincipalSpec(), {\n negotiateHubCaps: isHubEndpoint(localEp),\n });\n reportIdentity(session);\n await mcpForwardCommand({\n ...(cmdOpts.serviceId !== undefined ? { serviceId: cmdOpts.serviceId } : {}),\n local,\n command: { argv: mcpCommand },\n ...(cmdOpts.env !== undefined ? { env: cmdOpts.env } : {}),\n });\n } finally {\n local.close();\n }\n });\n\n program\n .command('identity')\n .description('Inspect the persistent principal used by connected CLI commands.')\n .command('show')\n .description('Print the resolved persistent CLI identity.')\n .option('--json', 'stable machine-readable JSON output')\n .action(async (opts: { json?: boolean; }) => {\n await withResolvedSigning(endpoint, getPrincipalSpec(), async (_conn, session) => {\n const out = formatCliIdentity(cliIdentity(session), opts.json === true);\n process.stdout.write(out + '\\n');\n });\n });\n\n const approval = program\n .command('approval')\n .description('Inspect and decide pending Hub access approval requests.');\n\n approval\n .command('requests')\n .description('List pending requests whose capability audience is this CLI identity.')\n .option('--json', 'stable machine-readable JSON output')\n .action(async (opts: { json?: boolean; }) => {\n await withApprovalClient(endpoint, getPrincipalSpec(), async (client) => {\n const out = formatApprovalRequests(\n await client.requests(),\n client.principalId,\n opts.json === true,\n );\n process.stdout.write(out + '\\n');\n });\n });\n\n approval\n .command('approve <request-id>')\n .description('Approve one pending request for this CLI identity.')\n .option('--json', 'stable machine-readable JSON output')\n .action(async (requestId: string, opts: { json?: boolean; }) => {\n await withApprovalClient(endpoint, getPrincipalSpec(), async (client) => {\n const outcome = await client.approve(requestId);\n process.stdout.write(\n formatApprovalDecision(\n 'approved',\n requestId,\n client.principalId,\n opts.json === true,\n outcome,\n ) + '\\n',\n );\n });\n });\n\n approval\n .command('deny <request-id>')\n .description('Deny one pending request for this CLI identity.')\n .option('--reason <text>', 'optional denial reason')\n .option('--json', 'stable machine-readable JSON output')\n .action(async (requestId: string, opts: { reason?: string; json?: boolean; }) => {\n await withApprovalClient(endpoint, getPrincipalSpec(), async (client) => {\n const outcome = await client.deny(requestId, opts.reason);\n process.stdout.write(\n formatApprovalDecision(\n 'denied',\n requestId,\n client.principalId,\n opts.json === true,\n outcome,\n ) + '\\n',\n );\n });\n });\n\n approval\n .command('ui')\n .description('Watch pending requests and approve or deny them interactively in the terminal.')\n .action(async () => {\n if (\n process.stdin.isTTY !== true\n || process.stdout.isTTY !== true\n || !Number.isInteger(process.stdout.columns)\n || process.stdout.columns <= 0\n || !Number.isInteger(process.stdout.rows)\n || process.stdout.rows <= 0\n ) {\n throw new Error('approval ui requires an interactive terminal with visible output');\n }\n const stop = new AbortController();\n const onSignal = () => stop.abort();\n await withApprovalClient(\n endpoint,\n getPrincipalSpec(),\n async (client) => {\n process.once('SIGINT', onSignal);\n process.once('SIGTERM', onSignal);\n try {\n const { runApprovalUi } = await import('./approval-ui/runApprovalUi');\n await runApprovalUi({ client, signal: stop.signal });\n } finally {\n process.removeListener('SIGINT', onSignal);\n process.removeListener('SIGTERM', onSignal);\n }\n },\n () => { /* Ink owns the terminal while the approval UI is active. */ },\n );\n });\n }\n\n program\n .command('ui')\n .description('Launch the terminal UI (form-based browser of services + methods).')\n .action(async () => {\n const acquired = await acquireConnection(endpoint);\n const { runUi } = await import('./ui/runUi');\n try {\n await runUi({ endpoint: acquired.ep, principalSpec: getPrincipalSpec() });\n } finally {\n acquired.running?.dispose();\n }\n });\n\n if (profile === 'hub') {\n program\n .command('logout')\n .description(\n 'Delete the stored CLI identity and cached capabilities. Next call will mint a fresh keypair and prompt for consent again.',\n )\n .action(async () => {\n const removed = await logoutCliIdentity();\n if (removed.length === 0) {\n process.stdout.write('linkrpc: no stored identity found.\\n');\n return;\n }\n for (const f of removed) {\n process.stdout.write(`removed ${f}\\n`);\n }\n });\n }\n\n program\n .command('completions <shell>')\n .description(\n 'Print a shell completion script. Supported: powershell. Install with ' +\n '`hub completions powershell | Out-String | Invoke-Expression` (one-shot) or ' +\n 'append to $PROFILE.',\n )\n .action((shell: string) => {\n try {\n const script = completionsCommand({ shell });\n process.stdout.write(script);\n if (!script.endsWith('\\n')) process.stdout.write('\\n');\n } catch (e) {\n process.stderr.write(`linkrpc: ${(e as Error).message}\\n`);\n process.exit(2);\n }\n });\n\n program\n .command('_complete')\n .description(\n '(internal) Emit completion candidates for a partial command line. ' +\n 'Invoked by the scripts produced by `hub completions`.',\n )\n .option('--line <line>', 'the partial command line, including the binary name')\n .option('--point <n>', 'cursor position (0-indexed) into --line', (v) => Number.parseInt(v, 10))\n .action(async (opts: { line?: string; point?: number; }) => {\n // The completer must NEVER write to stderr or non-zero-exit — that\n // would surface in the user's prompt. Always exit 0 with whatever\n // we managed to compute (possibly nothing). Force-exit at the end\n // so any open socket / setup-signing timer can't keep the process\n // alive past the action — that hangs the user's shell on TAB.\n try {\n const line = opts.line ?? '';\n const point = typeof opts.point === 'number' && !Number.isNaN(opts.point)\n ? opts.point\n : line.length;\n const out = await internalCompleteCommand({ line, point });\n if (out.length > 0) process.stdout.write(out + '\\n');\n } catch {\n // swallow\n }\n // Force-exit: completion is one-shot and must never hang.\n process.exit(0);\n });\n\n if (profile === 'rpc') {\n program\n .command('hub')\n .description('Run the same shared commands with the hub profile and expose hub-only commands.');\n }\n\n await program.parseAsync([\n 'node',\n cliInvocation.programName,\n ...rewriteParamShortcuts(cliInvocation.argv),\n ]);\n}\n\nfunction collectContextOverrides(program: Command, actionCommand: Command): ContextValues {\n const opts = program.opts();\n const result: Record<string, unknown> = {};\n copyExplicit(program, opts, result, 'endpoint');\n copyExplicit(program, opts, result, 'endpointCmd');\n copyExplicit(program, opts, result, 'endpointCmdStdio');\n copyExplicit(program, opts, result, 'endpointCmdEnv');\n copyExplicit(program, opts, result, 'endpointToken');\n copyExplicit(program, opts, result, 'endpointCmdCwd');\n copyExplicit(program, opts, result, 'config');\n copyExplicit(program, opts, result, 'provisionIdentity');\n copyExplicit(program, opts, result, 'provisionIdentitySlot');\n copyExplicit(program, opts, result, 'principal');\n copyExplicit(program, opts, result, 'schema');\n copyExplicit(program, opts, result, 'validation');\n\n if (getCommandPath(actionCommand) === 'connection create') {\n const actionOpts = actionCommand.opts();\n copyExplicit(actionCommand, actionOpts, result, 'timeout', 'connectionTimeout');\n copyExplicit(actionCommand, actionOpts, result, 'ttl', 'connectionTtl');\n copyExplicit(actionCommand, actionOpts, result, 'notificationLimit');\n }\n return result as ContextValues;\n}\n\nfunction copyExplicit(\n command: Command,\n source: Record<string, unknown>,\n target: Record<string, unknown>,\n optionName: string,\n contextName = optionName,\n): void {\n if (command.getOptionValueSource(optionName) === 'cli') {\n target[contextName] = source[optionName];\n }\n}\n\nfunction explicitOption<T>(command: Command, name: string): T | undefined {\n return command.getOptionValueSource(name) === 'cli'\n ? command.opts()[name] as T\n : undefined;\n}\n\nasync function createContextFromInvocation(\n store: ContextStore,\n reference: Exclude<ContextReference, { readonly kind: 'empty'; }>,\n values: ContextValues,\n): Promise<void> {\n await store.replace(reference, values, { createOnly: true });\n process.stderr.write(`linkrpc: created context ${formatContextReference(reference)}.\\n`);\n}\n\nasync function createConnectionContext(\n store: ContextStore,\n reference: Exclude<ContextReference, { readonly kind: 'empty'; }>,\n values: ContextValues,\n brokerEndpoint: string,\n): Promise<void> {\n const {\n endpoint: _endpoint,\n endpointCmd: _endpointCmd,\n endpointCmdStdio: _endpointCmdStdio,\n endpointCmdEnv: _endpointCmdEnv,\n endpointToken: _endpointToken,\n endpointCmdCwd: _endpointCmdCwd,\n provisionIdentity: _provisionIdentity,\n provisionIdentitySlot: _provisionIdentitySlot,\n ...rest\n } = values;\n const connectionEndpoint = splitEndpointToken(brokerEndpoint);\n await createContextFromInvocation(store, reference, {\n ...rest,\n ...connectionEndpoint,\n });\n}\n\nfunction splitEndpointToken(endpoint: string): Pick<ContextValues, 'endpoint' | 'endpointToken'> {\n const parsed = parseEndpointUri(endpoint);\n if ((parsed.kind !== 'socket' && parsed.kind !== 'ws') || parsed.token === undefined) {\n return { endpoint };\n }\n const { token, ...withoutToken } = parsed;\n const separator = formatEndpointUri(withoutToken).includes('?') ? '&' : '?';\n return {\n endpoint: `${formatEndpointUri(withoutToken)}${separator}token=%`,\n endpointToken: token,\n };\n}\n\nasync function stopConnectionBroker(endpoint: string): Promise<void> {\n const connection = await connectEndpoint(parseEndpointUri(endpoint));\n try {\n await disconnectBroker(connection.channel);\n } finally {\n connection.close();\n }\n}\n\nfunction mutableReference(\n reference: ContextReference,\n): Exclude<ContextReference, { readonly kind: 'empty'; }> {\n if (reference.kind === 'empty') {\n throw new Error(':empty is immutable and cannot be modified');\n }\n return reference;\n}\n\nfunction printSelectedContext(effective: boolean): void {\n if (g_invocation === undefined) throw new Error('context resolver is unavailable');\n const selected = g_invocation.selected;\n process.stdout.write('Context\\n');\n process.stdout.write(` Reference: ${formatContextReference(selected.reference)}\\n`);\n process.stdout.write(` Selected via: ${contextSelectionDescription(selected.selectedBy)}\\n`);\n if (effective) {\n process.stdout.write(` Profile: ${g_invocation.profile}\\n`);\n const environmentStatus = g_invocation.environmentApplied\n ? Object.keys(g_invocation.environmentValues).length > 0\n ? 'enabled'\n : 'enabled (no variables set)'\n : 'disabled';\n process.stdout.write(\n ` Environment overrides: ${environmentStatus}\\n`,\n );\n }\n\n process.stdout.write('\\nStored defaults\\n');\n printContextValues(selected.context?.values ?? {}, false);\n if (!effective) return;\n\n process.stdout.write('\\nEffective values\\n');\n printContextValues(g_invocation.values, false, (key) => {\n if (hasContextValue(g_invocation?.cliOverrides, key)) return 'command line';\n if (hasContextValue(g_invocation?.environmentValues, key)) return 'environment';\n if (hasContextValue(g_invocation?.contextValues, key)) return 'context';\n return undefined;\n });\n}\n\nfunction contextSelectionDescription(selectedBy: ResolvedInvocationContext['selected']['selectedBy']): string {\n switch (selectedBy) {\n case 'argument': return '--context';\n case 'environment': return 'LINKRPC_CONTEXT (HUBRPC_CONTEXT fallback)';\n case 'cwd': return 'current-directory lookup';\n case 'root': return ':root fallback';\n case 'empty': return 'no matching context (:empty)';\n }\n}\n\nfunction hasContextValue(\n values: ContextValues | undefined,\n key: keyof ContextValues,\n): boolean {\n return values !== undefined && values[key] !== undefined;\n}\n\nfunction printContextValues(\n values: ContextValues,\n revealToken: boolean,\n source?: (key: keyof ContextValues) => string | undefined,\n): void {\n const entries = Object.entries(values);\n if (entries.length === 0) {\n process.stdout.write(' (none)\\n');\n return;\n }\n for (const [key, value] of entries) {\n const contextKey = key as keyof ContextValues;\n const rendered = key === 'endpointToken' && !revealToken\n ? '<stored>'\n : key === 'endpoint' && typeof value === 'string' && !revealToken\n ? redactEndpointTokens(value)\n : typeof value === 'string'\n ? value\n : JSON.stringify(value);\n const valueSource = source?.(contextKey);\n process.stdout.write(\n ` --${contextValueFlag(contextKey)} = ${rendered}${valueSource ? ` (${valueSource})` : ''}\\n`,\n );\n }\n\n function redactEndpointTokens(endpoint: string): string {\n return endpoint.replace(/([?&]token=)([^&#]*)/g, (_match, prefix: string, token: string) =>\n `${prefix}${token === '%' ? '%' : '<stored>'}`);\n }\n}\n\nfunction contextValueFlag(key: keyof ContextValues): string {\n const names: Record<keyof ContextValues, string> = {\n endpoint: 'endpoint',\n endpointCmd: 'endpoint-cmd',\n endpointCmdStdio: 'endpoint-cmd-stdio',\n endpointCmdEnv: 'endpoint-cmd-env',\n endpointToken: 'endpoint-token',\n endpointCmdCwd: 'endpoint-cmd-cwd',\n config: 'config',\n provisionIdentity: 'provision-identity',\n provisionIdentitySlot: 'provision-identity-slot',\n principal: 'principal',\n schema: 'schema',\n validation: 'validation',\n connectionTimeout: 'connection-timeout',\n connectionTtl: 'connection-ttl',\n notificationLimit: 'notification-limit',\n };\n return names[key];\n}\n\nfunction parseContextValueKey(value: string): keyof ContextValues {\n const entry = (Object.keys({\n endpoint: true,\n endpointCmd: true,\n endpointCmdStdio: true,\n endpointCmdEnv: true,\n endpointToken: true,\n endpointCmdCwd: true,\n config: true,\n provisionIdentity: true,\n provisionIdentitySlot: true,\n principal: true,\n schema: true,\n validation: true,\n connectionTimeout: true,\n connectionTtl: true,\n notificationLimit: true,\n }) as (keyof ContextValues)[]).find((key) => contextValueFlag(key) === value);\n if (entry === undefined) throw new InvalidArgumentError(`unknown context value \"${value}\"`);\n return entry;\n}\n\nfunction effectiveValidation(profile: CliProfile): ValidationMode {\n return g_invocation?.values.validation ?? validationDefault(profile);\n}\n\nfunction parseValidationMode(value: string): ValidationMode {\n if (value === 'auto' || value === 'required' || value === 'off') return value;\n throw new InvalidArgumentError(\"--validation must be 'auto', 'required', or 'off'\");\n}\n\nfunction getCommandPath(command: Command): string {\n const names: string[] = [];\n for (let cursor: Command | null = command; cursor?.parent !== null; cursor = cursor.parent) {\n names.unshift(cursor.name());\n }\n return names.join(' ');\n}\n\nfunction commandUsesEndpoint(commandPath: string): boolean {\n return !(\n commandPath === 'context'\n || commandPath.startsWith('context ')\n || commandPath === 'codegen'\n || commandPath === 'schema hash'\n || commandPath === 'completions'\n || commandPath === '_complete'\n || commandPath === '_connection-broker'\n || commandPath === 'serve'\n || commandPath === 'logout'\n );\n}\n\nfunction hasEndpointOverrides(values: ContextValues): boolean {\n return values.endpoint !== undefined\n || values.endpointCmd !== undefined\n || values.endpointCmdStdio !== undefined\n || values.endpointCmdEnv !== undefined\n || values.endpointToken !== undefined\n || values.endpointCmdCwd !== undefined\n || values.provisionIdentity !== undefined\n || values.provisionIdentitySlot !== undefined;\n}\n\nasync function withChannel(\n endpoint: ResolvedEndpoint | undefined,\n principalSpec: PrincipalSpec,\n fn: (channel: import('@hediet/linkrpc-client').CliChannel) => Promise<void>,\n opts: {\n requestReflectionAccess?: boolean;\n requestTopologyAccess?: { readonly sourceServiceIds?: readonly string[] };\n } = {},\n): Promise<void> {\n const acquired = await acquireConnection(endpoint);\n // When `--config` runs an in-process hub, that hub already logs its routed\n // traffic (richer than the client leg) — so only tap the wire for a direct\n // remote connection, to avoid double-logging the control socket.\n const conn = await connectEndpoint(acquired.ep, acquired.running === undefined ? wireLog('hub') : undefined);\n try {\n const schemaSource = g_invocation?.values.schema;\n const channel = schemaSource === undefined\n ? conn.channel\n : withStaticHubReflection(conn.channel, await loadStaticHubSchema(schemaSource));\n if (\n acquired.ep.kind === 'ws-no-init'\n || (acquired.ep.kind === 'socket' && acquired.ep.brokerMode === 'raw')\n ) {\n await fn(channel);\n return;\n }\n if (g_invocation?.profile === 'rpc') {\n await fn(channel);\n return;\n }\n\n const session = await setupSigning(conn.channel, conn.signing, principalSpec, {\n negotiateHubCaps: acquired.running !== undefined || isHubEndpoint(acquired.ep),\n });\n reportIdentity(session);\n // Up-front, batched reflection grant across all services. One consent\n // prompt covers `ls` / `schema` / `defaults`; if denied we fall back to\n // per-call auto-cap negotiation installed by `setupSigning`.\n if (\n opts.requestReflectionAccess !== false\n && schemaSource === undefined\n && (acquired.running !== undefined || isHubEndpoint(acquired.ep))\n ) {\n const status = await requestReflectionAccess(session);\n if (status === 'denied') {\n process.stderr.write(\n 'linkrpc: reflection access denied; falling back to per-call negotiation.\\n',\n );\n }\n }\n if (\n opts.requestTopologyAccess !== undefined\n && (acquired.running !== undefined || isHubEndpoint(acquired.ep))\n ) {\n const status = await requestTopologyAccess(session, opts.requestTopologyAccess);\n if (status === 'denied') {\n process.stderr.write(\n 'linkrpc: topology access denied; topology sources may be inaccessible.\\n',\n );\n }\n }\n await fn(channel);\n } finally {\n conn.close();\n acquired.running?.dispose();\n }\n}\n\nasync function withResolvedSigning(\n endpoint: ResolvedEndpoint | undefined,\n principalSpec: PrincipalSpec,\n fn: (connection: CliConnection, session: SigningSession) => Promise<void>,\n): Promise<void> {\n const acquired = await acquireConnection(endpoint);\n if (\n acquired.ep.kind === 'ws-no-init'\n || (acquired.ep.kind === 'socket' && acquired.ep.brokerMode === 'raw')\n ) {\n acquired.running?.dispose();\n throw new Error('identity and approval commands require a LinkRPC endpoint');\n }\n const conn = await connectEndpoint(acquired.ep, acquired.running === undefined ? wireLog('hub') : undefined);\n try {\n const session = await setupSigning(conn.channel, conn.signing, principalSpec, {\n negotiateHubCaps: acquired.running !== undefined || isHubEndpoint(acquired.ep),\n autoNegotiatePerCall: false,\n });\n await fn(conn, session);\n } finally {\n conn.close();\n acquired.running?.dispose();\n }\n}\n\nasync function withApprovalClient(\n endpoint: ResolvedEndpoint | undefined,\n principalSpec: PrincipalSpec,\n fn: (client: ApprovalCommandClient) => Promise<void>,\n log: (line: string) => void = (line) => process.stderr.write(`linkrpc: ${line}\\n`),\n): Promise<void> {\n await withResolvedSigning(endpoint, principalSpec, async (conn, session) => {\n reportIdentity(session);\n await bootstrapApprovalCommandCapability(session.principal);\n const connection = new LinkRpcConnection(conn.rpcChannel);\n const client = createHubApprovalCommandClient(\n connection,\n session.principal.identity,\n log,\n );\n try {\n await fn(client);\n } finally {\n client.dispose();\n }\n });\n}\n\nasync function withRawConnection(\n endpoint: ResolvedEndpoint | undefined,\n fn: (channel: import('@hediet/linkrpc-client').CliChannel) => Promise<void>,\n): Promise<void> {\n if (g_hubConfigPath !== undefined) {\n throw new Error('connection broker commands do not support --config');\n }\n const conn = await connectEndpoint(needEndpoint(endpoint), wireLog('connection broker'));\n try {\n await fn(conn.channel);\n } finally {\n conn.close();\n }\n}\n\nfunction parsePositiveInteger(value: string, option: string): number {\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new InvalidArgumentError(`${option} must be a positive integer`);\n }\n return parsed;\n}\n\nfunction parseNonNegativeInteger(value: string, option: string): number {\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 0) {\n throw new InvalidArgumentError(`${option} must be a non-negative integer`);\n }\n return parsed;\n}\n\n/**\n * Module-level config path, set per-command in the `preAction` hook. When set,\n * client commands run an in-process hub from the config and target its private\n * control socket instead of `--endpoint`.\n */\nlet g_hubConfigPath: string | undefined;\nlet g_contextStore: ContextStore | undefined;\nlet g_invocation: ResolvedInvocationContext | undefined;\n\n/**\n * Module-level flag, set per-command in the `preAction` hook. When set, the\n * in-process hub (`-c, --config` or `serve`) logs every routed JSON-RPC\n * message to stderr. Forced off for `ui` (it would corrupt the TUI).\n */\nlet g_logMessages = false;\nlet g_logTransport = false;\n\n/**\n * Build the wire-tap options for a direct {@link connect}, or `undefined` when\n * `--log-messages` is off. Logs every JSON-RPC message crossing the client\n * transport to stderr, rendered like the hub \"Flows\" view — the way to observe\n * a connection that never routes through a local hub.\n */\nfunction wireLog(remoteLabel: string): ConnectLogOptions | undefined {\n if (!g_logMessages && !g_logTransport) return undefined;\n return {\n ...(g_logMessages\n ? { log: (line: string) => process.stderr.write(`linkrpc: ${line}\\n`) }\n : {}),\n ...(g_logTransport\n ? {\n trace: (direction: 'send' | 'receive', message: import('@hediet/linkrpc').JsonRpcMessage) =>\n process.stderr.write(`linkrpc: transport ${direction} ${JSON.stringify(message)}\\n`),\n }\n : {}),\n remoteLabel,\n };\n}\n\n/**\n * Resolve the endpoint a client command should connect to. With `--config`,\n * spins up an in-process hub and returns its control socket (the caller must\n * `running.dispose()` when done); otherwise returns the resolved `--endpoint`.\n */\nasync function acquireConnection(\n endpoint: ResolvedEndpoint | undefined,\n): Promise<{ ep: ResolvedEndpoint; running?: RunningHub; }> {\n if (g_hubConfigPath !== undefined) {\n const config: HubConfig = loadHubConfig(g_hubConfigPath);\n const running = await runHub({ config, logMessages: g_logMessages });\n return {\n ep: { kind: 'socket', path: running.controlEndpoint.path, token: running.controlEndpoint.token },\n running,\n };\n }\n return { ep: needEndpoint(endpoint) };\n}\n\n/** Print the identity used to sign calls to stderr (keeps stdout clean for JSON output). */\nfunction reportIdentity(session: SigningSession): void {\n process.stderr.write(\n `linkrpc: identity ${formatPrincipalSource(session.principalSource, session.principal.id)\n }\\n`,\n );\n}\n\nfunction needEndpoint(endpoint: ResolvedEndpoint | undefined): ResolvedEndpoint {\n if (!endpoint) {\n process.stderr.write(\n 'linkrpc: this command requires --endpoint / --endpoint-cmd / --endpoint-cmd-stdio ' +\n 'or the LINKRPC_ENDPOINT env var to be set.\\n',\n );\n process.exit(2);\n }\n return endpoint;\n}\n\n/**\n * Resolve the ws/socket bound-token listener `connect-as` splices the target\n * onto: an explicit `--hub-endpoint <uri>`, else the fallback endpoint when it\n * is itself a dial-able ws/socket. Throws otherwise (cmd endpoints aren't\n * dial-able bound listeners).\n */\nfunction _resolveDialEndpoint(\n hubEndpoint: string | undefined,\n fallback: ResolvedEndpoint,\n): DialEndpoint {\n if (hubEndpoint !== undefined) {\n const spec = parseEndpointUri(hubEndpoint);\n if (spec.kind !== 'ws' && spec.kind !== 'socket') {\n throw new Error(`--hub-endpoint must be a ws/socket URI, got '${spec.kind}'`);\n }\n return spec;\n }\n if (fallback.kind === 'ws' || fallback.kind === 'socket') {\n return fallback;\n }\n throw new Error(\n 'connect-as requires --hub-endpoint <ws/socket uri> (the bound-token listener); ' +\n `--endpoint resolved to '${fallback.kind}', which is not a dial-able bound listener`,\n );\n}\n\n/** Resolve on the next `SIGINT` / `SIGTERM`. */\nfunction _untilSignalled(): Promise<void> {\n return new Promise<void>((resolve) => {\n const done = (): void => {\n process.removeListener('SIGINT', done);\n process.removeListener('SIGTERM', done);\n resolve();\n };\n process.once('SIGINT', done);\n process.once('SIGTERM', done);\n });\n}\n\nfunction resolveGraphFormat(\n rawFormat: unknown,\n aliases: { readonly json: boolean; readonly stream: boolean; readonly watch: boolean },\n): TopologyFormat {\n if (aliases.json && aliases.stream) {\n throw new InvalidArgumentError('--json and --stream cannot be combined');\n }\n if (rawFormat !== undefined && (aliases.json || aliases.stream)) {\n throw new InvalidArgumentError('--format cannot be combined with --json or --stream');\n }\n if (rawFormat !== undefined\n && rawFormat !== 'pretty'\n && rawFormat !== 'json'\n && rawFormat !== 'jsonl') {\n throw new InvalidArgumentError(\"--format must be 'pretty', 'json', or 'jsonl'\");\n }\n if (aliases.json) return 'json';\n if (aliases.stream) return 'jsonl';\n if (rawFormat !== undefined) return rawFormat;\n return aliases.watch && !process.stdout.isTTY ? 'jsonl' : 'pretty';\n}\n\nfunction collectOption(value: string, previous: readonly string[] | undefined): readonly string[] {\n return [...(previous ?? []), value];\n}\n\nfunction repaintTerminal(frame: string): void {\n process.stdout.write(`\\u001b[2J\\u001b[H${frame}\\n`);\n}\n\nfunction parseInterfaceRef(raw: string): { id: string; hash: string | undefined; } {\n const at = raw.lastIndexOf('@');\n if (at > 0 && !raw.slice(at + 1).includes('::')) {\n return { id: raw.slice(0, at), hash: raw.slice(at + 1) };\n }\n return { id: raw, hash: undefined };\n}\n\nexport function runCli(executableName: 'linkrpc' | 'rpc' | 'hub'): void {\n main(process.argv.slice(2), executableName).catch((e: unknown) => {\n process.stderr.write(`linkrpc: ${formatCliError(e)}\\n`);\n process.exit(1);\n });\n}\n\nfunction formatCliError(error: unknown): string {\n if (typeof error !== 'object' || error === null) return String(error);\n\n const value = error as {\n readonly code?: unknown;\n readonly message?: unknown;\n readonly data?: unknown;\n };\n const message = typeof value.message === 'string' ? value.message : String(error);\n if (typeof value.code !== 'number' && typeof value.code !== 'string') return message;\n\n const data = value.data === undefined ? '' : ` data=${safeJson(value.data)}`;\n return `[${value.code}] ${message}${data}`;\n}\n\nfunction safeJson(value: unknown): string {\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n"],"x_google_ignoreList":[30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,SAAgB,cAAc,OAAoC;CAC9D,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAEhC,MAAM,WADO,UAAU,MAAM,aAAa,GAAG,MAAM,IAAI,MAAA,CAClC,KAAK;CAC1B,IAAI,QAAQ,WAAW,GAAG,OAAO,KAAA;CACjC,IAAI;EACA,OAAO,KAAK,MAAM,OAAO;CAC7B,SAAS,GAAG;EACR,MAAM,IAAI,MAAM,2BAA4B,EAAY,QAAQ,EAAE;CACtE;AACJ;AAEA,SAAgB,WAAW,GAAoB;CAC3C,IAAI,MAAM,KAAA,GAAW,OAAO;CAC5B,OAAO,KAAK,UAAU,GAAG,MAAM,CAAC;AACpC;;;ACSA,MAAM,iBAAiB;AAEvB,SAAS,mBAAmB,IAAqB;CAC7C,OAAO,GAAG,WAAW,cAAc;AACvC;AAEA,SAAS,iBAAiB,IAAqB;CAC3C,OAAO,CAAC,mBAAmB,EAAE;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