@hediet/linkrpc-cli 0.0.3-next.20261102.2 → 0.0.3-next.20261104.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"daemon.js","names":["path","fs","fs","fs","path","path","fs","path","path","fs","path","path","parse","parser.parse","edit.setProperty","edit.applyEdit","jsonc.parse","jsonc.printParseErrorCode","jsonc.modify","jsonc.applyEdits","path","fs","path","fs","path","fs","fs","fs","path","path","path","crossSpawn","_message","fs","path","path","fs"],"sources":["../../linkrpc-hub-daemon/src/packageInfo.ts","../../linkrpc-hub-daemon/src/autostart/launch.ts","../../linkrpc-hub-daemon/src/autostart/launchd.ts","../../linkrpc-hub-daemon/src/autostart/linux.ts","../../linkrpc-hub-daemon/src/autostart/windows.ts","../../linkrpc-hub-daemon/src/autostart/autostart.ts","../../linkrpc-hub-daemon/src/discovery.ts","../../linkrpc-hub-daemon/src/callLog/callQuery.ts","../../linkrpc-hub-daemon/src/callLog/callRecord.ts","../../linkrpc-hub-daemon/src/managementInterface.ts","../../linkrpc-hub-daemon/src/paths.ts","../../linkrpc-hub-daemon/src/endpointInterface.ts","../../linkrpc-hub-daemon/src/client.ts","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/scanner.js","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/string-intern.js","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/format.js","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/parser.js","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/edit.js","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js","../../linkrpc-hub-daemon/src/callLog/callLogConfig.ts","../../linkrpc-hub-daemon/src/config.ts","../../linkrpc-hub-daemon/src/control.ts","../../linkrpc-hub-daemon/src/callLog/callLogService.ts","../../linkrpc-hub-daemon/src/callLog/callLogStore.ts","../../linkrpc-hub-daemon/src/callLog/payloadPolicy.ts","../../linkrpc-hub-daemon/src/callLog/portPeers.ts","../../linkrpc-hub-daemon/src/participantDescriptors.ts","../../linkrpc-hub-daemon/src/callLog/callRecorder.ts","../../linkrpc-hub-daemon/src/callLog/callLog.ts","../../linkrpc-hub-daemon/src/configFile.ts","../../linkrpc-hub-daemon/src/daemonLog.ts","../../linkrpc-hub-daemon/src/singleInstance.ts","../../linkrpc-hub-daemon/src/logBuffer.ts","../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js","../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js","../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js","../../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js","../../../node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js","../../../node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js","../../../node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js","../../linkrpc-hub-daemon/src/processTree.ts","../../linkrpc-hub-daemon/src/processIo.ts","../../linkrpc-hub-daemon/src/supervisor.ts","../../linkrpc-hub-daemon/src/connectionSupervisor.ts","../../linkrpc-hub-daemon/src/screenHistory.ts","../../linkrpc-hub-daemon/src/managedEndpoints.ts","../../linkrpc-hub-daemon/src/daemon.ts","../../linkrpc-hub-daemon/src/stdioBridge.ts","../../linkrpc-hub-daemon/src/watchdog.ts","../../linkrpc-hub-daemon/src/cli.ts"],"sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst PACKAGE_NAME = '@hediet/linkrpc-hub-daemon';\nconst CLI_PACKAGE_NAME = '@hediet/linkrpc-cli';\n\n/** The root directory of this package (works from `src/` and bundled `dist/`). */\nexport function packageRoot(): string {\n let dir = path.dirname(fileURLToPath(import.meta.url));\n while (true) {\n const manifest = path.join(dir, 'package.json');\n if (fs.existsSync(manifest)) {\n const name = JSON.parse(fs.readFileSync(manifest, 'utf8')).name;\n if (name === PACKAGE_NAME || name === CLI_PACKAGE_NAME) return dir;\n }\n const parent = path.dirname(dir);\n if (parent === dir) throw new Error(`cannot locate the ${PACKAGE_NAME} package root`);\n dir = parent;\n }\n}\n\nexport function packageVersion(): string {\n return JSON.parse(fs.readFileSync(path.join(packageRoot(), 'package.json'), 'utf8')).version;\n}\n\n/** The daemon CLI script; `node <cliScript> run` runs the daemon. */\nexport function cliScript(): string {\n const root = packageRoot();\n const { name } = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));\n return path.join(root, 'dist', name === CLI_PACKAGE_NAME ? 'daemon.js' : 'cli.js');\n}\n","import { spawn } from 'node:child_process';\nimport * as fs from 'node:fs';\nimport { cliScript } from '../packageInfo';\nimport type { HubHome } from '../paths';\n\n/** A process to start: executable, arguments, and extra environment. */\nexport interface LaunchCommand {\n readonly executable: string;\n readonly args: readonly string[];\n readonly env: Readonly<Record<string, string>>;\n}\n\n/** How to run the daemon, as registered with the OS. */\nexport interface DaemonLaunch {\n /** The daemon in the foreground, for OS managers that restart it on failure (launchd, systemd). */\n readonly foreground: LaunchCommand;\n /** The daemon under its own crash-restart watchdog, for launchers without supervision. */\n readonly keepAlive: LaunchCommand;\n /** The keep-alive executable opens no console window (a GUI-subsystem binary on Windows). */\n readonly windowless: boolean;\n}\n\n/**\n * Run the daemon with this Node.js runtime and the package's CLI script. The\n * executable is resolved through symlinks: version managers (fnm, nvm, volta)\n * expose per-shell paths that do not survive a logout.\n */\nexport function nodeDaemonLaunch(home: HubHome, executable: string = fs.realpathSync(process.execPath), env: Readonly<Record<string, string>> = {}): DaemonLaunch {\n const run = [cliScript(), ...(home.customDir !== undefined ? ['--home', home.customDir] : []), 'run', '--quiet'];\n return {\n foreground: { executable, args: run, env },\n keepAlive: { executable, args: [...run, '--keep-alive'], env },\n windowless: false,\n };\n}\n\n/** Start `command` detached from this process, without a console window. */\nexport function spawnDetached(command: LaunchCommand): void {\n const child = spawn(command.executable, command.args, {\n detached: true,\n stdio: 'ignore',\n windowsHide: true,\n env: { ...process.env, ...command.env },\n });\n child.on('error', () => { /* surfaced by the readiness wait */ });\n child.unref();\n}\n\nexport interface ExecResult {\n readonly code: number;\n readonly stdout: string;\n readonly stderr: string;\n}\n\nexport type Exec = (file: string, args: readonly string[]) => Promise<ExecResult>;\n\n/** Run a short-lived command and capture its output. Never rejects. */\nexport const execCommand: Exec = (file, args) => new Promise(resolve => {\n const child = spawn(file, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });\n let stdout = '';\n let stderr = '';\n child.stdout.setEncoding('utf8').on('data', (chunk: string) => { stdout += chunk; });\n child.stderr.setEncoding('utf8').on('data', (chunk: string) => { stderr += chunk; });\n child.once('error', error => resolve({ code: -1, stdout, stderr: error.message }));\n child.once('close', code => resolve({ code: code ?? -1, stdout, stderr }));\n});\n\nexport function checkExec(result: ExecResult, what: string): void {\n if (result.code !== 0) throw new Error(`${what} failed (${result.code}): ${(result.stderr || result.stdout).trim()}`);\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { AutostartManager } from './autostart';\nimport { checkExec, type DaemonLaunch, type Exec } from './launch';\n\n/**\n * macOS login autostart through a per-user LaunchAgent. launchd restarts the\n * daemon after crashes but not after an intentional (exit code 0) stop.\n */\nexport class LaunchdAutostart implements AutostartManager {\n public readonly description = 'macOS LaunchAgent';\n\n constructor(\n private readonly _label: string,\n private readonly _plistPath: string,\n private readonly _exec: Exec,\n private readonly _uid: number,\n ) { }\n\n public async isEnabled(): Promise<boolean> {\n return fs.existsSync(this._plistPath);\n }\n\n /** Registers for the next login; does not start the daemon now. */\n public async enable(launch: DaemonLaunch): Promise<void> {\n fs.mkdirSync(path.dirname(this._plistPath), { recursive: true });\n fs.writeFileSync(this._plistPath, launchdPlist(this._label, launch));\n }\n\n /** Unregisters; a running daemon keeps running. */\n public async disable(): Promise<void> {\n fs.rmSync(this._plistPath, { force: true });\n }\n\n public async startManaged(): Promise<boolean> {\n if (!fs.existsSync(this._plistPath)) return false;\n const domain = `gui/${this._uid}`;\n const kickstart = await this._exec('launchctl', ['kickstart', `${domain}/${this._label}`]);\n if (kickstart.code === 0) return true;\n checkExec(await this._exec('launchctl', ['bootstrap', domain, this._plistPath]), 'launchctl bootstrap');\n return true;\n }\n}\n\nexport function launchdPlist(label: string, launch: DaemonLaunch): string {\n const { executable, args, env } = launch.foreground;\n const strings = (values: readonly string[]) => values.map(v => ` <string>${_xml(v)}</string>`).join('\\n');\n const envEntries = Object.entries(env)\n .map(([key, value]) => ` <key>${_xml(key)}</key>\\n <string>${_xml(value)}</string>`)\n .join('\\n');\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>Label</key>\n <string>${_xml(label)}</string>\n <key>ProgramArguments</key>\n <array>\n${strings([executable, ...args])}\n </array>\n <key>EnvironmentVariables</key>\n <dict>\n${envEntries}\n </dict>\n <key>RunAtLoad</key>\n <true/>\n <key>KeepAlive</key>\n <dict>\n <key>SuccessfulExit</key>\n <false/>\n </dict>\n <key>ProcessType</key>\n <string>Background</string>\n</dict>\n</plist>\n`;\n}\n\nfunction _xml(value: string): string {\n return value\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&apos;');\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { AutostartManager } from './autostart';\nimport { checkExec, type DaemonLaunch, type Exec, type LaunchCommand } from './launch';\n\n/**\n * Linux login autostart through a systemd user unit. systemd restarts the\n * daemon after crashes (`Restart=on-failure`) but not after an intentional stop.\n */\nexport class SystemdUserAutostart implements AutostartManager {\n public readonly description = 'systemd user service';\n\n constructor(\n private readonly _unitName: string,\n private readonly _unitPath: string,\n private readonly _exec: Exec,\n ) { }\n\n public async isEnabled(): Promise<boolean> {\n const result = await this._exec('systemctl', ['--user', 'is-enabled', this._unitName]);\n return result.code === 0 && result.stdout.trim() === 'enabled';\n }\n\n /** Registers for the next login; does not start the daemon now. */\n public async enable(launch: DaemonLaunch): Promise<void> {\n fs.mkdirSync(path.dirname(this._unitPath), { recursive: true });\n fs.writeFileSync(this._unitPath, systemdUnit(launch));\n checkExec(await this._exec('systemctl', ['--user', 'daemon-reload']), 'systemctl daemon-reload');\n checkExec(await this._exec('systemctl', ['--user', 'enable', this._unitName]), 'systemctl enable');\n }\n\n /** Unregisters; a running daemon keeps running. */\n public async disable(): Promise<void> {\n await this._exec('systemctl', ['--user', 'disable', this._unitName]);\n fs.rmSync(this._unitPath, { force: true });\n await this._exec('systemctl', ['--user', 'daemon-reload']);\n }\n\n public async startManaged(): Promise<boolean> {\n if (!await this.isEnabled()) return false;\n checkExec(await this._exec('systemctl', ['--user', 'start', this._unitName]), 'systemctl start');\n return true;\n }\n}\n\nexport function systemdUnit(launch: DaemonLaunch): string {\n const { executable, args, env } = launch.foreground;\n const environment = Object.entries(env).map(([key, value]) => `Environment=${_systemdQuote(`${key}=${value}`)}\\n`).join('');\n return `[Unit]\nDescription=LinkRPC user hub\n\n[Service]\nType=simple\nExecStart=${[executable, ...args].map(_systemdQuote).join(' ')}\n${environment}Restart=on-failure\nRestartSec=2\n\n[Install]\nWantedBy=default.target\n`;\n}\n\n/**\n * Linux login autostart through an XDG autostart entry, for desktops without\n * a systemd user instance. Also used for the tray app.\n */\nexport class XdgAutostart implements AutostartManager {\n public readonly description = 'XDG autostart';\n\n constructor(\n private readonly _desktopFile: string,\n private readonly _displayName: string,\n ) { }\n\n public async isEnabled(): Promise<boolean> {\n return fs.existsSync(this._desktopFile);\n }\n\n public async enable(launch: DaemonLaunch): Promise<void> {\n this.enableCommand(launch.keepAlive);\n }\n\n public enableCommand(command: LaunchCommand): void {\n fs.mkdirSync(path.dirname(this._desktopFile), { recursive: true });\n fs.writeFileSync(this._desktopFile, xdgDesktopEntry(this._displayName, command));\n }\n\n public async disable(): Promise<void> {\n fs.rmSync(this._desktopFile, { force: true });\n }\n\n public async startManaged(): Promise<boolean> {\n return false;\n }\n}\n\nexport function xdgDesktopEntry(name: string, command: LaunchCommand): string {\n const env = Object.entries(command.env).map(([key, value]) => `${key}=${value}`);\n const argv = [...(env.length > 0 ? ['env', ...env] : []), command.executable, ...command.args];\n return `[Desktop Entry]\nType=Application\nName=${name}\nExec=${argv.map(_desktopExecQuote).join(' ')}\nTerminal=false\nNoDisplay=true\nX-GNOME-Autostart-enabled=true\n`;\n}\n\nfunction _systemdQuote(arg: string): string {\n const escaped = arg.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"').replace(/%/g, '%%').replace(/\\$/g, '$$$$');\n return `\"${escaped}\"`;\n}\n\n/** Desktop Entry `Exec` quoting, then string-value escaping of backslashes. */\nfunction _desktopExecQuote(arg: string): string {\n const percentEscaped = arg.replace(/%/g, '%%');\n if (/^[A-Za-z0-9_@%+=:,./-]+$/.test(percentEscaped)) return percentEscaped;\n const quoted = `\"${percentEscaped.replace(/([\"`$\\\\])/g, '\\\\$1')}\"`;\n return quoted.replace(/\\\\/g, '\\\\\\\\');\n}\n","import * as path from 'node:path';\nimport { checkExec, type DaemonLaunch, type Exec } from './launch';\nimport type { AutostartManager } from './autostart';\n\nconst RUN_KEY = 'HKCU\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run';\n/** Where Task Manager's \"Startup apps\" toggle records disabled entries. */\nconst STARTUP_APPROVED_KEY = 'HKCU\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\StartupApproved\\\\Run';\n\n/**\n * Windows login autostart through the per-user `Run` key: no elevation, and\n * listed under Task Manager's startup apps. The daemon runs under its own\n * keep-alive watchdog; console executables are hosted by a headless conhost so\n * that no window appears.\n */\nexport class WindowsRunKeyAutostart implements AutostartManager {\n public readonly description = 'Windows login (HKCU Run key)';\n private readonly _reg: string;\n private readonly _conhost: string;\n\n constructor(\n private readonly _valueName: string,\n private readonly _exec: Exec,\n systemRoot: string = process.env.SystemRoot ?? 'C:\\\\Windows',\n ) {\n this._reg = path.win32.join(systemRoot, 'System32', 'reg.exe');\n this._conhost = path.win32.join(systemRoot, 'System32', 'conhost.exe');\n }\n\n public async isEnabled(): Promise<boolean> {\n const registered = await this._exec(this._reg, ['query', RUN_KEY, '/v', this._valueName]);\n if (registered.code !== 0) return false;\n const approval = await this._exec(this._reg, ['query', STARTUP_APPROVED_KEY, '/v', this._valueName]);\n if (approval.code !== 0) return true;\n const flags = /REG_BINARY\\s+([0-9A-F]{2})/i.exec(approval.stdout)?.[1];\n return flags === undefined || (parseInt(flags, 16) & 1) === 0;\n }\n\n public async enable(launch: DaemonLaunch): Promise<void> {\n checkExec(\n await this._exec(this._reg, ['add', RUN_KEY, '/v', this._valueName, '/t', 'REG_SZ', '/d', this.commandLine(launch), '/f']),\n 'registering the login entry',\n );\n await this._exec(this._reg, ['delete', STARTUP_APPROVED_KEY, '/v', this._valueName, '/f']);\n }\n\n public async disable(): Promise<void> {\n await this._exec(this._reg, ['delete', RUN_KEY, '/v', this._valueName, '/f']);\n }\n\n public async startManaged(): Promise<boolean> {\n return false;\n }\n\n /** The `Run` value: keep-alive command line, windowless. */\n public commandLine(launch: DaemonLaunch): string {\n const { executable, args, env } = launch.keepAlive;\n if (Object.keys(env).length > 0) {\n throw new Error('Windows login entries cannot set environment variables; use a launch without env');\n }\n const command = [executable, ...args].map(quoteWindowsArg);\n return (launch.windowless ? command : [quoteWindowsArg(this._conhost), '--headless', ...command]).join(' ');\n }\n}\n\n/** Quote one argument for `CommandLineToArgvW`/MSVCRT parsing. */\nexport function quoteWindowsArg(arg: string): string {\n if (arg !== '' && !/[\\s\"]/.test(arg)) return arg;\n let quoted = '\"';\n let backslashes = 0;\n for (const char of arg) {\n if (char === '\\\\') {\n backslashes++;\n continue;\n }\n quoted += char === '\"' ? '\\\\'.repeat(backslashes * 2 + 1) + '\"' : '\\\\'.repeat(backslashes) + char;\n backslashes = 0;\n }\n return quoted + '\\\\'.repeat(backslashes * 2) + '\"';\n}\n","import * as os from 'node:os';\nimport * as path from 'node:path';\nimport type { HubHome } from '../paths';\nimport { type DaemonLaunch, type Exec, execCommand } from './launch';\nimport { LaunchdAutostart } from './launchd';\nimport { SystemdUserAutostart, XdgAutostart } from './linux';\nimport { WindowsRunKeyAutostart } from './windows';\n\n/**\n * Registers the daemon to start at user login. Enabling or disabling never\n * starts or stops a running daemon.\n */\nexport interface AutostartManager {\n /** Human-readable mechanism, e.g. \"systemd user service\". */\n readonly description: string;\n isEnabled(): Promise<boolean>;\n enable(launch: DaemonLaunch): Promise<void>;\n disable(): Promise<void>;\n /**\n * Start the daemon through the OS manager, so that it supervises this\n * instance too. Resolves `false` when the mechanism cannot (or is not\n * registered to) start it; the caller then starts it directly.\n */\n startManaged(): Promise<boolean>;\n}\n\nexport interface AutostartOptions {\n readonly home: HubHome;\n readonly platform?: NodeJS.Platform;\n readonly exec?: Exec;\n readonly homedir?: string;\n readonly env?: NodeJS.ProcessEnv;\n}\n\n/** The login-autostart mechanism of this platform. */\nexport async function createAutostartManager(options: AutostartOptions): Promise<AutostartManager> {\n const platform = options.platform ?? process.platform;\n const exec = options.exec ?? execCommand;\n const homedir = options.homedir ?? os.homedir();\n const env = options.env ?? process.env;\n const name = options.home.instanceName;\n if (platform === 'win32') return new WindowsRunKeyAutostart(name, exec);\n if (platform === 'darwin') {\n const label = `dev.hediet.${name}`;\n const uid = process.getuid?.() ?? 0;\n return new LaunchdAutostart(label, path.posix.join(homedir, 'Library', 'LaunchAgents', `${label}.plist`), exec, uid);\n }\n const configHome = env.XDG_CONFIG_HOME || path.posix.join(homedir, '.config');\n if ((await exec('systemctl', ['--user', 'show-environment'])).code === 0) {\n return new SystemdUserAutostart(`${name}.service`, path.posix.join(configHome, 'systemd', 'user', `${name}.service`), exec);\n }\n return new XdgAutostart(path.posix.join(configHome, 'autostart', `${name}.desktop`), 'LinkRPC Hub');\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { z } from 'zod';\n\n/**\n * How to reach one daemon endpoint. The daemon writes one file for\n * applications ({@link HubHome.discoveryFile}) and one for management\n * ({@link HubHome.managementFile}); both are private to the user.\n */\nexport const EndpointDiscoverySchema = z.object({\n version: z.literal(1),\n pid: z.number().int(),\n /** Named pipe (Windows) or Unix socket path. */\n endpoint: z.string().min(1),\n /** Absent when the endpoint requires no token. */\n token: z.string().min(1).optional(),\n});\nexport type EndpointDiscovery = z.infer<typeof EndpointDiscoverySchema>;\n\n/** The published endpoint, or `undefined` when absent or unreadable. */\nexport function readEndpointDiscovery(file: string): EndpointDiscovery | undefined {\n let text: string;\n try {\n text = fs.readFileSync(file, 'utf8');\n } catch {\n return undefined;\n }\n try {\n const parsed = EndpointDiscoverySchema.safeParse(JSON.parse(text));\n return parsed.success ? parsed.data : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Atomically write a JSON file readable only by the current user. */\nexport function writePrivateJson(file: string, value: unknown): void {\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });\n const tmp = `${file}.${process.pid}.tmp`;\n fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + '\\n', { mode: 0o600 });\n fs.renameSync(tmp, file);\n}\n","/**\n * The call-log query language, shared by the daemon (which filters) and UIs\n * (which build terms). Dependency-free so sandboxed renderers can bundle it.\n *\n * A query is a list of space-separated terms that must all match:\n * - `text`: case-insensitive substring of the method, caller, target,\n * principal, or error message. Quote terms with spaces: `\"no route\"`.\n * - `method:<glob>`: matches `service::interface::member` (the service is\n * empty for root-form calls); `*` matches any characters.\n * - `service:<name>`: the call came from or went to that configured daemon\n * service (e.g. `service:devtunnel`); case-insensitive, no wildcards.\n * - `-<term>` negates a term, e.g. `-method:hediet/devbox::*`.\n */\nimport type { CallRecord } from './callRecord';\n\n/** A call's method split at its parts. */\nexport interface CallTarget {\n /** Absent for root-form calls (`interface::member`). */\n readonly serviceId: string | undefined;\n readonly interfaceId: string | undefined;\n readonly member: string;\n}\n\nexport function callTargetOf(record: Pick<CallRecord, 'method' | 'serviceId'>): CallTarget {\n const { serviceId } = record;\n const rest = serviceId !== undefined && record.method.startsWith(`${serviceId}::`)\n ? record.method.slice(serviceId.length + 2)\n : record.method.replace(/^::/, '');\n const separator = rest.lastIndexOf('::');\n return separator < 0\n ? { serviceId, interfaceId: undefined, member: rest }\n : { serviceId, interfaceId: rest.slice(0, separator), member: rest.slice(separator + 2) };\n}\n\n/**\n * A `method:` glob for the given parts; omitted parts match anything, e.g.\n * `{ serviceId: 'a' }` → `a::*`, `{ interfaceId: 'i', member: 'm' }` → `*::i::m`.\n */\nexport function methodPattern(target: Partial<CallTarget>): string {\n const parts = [target.serviceId ?? '*', target.interfaceId ?? '*', target.member ?? '*'];\n while (parts.length > 1 && parts.at(-1) === '*' && parts.at(-2) === '*') parts.pop();\n return parts.join('::');\n}\n\n/** The term that excludes calls matching `methodPattern(target)`. */\nexport function excludeMethodTerm(target: Partial<CallTarget>): string {\n return `-method:${methodPattern(target)}`;\n}\n\n/** The term that limits the log to calls through a configured daemon service. */\nexport function serviceTerm(name: string): string {\n return `service:${name}`;\n}\n\ninterface Term {\n readonly negated: boolean;\n readonly test: (record: CallRecord) => boolean;\n}\n\nconst TERM = /(-?)(?:(method|service):)?(\"[^\"]*\"?|\\S+)/g;\n\nexport class CallQuery {\n public static parse(text: string): CallQuery {\n const terms: Term[] = [];\n for (const [, negation, qualifier, raw] of text.matchAll(TERM)) {\n const value = _unquote(raw!);\n if (value === '') continue;\n terms.push({\n negated: negation === '-',\n test: qualifier === 'method' ? _methodTest(value)\n : qualifier === 'service' ? _serviceTest(value.toLowerCase())\n : _textTest(value.toLowerCase()),\n });\n }\n return new CallQuery(terms);\n }\n\n /** `text` with `term` appended, unless an equal term is already present. */\n public static appendTerm(text: string, term: string): string {\n const existing = [...text.matchAll(TERM)].map(match => match[0]);\n return existing.includes(term) ? text : [text.trim(), term].filter(part => part !== '').join(' ');\n }\n\n private constructor(private readonly _terms: readonly Term[]) { }\n\n public matches(record: CallRecord): boolean {\n return this._terms.every(term => term.test(record) !== term.negated);\n }\n}\n\nfunction _textTest(needle: string): (record: CallRecord) => boolean {\n return record => [record.method, record.from.label, record.to?.label, record.principal, record.error?.message]\n .some(value => value?.toLowerCase().includes(needle));\n}\n\nfunction _serviceTest(name: string): (record: CallRecord) => boolean {\n return record => [record.from.service, record.to?.service].some(service => service?.toLowerCase() === name);\n}\n\nfunction _methodTest(glob: string): (record: CallRecord) => boolean {\n const escaped = glob.split('*').map(part => part.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')).join('.*');\n const pattern = new RegExp(`^${escaped}$`, 'i');\n return record => {\n const { serviceId, interfaceId, member } = callTargetOf(record);\n return pattern.test([serviceId ?? '', interfaceId ?? '', member].join('::'));\n };\n}\n\nfunction _unquote(raw: string): string {\n return raw.startsWith('\"') ? raw.slice(1, raw.endsWith('\"') && raw.length > 1 ? -1 : undefined) : raw;\n}\n","/**\n * The persisted call-log record and its filter. Schema-only (no Node.js APIs)\n * so management clients and UIs can share it.\n */\nimport { logLevelSchema } from '@hediet/linkrpc-infra/logging';\nimport { z } from 'zod';\nimport { CallQuery } from './callQuery';\n\n/** `linkrpc.logging` levels. A threshold records calls at or above it. */\nexport const CallLogLevelSchema = z.enum(logLevelSchema.options);\nexport type CallLogLevel = z.infer<typeof CallLogLevelSchema>;\n\n/**\n * The level of a recorded call: failures are `error`, requests `info`,\n * notifications `debug`, and stream frames reported apart from their request\n * `trace`. `warn` records the same calls as `error`.\n */\nexport const CallRecordLevelSchema = z.enum(['error', 'info', 'debug', 'trace']);\nexport type CallRecordLevel = z.infer<typeof CallRecordLevelSchema>;\n\n/** One side of a call at the hub: the port's friendly label and its transport. */\nexport const CallPeerSchema = z.object({\n /** The port's claimed prefix (e.g. `hediet/devbox`) or an edge id (`e12`). */\n label: z.string(),\n /** E.g. `named-pipe \\\\.\\pipe\\linkrpc-hub-user` or `websocket 10.0.0.2:51234`. */\n transport: z.string().optional(),\n /** The configured daemon service connected through this port, e.g. `devtunnel`. */\n service: z.string().optional(),\n});\nexport type CallPeer = z.infer<typeof CallPeerSchema>;\n\n/**\n * One NDJSON line. A call still in flight is written as `pending` and written\n * again under the same `id` when it settles; readers keep the newest record per id.\n */\nexport const CallRecordSchema = z.object({\n v: z.literal(1),\n id: z.string(),\n /** Start, epoch ms. */\n at: z.number(),\n level: CallRecordLevelSchema,\n kind: z.enum(['request', 'notification', 'stream']),\n status: z.enum(['pending', 'completed', 'failed', 'unroutable', 'dropped']),\n durationMs: z.number(),\n /** The wire method, e.g. `hediet/pc2/compute::linkrpc.compute::exec`. */\n method: z.string(),\n serviceId: z.string().optional(),\n /** Where the call entered the hub. */\n from: CallPeerSchema,\n /** Where the hub forwarded it; absent when the hub consumed or dropped it. */\n to: CallPeerSchema.optional(),\n /** `$hubrpc.principal` of a signed call; verified when the hub checks forwarded calls. */\n principal: z.string().optional(),\n error: z.object({ code: z.number(), message: z.string() }).optional(),\n /** UTF-8 size of the application params (without `$hubrpc*` meta). */\n paramsBytes: z.number().int().optional(),\n resultBytes: z.number().int().optional(),\n /** Redacted and truncated per the `callLog.payloads` policy; absent for `mode: \"none\"`. */\n params: z.unknown().optional(),\n result: z.unknown().optional(),\n /** Stream frames folded into this record (frames shortly after the request starts). */\n streamFrames: z.number().int().optional(),\n});\nexport type CallRecord = z.infer<typeof CallRecordSchema>;\n\nexport const CallFilterSchema = z.object({\n /** A {@link CallQuery}: space-separated terms, `-term` to exclude, `method:<glob>` for methods. */\n text: z.string().optional(),\n /** Only records at or above this level, e.g. `error` for failures. */\n minLevel: CallRecordLevelSchema.optional(),\n /** Start time bounds, epoch ms (inclusive). */\n since: z.number().optional(),\n until: z.number().optional(),\n});\nexport type CallFilter = z.infer<typeof CallFilterSchema>;\n\nconst SEVERITY: Readonly<Record<CallLogLevel, number>> = { trace: 0, debug: 1, info: 2, warn: 3, error: 4, off: 5 };\n\n/** Whether a record at `level` is recorded or shown at `threshold`. */\nexport function isCallLevelEnabled(level: CallRecordLevel, threshold: CallLogLevel): boolean {\n return SEVERITY[level] >= SEVERITY[threshold];\n}\n\n/** Parses `filter` once; the result tests records against it. */\nexport function createCallMatcher(filter: CallFilter): (record: CallRecord) => boolean {\n const query = filter.text ? CallQuery.parse(filter.text) : undefined;\n return record => {\n if (filter.minLevel !== undefined && !isCallLevelEnabled(record.level, filter.minLevel)) return false;\n if (filter.since !== undefined && record.at < filter.since) return false;\n if (filter.until !== undefined && record.at > filter.until) return false;\n return query?.matches(record) ?? true;\n };\n}\n","import { defineInterface, requestType } from '@hediet/linkrpc';\nimport { z } from 'zod';\nimport { CallFilterSchema, CallLogLevelSchema, CallRecordSchema } from './callLog/callRecord';\n\nexport const ServiceStateSchema = z.enum([\n /** `enabled: false` in the config. */\n 'disabled',\n /** Exited without a pending restart. */\n 'stopped',\n /** Spawned, waiting for readiness (hub connection or spawn). */\n 'starting',\n 'running',\n /** Exited; restarting after a delay. */\n 'backoff',\n 'stopping',\n /** Exited abnormally and the restart policy gave up. */\n 'failed',\n]);\nexport type ServiceState = z.infer<typeof ServiceStateSchema>;\n\nexport const ServiceStatusSchema = z.object({\n name: z.string(),\n description: z.string().optional(),\n /** Namespace the service may claim on the hub. */\n serviceId: z.string(),\n enabled: z.boolean(),\n state: ServiceStateSchema,\n /** Epoch ms of the last state change. */\n since: z.number(),\n pid: z.number().int().optional(),\n /** Open hub connections of this service. */\n connections: z.number().int(),\n /** Restarts since the service was (re)configured. */\n restarts: z.number().int(),\n lastExit: z.object({\n code: z.number().int().nullable(),\n signal: z.string().nullable(),\n at: z.number(),\n }).optional(),\n error: z.string().optional(),\n});\nexport type ServiceStatus = z.infer<typeof ServiceStatusSchema>;\n\nexport const DaemonStatusSchema = z.object({\n pid: z.number().int(),\n version: z.string(),\n startedAt: z.number(),\n /** Application endpoint (named pipe or Unix socket). */\n endpoint: z.string(),\n configFile: z.string(),\n logFile: z.string(),\n config: z.object({\n /** Revision of the applied config file. */\n revision: z.string().optional(),\n appliedAt: z.number().optional(),\n /** Why the current file is not applied; the previous config keeps running. */\n error: z.string().optional(),\n }),\n hub: z.object({\n startedAt: z.number(),\n listeners: z.array(z.object({ type: z.string(), address: z.string() })),\n error: z.string().optional(),\n }),\n callLog: z.object({\n level: CallLogLevelSchema,\n /** Directory of the NDJSON call-log files. */\n directory: z.string(),\n /** Where the log is served as `linkrpc.logging` while the hub runs. */\n serviceId: z.string().optional(),\n error: z.string().optional(),\n }),\n services: z.array(ServiceStatusSchema),\n});\nexport type DaemonStatus = z.infer<typeof DaemonStatusSchema>;\n\nexport const LogLineSchema = z.object({\n at: z.number(),\n stream: z.enum(['stdout', 'stderr', 'daemon']),\n text: z.string(),\n});\nexport type LogLine = z.infer<typeof LogLineSchema>;\n\nexport const ConfigDocumentSchema = z.object({\n path: z.string(),\n text: z.string(),\n /** Opaque content revision; pass it back to `setConfig`. */\n revision: z.string(),\n});\nexport type ConfigDocument = z.infer<typeof ConfigDocumentSchema>;\n\n/** Management API of the local hub daemon, served on its management endpoint. */\nexport const hubDaemonManagementInterface = defineInterface(\n { id: 'linkrpc.hubDaemon', description: 'Manage the local LinkRPC hub daemon.' },\n {\n getStatus: requestType(z.object({}), DaemonStatusSchema),\n /** Streams the status on every change until cancelled. */\n watchStatus: requestType(z.object({}), z.object({})).withStream({ server: DaemonStatusSchema }),\n /** Re-read the config file and apply what changed. */\n reloadConfig: requestType(z.object({}), DaemonStatusSchema),\n getConfig: requestType(z.object({}), ConfigDocumentSchema),\n /** Validate, write, and apply; rejects when the file changed since `expectedRevision`. */\n setConfig: requestType(\n z.object({ text: z.string(), expectedRevision: z.string() }),\n z.object({ revision: z.string() }),\n ),\n /** Persistently enable or disable a service in the config file. */\n setServiceEnabled: requestType(z.object({ name: z.string(), enabled: z.boolean() }), z.object({})),\n restartService: requestType(z.object({ name: z.string() }), z.object({})),\n getServiceLogs: requestType(\n z.object({ name: z.string(), limit: z.number().int().positive().optional() }),\n z.object({ lines: z.array(LogLineSchema) }),\n ),\n /** Persist `callLog.level` in the config file and apply it (`off` stops recording). */\n setCallLogLevel: requestType(z.object({ level: CallLogLevelSchema }), z.object({})),\n /** Read recorded calls from the call-log files, newest first. */\n queryCalls: requestType(\n z.object({ filter: CallFilterSchema.optional(), limit: z.number().int().positive().max(5_000).optional() }),\n z.object({ calls: z.array(CallRecordSchema), truncated: z.boolean() }),\n ),\n /** Streams matching records as they are written, until cancelled. */\n watchCalls: requestType(z.object({ filter: CallFilterSchema.optional() }), z.object({}))\n .withStream({ server: CallRecordSchema }),\n /** Stop all services and exit. Intentional: autostart managers do not restart it. */\n shutdown: requestType(z.object({}), z.object({})),\n },\n);\n","import { createHash, randomUUID } from 'node:crypto';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\n\n/** Overrides every hub location with one directory (tests, portable installs). */\nexport const LINKRPC_HUB_HOME_VAR = 'LINKRPC_HUB_HOME';\n\n/** Unix domain socket paths longer than this fail to bind on macOS. */\nconst MAX_UNIX_SOCKET_PATH = 103;\n\n/**\n * Where one per-user hub keeps its configuration, state, and local sockets.\n * All daemon, CLI, and desktop processes of a user resolve the same home.\n */\nexport class HubHome {\n /**\n * The per-user default:\n * - Windows: `%LOCALAPPDATA%\\linkrpc\\hub`\n * - macOS: `~/Library/Application Support/linkrpc/hub`\n * - Linux: `$XDG_CONFIG_HOME/linkrpc/hub` (config), `$XDG_STATE_HOME/linkrpc/hub`\n * (state), `$XDG_RUNTIME_DIR/linkrpc-hub` (sockets)\n *\n * `LINKRPC_HUB_HOME` places everything under one directory instead.\n */\n public static resolve(\n env: NodeJS.ProcessEnv = process.env,\n platform: NodeJS.Platform = process.platform,\n homedir: string = os.homedir(),\n ): HubHome {\n const p = platform === 'win32' ? path.win32 : path.posix;\n const override = env[LINKRPC_HUB_HOME_VAR];\n if (override) return HubHome.at(override, platform);\n if (platform === 'win32') {\n const base = p.join(env.LOCALAPPDATA ?? p.join(homedir, 'AppData', 'Local'), 'linkrpc', 'hub');\n return new HubHome(p.join(base, 'config.json'), base, p.join(base, 'run'), platform, undefined);\n }\n if (platform === 'darwin') {\n const base = p.join(homedir, 'Library', 'Application Support', 'linkrpc', 'hub');\n return new HubHome(p.join(base, 'config.json'), base, p.join(base, 'run'), platform, undefined);\n }\n const configDir = p.join(env.XDG_CONFIG_HOME || p.join(homedir, '.config'), 'linkrpc', 'hub');\n const stateDir = p.join(env.XDG_STATE_HOME || p.join(homedir, '.local', 'state'), 'linkrpc', 'hub');\n const runtimeDir = env.XDG_RUNTIME_DIR ? p.join(env.XDG_RUNTIME_DIR, 'linkrpc-hub') : p.join(stateDir, 'run');\n return new HubHome(p.join(configDir, 'config.json'), stateDir, runtimeDir, platform, undefined);\n }\n\n /** A custom home with config, state, and sockets all below `dir`. */\n public static at(dir: string, platform: NodeJS.Platform = process.platform): HubHome {\n const p = platform === 'win32' ? path.win32 : path.posix;\n return new HubHome(p.join(dir, 'config.json'), dir, p.join(dir, 'run'), platform, dir);\n }\n\n private constructor(\n public readonly configFile: string,\n public readonly stateDir: string,\n /** Private (0700) directory for Unix sockets. Unused on Windows. */\n public readonly runtimeDir: string,\n private readonly _platform: NodeJS.Platform,\n /** The directory of a custom home (`--home`, `LINKRPC_HUB_HOME`); `undefined` for the default. */\n public readonly customDir: string | undefined,\n ) { }\n\n private get _path(): path.PlatformPath {\n return this._platform === 'win32' ? path.win32 : path.posix;\n }\n\n public get configDir(): string {\n return this._path.dirname(this.configFile);\n }\n\n /** JSON Schema written next to the config for editor validation. */\n public get configSchemaFile(): string {\n return this._path.join(this.configDir, 'config.schema.json');\n }\n\n /** Endpoint + token for applications; present while the daemon runs. */\n public get discoveryFile(): string {\n return this._path.join(this.stateDir, 'hub.json');\n }\n\n /** Endpoint + token for the management API; present while the daemon runs. */\n public get managementFile(): string {\n return this._path.join(this.stateDir, 'management.json');\n }\n\n public get logFile(): string {\n return this._path.join(this.stateDir, 'daemon.log');\n }\n\n /** NDJSON call-log files (`callLog` in the config). */\n public get callLogDir(): string {\n return this._path.join(this.stateDir, 'calls');\n }\n\n /** Persistent managed identities of services. */\n public get identityDir(): string {\n return this._path.join(this.stateDir, 'identities');\n }\n\n /** Distinguishes OS registrations (autostart entries) of custom homes from the default one. */\n public get instanceName(): string {\n if (this.customDir === undefined) return 'linkrpc-hub';\n return `linkrpc-hub-${createHash('sha256').update(this.customDir).digest('hex').slice(0, 8)}`;\n }\n\n /**\n * The fixed application endpoint unless `localEndpoint.path` overrides it.\n * Windows pipes share one machine-wide namespace, so the name includes the\n * user; Unix sockets live in the user's private runtime directory.\n */\n public get defaultAppEndpoint(): string {\n if (this._platform === 'win32') {\n const user = os.userInfo().username.replace(/[^A-Za-z0-9._-]/g, '_');\n return `\\\\\\\\.\\\\pipe\\\\${this.instanceName}-${user}`;\n }\n return this._unixSocketPath('hub.sock');\n }\n\n /**\n * The single-instance lock endpoint. Fixed per home so that a second daemon\n * for the same home fails to bind it.\n */\n public get lockEndpoint(): string {\n if (this._platform === 'win32') {\n const key = createHash('sha256').update(this.stateDir.toLowerCase()).digest('hex').slice(0, 24);\n return `\\\\\\\\.\\\\pipe\\\\linkrpc-hub-lock-${key}`;\n }\n return this._unixSocketPath('daemon.lock');\n }\n\n /**\n * A fresh endpoint for a daemon listener. Windows pipe names are random\n * (pipes are a global namespace); Unix sockets live in the private runtime dir.\n */\n public allocEndpoint(name: string): string {\n if (this._platform === 'win32') return `\\\\\\\\.\\\\pipe\\\\linkrpc-hub-${name}-${randomUUID()}`;\n return this._unixSocketPath(`${name}.sock`);\n }\n\n private _unixSocketPath(name: string): string {\n const socketPath = this._path.join(this.runtimeDir, name);\n if (Buffer.byteLength(socketPath) > MAX_UNIX_SOCKET_PATH) {\n throw new Error(`socket path is too long for this platform: ${socketPath}`);\n }\n return socketPath;\n }\n}\n","import { defineInterface, requestType } from '@hediet/linkrpc';\nimport {\n ConsoleTemplate,\n consoleAttachParamsSchema,\n consoleClientMessageSchema,\n consoleExitSchema,\n consoleModeSchema,\n consoleServerMessageSchema,\n} from '@hediet/linkrpc-infra/console';\nimport { z } from 'zod';\nimport { ServiceStatusSchema } from './managementInterface';\n\nexport const endpointAddress = z.object({\n namespace: z.string().min(1),\n id: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).default('main'),\n});\nexport const processSource = z.object({\n kind: z.literal('process'),\n command: z.array(z.string().min(1)).min(1),\n cwd: z.string().optional(),\n env: z.record(z.string(), z.string()).default({}),\n rpc: z.boolean().default(true),\n /** Run in a pseudoterminal: stdout and stderr merge, and attachments can resize it. */\n tty: z.boolean().default(false),\n readiness: z.enum(['connected', 'spawned']).default('connected'),\n});\nexport const endpointDefinition = endpointAddress.extend({\n source: z.discriminatedUnion('kind', [\n processSource,\n z.object({ kind: z.literal('connection'), endpoint: z.string().min(1) }),\n ]),\n persistent: z.boolean().default(false),\n restart: z.enum(['never', 'on-failure', 'always']).default('never'),\n});\nexport type EndpointDefinition = z.infer<typeof endpointDefinition>;\nexport type EndpointAddress = z.infer<typeof endpointAddress>;\nexport const endpointStatus = endpointAddress.extend({\n instanceId: z.string(),\n serviceId: z.string(),\n persistent: z.boolean(),\n restart: endpointDefinition.shape.restart,\n desired: z.boolean(),\n /** Owned by a `run` call that stops and removes it when the call ends. */\n owned: z.boolean(),\n sourceKind: z.enum(['process', 'connection']),\n rpc: z.boolean(),\n /** Process endpoints have a console, reachable through the `consoles` template instance. */\n console: z.object({ mode: consoleModeSchema }).optional(),\n runtime: ServiceStatusSchema,\n});\nexport type EndpointStatus = z.infer<typeof endpointStatus>;\n\nconst replace = z.boolean().optional()\n .describe('Stop and remove an existing endpoint with the same address first, including persistent and owned ones.');\nexport const runParams = z.object({\n definition: endpointDefinition.extend({ source: processSource }),\n /** The call owns the endpoint: ending it (cancellation, disconnect, or completion) stops and removes it. */\n owner: z.boolean().optional(),\n replace,\n console: consoleAttachParamsSchema,\n});\nexport type RunParams = z.infer<typeof runParams>;\nexport const runEvent = z.union([\n consoleServerMessageSchema,\n z.object({ t: z.literal('status'), status: endpointStatus }),\n]);\nexport type RunEvent = z.infer<typeof runEvent>;\nexport const watchEvent = z.discriminatedUnion('t', [\n z.object({ t: z.literal('status'), status: endpointStatus }),\n z.object({ t: z.literal('removed') }),\n]);\nexport type WatchEvent = z.infer<typeof watchEvent>;\n\n/** Console template parameters: the endpoint whose process console to use. */\nexport const consoleAddress = z.object({ namespace: z.string().min(1), id: z.string().min(1) });\n\nexport const managedEndpointsInterface = defineInterface({\n id: 'linkrpc.managedEndpoints',\n description: 'Manage named processes and connections on this execution host. Starting endpoints executes with this host user\\'s privileges. '\n + 'Process consoles are served by the `consoles` instance of the `linkrpc.console.v1` template, with the endpoint address as params.',\n}, {\n consoles: ConsoleTemplate({ params: consoleAddress }).mapMembers({ info: 'consoleInfo', attach: 'attachConsole' }),\n info: requestType(z.object({}), z.object({ hostname: z.string(), platform: z.string(), cwd: z.string(), servicePrefix: z.string() })),\n list: requestType(z.object({ namespace: z.string().optional() }), z.array(endpointStatus)),\n create: requestType(endpointDefinition.extend({ replace }), endpointStatus),\n run: requestType(runParams, z.object({ exit: z.nullable(consoleExitSchema) }), {\n description: 'Create a process endpoint and attach to its console in one call. The stream carries the '\n + '`linkrpc.console` attach protocol plus `status` events. Without `owner`, cancelling detaches.',\n }).withStream({ client: consoleClientMessageSchema, server: runEvent }),\n watch: requestType(endpointAddress, z.object({})).withStream({ server: watchEvent }),\n start: requestType(endpointAddress, endpointStatus),\n stop: requestType(endpointAddress, z.object({})),\n remove: requestType(endpointAddress, z.object({})),\n configure: requestType(endpointAddress.extend({\n persistent: z.boolean().optional(),\n restart: z.enum(['never', 'on-failure', 'always']).optional(),\n }), endpointStatus),\n});\n","/**\n * Client entry point: connect applications and management tools to the\n * user's local hub daemon. Free of hub-server dependencies.\n */\nimport type { InterfaceClient } from '@hediet/linkrpc';\nimport { connectToHub, LINKRPC_ENDPOINT_VAR, type ConnectToHubOptions, type HubClientHandle } from '@hediet/linkrpc/node';\nimport { readEndpointDiscovery } from './discovery';\nimport { hubDaemonManagementInterface } from './managementInterface';\nimport { HubHome } from './paths';\n\nexport * from './managementInterface';\nexport * from './callLog/callRecord';\nexport * from './callLog/callQuery';\nexport * from './endpointInterface';\nexport { type EndpointDiscovery, readEndpointDiscovery } from './discovery';\nexport { HubHome, LINKRPC_HUB_HOME_VAR } from './paths';\n\nexport interface ConnectToLocalHubOptions extends ConnectToHubOptions {\n readonly home?: HubHome;\n}\n\n/**\n * Connect to the local hub. Resolution order: explicit `endpoint`,\n * `LINKRPC_ENDPOINT` (set for services the daemon manages), then the running\n * daemon's discovery file.\n */\nexport async function connectToLocalHub(options: ConnectToLocalHubOptions = {}): Promise<HubClientHandle> {\n const { home, ...connectOptions } = options;\n if (connectOptions.endpoint !== undefined || process.env[LINKRPC_ENDPOINT_VAR]) {\n return connectToHub(connectOptions);\n }\n const resolvedHome = home ?? HubHome.resolve();\n const discovery = readEndpointDiscovery(resolvedHome.discoveryFile);\n if (!discovery) {\n throw new Error(`The local LinkRPC hub is not running (no ${resolvedHome.discoveryFile}).`);\n }\n return connectToHub({ ...connectOptions, endpoint: discovery.endpoint, token: discovery.token ?? '' });\n}\n\nexport interface HubManagementConnection {\n readonly management: InterfaceClient<typeof hubDaemonManagementInterface>;\n onClose(listener: () => void): { dispose(): void; };\n close(): void;\n}\n\n/** Connect to the daemon's management API. Rejects when the daemon is not running. */\nexport async function connectToHubManagement(home: HubHome = HubHome.resolve()): Promise<HubManagementConnection> {\n const discovery = readEndpointDiscovery(home.managementFile);\n if (!discovery) {\n throw new Error(`The local LinkRPC hub is not running (no ${home.managementFile}).`);\n }\n const handle = await connectToHub({ endpoint: discovery.endpoint, token: discovery.token ?? '' });\n return {\n management: handle.connection.get(hubDaemonManagementInterface),\n onClose: listener => handle.onClose(listener),\n close: () => handle.close(),\n };\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'use strict';\n/**\n * Creates a JSON scanner on the given text.\n * If ignoreTrivia is set, whitespaces or comments are ignored.\n */\nexport function createScanner(text, ignoreTrivia = false) {\n const len = text.length;\n let pos = 0, value = '', tokenOffset = 0, token = 16 /* SyntaxKind.Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* ScanError.None */;\n function scanHexDigits(count, exact) {\n let digits = 0;\n let value = 0;\n while (digits < count || !exact) {\n let ch = text.charCodeAt(pos);\n if (ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */) {\n value = value * 16 + ch - 48 /* CharacterCodes._0 */;\n }\n else if (ch >= 65 /* CharacterCodes.A */ && ch <= 70 /* CharacterCodes.F */) {\n value = value * 16 + ch - 65 /* CharacterCodes.A */ + 10;\n }\n else if (ch >= 97 /* CharacterCodes.a */ && ch <= 102 /* CharacterCodes.f */) {\n value = value * 16 + ch - 97 /* CharacterCodes.a */ + 10;\n }\n else {\n break;\n }\n pos++;\n digits++;\n }\n if (digits < count) {\n value = -1;\n }\n return value;\n }\n function setPosition(newPosition) {\n pos = newPosition;\n value = '';\n tokenOffset = 0;\n token = 16 /* SyntaxKind.Unknown */;\n scanError = 0 /* ScanError.None */;\n }\n function scanNumber() {\n let start = pos;\n if (text.charCodeAt(pos) === 48 /* CharacterCodes._0 */) {\n pos++;\n }\n else {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n }\n if (pos < text.length && text.charCodeAt(pos) === 46 /* CharacterCodes.dot */) {\n pos++;\n if (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n }\n else {\n scanError = 3 /* ScanError.UnexpectedEndOfNumber */;\n return text.substring(start, pos);\n }\n }\n let end = pos;\n if (pos < text.length && (text.charCodeAt(pos) === 69 /* CharacterCodes.E */ || text.charCodeAt(pos) === 101 /* CharacterCodes.e */)) {\n pos++;\n if (pos < text.length && text.charCodeAt(pos) === 43 /* CharacterCodes.plus */ || text.charCodeAt(pos) === 45 /* CharacterCodes.minus */) {\n pos++;\n }\n if (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n end = pos;\n }\n else {\n scanError = 3 /* ScanError.UnexpectedEndOfNumber */;\n }\n }\n return text.substring(start, end);\n }\n function scanString() {\n let result = '', start = pos;\n while (true) {\n if (pos >= len) {\n result += text.substring(start, pos);\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n const ch = text.charCodeAt(pos);\n if (ch === 34 /* CharacterCodes.doubleQuote */) {\n result += text.substring(start, pos);\n pos++;\n break;\n }\n if (ch === 92 /* CharacterCodes.backslash */) {\n result += text.substring(start, pos);\n pos++;\n if (pos >= len) {\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n const ch2 = text.charCodeAt(pos++);\n switch (ch2) {\n case 34 /* CharacterCodes.doubleQuote */:\n result += '\\\"';\n break;\n case 92 /* CharacterCodes.backslash */:\n result += '\\\\';\n break;\n case 47 /* CharacterCodes.slash */:\n result += '/';\n break;\n case 98 /* CharacterCodes.b */:\n result += '\\b';\n break;\n case 102 /* CharacterCodes.f */:\n result += '\\f';\n break;\n case 110 /* CharacterCodes.n */:\n result += '\\n';\n break;\n case 114 /* CharacterCodes.r */:\n result += '\\r';\n break;\n case 116 /* CharacterCodes.t */:\n result += '\\t';\n break;\n case 117 /* CharacterCodes.u */:\n const ch3 = scanHexDigits(4, true);\n if (ch3 >= 0) {\n result += String.fromCharCode(ch3);\n }\n else {\n scanError = 4 /* ScanError.InvalidUnicode */;\n }\n break;\n default:\n scanError = 5 /* ScanError.InvalidEscapeCharacter */;\n }\n start = pos;\n continue;\n }\n if (ch >= 0 && ch <= 0x1f) {\n if (isLineBreak(ch)) {\n result += text.substring(start, pos);\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n else {\n scanError = 6 /* ScanError.InvalidCharacter */;\n // mark as error but continue with string\n }\n }\n pos++;\n }\n return result;\n }\n function scanNext() {\n value = '';\n scanError = 0 /* ScanError.None */;\n tokenOffset = pos;\n lineStartOffset = lineNumber;\n prevTokenLineStartOffset = tokenLineStartOffset;\n if (pos >= len) {\n // at the end\n tokenOffset = len;\n return token = 17 /* SyntaxKind.EOF */;\n }\n let code = text.charCodeAt(pos);\n // trivia: whitespace\n if (isWhiteSpace(code)) {\n do {\n pos++;\n value += String.fromCharCode(code);\n code = text.charCodeAt(pos);\n } while (isWhiteSpace(code));\n return token = 15 /* SyntaxKind.Trivia */;\n }\n // trivia: newlines\n if (isLineBreak(code)) {\n pos++;\n value += String.fromCharCode(code);\n if (code === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) {\n pos++;\n value += '\\n';\n }\n lineNumber++;\n tokenLineStartOffset = pos;\n return token = 14 /* SyntaxKind.LineBreakTrivia */;\n }\n switch (code) {\n // tokens: []{}:,\n case 123 /* CharacterCodes.openBrace */:\n pos++;\n return token = 1 /* SyntaxKind.OpenBraceToken */;\n case 125 /* CharacterCodes.closeBrace */:\n pos++;\n return token = 2 /* SyntaxKind.CloseBraceToken */;\n case 91 /* CharacterCodes.openBracket */:\n pos++;\n return token = 3 /* SyntaxKind.OpenBracketToken */;\n case 93 /* CharacterCodes.closeBracket */:\n pos++;\n return token = 4 /* SyntaxKind.CloseBracketToken */;\n case 58 /* CharacterCodes.colon */:\n pos++;\n return token = 6 /* SyntaxKind.ColonToken */;\n case 44 /* CharacterCodes.comma */:\n pos++;\n return token = 5 /* SyntaxKind.CommaToken */;\n // strings\n case 34 /* CharacterCodes.doubleQuote */:\n pos++;\n value = scanString();\n return token = 10 /* SyntaxKind.StringLiteral */;\n // comments\n case 47 /* CharacterCodes.slash */:\n const start = pos - 1;\n // Single-line comment\n if (text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) {\n pos += 2;\n while (pos < len) {\n if (isLineBreak(text.charCodeAt(pos))) {\n break;\n }\n pos++;\n }\n value = text.substring(start, pos);\n return token = 12 /* SyntaxKind.LineCommentTrivia */;\n }\n // Multi-line comment\n if (text.charCodeAt(pos + 1) === 42 /* CharacterCodes.asterisk */) {\n pos += 2;\n const safeLength = len - 1; // For lookahead.\n let commentClosed = false;\n while (pos < safeLength) {\n const ch = text.charCodeAt(pos);\n if (ch === 42 /* CharacterCodes.asterisk */ && text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) {\n pos += 2;\n commentClosed = true;\n break;\n }\n pos++;\n if (isLineBreak(ch)) {\n if (ch === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) {\n pos++;\n }\n lineNumber++;\n tokenLineStartOffset = pos;\n }\n }\n if (!commentClosed) {\n pos++;\n scanError = 1 /* ScanError.UnexpectedEndOfComment */;\n }\n value = text.substring(start, pos);\n return token = 13 /* SyntaxKind.BlockCommentTrivia */;\n }\n // just a single slash\n value += String.fromCharCode(code);\n pos++;\n return token = 16 /* SyntaxKind.Unknown */;\n // numbers\n case 45 /* CharacterCodes.minus */:\n value += String.fromCharCode(code);\n pos++;\n if (pos === len || !isDigit(text.charCodeAt(pos))) {\n return token = 16 /* SyntaxKind.Unknown */;\n }\n // found a minus, followed by a number so\n // we fall through to proceed with scanning\n // numbers\n case 48 /* CharacterCodes._0 */:\n case 49 /* CharacterCodes._1 */:\n case 50 /* CharacterCodes._2 */:\n case 51 /* CharacterCodes._3 */:\n case 52 /* CharacterCodes._4 */:\n case 53 /* CharacterCodes._5 */:\n case 54 /* CharacterCodes._6 */:\n case 55 /* CharacterCodes._7 */:\n case 56 /* CharacterCodes._8 */:\n case 57 /* CharacterCodes._9 */:\n value += scanNumber();\n return token = 11 /* SyntaxKind.NumericLiteral */;\n // literals and unknown symbols\n default:\n // is a literal? Read the full word.\n while (pos < len && isUnknownContentCharacter(code)) {\n pos++;\n code = text.charCodeAt(pos);\n }\n if (tokenOffset !== pos) {\n value = text.substring(tokenOffset, pos);\n // keywords: true, false, null\n switch (value) {\n case 'true': return token = 8 /* SyntaxKind.TrueKeyword */;\n case 'false': return token = 9 /* SyntaxKind.FalseKeyword */;\n case 'null': return token = 7 /* SyntaxKind.NullKeyword */;\n }\n return token = 16 /* SyntaxKind.Unknown */;\n }\n // some\n value += String.fromCharCode(code);\n pos++;\n return token = 16 /* SyntaxKind.Unknown */;\n }\n }\n function isUnknownContentCharacter(code) {\n if (isWhiteSpace(code) || isLineBreak(code)) {\n return false;\n }\n switch (code) {\n case 125 /* CharacterCodes.closeBrace */:\n case 93 /* CharacterCodes.closeBracket */:\n case 123 /* CharacterCodes.openBrace */:\n case 91 /* CharacterCodes.openBracket */:\n case 34 /* CharacterCodes.doubleQuote */:\n case 58 /* CharacterCodes.colon */:\n case 44 /* CharacterCodes.comma */:\n case 47 /* CharacterCodes.slash */:\n return false;\n }\n return true;\n }\n function scanNextNonTrivia() {\n let result;\n do {\n result = scanNext();\n } while (result >= 12 /* SyntaxKind.LineCommentTrivia */ && result <= 15 /* SyntaxKind.Trivia */);\n return result;\n }\n return {\n setPosition: setPosition,\n getPosition: () => pos,\n scan: ignoreTrivia ? scanNextNonTrivia : scanNext,\n getToken: () => token,\n getTokenValue: () => value,\n getTokenOffset: () => tokenOffset,\n getTokenLength: () => pos - tokenOffset,\n getTokenStartLine: () => lineStartOffset,\n getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset,\n getTokenError: () => scanError,\n };\n}\nfunction isWhiteSpace(ch) {\n return ch === 32 /* CharacterCodes.space */ || ch === 9 /* CharacterCodes.tab */;\n}\nfunction isLineBreak(ch) {\n return ch === 10 /* CharacterCodes.lineFeed */ || ch === 13 /* CharacterCodes.carriageReturn */;\n}\nfunction isDigit(ch) {\n return ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */;\n}\nvar CharacterCodes;\n(function (CharacterCodes) {\n CharacterCodes[CharacterCodes[\"lineFeed\"] = 10] = \"lineFeed\";\n CharacterCodes[CharacterCodes[\"carriageReturn\"] = 13] = \"carriageReturn\";\n CharacterCodes[CharacterCodes[\"space\"] = 32] = \"space\";\n CharacterCodes[CharacterCodes[\"_0\"] = 48] = \"_0\";\n CharacterCodes[CharacterCodes[\"_1\"] = 49] = \"_1\";\n CharacterCodes[CharacterCodes[\"_2\"] = 50] = \"_2\";\n CharacterCodes[CharacterCodes[\"_3\"] = 51] = \"_3\";\n CharacterCodes[CharacterCodes[\"_4\"] = 52] = \"_4\";\n CharacterCodes[CharacterCodes[\"_5\"] = 53] = \"_5\";\n CharacterCodes[CharacterCodes[\"_6\"] = 54] = \"_6\";\n CharacterCodes[CharacterCodes[\"_7\"] = 55] = \"_7\";\n CharacterCodes[CharacterCodes[\"_8\"] = 56] = \"_8\";\n CharacterCodes[CharacterCodes[\"_9\"] = 57] = \"_9\";\n CharacterCodes[CharacterCodes[\"a\"] = 97] = \"a\";\n CharacterCodes[CharacterCodes[\"b\"] = 98] = \"b\";\n CharacterCodes[CharacterCodes[\"c\"] = 99] = \"c\";\n CharacterCodes[CharacterCodes[\"d\"] = 100] = \"d\";\n CharacterCodes[CharacterCodes[\"e\"] = 101] = \"e\";\n CharacterCodes[CharacterCodes[\"f\"] = 102] = \"f\";\n CharacterCodes[CharacterCodes[\"g\"] = 103] = \"g\";\n CharacterCodes[CharacterCodes[\"h\"] = 104] = \"h\";\n CharacterCodes[CharacterCodes[\"i\"] = 105] = \"i\";\n CharacterCodes[CharacterCodes[\"j\"] = 106] = \"j\";\n CharacterCodes[CharacterCodes[\"k\"] = 107] = \"k\";\n CharacterCodes[CharacterCodes[\"l\"] = 108] = \"l\";\n CharacterCodes[CharacterCodes[\"m\"] = 109] = \"m\";\n CharacterCodes[CharacterCodes[\"n\"] = 110] = \"n\";\n CharacterCodes[CharacterCodes[\"o\"] = 111] = \"o\";\n CharacterCodes[CharacterCodes[\"p\"] = 112] = \"p\";\n CharacterCodes[CharacterCodes[\"q\"] = 113] = \"q\";\n CharacterCodes[CharacterCodes[\"r\"] = 114] = \"r\";\n CharacterCodes[CharacterCodes[\"s\"] = 115] = \"s\";\n CharacterCodes[CharacterCodes[\"t\"] = 116] = \"t\";\n CharacterCodes[CharacterCodes[\"u\"] = 117] = \"u\";\n CharacterCodes[CharacterCodes[\"v\"] = 118] = \"v\";\n CharacterCodes[CharacterCodes[\"w\"] = 119] = \"w\";\n CharacterCodes[CharacterCodes[\"x\"] = 120] = \"x\";\n CharacterCodes[CharacterCodes[\"y\"] = 121] = \"y\";\n CharacterCodes[CharacterCodes[\"z\"] = 122] = \"z\";\n CharacterCodes[CharacterCodes[\"A\"] = 65] = \"A\";\n CharacterCodes[CharacterCodes[\"B\"] = 66] = \"B\";\n CharacterCodes[CharacterCodes[\"C\"] = 67] = \"C\";\n CharacterCodes[CharacterCodes[\"D\"] = 68] = \"D\";\n CharacterCodes[CharacterCodes[\"E\"] = 69] = \"E\";\n CharacterCodes[CharacterCodes[\"F\"] = 70] = \"F\";\n CharacterCodes[CharacterCodes[\"G\"] = 71] = \"G\";\n CharacterCodes[CharacterCodes[\"H\"] = 72] = \"H\";\n CharacterCodes[CharacterCodes[\"I\"] = 73] = \"I\";\n CharacterCodes[CharacterCodes[\"J\"] = 74] = \"J\";\n CharacterCodes[CharacterCodes[\"K\"] = 75] = \"K\";\n CharacterCodes[CharacterCodes[\"L\"] = 76] = \"L\";\n CharacterCodes[CharacterCodes[\"M\"] = 77] = \"M\";\n CharacterCodes[CharacterCodes[\"N\"] = 78] = \"N\";\n CharacterCodes[CharacterCodes[\"O\"] = 79] = \"O\";\n CharacterCodes[CharacterCodes[\"P\"] = 80] = \"P\";\n CharacterCodes[CharacterCodes[\"Q\"] = 81] = \"Q\";\n CharacterCodes[CharacterCodes[\"R\"] = 82] = \"R\";\n CharacterCodes[CharacterCodes[\"S\"] = 83] = \"S\";\n CharacterCodes[CharacterCodes[\"T\"] = 84] = \"T\";\n CharacterCodes[CharacterCodes[\"U\"] = 85] = \"U\";\n CharacterCodes[CharacterCodes[\"V\"] = 86] = \"V\";\n CharacterCodes[CharacterCodes[\"W\"] = 87] = \"W\";\n CharacterCodes[CharacterCodes[\"X\"] = 88] = \"X\";\n CharacterCodes[CharacterCodes[\"Y\"] = 89] = \"Y\";\n CharacterCodes[CharacterCodes[\"Z\"] = 90] = \"Z\";\n CharacterCodes[CharacterCodes[\"asterisk\"] = 42] = \"asterisk\";\n CharacterCodes[CharacterCodes[\"backslash\"] = 92] = \"backslash\";\n CharacterCodes[CharacterCodes[\"closeBrace\"] = 125] = \"closeBrace\";\n CharacterCodes[CharacterCodes[\"closeBracket\"] = 93] = \"closeBracket\";\n CharacterCodes[CharacterCodes[\"colon\"] = 58] = \"colon\";\n CharacterCodes[CharacterCodes[\"comma\"] = 44] = \"comma\";\n CharacterCodes[CharacterCodes[\"dot\"] = 46] = \"dot\";\n CharacterCodes[CharacterCodes[\"doubleQuote\"] = 34] = \"doubleQuote\";\n CharacterCodes[CharacterCodes[\"minus\"] = 45] = \"minus\";\n CharacterCodes[CharacterCodes[\"openBrace\"] = 123] = \"openBrace\";\n CharacterCodes[CharacterCodes[\"openBracket\"] = 91] = \"openBracket\";\n CharacterCodes[CharacterCodes[\"plus\"] = 43] = \"plus\";\n CharacterCodes[CharacterCodes[\"slash\"] = 47] = \"slash\";\n CharacterCodes[CharacterCodes[\"formFeed\"] = 12] = \"formFeed\";\n CharacterCodes[CharacterCodes[\"tab\"] = 9] = \"tab\";\n})(CharacterCodes || (CharacterCodes = {}));\n","export const cachedSpaces = new Array(20).fill(0).map((_, index) => {\n return ' '.repeat(index);\n});\nconst maxCachedValues = 200;\nexport const cachedBreakLinesWithSpaces = {\n ' ': {\n '\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\n' + ' '.repeat(index);\n }),\n '\\r': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r' + ' '.repeat(index);\n }),\n '\\r\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r\\n' + ' '.repeat(index);\n }),\n },\n '\\t': {\n '\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\n' + '\\t'.repeat(index);\n }),\n '\\r': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r' + '\\t'.repeat(index);\n }),\n '\\r\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r\\n' + '\\t'.repeat(index);\n }),\n }\n};\nexport const supportedEols = ['\\n', '\\r', '\\r\\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'use strict';\nimport { createScanner } from './scanner';\nimport { cachedSpaces, cachedBreakLinesWithSpaces, supportedEols } from './string-intern';\nexport function format(documentText, range, options) {\n let initialIndentLevel;\n let formatText;\n let formatTextStart;\n let rangeStart;\n let rangeEnd;\n if (range) {\n rangeStart = range.offset;\n rangeEnd = rangeStart + range.length;\n formatTextStart = rangeStart;\n while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {\n formatTextStart--;\n }\n let endOffset = rangeEnd;\n while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {\n endOffset++;\n }\n formatText = documentText.substring(formatTextStart, endOffset);\n initialIndentLevel = computeIndentLevel(formatText, options);\n }\n else {\n formatText = documentText;\n initialIndentLevel = 0;\n formatTextStart = 0;\n rangeStart = 0;\n rangeEnd = documentText.length;\n }\n const eol = getEOL(options, documentText);\n const eolFastPathSupported = supportedEols.includes(eol);\n let numberLineBreaks = 0;\n let indentLevel = 0;\n let indentValue;\n if (options.insertSpaces) {\n indentValue = cachedSpaces[options.tabSize || 4] ?? repeat(cachedSpaces[1], options.tabSize || 4);\n }\n else {\n indentValue = '\\t';\n }\n const indentType = indentValue === '\\t' ? '\\t' : ' ';\n let scanner = createScanner(formatText, false);\n let hasError = false;\n function newLinesAndIndent() {\n if (numberLineBreaks > 1) {\n return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel);\n }\n const amountOfSpaces = indentValue.length * (initialIndentLevel + indentLevel);\n if (!eolFastPathSupported || amountOfSpaces > cachedBreakLinesWithSpaces[indentType][eol].length) {\n return eol + repeat(indentValue, initialIndentLevel + indentLevel);\n }\n if (amountOfSpaces <= 0) {\n return eol;\n }\n return cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces];\n }\n function scanNext() {\n let token = scanner.scan();\n numberLineBreaks = 0;\n while (token === 15 /* SyntaxKind.Trivia */ || token === 14 /* SyntaxKind.LineBreakTrivia */) {\n if (token === 14 /* SyntaxKind.LineBreakTrivia */ && options.keepLines) {\n numberLineBreaks += 1;\n }\n else if (token === 14 /* SyntaxKind.LineBreakTrivia */) {\n numberLineBreaks = 1;\n }\n token = scanner.scan();\n }\n hasError = token === 16 /* SyntaxKind.Unknown */ || scanner.getTokenError() !== 0 /* ScanError.None */;\n return token;\n }\n const editOperations = [];\n function addEdit(text, startOffset, endOffset) {\n if (!hasError && (!range || (startOffset < rangeEnd && endOffset > rangeStart)) && documentText.substring(startOffset, endOffset) !== text) {\n editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });\n }\n }\n let firstToken = scanNext();\n if (options.keepLines && numberLineBreaks > 0) {\n addEdit(repeat(eol, numberLineBreaks), 0, 0);\n }\n if (firstToken !== 17 /* SyntaxKind.EOF */) {\n let firstTokenStart = scanner.getTokenOffset() + formatTextStart;\n let initialIndent = (indentValue.length * initialIndentLevel < 20) && options.insertSpaces\n ? cachedSpaces[indentValue.length * initialIndentLevel]\n : repeat(indentValue, initialIndentLevel);\n addEdit(initialIndent, formatTextStart, firstTokenStart);\n }\n while (firstToken !== 17 /* SyntaxKind.EOF */) {\n let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;\n let secondToken = scanNext();\n let replaceContent = '';\n let needsLineBreak = false;\n while (numberLineBreaks === 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) {\n let commentTokenStart = scanner.getTokenOffset() + formatTextStart;\n addEdit(cachedSpaces[1], firstTokenEnd, commentTokenStart);\n firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;\n needsLineBreak = secondToken === 12 /* SyntaxKind.LineCommentTrivia */;\n replaceContent = needsLineBreak ? newLinesAndIndent() : '';\n secondToken = scanNext();\n }\n if (secondToken === 2 /* SyntaxKind.CloseBraceToken */) {\n if (firstToken !== 1 /* SyntaxKind.OpenBraceToken */) {\n indentLevel--;\n }\n ;\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1 /* SyntaxKind.OpenBraceToken */) {\n replaceContent = newLinesAndIndent();\n }\n else if (options.keepLines) {\n replaceContent = cachedSpaces[1];\n }\n }\n else if (secondToken === 4 /* SyntaxKind.CloseBracketToken */) {\n if (firstToken !== 3 /* SyntaxKind.OpenBracketToken */) {\n indentLevel--;\n }\n ;\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3 /* SyntaxKind.OpenBracketToken */) {\n replaceContent = newLinesAndIndent();\n }\n else if (options.keepLines) {\n replaceContent = cachedSpaces[1];\n }\n }\n else {\n switch (firstToken) {\n case 3 /* SyntaxKind.OpenBracketToken */:\n case 1 /* SyntaxKind.OpenBraceToken */:\n indentLevel++;\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {\n replaceContent = newLinesAndIndent();\n }\n else {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 5 /* SyntaxKind.CommaToken */:\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {\n replaceContent = newLinesAndIndent();\n }\n else {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 12 /* SyntaxKind.LineCommentTrivia */:\n replaceContent = newLinesAndIndent();\n break;\n case 13 /* SyntaxKind.BlockCommentTrivia */:\n if (numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else if (!needsLineBreak) {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 6 /* SyntaxKind.ColonToken */:\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else if (!needsLineBreak) {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 10 /* SyntaxKind.StringLiteral */:\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else if (secondToken === 6 /* SyntaxKind.ColonToken */ && !needsLineBreak) {\n replaceContent = '';\n }\n break;\n case 7 /* SyntaxKind.NullKeyword */:\n case 8 /* SyntaxKind.TrueKeyword */:\n case 9 /* SyntaxKind.FalseKeyword */:\n case 11 /* SyntaxKind.NumericLiteral */:\n case 2 /* SyntaxKind.CloseBraceToken */:\n case 4 /* SyntaxKind.CloseBracketToken */:\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else {\n if ((secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */) && !needsLineBreak) {\n replaceContent = cachedSpaces[1];\n }\n else if (secondToken !== 5 /* SyntaxKind.CommaToken */ && secondToken !== 17 /* SyntaxKind.EOF */) {\n hasError = true;\n }\n }\n break;\n case 16 /* SyntaxKind.Unknown */:\n hasError = true;\n break;\n }\n if (numberLineBreaks > 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) {\n replaceContent = newLinesAndIndent();\n }\n }\n if (secondToken === 17 /* SyntaxKind.EOF */) {\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else {\n replaceContent = options.insertFinalNewline ? eol : '';\n }\n }\n const secondTokenStart = scanner.getTokenOffset() + formatTextStart;\n addEdit(replaceContent, firstTokenEnd, secondTokenStart);\n firstToken = secondToken;\n }\n return editOperations;\n}\nfunction repeat(s, count) {\n let result = '';\n for (let i = 0; i < count; i++) {\n result += s;\n }\n return result;\n}\nfunction computeIndentLevel(content, options) {\n let i = 0;\n let nChars = 0;\n const tabSize = options.tabSize || 4;\n while (i < content.length) {\n let ch = content.charAt(i);\n if (ch === cachedSpaces[1]) {\n nChars++;\n }\n else if (ch === '\\t') {\n nChars += tabSize;\n }\n else {\n break;\n }\n i++;\n }\n return Math.floor(nChars / tabSize);\n}\nfunction getEOL(options, text) {\n for (let i = 0; i < text.length; i++) {\n const ch = text.charAt(i);\n if (ch === '\\r') {\n if (i + 1 < text.length && text.charAt(i + 1) === '\\n') {\n return '\\r\\n';\n }\n return '\\r';\n }\n else if (ch === '\\n') {\n return '\\n';\n }\n }\n return (options && options.eol) || '\\n';\n}\nexport function isEOL(text, offset) {\n return '\\r\\n'.indexOf(text.charAt(offset)) !== -1;\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'use strict';\nimport { createScanner } from './scanner';\nvar ParseOptions;\n(function (ParseOptions) {\n ParseOptions.DEFAULT = {\n allowTrailingComma: false\n };\n})(ParseOptions || (ParseOptions = {}));\n/**\n * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.\n */\nexport function getLocation(text, position) {\n const segments = []; // strings or numbers\n const earlyReturnException = new Object();\n let previousNode = undefined;\n const previousNodeInst = {\n value: {},\n offset: 0,\n length: 0,\n type: 'object',\n parent: undefined\n };\n let isAtPropertyKey = false;\n function setPreviousNode(value, offset, length, type) {\n previousNodeInst.value = value;\n previousNodeInst.offset = offset;\n previousNodeInst.length = length;\n previousNodeInst.type = type;\n previousNodeInst.colonOffset = undefined;\n previousNode = previousNodeInst;\n }\n try {\n visit(text, {\n onObjectBegin: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n isAtPropertyKey = position > offset;\n segments.push(''); // push a placeholder (will be replaced)\n },\n onObjectProperty: (name, offset, length) => {\n if (position < offset) {\n throw earlyReturnException;\n }\n setPreviousNode(name, offset, length, 'property');\n segments[segments.length - 1] = name;\n if (position <= offset + length) {\n throw earlyReturnException;\n }\n },\n onObjectEnd: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.pop();\n },\n onArrayBegin: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.push(0);\n },\n onArrayEnd: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.pop();\n },\n onLiteralValue: (value, offset, length) => {\n if (position < offset) {\n throw earlyReturnException;\n }\n setPreviousNode(value, offset, length, getNodeType(value));\n if (position <= offset + length) {\n throw earlyReturnException;\n }\n },\n onSeparator: (sep, offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n if (sep === ':' && previousNode && previousNode.type === 'property') {\n previousNode.colonOffset = offset;\n isAtPropertyKey = false;\n previousNode = undefined;\n }\n else if (sep === ',') {\n const last = segments[segments.length - 1];\n if (typeof last === 'number') {\n segments[segments.length - 1] = last + 1;\n }\n else {\n isAtPropertyKey = true;\n segments[segments.length - 1] = '';\n }\n previousNode = undefined;\n }\n }\n });\n }\n catch (e) {\n if (e !== earlyReturnException) {\n throw e;\n }\n }\n return {\n path: segments,\n previousNode,\n isAtPropertyKey,\n matches: (pattern) => {\n let k = 0;\n for (let i = 0; k < pattern.length && i < segments.length; i++) {\n if (pattern[k] === segments[i] || pattern[k] === '*') {\n k++;\n }\n else if (pattern[k] !== '**') {\n return false;\n }\n }\n return k === pattern.length;\n }\n };\n}\n/**\n * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n * Therefore always check the errors list to find out if the input was valid.\n */\nexport function parse(text, errors = [], options = ParseOptions.DEFAULT) {\n let currentProperty = null;\n let currentParent = [];\n const previousParents = [];\n function onValue(value) {\n if (Array.isArray(currentParent)) {\n currentParent.push(value);\n }\n else if (currentProperty !== null) {\n currentParent[currentProperty] = value;\n }\n }\n const visitor = {\n onObjectBegin: () => {\n const object = {};\n onValue(object);\n previousParents.push(currentParent);\n currentParent = object;\n currentProperty = null;\n },\n onObjectProperty: (name) => {\n currentProperty = name;\n },\n onObjectEnd: () => {\n currentParent = previousParents.pop();\n },\n onArrayBegin: () => {\n const array = [];\n onValue(array);\n previousParents.push(currentParent);\n currentParent = array;\n currentProperty = null;\n },\n onArrayEnd: () => {\n currentParent = previousParents.pop();\n },\n onLiteralValue: onValue,\n onError: (error, offset, length) => {\n errors.push({ error, offset, length });\n }\n };\n visit(text, visitor, options);\n return currentParent[0];\n}\n/**\n * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n */\nexport function parseTree(text, errors = [], options = ParseOptions.DEFAULT) {\n let currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root\n function ensurePropertyComplete(endOffset) {\n if (currentParent.type === 'property') {\n currentParent.length = endOffset - currentParent.offset;\n currentParent = currentParent.parent;\n }\n }\n function onValue(valueNode) {\n currentParent.children.push(valueNode);\n return valueNode;\n }\n const visitor = {\n onObjectBegin: (offset) => {\n currentParent = onValue({ type: 'object', offset, length: -1, parent: currentParent, children: [] });\n },\n onObjectProperty: (name, offset, length) => {\n currentParent = onValue({ type: 'property', offset, length: -1, parent: currentParent, children: [] });\n currentParent.children.push({ type: 'string', value: name, offset, length, parent: currentParent });\n },\n onObjectEnd: (offset, length) => {\n ensurePropertyComplete(offset + length); // in case of a missing value for a property: make sure property is complete\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onArrayBegin: (offset, length) => {\n currentParent = onValue({ type: 'array', offset, length: -1, parent: currentParent, children: [] });\n },\n onArrayEnd: (offset, length) => {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onLiteralValue: (value, offset, length) => {\n onValue({ type: getNodeType(value), offset, length, parent: currentParent, value });\n ensurePropertyComplete(offset + length);\n },\n onSeparator: (sep, offset, length) => {\n if (currentParent.type === 'property') {\n if (sep === ':') {\n currentParent.colonOffset = offset;\n }\n else if (sep === ',') {\n ensurePropertyComplete(offset);\n }\n }\n },\n onError: (error, offset, length) => {\n errors.push({ error, offset, length });\n }\n };\n visit(text, visitor, options);\n const result = currentParent.children[0];\n if (result) {\n delete result.parent;\n }\n return result;\n}\n/**\n * Finds the node at the given path in a JSON DOM.\n */\nexport function findNodeAtLocation(root, path) {\n if (!root) {\n return undefined;\n }\n let node = root;\n for (let segment of path) {\n if (typeof segment === 'string') {\n if (node.type !== 'object' || !Array.isArray(node.children)) {\n return undefined;\n }\n let found = false;\n for (const propertyNode of node.children) {\n if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {\n node = propertyNode.children[1];\n found = true;\n break;\n }\n }\n if (!found) {\n return undefined;\n }\n }\n else {\n const index = segment;\n if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {\n return undefined;\n }\n node = node.children[index];\n }\n }\n return node;\n}\n/**\n * Gets the JSON path of the given JSON DOM node\n */\nexport function getNodePath(node) {\n if (!node.parent || !node.parent.children) {\n return [];\n }\n const path = getNodePath(node.parent);\n if (node.parent.type === 'property') {\n const key = node.parent.children[0].value;\n path.push(key);\n }\n else if (node.parent.type === 'array') {\n const index = node.parent.children.indexOf(node);\n if (index !== -1) {\n path.push(index);\n }\n }\n return path;\n}\n/**\n * Evaluates the JavaScript object of the given JSON DOM node\n */\nexport function getNodeValue(node) {\n switch (node.type) {\n case 'array':\n return node.children.map(getNodeValue);\n case 'object':\n const obj = Object.create(null);\n for (let prop of node.children) {\n const valueNode = prop.children[1];\n if (valueNode) {\n obj[prop.children[0].value] = getNodeValue(valueNode);\n }\n }\n return obj;\n case 'null':\n case 'string':\n case 'number':\n case 'boolean':\n return node.value;\n default:\n return undefined;\n }\n}\nexport function contains(node, offset, includeRightBound = false) {\n return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length));\n}\n/**\n * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.\n */\nexport function findNodeAtOffset(node, offset, includeRightBound = false) {\n if (contains(node, offset, includeRightBound)) {\n const children = node.children;\n if (Array.isArray(children)) {\n for (let i = 0; i < children.length && children[i].offset <= offset; i++) {\n const item = findNodeAtOffset(children[i], offset, includeRightBound);\n if (item) {\n return item;\n }\n }\n }\n return node;\n }\n return undefined;\n}\n/**\n * Parses the given text and invokes the visitor functions for each object, array and literal reached.\n */\nexport function visit(text, visitor, options = ParseOptions.DEFAULT) {\n const _scanner = createScanner(text, false);\n // Important: Only pass copies of this to visitor functions to prevent accidental modification, and\n // to not affect visitor functions which stored a reference to a previous JSONPath\n const _jsonPath = [];\n // Depth of onXXXBegin() callbacks suppressed. onXXXEnd() decrements this if it isn't 0 already.\n // Callbacks are only called when this value is 0.\n let suppressedCallbacks = 0;\n function toNoArgVisit(visitFunction) {\n return visitFunction ? () => suppressedCallbacks === 0 && visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;\n }\n function toOneArgVisit(visitFunction) {\n return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;\n }\n function toOneArgVisitWithPath(visitFunction) {\n return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;\n }\n function toBeginVisit(visitFunction) {\n return visitFunction ?\n () => {\n if (suppressedCallbacks > 0) {\n suppressedCallbacks++;\n }\n else {\n let cbReturn = visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice());\n if (cbReturn === false) {\n suppressedCallbacks = 1;\n }\n }\n }\n : () => true;\n }\n function toEndVisit(visitFunction) {\n return visitFunction ?\n () => {\n if (suppressedCallbacks > 0) {\n suppressedCallbacks--;\n }\n if (suppressedCallbacks === 0) {\n visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter());\n }\n }\n : () => true;\n }\n const onObjectBegin = toBeginVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toEndVisit(visitor.onObjectEnd), onArrayBegin = toBeginVisit(visitor.onArrayBegin), onArrayEnd = toEndVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);\n const disallowComments = options && options.disallowComments;\n const allowTrailingComma = options && options.allowTrailingComma;\n function scanNext() {\n while (true) {\n const token = _scanner.scan();\n switch (_scanner.getTokenError()) {\n case 4 /* ScanError.InvalidUnicode */:\n handleError(14 /* ParseErrorCode.InvalidUnicode */);\n break;\n case 5 /* ScanError.InvalidEscapeCharacter */:\n handleError(15 /* ParseErrorCode.InvalidEscapeCharacter */);\n break;\n case 3 /* ScanError.UnexpectedEndOfNumber */:\n handleError(13 /* ParseErrorCode.UnexpectedEndOfNumber */);\n break;\n case 1 /* ScanError.UnexpectedEndOfComment */:\n if (!disallowComments) {\n handleError(11 /* ParseErrorCode.UnexpectedEndOfComment */);\n }\n break;\n case 2 /* ScanError.UnexpectedEndOfString */:\n handleError(12 /* ParseErrorCode.UnexpectedEndOfString */);\n break;\n case 6 /* ScanError.InvalidCharacter */:\n handleError(16 /* ParseErrorCode.InvalidCharacter */);\n break;\n }\n switch (token) {\n case 12 /* SyntaxKind.LineCommentTrivia */:\n case 13 /* SyntaxKind.BlockCommentTrivia */:\n if (disallowComments) {\n handleError(10 /* ParseErrorCode.InvalidCommentToken */);\n }\n else {\n onComment();\n }\n break;\n case 16 /* SyntaxKind.Unknown */:\n handleError(1 /* ParseErrorCode.InvalidSymbol */);\n break;\n case 15 /* SyntaxKind.Trivia */:\n case 14 /* SyntaxKind.LineBreakTrivia */:\n break;\n default:\n return token;\n }\n }\n }\n function handleError(error, skipUntilAfter = [], skipUntil = []) {\n onError(error);\n if (skipUntilAfter.length + skipUntil.length > 0) {\n let token = _scanner.getToken();\n while (token !== 17 /* SyntaxKind.EOF */) {\n if (skipUntilAfter.indexOf(token) !== -1) {\n scanNext();\n break;\n }\n else if (skipUntil.indexOf(token) !== -1) {\n break;\n }\n token = scanNext();\n }\n }\n }\n function parseString(isValue) {\n const value = _scanner.getTokenValue();\n if (isValue) {\n onLiteralValue(value);\n }\n else {\n onObjectProperty(value);\n // add property name afterwards\n _jsonPath.push(value);\n }\n scanNext();\n return true;\n }\n function parseLiteral() {\n switch (_scanner.getToken()) {\n case 11 /* SyntaxKind.NumericLiteral */:\n const tokenValue = _scanner.getTokenValue();\n let value = Number(tokenValue);\n if (isNaN(value)) {\n handleError(2 /* ParseErrorCode.InvalidNumberFormat */);\n value = 0;\n }\n onLiteralValue(value);\n break;\n case 7 /* SyntaxKind.NullKeyword */:\n onLiteralValue(null);\n break;\n case 8 /* SyntaxKind.TrueKeyword */:\n onLiteralValue(true);\n break;\n case 9 /* SyntaxKind.FalseKeyword */:\n onLiteralValue(false);\n break;\n default:\n return false;\n }\n scanNext();\n return true;\n }\n function parseProperty() {\n if (_scanner.getToken() !== 10 /* SyntaxKind.StringLiteral */) {\n handleError(3 /* ParseErrorCode.PropertyNameExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n return false;\n }\n parseString(false);\n if (_scanner.getToken() === 6 /* SyntaxKind.ColonToken */) {\n onSeparator(':');\n scanNext(); // consume colon\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n }\n else {\n handleError(5 /* ParseErrorCode.ColonExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n _jsonPath.pop(); // remove processed property name\n return true;\n }\n function parseObject() {\n onObjectBegin();\n scanNext(); // consume open brace\n let needsComma = false;\n while (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) {\n if (!needsComma) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n }\n onSeparator(',');\n scanNext(); // consume comma\n if (_scanner.getToken() === 2 /* SyntaxKind.CloseBraceToken */ && allowTrailingComma) {\n break;\n }\n }\n else if (needsComma) {\n handleError(6 /* ParseErrorCode.CommaExpected */, [], []);\n }\n if (!parseProperty()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n needsComma = true;\n }\n onObjectEnd();\n if (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */) {\n handleError(7 /* ParseErrorCode.CloseBraceExpected */, [2 /* SyntaxKind.CloseBraceToken */], []);\n }\n else {\n scanNext(); // consume close brace\n }\n return true;\n }\n function parseArray() {\n onArrayBegin();\n scanNext(); // consume open bracket\n let isFirstElement = true;\n let needsComma = false;\n while (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) {\n if (!needsComma) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n }\n onSeparator(',');\n scanNext(); // consume comma\n if (_scanner.getToken() === 4 /* SyntaxKind.CloseBracketToken */ && allowTrailingComma) {\n break;\n }\n }\n else if (needsComma) {\n handleError(6 /* ParseErrorCode.CommaExpected */, [], []);\n }\n if (isFirstElement) {\n _jsonPath.push(0);\n isFirstElement = false;\n }\n else {\n _jsonPath[_jsonPath.length - 1]++;\n }\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [4 /* SyntaxKind.CloseBracketToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n needsComma = true;\n }\n onArrayEnd();\n if (!isFirstElement) {\n _jsonPath.pop(); // remove array index\n }\n if (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */) {\n handleError(8 /* ParseErrorCode.CloseBracketExpected */, [4 /* SyntaxKind.CloseBracketToken */], []);\n }\n else {\n scanNext(); // consume close bracket\n }\n return true;\n }\n function parseValue() {\n switch (_scanner.getToken()) {\n case 3 /* SyntaxKind.OpenBracketToken */:\n return parseArray();\n case 1 /* SyntaxKind.OpenBraceToken */:\n return parseObject();\n case 10 /* SyntaxKind.StringLiteral */:\n return parseString(true);\n default:\n return parseLiteral();\n }\n }\n scanNext();\n if (_scanner.getToken() === 17 /* SyntaxKind.EOF */) {\n if (options.allowEmptyContent) {\n return true;\n }\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n return false;\n }\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n return false;\n }\n if (_scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n handleError(9 /* ParseErrorCode.EndOfFileExpected */, [], []);\n }\n return true;\n}\n/**\n * Takes JSON with JavaScript-style comments and remove\n * them. Optionally replaces every none-newline character\n * of comments with a replaceCharacter\n */\nexport function stripComments(text, replaceCh) {\n let _scanner = createScanner(text), parts = [], kind, offset = 0, pos;\n do {\n pos = _scanner.getPosition();\n kind = _scanner.scan();\n switch (kind) {\n case 12 /* SyntaxKind.LineCommentTrivia */:\n case 13 /* SyntaxKind.BlockCommentTrivia */:\n case 17 /* SyntaxKind.EOF */:\n if (offset !== pos) {\n parts.push(text.substring(offset, pos));\n }\n if (replaceCh !== undefined) {\n parts.push(_scanner.getTokenValue().replace(/[^\\r\\n]/g, replaceCh));\n }\n offset = _scanner.getPosition();\n break;\n }\n } while (kind !== 17 /* SyntaxKind.EOF */);\n return parts.join('');\n}\nexport function getNodeType(value) {\n switch (typeof value) {\n case 'boolean': return 'boolean';\n case 'number': return 'number';\n case 'string': return 'string';\n case 'object': {\n if (!value) {\n return 'null';\n }\n else if (Array.isArray(value)) {\n return 'array';\n }\n return 'object';\n }\n default: return 'null';\n }\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'use strict';\nimport { format, isEOL } from './format';\nimport { parseTree, findNodeAtLocation } from './parser';\nexport function removeProperty(text, path, options) {\n return setProperty(text, path, void 0, options);\n}\nexport function setProperty(text, originalPath, value, options) {\n const path = originalPath.slice();\n const errors = [];\n const root = parseTree(text, errors);\n let parent = void 0;\n let lastSegment = void 0;\n while (path.length > 0) {\n lastSegment = path.pop();\n parent = findNodeAtLocation(root, path);\n if (parent === void 0 && value !== void 0) {\n if (typeof lastSegment === 'string') {\n value = { [lastSegment]: value };\n }\n else {\n value = [value];\n }\n }\n else {\n break;\n }\n }\n if (!parent) {\n // empty document\n if (value === void 0) { // delete\n throw new Error('Can not delete in empty document');\n }\n return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options);\n }\n else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) {\n const existing = findNodeAtLocation(parent, [lastSegment]);\n if (existing !== void 0) {\n if (value === void 0) { // delete\n if (!existing.parent) {\n throw new Error('Malformed AST');\n }\n const propertyIndex = parent.children.indexOf(existing.parent);\n let removeBegin;\n let removeEnd = existing.parent.offset + existing.parent.length;\n if (propertyIndex > 0) {\n // remove the comma of the previous node\n let previous = parent.children[propertyIndex - 1];\n removeBegin = previous.offset + previous.length;\n }\n else {\n removeBegin = parent.offset + 1;\n if (parent.children.length > 1) {\n // remove the comma of the next node\n let next = parent.children[1];\n removeEnd = next.offset;\n }\n }\n return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, options);\n }\n else {\n // set value of existing property\n return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options);\n }\n }\n else {\n if (value === void 0) { // delete\n return []; // property does not exist, nothing to do\n }\n const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;\n const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map(p => p.children[0].value)) : parent.children.length;\n let edit;\n if (index > 0) {\n let previous = parent.children[index - 1];\n edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };\n }\n else if (parent.children.length === 0) {\n edit = { offset: parent.offset + 1, length: 0, content: newProperty };\n }\n else {\n edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' };\n }\n return withFormatting(text, edit, options);\n }\n }\n else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) {\n const insertIndex = lastSegment;\n if (insertIndex === -1) {\n // Insert\n const newProperty = `${JSON.stringify(value)}`;\n let edit;\n if (parent.children.length === 0) {\n edit = { offset: parent.offset + 1, length: 0, content: newProperty };\n }\n else {\n const previous = parent.children[parent.children.length - 1];\n edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };\n }\n return withFormatting(text, edit, options);\n }\n else if (value === void 0 && parent.children.length >= 0) {\n // Removal\n const removalIndex = lastSegment;\n const toRemove = parent.children[removalIndex];\n let edit;\n if (parent.children.length === 1) {\n // only item\n edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' };\n }\n else if (parent.children.length - 1 === removalIndex) {\n // last item\n let previous = parent.children[removalIndex - 1];\n let offset = previous.offset + previous.length;\n let parentEndOffset = parent.offset + parent.length;\n edit = { offset, length: parentEndOffset - 2 - offset, content: '' };\n }\n else {\n edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' };\n }\n return withFormatting(text, edit, options);\n }\n else if (value !== void 0) {\n let edit;\n const newProperty = `${JSON.stringify(value)}`;\n if (!options.isArrayInsertion && parent.children.length > lastSegment) {\n const toModify = parent.children[lastSegment];\n edit = { offset: toModify.offset, length: toModify.length, content: newProperty };\n }\n else if (parent.children.length === 0 || lastSegment === 0) {\n edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + ',' };\n }\n else {\n const index = lastSegment > parent.children.length ? parent.children.length : lastSegment;\n const previous = parent.children[index - 1];\n edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };\n }\n return withFormatting(text, edit, options);\n }\n else {\n throw new Error(`Can not ${value === void 0 ? 'remove' : (options.isArrayInsertion ? 'insert' : 'modify')} Array index ${insertIndex} as length is not sufficient`);\n }\n }\n else {\n throw new Error(`Can not add ${typeof lastSegment !== 'number' ? 'index' : 'property'} to parent of type ${parent.type}`);\n }\n}\nfunction withFormatting(text, edit, options) {\n if (!options.formattingOptions) {\n return [edit];\n }\n // apply the edit\n let newText = applyEdit(text, edit);\n // format the new text\n let begin = edit.offset;\n let end = edit.offset + edit.content.length;\n if (edit.length === 0 || edit.content.length === 0) { // insert or remove\n while (begin > 0 && !isEOL(newText, begin - 1)) {\n begin--;\n }\n while (end < newText.length && !isEOL(newText, end)) {\n end++;\n }\n }\n const edits = format(newText, { offset: begin, length: end - begin }, { ...options.formattingOptions, keepLines: false });\n // apply the formatting edits and track the begin and end offsets of the changes\n for (let i = edits.length - 1; i >= 0; i--) {\n const edit = edits[i];\n newText = applyEdit(newText, edit);\n begin = Math.min(begin, edit.offset);\n end = Math.max(end, edit.offset + edit.length);\n end += edit.content.length - edit.length;\n }\n // create a single edit with all changes\n const editLength = text.length - (newText.length - end) - begin;\n return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];\n}\nexport function applyEdit(text, edit) {\n return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);\n}\nexport function isWS(text, offset) {\n return '\\r\\n \\t'.indexOf(text.charAt(offset)) !== -1;\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'use strict';\nimport * as formatter from './impl/format';\nimport * as edit from './impl/edit';\nimport * as scanner from './impl/scanner';\nimport * as parser from './impl/parser';\n/**\n * Creates a JSON scanner on the given text.\n * If ignoreTrivia is set, whitespaces or comments are ignored.\n */\nexport const createScanner = scanner.createScanner;\nexport var ScanError;\n(function (ScanError) {\n ScanError[ScanError[\"None\"] = 0] = \"None\";\n ScanError[ScanError[\"UnexpectedEndOfComment\"] = 1] = \"UnexpectedEndOfComment\";\n ScanError[ScanError[\"UnexpectedEndOfString\"] = 2] = \"UnexpectedEndOfString\";\n ScanError[ScanError[\"UnexpectedEndOfNumber\"] = 3] = \"UnexpectedEndOfNumber\";\n ScanError[ScanError[\"InvalidUnicode\"] = 4] = \"InvalidUnicode\";\n ScanError[ScanError[\"InvalidEscapeCharacter\"] = 5] = \"InvalidEscapeCharacter\";\n ScanError[ScanError[\"InvalidCharacter\"] = 6] = \"InvalidCharacter\";\n})(ScanError || (ScanError = {}));\nexport var SyntaxKind;\n(function (SyntaxKind) {\n SyntaxKind[SyntaxKind[\"OpenBraceToken\"] = 1] = \"OpenBraceToken\";\n SyntaxKind[SyntaxKind[\"CloseBraceToken\"] = 2] = \"CloseBraceToken\";\n SyntaxKind[SyntaxKind[\"OpenBracketToken\"] = 3] = \"OpenBracketToken\";\n SyntaxKind[SyntaxKind[\"CloseBracketToken\"] = 4] = \"CloseBracketToken\";\n SyntaxKind[SyntaxKind[\"CommaToken\"] = 5] = \"CommaToken\";\n SyntaxKind[SyntaxKind[\"ColonToken\"] = 6] = \"ColonToken\";\n SyntaxKind[SyntaxKind[\"NullKeyword\"] = 7] = \"NullKeyword\";\n SyntaxKind[SyntaxKind[\"TrueKeyword\"] = 8] = \"TrueKeyword\";\n SyntaxKind[SyntaxKind[\"FalseKeyword\"] = 9] = \"FalseKeyword\";\n SyntaxKind[SyntaxKind[\"StringLiteral\"] = 10] = \"StringLiteral\";\n SyntaxKind[SyntaxKind[\"NumericLiteral\"] = 11] = \"NumericLiteral\";\n SyntaxKind[SyntaxKind[\"LineCommentTrivia\"] = 12] = \"LineCommentTrivia\";\n SyntaxKind[SyntaxKind[\"BlockCommentTrivia\"] = 13] = \"BlockCommentTrivia\";\n SyntaxKind[SyntaxKind[\"LineBreakTrivia\"] = 14] = \"LineBreakTrivia\";\n SyntaxKind[SyntaxKind[\"Trivia\"] = 15] = \"Trivia\";\n SyntaxKind[SyntaxKind[\"Unknown\"] = 16] = \"Unknown\";\n SyntaxKind[SyntaxKind[\"EOF\"] = 17] = \"EOF\";\n})(SyntaxKind || (SyntaxKind = {}));\n/**\n * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.\n */\nexport const getLocation = parser.getLocation;\n/**\n * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n * Therefore, always check the errors list to find out if the input was valid.\n */\nexport const parse = parser.parse;\n/**\n * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n */\nexport const parseTree = parser.parseTree;\n/**\n * Finds the node at the given path in a JSON DOM.\n */\nexport const findNodeAtLocation = parser.findNodeAtLocation;\n/**\n * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.\n */\nexport const findNodeAtOffset = parser.findNodeAtOffset;\n/**\n * Gets the JSON path of the given JSON DOM node\n */\nexport const getNodePath = parser.getNodePath;\n/**\n * Evaluates the JavaScript object of the given JSON DOM node\n */\nexport const getNodeValue = parser.getNodeValue;\n/**\n * Parses the given text and invokes the visitor functions for each object, array and literal reached.\n */\nexport const visit = parser.visit;\n/**\n * Takes JSON with JavaScript-style comments and remove\n * them. Optionally replaces every none-newline character\n * of comments with a replaceCharacter\n */\nexport const stripComments = parser.stripComments;\nexport var ParseErrorCode;\n(function (ParseErrorCode) {\n ParseErrorCode[ParseErrorCode[\"InvalidSymbol\"] = 1] = \"InvalidSymbol\";\n ParseErrorCode[ParseErrorCode[\"InvalidNumberFormat\"] = 2] = \"InvalidNumberFormat\";\n ParseErrorCode[ParseErrorCode[\"PropertyNameExpected\"] = 3] = \"PropertyNameExpected\";\n ParseErrorCode[ParseErrorCode[\"ValueExpected\"] = 4] = \"ValueExpected\";\n ParseErrorCode[ParseErrorCode[\"ColonExpected\"] = 5] = \"ColonExpected\";\n ParseErrorCode[ParseErrorCode[\"CommaExpected\"] = 6] = \"CommaExpected\";\n ParseErrorCode[ParseErrorCode[\"CloseBraceExpected\"] = 7] = \"CloseBraceExpected\";\n ParseErrorCode[ParseErrorCode[\"CloseBracketExpected\"] = 8] = \"CloseBracketExpected\";\n ParseErrorCode[ParseErrorCode[\"EndOfFileExpected\"] = 9] = \"EndOfFileExpected\";\n ParseErrorCode[ParseErrorCode[\"InvalidCommentToken\"] = 10] = \"InvalidCommentToken\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfComment\"] = 11] = \"UnexpectedEndOfComment\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfString\"] = 12] = \"UnexpectedEndOfString\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfNumber\"] = 13] = \"UnexpectedEndOfNumber\";\n ParseErrorCode[ParseErrorCode[\"InvalidUnicode\"] = 14] = \"InvalidUnicode\";\n ParseErrorCode[ParseErrorCode[\"InvalidEscapeCharacter\"] = 15] = \"InvalidEscapeCharacter\";\n ParseErrorCode[ParseErrorCode[\"InvalidCharacter\"] = 16] = \"InvalidCharacter\";\n})(ParseErrorCode || (ParseErrorCode = {}));\nexport function printParseErrorCode(code) {\n switch (code) {\n case 1 /* ParseErrorCode.InvalidSymbol */: return 'InvalidSymbol';\n case 2 /* ParseErrorCode.InvalidNumberFormat */: return 'InvalidNumberFormat';\n case 3 /* ParseErrorCode.PropertyNameExpected */: return 'PropertyNameExpected';\n case 4 /* ParseErrorCode.ValueExpected */: return 'ValueExpected';\n case 5 /* ParseErrorCode.ColonExpected */: return 'ColonExpected';\n case 6 /* ParseErrorCode.CommaExpected */: return 'CommaExpected';\n case 7 /* ParseErrorCode.CloseBraceExpected */: return 'CloseBraceExpected';\n case 8 /* ParseErrorCode.CloseBracketExpected */: return 'CloseBracketExpected';\n case 9 /* ParseErrorCode.EndOfFileExpected */: return 'EndOfFileExpected';\n case 10 /* ParseErrorCode.InvalidCommentToken */: return 'InvalidCommentToken';\n case 11 /* ParseErrorCode.UnexpectedEndOfComment */: return 'UnexpectedEndOfComment';\n case 12 /* ParseErrorCode.UnexpectedEndOfString */: return 'UnexpectedEndOfString';\n case 13 /* ParseErrorCode.UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber';\n case 14 /* ParseErrorCode.InvalidUnicode */: return 'InvalidUnicode';\n case 15 /* ParseErrorCode.InvalidEscapeCharacter */: return 'InvalidEscapeCharacter';\n case 16 /* ParseErrorCode.InvalidCharacter */: return 'InvalidCharacter';\n }\n return '<unknown ParseErrorCode>';\n}\n/**\n * Computes the edit operations needed to format a JSON document.\n *\n * @param documentText The input text\n * @param range The range to format or `undefined` to format the full content\n * @param options The formatting options\n * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}.\n * To apply the edit operations to the input, use {@linkcode applyEdits}.\n */\nexport function format(documentText, range, options) {\n return formatter.format(documentText, range, options);\n}\n/**\n * Computes the edit operations needed to modify a value in the JSON document.\n *\n * @param documentText The input text\n * @param path The path of the value to change. The path represents either to the document root, a property or an array item.\n * If the path points to an non-existing property or item, it will be created.\n * @param value The new value for the specified property or item. If the value is undefined,\n * the property or item will be removed.\n * @param options Options\n * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}.\n * To apply the edit operations to the input, use {@linkcode applyEdits}.\n */\nexport function modify(text, path, value, options) {\n return edit.setProperty(text, path, value, options);\n}\n/**\n * Applies edits to an input string.\n * @param text The input text\n * @param edits Edit operations following the format described in {@linkcode EditResult}.\n * @returns The text with the applied edits.\n * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}.\n */\nexport function applyEdits(text, edits) {\n let sortedEdits = edits.slice(0).sort((a, b) => {\n const diff = a.offset - b.offset;\n if (diff === 0) {\n return a.length - b.length;\n }\n return diff;\n });\n let lastModifiedOffset = text.length;\n for (let i = sortedEdits.length - 1; i >= 0; i--) {\n let e = sortedEdits[i];\n if (e.offset + e.length <= lastModifiedOffset) {\n text = edit.applyEdit(text, e);\n }\n else {\n throw new Error('Overlapping edit');\n }\n lastModifiedOffset = e.offset;\n }\n return text;\n}\n","import { z } from 'zod';\nimport { CallLogLevelSchema } from './callRecord';\n\n/** Keys whose values are replaced by `[redacted]`; matched case-insensitively, ignoring `_`/`-`, as substrings. */\nexport const DEFAULT_REDACT_KEYS: readonly string[] = [\n 'password', 'passwd', 'secret', 'token', 'apikey', 'privatekey', 'authorization', 'cookie', 'credential',\n];\n\nconst PayloadPolicySchema = z.object({\n /**\n * `none` records only sizes; `truncated` (default) cuts long strings,\n * arrays, and deep nesting per property; `full` records payloads as sent.\n * Redaction applies to `truncated` and `full`.\n */\n mode: z.enum(['none', 'truncated', 'full']).default('truncated'),\n maxStringLength: z.number().int().positive().default(256),\n maxArrayItems: z.number().int().positive().default(50),\n maxDepth: z.number().int().positive().default(8),\n /** `[]` turns redaction off. */\n redactKeys: z.array(z.string().min(1)).default([...DEFAULT_REDACT_KEYS]),\n}).strict().prefault({});\n\nexport type PayloadPolicy = z.output<typeof PayloadPolicySchema>;\n\nconst RotationSchema = z.object({\n /** Start a new file once the current one reaches this size. */\n maxFileSizeMb: z.number().positive().default(10),\n /** Delete the oldest files beyond this count. */\n maxFiles: z.number().int().positive().default(20),\n /** Delete files last written longer ago than this. */\n maxAgeDays: z.number().positive().default(14),\n}).strict().prefault({});\n\nexport type CallLogRotation = z.output<typeof RotationSchema>;\n\n/**\n * Persistent log of the calls routed through the hub, written as NDJSON to\n * `<state dir>/calls`. Changes apply without restarting the hub.\n */\nexport const CallLogConfigSchema = z.object({\n /**\n * `off` (default) records nothing; `error`/`warn` failed calls; `info`\n * every request; `debug` also notifications; `trace` also stream frames.\n */\n level: CallLogLevelSchema.default('off'),\n payloads: PayloadPolicySchema,\n rotation: RotationSchema,\n}).strict().prefault({});\n\nexport type CallLogConfig = z.output<typeof CallLogConfigSchema>;\n","import { type HubConfig, hubConfigJsonSchema, parseHubConfig } from '@hediet/linkrpc-hub';\nimport * as jsonc from 'jsonc-parser';\nimport { z } from 'zod';\nimport { type CallLogConfig, CallLogConfigSchema } from './callLog/callLogConfig';\nimport type { CallLogLevel } from './callLog/callRecord';\n\nconst SERVICE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\n/** A process the daemon starts and supervises, or a LinkRPC endpoint it connects, optionally connected to the hub. */\nexport const ManagedServiceSchema = z.object({\n description: z.string().optional(),\n /** Executable and arguments (no shell). `.cmd`/`.bat` shims work on Windows. Set exactly one of `command` and `endpoint`. */\n command: z.array(z.string().min(1)).min(1).optional(),\n /**\n * A LinkRPC endpoint URI to connect instead of starting a process, for\n * example another hub reached through\n * `cmd-stdio:?argv=ssh&argv=vm&argv=linkrpc-hub-daemon&argv=bridge-stdio`,\n * or `unix:`/`npipe:`/`ws:`. The endpoint joins this hub like a service:\n * it may serve only `serviceId`, and its own calls pass the hub's\n * forwarded-call checks.\n */\n endpoint: z.string().min(1).optional(),\n /** Extra environment. RPC services also receive `LINKRPC_ENDPOINT`/`LINKRPC_TOKEN`. */\n env: z.record(z.string(), z.string()).default({}),\n cwd: z.string().optional(),\n /** `false` keeps the service configured but stopped. */\n enabled: z.boolean().default(true),\n restart: z.enum(['always', 'on-failure', 'never']).default('on-failure'),\n /** `false` runs a plain stdio process without a participant socket or identity. */\n rpc: z.boolean().default(true),\n /** Run in a pseudoterminal: stdout and stderr merge, and attachments can resize it. */\n tty: z.boolean().default(false),\n /**\n * When the service counts as running: after it connects to the hub\n * (`connected`, for LinkRPC services) or as soon as it spawned.\n * Plain stdio processes (`rpc: false`) always use spawned readiness.\n */\n readiness: z.enum(['connected', 'spawned']).default('connected'),\n /**\n * Namespace the service may claim on the hub. Defaults to\n * `<hubServiceId>/<name>`, so one prefix addresses the whole hub.\n */\n serviceId: z.string().min(1).optional(),\n /** Provision a persistent managed identity (slot `service:<name>`). */\n managedIdentity: z.boolean().default(true),\n /** A `connected` service that does not connect in time is restarted. */\n startTimeoutMs: z.number().int().positive().default(30_000),\n /** Grace period after disconnecting (and SIGTERM on POSIX) before killing the process tree. */\n stopTimeoutMs: z.number().int().positive().default(5_000),\n}).strict().superRefine((service, context) => {\n if ((service.command === undefined) === (service.endpoint === undefined)) {\n context.addIssue({ code: 'custom', message: 'set exactly one of \"command\" and \"endpoint\"' });\n }\n if (service.endpoint === undefined) return;\n const processOnly = [\n Object.keys(service.env).length > 0 && 'env',\n service.cwd !== undefined && 'cwd',\n !service.rpc && 'rpc',\n service.tty && 'tty',\n service.readiness !== 'connected' && 'readiness',\n ].filter(field => field !== false);\n if (processOnly.length > 0) {\n context.addIssue({ code: 'custom', message: `\"${processOnly.join('\", \"')}\" only apply to \"command\" services` });\n }\n});\n\nexport type ManagedService = z.output<typeof ManagedServiceSchema> & { readonly serviceId: string; };\n\nconst ServicesSchema = z.record(\n z.string().regex(SERVICE_NAME, 'service names use letters, digits, \".\", \"_\", and \"-\"'),\n ManagedServiceSchema,\n).default({});\n\n/** The daemon's application endpoint (named pipe / Unix socket). */\nconst LocalEndpointSchema = z.object({\n /**\n * Named pipe (Windows, `\\\\.\\pipe\\name`) or Unix socket path. Defaults to a\n * fixed per-user name (see `linkrpc-hub-daemon status`).\n */\n path: z.string().min(1).optional(),\n /**\n * Token clients must present. By default there is none: the endpoint is\n * reachable only by the OS user (pipe ACL / private socket directory).\n */\n token: z.string().min(1).optional(),\n}).strict().default({});\n\nexport type LocalEndpointConfig = z.output<typeof LocalEndpointSchema>;\n\n/** The daemon config file: a hub config plus supervised `services`. */\nexport interface DaemonConfig {\n readonly hub: HubConfig;\n readonly localEndpoint: LocalEndpointConfig;\n readonly callLog: CallLogConfig;\n readonly services: Readonly<Record<string, ManagedService>>;\n}\n\n/**\n * Parse a config file's text. Comments and trailing commas are allowed.\n * Throws a readable error on invalid input.\n */\nexport function parseDaemonConfigText(text: string): DaemonConfig {\n if (text.trim() === '') return parseDaemonConfig({});\n const errors: jsonc.ParseError[] = [];\n const raw: unknown = jsonc.parse(text, errors, { allowTrailingComma: true });\n if (errors.length > 0) {\n const first = errors[0]!;\n const { line, column } = _position(text, first.offset);\n throw new Error(`invalid JSON at ${line}:${column}: ${jsonc.printParseErrorCode(first.error)}`);\n }\n return parseDaemonConfig(raw);\n}\n\n/**\n * Validate a parsed config. Unlike a standalone hub, the per-user hub defaults\n * to `forwardChecking: false`: the OS user is the trust boundary of its\n * private endpoints.\n */\nexport function parseDaemonConfig(raw: unknown): DaemonConfig {\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {\n throw new Error('config must be a JSON object');\n }\n const record = raw as Record<string, unknown>;\n let hub: HubConfig;\n let localEndpoint: LocalEndpointConfig;\n let callLog: CallLogConfig;\n let parsedServices: Record<string, z.output<typeof ManagedServiceSchema>>;\n try {\n const { $schema: _editorSchema, ...hubFields } = parseHubConfig({ ...record, forwardChecking: record.forwardChecking ?? false });\n hub = hubFields;\n localEndpoint = LocalEndpointSchema.parse(record.localEndpoint);\n callLog = CallLogConfigSchema.parse(record.callLog);\n parsedServices = ServicesSchema.parse(record.services);\n } catch (error) {\n if (error instanceof z.ZodError) throw new Error(z.prettifyError(error));\n throw error;\n }\n const services: Record<string, ManagedService> = {};\n const owners = new Map<string, string>();\n for (const [name, service] of Object.entries(parsedServices)) {\n const serviceId = service.serviceId ?? `${hub.hubServiceId}/${name}`;\n const owner = owners.get(serviceId);\n if (owner !== undefined) {\n throw new Error(`services '${owner}' and '${name}' both claim serviceId '${serviceId}'`);\n }\n owners.set(serviceId, name);\n services[name] = { ...service, serviceId };\n }\n return { hub, localEndpoint, callLog, services };\n}\n\n/** How applying `next` over a running `previous` service must proceed. */\nexport type ServiceChange = 'none' | 'inPlace' | 'restart';\n\nconst IN_PLACE_FIELDS = ['description', 'enabled', 'restart', 'startTimeoutMs', 'stopTimeoutMs'] as const;\n\nexport function classifyServiceChange(previous: ManagedService, next: ManagedService): ServiceChange {\n if (stableKey(_withoutInPlaceFields(previous)) !== stableKey(_withoutInPlaceFields(next))) return 'restart';\n return stableKey(previous) === stableKey(next) ? 'none' : 'inPlace';\n}\n\n/** A canonical serialization: equal for semantically equal JSON values. */\nexport function stableKey(value: unknown): string {\n return JSON.stringify(value, (_key, v: unknown) => {\n if (v === null || typeof v !== 'object' || Array.isArray(v)) return v;\n return Object.fromEntries(\n Object.entries(v as Record<string, unknown>)\n .filter(([, entry]) => entry !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n );\n });\n}\n\n/**\n * Persistently enable or disable `name` with a minimal text edit, keeping the\n * file's comments and formatting. Enabling removes the key (the default).\n */\nexport function setServiceEnabledInText(text: string, name: string, enabled: boolean): string {\n const config = parseDaemonConfigText(text);\n if (!(name in config.services)) throw new Error(`unknown service '${name}'`);\n return _modify(text, ['services', name, 'enabled'], enabled ? undefined : false);\n}\n\n/** Persist `callLog.level` with a minimal text edit. `off` removes the key (the default), and `callLog` once empty. */\nexport function setCallLogLevelInText(text: string, level: CallLogLevel): string {\n parseDaemonConfigText(text);\n const edited = _modify(text, ['callLog', 'level'], level === 'off' ? undefined : level);\n const callLog: unknown = jsonc.parse(edited, [], { allowTrailingComma: true })?.callLog;\n const empty = callLog !== null && typeof callLog === 'object' && Object.keys(callLog).length === 0;\n return empty ? _modify(edited, ['callLog'], undefined) : edited;\n}\n\nfunction _modify(text: string, path: jsonc.JSONPath, value: unknown): string {\n const edits = jsonc.modify(text, path, value, {\n formattingOptions: { insertSpaces: true, tabSize: 4, eol: text.includes('\\r\\n') ? '\\r\\n' : '\\n' },\n });\n return jsonc.applyEdits(text, edits);\n}\n\n/** JSON Schema of the config file, for editor validation. */\nexport function daemonConfigJsonSchema(): unknown {\n const hubSchema = hubConfigJsonSchema() as { properties?: Record<string, Record<string, unknown>>; };\n const servicesSchema = z.toJSONSchema(\n z.object({ services: ServicesSchema, localEndpoint: LocalEndpointSchema, callLog: CallLogConfigSchema }),\n { target: 'draft-2020-12', io: 'input' },\n ) as { properties: Record<string, unknown>; };\n const forwardChecking = hubSchema.properties?.forwardChecking;\n return {\n ...hubSchema,\n properties: {\n ...hubSchema.properties,\n ...(forwardChecking ? { forwardChecking: { ...forwardChecking, default: false } } : {}),\n localEndpoint: servicesSchema.properties.localEndpoint,\n callLog: servicesSchema.properties.callLog,\n services: servicesSchema.properties.services,\n },\n };\n}\n\n/** The config written on first start. */\nexport const DEFAULT_CONFIG_TEXT = `{\n \"$schema\": \"./config.schema.json\",\n // Services the hub starts at login and keeps running. RPC-enabled services get\n // LINKRPC_ENDPOINT and LINKRPC_TOKEN and may claim the service ID\n // <hubServiceId>/<name> (default hub/<name>). Saving this file applies\n // changes; only changed services restart.\n \"services\": {\n // \"example\": {\n // \"command\": [\"node\", \"/path/to/service.js\"],\n // \"env\": { \"LOG_LEVEL\": \"info\" }\n // }\n }\n}\n`;\n\nfunction _withoutInPlaceFields(service: ManagedService): Record<string, unknown> {\n const copy: Record<string, unknown> = { ...service };\n for (const field of IN_PLACE_FIELDS) delete copy[field];\n return copy;\n}\n\nfunction _position(text: string, offset: number): { line: number; column: number; } {\n const before = text.slice(0, offset).split('\\n');\n return { line: before.length, column: before[before.length - 1]!.length + 1 };\n}\n","import { connectToHubManagement } from './client';\nimport type { AutostartManager } from './autostart/autostart';\nimport { type DaemonLaunch, spawnDetached } from './autostart/launch';\nimport { readEndpointDiscovery } from './discovery';\nimport type { DaemonStatus } from './managementInterface';\nimport type { HubHome } from './paths';\n\nconst POLL_MS = 200;\n\n/** The running daemon's status, or `undefined` when it does not answer. */\nexport async function queryDaemonStatus(home: HubHome, timeoutMs = 3_000): Promise<DaemonStatus | undefined> {\n let connection: Awaited<ReturnType<typeof connectToHubManagement>> | undefined;\n const attempt = (async () => {\n connection = await connectToHubManagement(home);\n return await connection.management.getStatus({});\n })();\n const timeout = new Promise<undefined>(resolve => setTimeout(() => resolve(undefined), timeoutMs).unref());\n try {\n return await Promise.race([attempt, timeout]);\n } catch {\n return undefined;\n } finally {\n attempt.catch(() => undefined).finally(() => connection?.close());\n }\n}\n\nexport interface StartDaemonOptions {\n readonly home: HubHome;\n readonly launch: DaemonLaunch;\n /** Start through the OS manager when it is registered there. */\n readonly autostart?: AutostartManager;\n readonly timeoutMs?: number;\n}\n\n/** Start the daemon in the background and wait until it answers. */\nexport async function startDaemon(options: StartDaemonOptions): Promise<'started' | 'already-running'> {\n if (await queryDaemonStatus(options.home)) return 'already-running';\n if (!await options.autostart?.startManaged()) spawnDetached(options.launch.keepAlive);\n const deadline = Date.now() + (options.timeoutMs ?? 20_000);\n while (Date.now() < deadline) {\n if (await queryDaemonStatus(options.home)) return 'started';\n await _sleep(POLL_MS);\n }\n throw new Error(`the hub daemon did not start; see ${options.home.logFile}`);\n}\n\n/** Ask the daemon to stop all services and exit, and wait until its process is gone. */\nexport async function stopDaemon(home: HubHome, timeoutMs = 30_000): Promise<'stopped' | 'not-running'> {\n const pid = readEndpointDiscovery(home.managementFile)?.pid;\n let connection: Awaited<ReturnType<typeof connectToHubManagement>>;\n try {\n connection = await connectToHubManagement(home);\n } catch (error) {\n if (pid === undefined) return 'not-running';\n if (error instanceof Error && 'code' in error && (error.code === 'ENOENT' || error.code === 'ECONNREFUSED') && !_isProcessAlive(pid)) {\n return 'not-running';\n }\n throw error;\n }\n try {\n await connection.management.shutdown({});\n } finally {\n connection.close();\n }\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (pid === undefined ? !await queryDaemonStatus(home) : !_isProcessAlive(pid)) return 'stopped';\n await _sleep(POLL_MS);\n }\n throw new Error(`the hub daemon did not stop within ${timeoutMs} ms`);\n}\n\nfunction _isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'EPERM';\n }\n}\n\nfunction _sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n","import type { JsonValue, LinkRpcConnection } from '@hediet/linkrpc';\nimport { type FlowSummary, formatFlowSummary } from '@hediet/linkrpc-hub';\nimport type { JsonDocumentEdit } from '@hediet/linkrpc-infra/json-document';\nimport { type LogDocument, type LogEntry, type LogLevel, type LogStreamEvent, loggingInterface } from '@hediet/linkrpc-infra/logging';\nimport { stableKey } from '../config';\nimport type { CallLogStore } from './callLogStore';\nimport type { CallRecord } from './callRecord';\n\n/** How many of the latest calls the `linkrpc.logging` document holds. */\nexport const CALL_LOG_WINDOW = 200;\n\n/**\n * The call log as a revisioned `linkrpc.logging` document: the latest\n * {@link CALL_LOG_WINDOW} calls (oldest first) plus the log's state. A call\n * that settles replaces its pending entry in place.\n */\nexport class CallLogDocument {\n private _entries: Array<{ readonly id: string; readonly entry: LogEntry; }> = [];\n private _state: Readonly<Record<string, unknown>>;\n private _revision = 0;\n private _loaded = false;\n private readonly _patchListeners = new Set<(event: LogStreamEvent) => void>();\n private readonly _subscription: { dispose(): void; };\n /** Resolves once the window holds the latest calls from disk. */\n public readonly ready: Promise<void>;\n\n constructor(\n private readonly _service: string,\n private readonly _startedAt: number,\n store: CallLogStore,\n state: Readonly<Record<string, unknown>>,\n ) {\n this._state = state;\n const early: CallRecord[] = [];\n this._subscription = store.onRecord(record => this._loaded ? this._add(record) : early.push(record));\n this.ready = store.query({}, CALL_LOG_WINDOW)\n .catch(() => ({ calls: [] }))\n .then(({ calls }) => {\n this._entries = [...calls].reverse().map(record => ({ id: record.id, entry: _toLogEntry(record) }));\n this._loaded = true;\n for (const record of early) this._add(record);\n });\n }\n\n public snapshot(): { revision: number; document: LogDocument; } {\n return {\n revision: this._revision,\n document: {\n schemaVersion: 1,\n service: this._service,\n startedAt: new Date(this._startedAt).toISOString(),\n state: this._state,\n entries: this._entries.map(({ entry }) => entry),\n },\n };\n }\n\n public setState(state: Readonly<Record<string, unknown>>): void {\n if (stableKey(state) === stableKey(this._state)) return;\n this._state = state;\n this._publish([{ op: 'set', path: '/state', value: state }]);\n }\n\n public onPatch(listener: (event: LogStreamEvent) => void): { dispose(): void; } {\n this._patchListeners.add(listener);\n return { dispose: () => this._patchListeners.delete(listener) };\n }\n\n public dispose(): void {\n this._subscription.dispose();\n this._patchListeners.clear();\n }\n\n private _add(record: CallRecord): void {\n const entry = _toLogEntry(record);\n const index = this._entries.findIndex(existing => existing.id === record.id);\n if (index >= 0) {\n this._entries[index] = { id: record.id, entry };\n this._publish([{ op: 'set', path: `/entries/${index}`, value: entry }]);\n return;\n }\n const edits: JsonDocumentEdit[] = [{ op: 'insert', path: '/entries', index: this._entries.length, value: entry }];\n this._entries.push({ id: record.id, entry });\n if (this._entries.length > CALL_LOG_WINDOW) {\n this._entries.shift();\n edits.push({ op: 'remove', path: '/entries/0' });\n }\n this._publish(edits);\n }\n\n private _publish(edits: JsonDocumentEdit[]): void {\n this._revision++;\n const event: LogStreamEvent = { type: 'patch', revision: this._revision, edits };\n for (const listener of [...this._patchListeners]) listener(event);\n }\n}\n\nexport interface CallLogLevelControl {\n level(): LogLevel;\n /** Persists the level in the daemon config. */\n setLevel(level: LogLevel): Promise<void>;\n}\n\n/** Serve `document` as `linkrpc.logging` under `serviceId`. */\nexport function registerCallLogService(\n connection: LinkRpcConnection,\n serviceId: string,\n document: CallLogDocument,\n control: CallLogLevelControl,\n): { dispose(): void; } {\n return connection.register(loggingInterface, {\n getLogLevel: () => ({ level: control.level() }),\n setLogLevel: async ({ level }) => {\n await control.setLevel(level);\n return {};\n },\n getLogSnapshot: async () => {\n await document.ready;\n return document.snapshot();\n },\n watchLog: async (_params, _ctx, stream) => {\n await document.ready;\n const send = (event: LogStreamEvent) => stream.send(event).catch(() => { /* the watcher went away */ });\n void send({ type: 'snapshot', ...document.snapshot() });\n const subscription = document.onPatch(event => void send(event));\n try {\n await new Promise<void>(resolve => {\n if (stream.signal.aborted) resolve();\n else stream.signal.addEventListener('abort', () => resolve(), { once: true });\n });\n } finally {\n subscription.dispose();\n }\n return {};\n },\n }, { serviceId });\n}\n\nfunction _toLogEntry(record: CallRecord): LogEntry {\n return {\n timestamp: new Date(record.at).toISOString(),\n level: record.level,\n message: formatFlowSummary(_asFlowSummary(record), 120),\n durationMs: record.durationMs,\n ...(record.error !== undefined ? { error: { name: 'RpcError', message: `${record.error.message} (code ${record.error.code})` } } : {}),\n attributes: record,\n };\n}\n\n/** Render a record like the hub's flow log (`--log-messages`, `hub traffic`). */\nfunction _asFlowSummary(record: CallRecord): FlowSummary {\n const params = record.params as JsonValue | undefined;\n const frame = record.kind === 'stream' ? params as { dir?: string; control?: string; payload?: JsonValue; } | undefined : undefined;\n return {\n id: record.id,\n kind: record.kind,\n method: record.method,\n params: frame ? undefined : params,\n status: record.status,\n result: record.result as JsonValue | undefined,\n error: record.error,\n startTs: record.at,\n endTs: record.status === 'pending' ? undefined : record.at + record.durationMs,\n durationMs: record.durationMs,\n path: [record.from.label, ...(record.to ? [record.to.label] : [])],\n partial: record.status === 'pending',\n ...(frame ? {\n stream: [{\n timeMs: record.at + record.durationMs,\n dir: frame.dir === 'toCallee' ? 'toCallee' : 'toCaller',\n ...(frame.control !== undefined ? { control: frame.control } : {}),\n ...(frame.payload !== undefined ? { payload: frame.payload } : {}),\n }],\n } : {}),\n };\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { CallLogRotation } from './callLogConfig';\nimport { type CallFilter, type CallRecord, createCallMatcher } from './callRecord';\n\nconst SEGMENT = /^calls-[0-9TZ-]+\\.ndjson$/;\nconst DAY_MS = 24 * 60 * 60_000;\n\nexport interface CallQueryResult {\n /** Newest first; one record per call id (the latest one written). */\n readonly calls: readonly CallRecord[];\n /** More records match beyond `limit`. */\n readonly truncated: boolean;\n}\n\n/**\n * The call log on disk: NDJSON segments `calls-<UTC start>.ndjson` in one\n * directory. Appends are buffered and written in order; a segment is closed\n * at `maxFileSizeMb`, and old segments beyond `maxFiles` or `maxAgeDays` are\n * deleted. The files are the source of truth for queries.\n */\nexport class CallLogStore {\n private readonly _queue: string[] = [];\n private readonly _listeners = new Set<(record: CallRecord) => void>();\n private _segment: { readonly file: string; readonly handle: fs.promises.FileHandle; size: number; } | undefined;\n private _drain: Promise<void> | undefined;\n private _lastStamp = 0;\n private _error: string | undefined;\n\n constructor(\n public readonly directory: string,\n private _rotation: CallLogRotation,\n private readonly _now: () => number = Date.now,\n ) { }\n\n /** The last write failure, if the latest write failed. */\n public get error(): string | undefined {\n return this._error;\n }\n\n public setRotation(rotation: CallLogRotation): void {\n this._rotation = rotation;\n }\n\n /** Queue `record` for writing and notify live listeners. */\n public append(record: CallRecord): void {\n this._queue.push(`${JSON.stringify(record)}\\n`);\n this._schedule();\n for (const listener of [...this._listeners]) listener(record);\n }\n\n public onRecord(listener: (record: CallRecord) => void): { dispose(): void; } {\n this._listeners.add(listener);\n return { dispose: () => this._listeners.delete(listener) };\n }\n\n /** Resolves once every appended record is written. */\n public async flush(): Promise<void> {\n while (this._drain) await this._drain;\n }\n\n public async query(filter: CallFilter = {}, limit = 200): Promise<CallQueryResult> {\n await this.flush();\n const matches = createCallMatcher(filter);\n const calls: CallRecord[] = [];\n const seen = new Set<string>();\n for (const name of (await this._segments()).reverse()) {\n const file = path.join(this.directory, name);\n let text: string;\n try {\n if (filter.since !== undefined && (await fs.promises.stat(file)).mtimeMs < filter.since) break;\n text = await fs.promises.readFile(file, 'utf8');\n } catch {\n continue; // deleted by retention meanwhile\n }\n const lines = text.split('\\n');\n for (let i = lines.length - 1; i >= 0; i--) {\n const record = _parseLine(lines[i]!);\n if (!record || seen.has(record.id)) continue;\n seen.add(record.id);\n if (!matches(record)) continue;\n if (calls.length === limit) return { calls, truncated: true };\n calls.push(record);\n }\n }\n return { calls, truncated: false };\n }\n\n public async close(): Promise<void> {\n await this.flush();\n this._listeners.clear();\n await this._closeSegment();\n }\n\n private _schedule(): void {\n this._drain ??= this._write().finally(() => {\n this._drain = undefined;\n if (this._queue.length > 0) this._schedule();\n });\n }\n\n private async _write(): Promise<void> {\n while (this._queue.length > 0) {\n const chunk = this._queue.splice(0).join('');\n try {\n const segment = this._segment ?? await this._openSegment();\n await segment.handle.write(chunk);\n segment.size += Buffer.byteLength(chunk);\n if (segment.size >= this._rotation.maxFileSizeMb * 1024 * 1024) await this._closeSegment();\n this._error = undefined;\n } catch (error) {\n this._error = `cannot write the call log: ${error instanceof Error ? error.message : String(error)}`;\n await this._closeSegment().catch(() => { /* reopened on the next write */ });\n }\n }\n }\n\n /** Continue the newest segment while it has room; otherwise start one and apply retention. */\n private async _openSegment(): Promise<NonNullable<CallLogStore['_segment']>> {\n await fs.promises.mkdir(this.directory, { recursive: true, mode: 0o700 });\n const newest = (await this._segments()).at(-1);\n if (newest !== undefined) {\n const file = path.join(this.directory, newest);\n const { size } = await fs.promises.stat(file);\n if (size < this._rotation.maxFileSizeMb * 1024 * 1024) {\n this._segment = { file, handle: await fs.promises.open(file, 'a', 0o600), size };\n return this._segment;\n }\n }\n const file = path.join(this.directory, `calls-${this._stamp()}.ndjson`);\n this._segment = { file, handle: await fs.promises.open(file, 'a', 0o600), size: 0 };\n await this._prune(file);\n return this._segment;\n }\n\n private async _closeSegment(): Promise<void> {\n const segment = this._segment;\n this._segment = undefined;\n await segment?.handle.close();\n }\n\n private async _prune(current: string): Promise<void> {\n const names = await this._segments();\n const expired = this._now() - this._rotation.maxAgeDays * DAY_MS;\n for (const [index, name] of names.entries()) {\n const file = path.join(this.directory, name);\n if (file === current) continue;\n const beyondCount = index < names.length - this._rotation.maxFiles;\n try {\n if (beyondCount || (await fs.promises.stat(file)).mtimeMs < expired) await fs.promises.rm(file, { force: true });\n } catch { /* already gone */ }\n }\n }\n\n /** Segment names, oldest first. */\n private async _segments(): Promise<string[]> {\n try {\n return (await fs.promises.readdir(this.directory)).filter(name => SEGMENT.test(name)).sort();\n } catch {\n return [];\n }\n }\n\n /** Sortable and unique: `2026-10-21T12-37-35-123Z`. */\n private _stamp(): string {\n this._lastStamp = Math.max(this._now(), this._lastStamp + 1);\n return new Date(this._lastStamp).toISOString().replace(/[:.]/g, '-');\n }\n}\n\nfunction _parseLine(line: string): CallRecord | undefined {\n if (line === '') return undefined;\n try {\n const value: unknown = JSON.parse(line);\n if (value === null || typeof value !== 'object' || !('v' in value) || value.v !== 1) return undefined;\n return value as CallRecord;\n } catch {\n return undefined; // a line cut short by a crash\n }\n}\n","import type { PayloadPolicy } from './callLogConfig';\n\nexport const REDACTED = '[redacted]';\n\n/**\n * Apply the payload policy to an application payload (`$hubrpc*` meta already\n * stripped): redact values under sensitive keys and, in `truncated` mode, cut\n * long strings, long arrays, and deep nesting per property. Returns\n * `undefined` for `mode: \"none\"`.\n */\nexport function shapePayload(value: unknown, policy: PayloadPolicy): unknown {\n if (policy.mode === 'none' || value === undefined) return undefined;\n const redactKeys = policy.redactKeys.map(_normalizeKey);\n const truncate = policy.mode === 'truncated';\n const shape = (current: unknown, depth: number): unknown => {\n if (typeof current === 'string') {\n if (!truncate || current.length <= policy.maxStringLength) return current;\n return `${current.slice(0, policy.maxStringLength)}…(+${current.length - policy.maxStringLength} chars)`;\n }\n if (current === null || typeof current !== 'object') return current;\n if (truncate && depth >= policy.maxDepth) return Array.isArray(current) ? '[…]' : '{…}';\n if (Array.isArray(current)) {\n const kept = truncate ? current.slice(0, policy.maxArrayItems) : current;\n const items = kept.map(item => shape(item, depth + 1));\n if (kept.length < current.length) items.push(`…(+${current.length - kept.length} items)`);\n return items;\n }\n return Object.fromEntries(Object.entries(current).map(([key, entry]) => {\n const normalized = _normalizeKey(key);\n return [key, redactKeys.some(redact => normalized.includes(redact)) ? REDACTED : shape(entry, depth + 1)];\n }));\n };\n return shape(value, 0);\n}\n\n/** UTF-8 size of the JSON encoding; `undefined` for absent payloads. */\nexport function payloadBytes(value: unknown): number | undefined {\n if (value === undefined) return undefined;\n const json = JSON.stringify(value);\n return json === undefined ? undefined : Buffer.byteLength(json);\n}\n\nfunction _normalizeKey(key: string): string {\n return key.toLowerCase().replace(/[_-]/g, '');\n}\n","import type { ParticipantDescriptor, TopologyGraph, TopologyTransportInfo } from '@hediet/linkrpc/inspection';\n\nconst MAX_HOPS = 3;\n/** Ports are never reused, so entries stay valid; the oldest are forgotten beyond this. */\nconst MAX_ENTRIES = 4_096;\n\n/** What the hub's topology graph says about the peer behind one of its ports. */\nexport interface PortPeer {\n /** How it is connected, e.g. `named-pipe \\\\.\\pipe\\…` or `websocket 10.0.0.2:5000`. */\n readonly transport?: string;\n /** The attacher's description of it, e.g. which managed service it is. */\n readonly descriptor?: ParticipantDescriptor;\n}\n\n/**\n * Describes the peer behind a hub port from the hub's topology graph: the\n * nearest link (within a few hops, not crossing the hub) that reports a\n * transport, and the nearest node with an attacher descriptor. A participant's\n * transport sits on its overlay's participant link, and its descriptor on the\n * node at the far end, two hops from the hub port.\n *\n * Call {@link observe} while the port's connection is open (when a call\n * enters): short-lived clients are gone from the topology by the time their\n * call is recorded.\n */\nexport class PortPeers {\n private readonly _known = new Map<string, PortPeer>();\n\n constructor(private readonly _readGraph: () => TopologyGraph) { }\n\n /** Resolve and remember `portId`'s peer; reads the graph only for unknown ports. */\n public observe(portId: string): void {\n if (this._known.has(portId)) return;\n for (const [port, peer] of _peersByHubPort(this._readGraph())) {\n if (!this._known.has(port)) this._remember(port, peer);\n }\n if (!this._known.has(portId)) this._remember(portId, {});\n }\n\n public describe(portId: string): PortPeer {\n return this._known.get(portId) ?? {};\n }\n\n private _remember(portId: string, peer: PortPeer): void {\n this._known.set(portId, peer);\n if (this._known.size > MAX_ENTRIES) this._known.delete(this._known.keys().next().value!);\n }\n}\n\nfunction _peersByHubPort(graph: TopologyGraph): Map<string, PortPeer> {\n const linksOf = new Map<string, TopologyGraph['links']>();\n for (const link of graph.links) {\n for (const nodeId of new Set([link.from.nodeId, link.to.nodeId])) {\n linksOf.set(nodeId, [...linksOf.get(nodeId) ?? [], link]);\n }\n }\n const nodes = new Map(graph.nodes.map(node => [node.nodeId, node]));\n const result = new Map<string, PortPeer>();\n for (const port of nodes.get(graph.entryNodeId)?.ports ?? []) {\n result.set(port.portId, _peerOf(graph.entryNodeId, port.portId, linksOf, nodes));\n }\n return result;\n}\n\nfunction _peerOf(\n hubNodeId: string,\n portId: string,\n linksOf: ReadonlyMap<string, TopologyGraph['links']>,\n nodes: ReadonlyMap<string, TopologyGraph['nodes'][number]>,\n): PortPeer {\n const isHubPort = (end: { nodeId: string; portId: string; }) => end.nodeId === hubNodeId && end.portId === portId;\n let frontier = (linksOf.get(hubNodeId) ?? []).filter(link => isHubPort(link.from) || isHubPort(link.to));\n const visited = new Set<string>([hubNodeId]);\n let transport: TopologyTransportInfo | undefined;\n let descriptor: ParticipantDescriptor | undefined;\n for (let hop = 0; hop < MAX_HOPS && frontier.length > 0 && (!transport || !descriptor); hop++) {\n transport ??= frontier.find(link => link.transport !== undefined)?.transport;\n const next: TopologyGraph['links'] = [];\n for (const link of frontier) {\n for (const nodeId of [link.from.nodeId, link.to.nodeId]) {\n if (visited.has(nodeId)) continue;\n visited.add(nodeId);\n descriptor ??= nodes.get(nodeId)?.descriptors?.find(source => source.source === 'attacher')?.descriptor;\n next.push(...(linksOf.get(nodeId) ?? []).filter(candidate => candidate !== link));\n }\n }\n frontier = next;\n }\n return {\n ...(transport !== undefined ? { transport: _format(transport) } : {}),\n ...(descriptor !== undefined ? { descriptor } : {}),\n };\n}\n\nfunction _format(transport: TopologyTransportInfo): string {\n const remote = transport.remote;\n const where = transport.path\n ?? (remote?.address !== undefined ? `${remote.address}${remote.port !== undefined ? `:${remote.port}` : ''}` : undefined);\n const forwardedFor = transport.metadata?.forwardedFor;\n return [transport.type, where, forwardedFor !== undefined ? `(for ${String(forwardedFor)})` : undefined]\n .filter(part => part !== undefined)\n .join(' ');\n}\n","/**\n * How the daemon describes the participants it connects to its hub: an\n * `attacher` descriptor on their topology node. Diagnostic only; the call log\n * and UIs use it to attribute traffic to configured services.\n */\nimport type { ParticipantDescriptor } from '@hediet/linkrpc/inspection';\n\nconst SERVICE_TYPE = 'linkrpc.hubDaemon.service';\nconst ENDPOINT_TYPE = 'linkrpc.hubDaemon.endpoint';\n\n/** A service configured under `services` in the daemon config. */\nexport function serviceDescriptor(name: string, serviceId: string): ParticipantDescriptor {\n return { type: SERVICE_TYPE, label: name, metadata: { serviceId } };\n}\n\n/** An endpoint managed through `linkrpc.managedEndpoints` (e.g. started by the CLI). */\nexport function endpointDescriptor(id: string, namespace: string, serviceId: string): ParticipantDescriptor {\n return { type: ENDPOINT_TYPE, label: id, metadata: { namespace, serviceId } };\n}\n\n/** The configured service a descriptor names, if it is one of ours. */\nexport function serviceNameOf(descriptor: ParticipantDescriptor | undefined): string | undefined {\n return descriptor?.type === SERVICE_TYPE ? descriptor.label : undefined;\n}\n","import { randomBytes } from 'node:crypto';\nimport { HUBRPC_META_KEY, parseMethodName, stripLinkRpcWireMeta } from '@hediet/linkrpc';\nimport type { InspectionHost } from '@hediet/linkrpc/inspection';\nimport { type FlowSummary, TrafficFlowAggregator } from '@hediet/linkrpc-hub';\nimport type { CallLogConfig } from './callLogConfig';\nimport { type CallPeer, type CallRecord, type CallRecordLevel, isCallLevelEnabled } from './callRecord';\nimport { payloadBytes, shapePayload } from './payloadPolicy';\nimport { PortPeers } from './portPeers';\nimport { serviceNameOf } from '../participantDescriptors';\n\n/** How long an unsettled call (e.g. a watch stream) is tracked before it is forgotten. */\nconst GIVE_UP_MS = 24 * 60 * 60_000;\n\nexport interface CallRecorderOptions {\n readonly inspection: InspectionHost;\n /** Read for every call, so level and payload changes apply immediately. */\n readonly config: () => CallLogConfig;\n readonly onRecord: (record: CallRecord) => void;\n /** Calls to this method prefix (the call log's own `linkrpc.logging`) are recorded without results or stream frames. */\n readonly ownMethodPrefix: string;\n}\n\n/**\n * Records the calls routed through a hub: observes its inspection traffic,\n * coalesces transits into flows with {@link TrafficFlowAggregator}, and turns\n * each flow into a {@link CallRecord}. Calls the hub itself originates\n * (peer discovery, ...) are not recorded.\n */\nexport class CallRecorder {\n private readonly _idPrefix = randomBytes(4).toString('hex');\n private readonly _aggregator: TrafficFlowAggregator;\n private readonly _peers: PortPeers;\n private readonly _observation: { dispose(): void; };\n\n constructor(private readonly _options: CallRecorderOptions) {\n this._peers = new PortPeers(() => _options.inspection.getGraph(''));\n this._aggregator = new TrafficFlowAggregator({ onFlow: flow => this._onFlow(flow), giveUpMs: GIVE_UP_MS });\n this._observation = _options.inspection.observeTraffic(transit => {\n if (transit.kind === 'request' || transit.kind === 'notification') {\n if (transit.in) this._peers.observe(transit.in.portId);\n if (transit.out) this._peers.observe(transit.out.portId);\n }\n this._aggregator.add(transit);\n });\n }\n\n public dispose(): void {\n this._observation.dispose();\n this._aggregator.dispose();\n }\n\n private _onFlow(flow: FlowSummary): void {\n const record = this._toRecord(flow, this._options.config());\n if (record) this._options.onRecord(record);\n }\n\n private _toRecord(flow: FlowSummary, config: CallLogConfig): CallRecord | undefined {\n if (flow.entryPortId === undefined || flow.method === undefined) return undefined;\n // The log never stores its own content: snapshots would copy earlier records into new ones.\n const ownCall = flow.method.startsWith(this._options.ownMethodPrefix);\n if (ownCall && flow.kind === 'stream') return undefined;\n const parsed = parseMethodName(flow.method);\n const serviceId = parsed?.kind === 'full' ? parsed.serviceId : undefined;\n const level = _levelOf(flow);\n if (!isCallLevelEnabled(level, config.level)) return undefined;\n\n const frame = flow.kind === 'stream' ? flow.stream?.[0] : undefined;\n const params = frame !== undefined\n ? { dir: frame.dir, ...(frame.control !== undefined ? { control: frame.control } : {}), payload: frame.payload }\n : stripLinkRpcWireMeta(flow.params);\n const principal = _principalOf(flow.params);\n const shapedParams = shapePayload(params, config.payloads);\n const shapedResult = ownCall ? undefined : shapePayload(flow.result, config.payloads);\n const paramsSize = payloadBytes(params);\n const resultSize = payloadBytes(flow.result);\n return {\n v: 1,\n id: `${this._idPrefix}-${flow.id}`,\n at: flow.startTs,\n level,\n kind: flow.kind === 'response' ? 'request' : flow.kind,\n status: flow.status,\n durationMs: flow.durationMs,\n method: flow.method,\n ...(serviceId !== undefined ? { serviceId } : {}),\n from: this._peer(flow.entryPortId),\n ...(flow.exitPortId !== undefined ? { to: this._peer(flow.exitPortId) } : {}),\n ...(principal !== undefined ? { principal } : {}),\n ...(flow.error !== undefined ? { error: { code: flow.error.code, message: flow.error.message } } : {}),\n ...(paramsSize !== undefined ? { paramsBytes: paramsSize } : {}),\n ...(resultSize !== undefined ? { resultBytes: resultSize } : {}),\n ...(shapedParams !== undefined ? { params: shapedParams } : {}),\n ...(shapedResult !== undefined ? { result: shapedResult } : {}),\n ...(frame === undefined && flow.stream !== undefined ? { streamFrames: flow.stream.length } : {}),\n };\n }\n\n private _peer(portId: string): CallPeer {\n const { transport, descriptor } = this._peers.describe(portId);\n const service = serviceNameOf(descriptor);\n return {\n label: this._aggregator.portLabel(portId),\n ...(transport !== undefined ? { transport } : {}),\n ...(service !== undefined ? { service } : {}),\n };\n }\n}\n\nfunction _levelOf(flow: FlowSummary): CallRecordLevel {\n if (flow.status === 'failed' || flow.status === 'unroutable' || flow.status === 'dropped') return 'error';\n if (flow.kind === 'stream') return 'trace';\n return flow.kind === 'notification' ? 'debug' : 'info';\n}\n\nfunction _principalOf(wireParams: unknown): string | undefined {\n if (wireParams === null || typeof wireParams !== 'object' || !(HUBRPC_META_KEY in wireParams)) return undefined;\n const meta: unknown = (wireParams as Record<string, unknown>)[HUBRPC_META_KEY];\n if (meta === null || typeof meta !== 'object' || !('principal' in meta)) return undefined;\n return typeof meta.principal === 'string' ? meta.principal : undefined;\n}\n","import type { LinkRpcConnection } from '@hediet/linkrpc';\nimport type { InspectionHost } from '@hediet/linkrpc/inspection';\nimport { loggingInterface } from '@hediet/linkrpc-infra/logging';\nimport { type CallLogConfig, CallLogConfigSchema } from './callLogConfig';\nimport { CallLogDocument, registerCallLogService } from './callLogService';\nimport { type CallQueryResult, CallLogStore } from './callLogStore';\nimport { type CallFilter, type CallLogLevel, type CallRecord, createCallMatcher } from './callRecord';\nimport { CallRecorder } from './callRecorder';\n\nexport interface CallLogStatus {\n readonly level: CallLogLevel;\n readonly directory: string;\n /** `<hubServiceId>/daemon` while the hub runs. */\n readonly serviceId?: string;\n readonly error?: string;\n}\n\ninterface AttachedHub {\n readonly inspection: InspectionHost;\n readonly serviceId: string;\n}\n\n/**\n * The daemon's persistent call log. Owns the files and the `linkrpc.logging`\n * document across hub restarts; records the attached hub's calls while the\n * configured level is not `off`. Configuration changes apply immediately.\n */\nexport class CallLog {\n private _config: CallLogConfig = CallLogConfigSchema.parse(undefined);\n private readonly _store: CallLogStore;\n private _document: CallLogDocument | undefined;\n private _hub: AttachedHub | undefined;\n private _recorder: CallRecorder | undefined;\n\n constructor(\n directory: string,\n private readonly _startedAt: number,\n /** Persists a level set over `linkrpc.logging` in the config file. */\n private readonly _persistLevel: (level: CallLogLevel) => Promise<void>,\n ) {\n this._store = new CallLogStore(directory, this._config.rotation);\n }\n\n public status(): CallLogStatus {\n return {\n level: this._config.level,\n directory: this._store.directory,\n ...(this._hub !== undefined ? { serviceId: this._hub.serviceId } : {}),\n ...(this._store.error !== undefined ? { error: this._store.error } : {}),\n };\n }\n\n public configure(config: CallLogConfig): void {\n this._config = config;\n this._store.setRotation(config.rotation);\n this._document?.setState(this._documentState());\n this._syncRecorder();\n }\n\n /**\n * Record the calls of a (re)started hub and serve the log as\n * `linkrpc.logging` under `serviceId` on `connection`.\n */\n public attach(inspection: InspectionHost, connection: LinkRpcConnection, serviceId: string): { dispose(): void; } {\n const hub: AttachedHub = { inspection, serviceId };\n this._hub = hub;\n this._recorder?.dispose();\n this._recorder = undefined;\n this._document?.dispose();\n const document = new CallLogDocument(serviceId, this._startedAt, this._store, this._documentState());\n this._document = document;\n const service = registerCallLogService(connection, serviceId, document, {\n level: () => this._config.level,\n setLevel: level => this._persistLevel(level),\n });\n this._syncRecorder();\n return {\n dispose: () => {\n service.dispose();\n if (this._hub !== hub) return;\n this._hub = undefined;\n this._document = undefined;\n document.dispose();\n this._syncRecorder();\n },\n };\n }\n\n public query(filter: CallFilter, limit?: number): Promise<CallQueryResult> {\n return this._store.query(filter, limit);\n }\n\n /** Live records matching `filter`, as they are written. */\n public watch(filter: CallFilter, listener: (record: CallRecord) => void): { dispose(): void; } {\n const matches = createCallMatcher(filter);\n return this._store.onRecord(record => {\n if (matches(record)) listener(record);\n });\n }\n\n public async close(): Promise<void> {\n this._recorder?.dispose();\n this._recorder = undefined;\n this._document?.dispose();\n await this._store.close();\n }\n\n private _syncRecorder(): void {\n const hub = this._hub;\n const record = hub !== undefined && this._config.level !== 'off';\n if (record && this._recorder === undefined) {\n this._recorder = new CallRecorder({\n inspection: hub.inspection,\n config: () => this._config,\n onRecord: call => this._store.append(call),\n ownMethodPrefix: `${hub.serviceId}::${loggingInterface.info.id}::`,\n });\n } else if (!record && this._recorder !== undefined) {\n this._recorder.dispose();\n this._recorder = undefined;\n }\n }\n\n private _documentState(): Readonly<Record<string, unknown>> {\n return { level: this._config.level, directory: this._store.directory, payloads: this._config.payloads.mode };\n }\n}\n","import { createHash } from 'node:crypto';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { daemonConfigJsonSchema, DEFAULT_CONFIG_TEXT, parseDaemonConfigText } from './config';\nimport type { ConfigDocument } from './managementInterface';\n\n/** Debounce for editors that save via several file operations. */\nconst WATCH_DEBOUNCE_MS = 150;\n\nexport class ConfigConflictError extends Error {\n constructor(file: string) {\n super(`${file} changed since it was read; reload and try again`);\n }\n}\n\n/** The daemon config file: revisioned reads, validated atomic writes, and change watching. */\nexport class ConfigFile {\n constructor(\n public readonly path: string,\n private readonly _schemaPath: string,\n ) { }\n\n /** Create the config (if missing) and refresh the JSON Schema beside it. */\n public ensureExists(): void {\n fs.mkdirSync(path.dirname(this.path), { recursive: true });\n fs.writeFileSync(this._schemaPath, JSON.stringify(daemonConfigJsonSchema(), null, 2) + '\\n');\n try {\n fs.writeFileSync(this.path, DEFAULT_CONFIG_TEXT, { flag: 'wx' });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n }\n }\n\n public read(): ConfigDocument {\n let text: string;\n try {\n text = fs.readFileSync(this.path, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n text = '';\n }\n return { path: this.path, text, revision: configRevision(text) };\n }\n\n /**\n * Replace the file if it still has `expectedRevision`. Invalid configs are\n * rejected before anything is written. Returns the new revision.\n */\n public write(text: string, expectedRevision: string): string {\n parseDaemonConfigText(text);\n if (this.read().revision !== expectedRevision) throw new ConfigConflictError(this.path);\n const tmp = `${this.path}.${process.pid}.tmp`;\n fs.writeFileSync(tmp, text);\n fs.renameSync(tmp, this.path);\n return configRevision(text);\n }\n\n /** Invoke `onChange` (debounced) whenever the file may have changed. */\n public watch(onChange: () => void): { dispose(): void; } {\n const name = path.basename(this.path);\n let timer: ReturnType<typeof setTimeout> | undefined;\n const watcher = fs.watch(path.dirname(this.path), (_event, filename) => {\n if (filename !== null && filename !== name) return;\n clearTimeout(timer);\n timer = setTimeout(onChange, WATCH_DEBOUNCE_MS);\n });\n watcher.on('error', () => { /* the next explicit reload re-reads the file */ });\n return {\n dispose: () => {\n clearTimeout(timer);\n watcher.close();\n },\n };\n }\n}\n\nexport function configRevision(text: string): string {\n return createHash('sha256').update(text).digest('hex').slice(0, 16);\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nconst MAX_LOG_BYTES = 5 * 1024 * 1024;\n\n/** The daemon's log file (rotated once at startup when large), optionally echoed to stderr. */\nexport class DaemonLog {\n public static open(file: string, options: { echo: boolean; }): DaemonLog {\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });\n try {\n if (fs.statSync(file).size > MAX_LOG_BYTES) fs.renameSync(file, `${file}.1`);\n } catch { /* no previous log */ }\n return new DaemonLog(fs.createWriteStream(file, { flags: 'a', mode: 0o600 }), options.echo);\n }\n\n private constructor(\n private readonly _stream: fs.WriteStream,\n private readonly _echo: boolean,\n ) { }\n\n public line(text: string): void {\n const line = `${new Date().toISOString()} ${text}\\n`;\n this._stream.write(line);\n if (this._echo) process.stderr.write(line);\n }\n\n public close(): Promise<void> {\n return new Promise(resolve => this._stream.end(resolve));\n }\n}\n","import * as fs from 'node:fs';\nimport * as net from 'node:net';\n\nexport class AlreadyRunningError extends Error {\n constructor() {\n super('The LinkRPC hub daemon is already running.');\n }\n}\n\n/**\n * Process-lifetime mutex: a bound local socket. The OS releases it when the\n * process dies, so no stale lock survives a crash (a stale Unix socket file is\n * detected by a refused probe connection and replaced).\n */\nexport class SingleInstanceLock {\n public static async acquire(endpoint: string): Promise<SingleInstanceLock> {\n try {\n return new SingleInstanceLock(await _listen(endpoint), endpoint);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EADDRINUSE') throw error;\n }\n if (process.platform === 'win32' || await _isAlive(endpoint)) throw new AlreadyRunningError();\n fs.rmSync(endpoint, { force: true });\n try {\n return new SingleInstanceLock(await _listen(endpoint), endpoint);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'EADDRINUSE') throw new AlreadyRunningError();\n throw error;\n }\n }\n\n private constructor(\n private readonly _server: net.Server,\n private readonly _endpoint: string,\n ) { }\n\n public dispose(): void {\n this._server.close();\n if (process.platform !== 'win32') fs.rmSync(this._endpoint, { force: true });\n }\n}\n\nfunction _listen(endpoint: string): Promise<net.Server> {\n return new Promise((resolve, reject) => {\n const server = net.createServer(socket => socket.destroy());\n server.once('error', reject);\n server.listen(endpoint, () => {\n server.off('error', reject);\n resolve(server);\n });\n });\n}\n\nfunction _isAlive(endpoint: string): Promise<boolean> {\n return new Promise(resolve => {\n const socket = net.connect(endpoint);\n socket.once('connect', () => {\n socket.destroy();\n resolve(true);\n });\n socket.once('error', () => resolve(false));\n });\n}\n","import type { LogLine } from './managementInterface';\n\n/** Output without a newline is cut into lines of at most this length. */\nconst MAX_LINE_LENGTH = 8_192;\n\n/** A bounded, line-oriented log of one service's output. */\nexport class LogBuffer {\n private readonly _lines: LogLine[] = [];\n private readonly _partial = new Map<LogLine['stream'], string>();\n\n constructor(private readonly _capacity = 1000) { }\n\n /** Append a chunk; returns the completed lines. Partial lines wait for their newline (up to a length limit). */\n public append(stream: LogLine['stream'], chunk: string): string[] {\n const parts = ((this._partial.get(stream) ?? '') + chunk).split(/\\r?\\n/);\n let partial = parts.pop()!;\n while (partial.length > MAX_LINE_LENGTH) {\n parts.push(partial.slice(0, MAX_LINE_LENGTH));\n partial = partial.slice(MAX_LINE_LENGTH);\n }\n this._partial.set(stream, partial);\n for (const text of parts) this._push({ at: Date.now(), stream, text });\n return parts;\n }\n\n public lines(limit = this._capacity): LogLine[] {\n return this._lines.slice(-limit);\n }\n\n private _push(line: LogLine): void {\n this._lines.push(line);\n if (this._lines.length > this._capacity) this._lines.splice(0, this._lines.length - this._capacity);\n }\n}\n","module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction checkPathExt (path, options) {\n var pathext = options.pathExt !== undefined ?\n options.pathExt : process.env.PATHEXT\n\n if (!pathext) {\n return true\n }\n\n pathext = pathext.split(';')\n if (pathext.indexOf('') !== -1) {\n return true\n }\n for (var i = 0; i < pathext.length; i++) {\n var p = pathext[i].toLowerCase()\n if (p && path.substr(-p.length).toLowerCase() === p) {\n return true\n }\n }\n return false\n}\n\nfunction checkStat (stat, path, options) {\n if (!stat.isSymbolicLink() && !stat.isFile()) {\n return false\n }\n return checkPathExt(path, options)\n}\n\nfunction isexe (path, options, cb) {\n fs.stat(path, function (er, stat) {\n cb(er, er ? false : checkStat(stat, path, options))\n })\n}\n\nfunction sync (path, options) {\n return checkStat(fs.statSync(path), path, options)\n}\n","module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction isexe (path, options, cb) {\n fs.stat(path, function (er, stat) {\n cb(er, er ? false : checkStat(stat, options))\n })\n}\n\nfunction sync (path, options) {\n return checkStat(fs.statSync(path), options)\n}\n\nfunction checkStat (stat, options) {\n return stat.isFile() && checkMode(stat, options)\n}\n\nfunction checkMode (stat, options) {\n var mod = stat.mode\n var uid = stat.uid\n var gid = stat.gid\n\n var myUid = options.uid !== undefined ?\n options.uid : process.getuid && process.getuid()\n var myGid = options.gid !== undefined ?\n options.gid : process.getgid && process.getgid()\n\n var u = parseInt('100', 8)\n var g = parseInt('010', 8)\n var o = parseInt('001', 8)\n var ug = u | g\n\n var ret = (mod & o) ||\n (mod & g) && gid === myGid ||\n (mod & u) && uid === myUid ||\n (mod & ug) && myUid === 0\n\n return ret\n}\n","var fs = require('fs')\nvar core\nif (process.platform === 'win32' || global.TESTING_WINDOWS) {\n core = require('./windows.js')\n} else {\n core = require('./mode.js')\n}\n\nmodule.exports = isexe\nisexe.sync = sync\n\nfunction isexe (path, options, cb) {\n if (typeof options === 'function') {\n cb = options\n options = {}\n }\n\n if (!cb) {\n if (typeof Promise !== 'function') {\n throw new TypeError('callback not provided')\n }\n\n return new Promise(function (resolve, reject) {\n isexe(path, options || {}, function (er, is) {\n if (er) {\n reject(er)\n } else {\n resolve(is)\n }\n })\n })\n }\n\n core(path, options || {}, function (er, is) {\n // ignore EACCES because that just means we aren't allowed to run it\n if (er) {\n if (er.code === 'EACCES' || options && options.ignoreErrors) {\n er = null\n is = false\n }\n }\n cb(er, is)\n })\n}\n\nfunction sync (path, options) {\n // my kingdom for a filtered catch\n try {\n return core.sync(path, options || {})\n } catch (er) {\n if (options && options.ignoreErrors || er.code === 'EACCES') {\n return false\n } else {\n throw er\n }\n }\n}\n","const isWindows = process.platform === 'win32' ||\n process.env.OSTYPE === 'cygwin' ||\n process.env.OSTYPE === 'msys'\n\nconst path = require('path')\nconst COLON = isWindows ? ';' : ':'\nconst isexe = require('isexe')\n\nconst getNotFoundError = (cmd) =>\n Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })\n\nconst getPathInfo = (cmd, opt) => {\n const colon = opt.colon || COLON\n\n // If it has a slash, then we don't bother searching the pathenv.\n // just check the file itself, and that's it.\n const pathEnv = cmd.match(/\\//) || isWindows && cmd.match(/\\\\/) ? ['']\n : (\n [\n // windows always checks the cwd first\n ...(isWindows ? [process.cwd()] : []),\n ...(opt.path || process.env.PATH ||\n /* istanbul ignore next: very unusual */ '').split(colon),\n ]\n )\n const pathExtExe = isWindows\n ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'\n : ''\n const pathExt = isWindows ? pathExtExe.split(colon) : ['']\n\n if (isWindows) {\n if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')\n pathExt.unshift('')\n }\n\n return {\n pathEnv,\n pathExt,\n pathExtExe,\n }\n}\n\nconst which = (cmd, opt, cb) => {\n if (typeof opt === 'function') {\n cb = opt\n opt = {}\n }\n if (!opt)\n opt = {}\n\n const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n const found = []\n\n const step = i => new Promise((resolve, reject) => {\n if (i === pathEnv.length)\n return opt.all && found.length ? resolve(found)\n : reject(getNotFoundError(cmd))\n\n const ppRaw = pathEnv[i]\n const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n const pCmd = path.join(pathPart, cmd)\n const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n : pCmd\n\n resolve(subStep(p, i, 0))\n })\n\n const subStep = (p, i, ii) => new Promise((resolve, reject) => {\n if (ii === pathExt.length)\n return resolve(step(i + 1))\n const ext = pathExt[ii]\n isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {\n if (!er && is) {\n if (opt.all)\n found.push(p + ext)\n else\n return resolve(p + ext)\n }\n return resolve(subStep(p, i, ii + 1))\n })\n })\n\n return cb ? step(0).then(res => cb(null, res), cb) : step(0)\n}\n\nconst whichSync = (cmd, opt) => {\n opt = opt || {}\n\n const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n const found = []\n\n for (let i = 0; i < pathEnv.length; i ++) {\n const ppRaw = pathEnv[i]\n const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n const pCmd = path.join(pathPart, cmd)\n const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n : pCmd\n\n for (let j = 0; j < pathExt.length; j ++) {\n const cur = p + pathExt[j]\n try {\n const is = isexe.sync(cur, { pathExt: pathExtExe })\n if (is) {\n if (opt.all)\n found.push(cur)\n else\n return cur\n }\n } catch (ex) {}\n }\n }\n\n if (opt.all && found.length)\n return found\n\n if (opt.nothrow)\n return null\n\n throw getNotFoundError(cmd)\n}\n\nmodule.exports = which\nwhich.sync = whichSync\n","'use strict';\n\nconst pathKey = (options = {}) => {\n\tconst environment = options.env || process.env;\n\tconst platform = options.platform || process.platform;\n\n\tif (platform !== 'win32') {\n\t\treturn 'PATH';\n\t}\n\n\treturn Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';\n};\n\nmodule.exports = pathKey;\n// TODO: Remove this for the next major release\nmodule.exports.default = pathKey;\n","'use strict';\n\nconst path = require('path');\nconst which = require('which');\nconst getPathKey = require('path-key');\n\nfunction resolveCommandAttempt(parsed, withoutPathExt) {\n const env = parsed.options.env || process.env;\n const cwd = process.cwd();\n const hasCustomCwd = parsed.options.cwd != null;\n // Worker threads do not have process.chdir()\n const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;\n\n // If a custom `cwd` was specified, we need to change the process cwd\n // because `which` will do stat calls but does not support a custom cwd\n if (shouldSwitchCwd) {\n try {\n process.chdir(parsed.options.cwd);\n } catch (err) {\n /* Empty */\n }\n }\n\n let resolved;\n\n try {\n resolved = which.sync(parsed.command, {\n path: env[getPathKey({ env })],\n pathExt: withoutPathExt ? path.delimiter : undefined,\n });\n } catch (e) {\n /* Empty */\n } finally {\n if (shouldSwitchCwd) {\n process.chdir(cwd);\n }\n }\n\n // If we successfully resolved, ensure that an absolute path is returned\n // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it\n if (resolved) {\n resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);\n }\n\n return resolved;\n}\n\nfunction resolveCommand(parsed) {\n return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);\n}\n\nmodule.exports = resolveCommand;\n","'use strict';\n\n// See http://www.robvanderwoude.com/escapechars.php\nconst metaCharsRegExp = /([()\\][%!^\"`<>&|;, *?])/g;\n\nfunction escapeCommand(arg) {\n // Escape meta chars\n arg = arg.replace(metaCharsRegExp, '^$1');\n\n return arg;\n}\n\nfunction escapeArgument(arg, doubleEscapeMetaChars) {\n // Convert to string\n arg = `${arg}`;\n\n // Algorithm below is based on https://qntm.org/cmd\n // It's slightly altered to disable JS backtracking to avoid hanging on specially crafted input\n // Please see https://github.com/moxystudio/node-cross-spawn/pull/160 for more information\n\n // Sequence of backslashes followed by a double quote:\n // double up all the backslashes and escape the double quote\n arg = arg.replace(/(?=(\\\\+?)?)\\1\"/g, '$1$1\\\\\"');\n\n // Sequence of backslashes followed by the end of the string\n // (which will become a double quote later):\n // double up all the backslashes\n arg = arg.replace(/(?=(\\\\+?)?)\\1$/, '$1$1');\n\n // All other backslashes occur literally\n\n // Quote the whole thing:\n arg = `\"${arg}\"`;\n\n // Escape meta chars\n arg = arg.replace(metaCharsRegExp, '^$1');\n\n // Double escape meta chars if necessary\n if (doubleEscapeMetaChars) {\n arg = arg.replace(metaCharsRegExp, '^$1');\n }\n\n return arg;\n}\n\nmodule.exports.command = escapeCommand;\nmodule.exports.argument = escapeArgument;\n","'use strict';\nmodule.exports = /^#!(.*)/;\n","'use strict';\nconst shebangRegex = require('shebang-regex');\n\nmodule.exports = (string = '') => {\n\tconst match = string.match(shebangRegex);\n\n\tif (!match) {\n\t\treturn null;\n\t}\n\n\tconst [path, argument] = match[0].replace(/#! ?/, '').split(' ');\n\tconst binary = path.split('/').pop();\n\n\tif (binary === 'env') {\n\t\treturn argument;\n\t}\n\n\treturn argument ? `${binary} ${argument}` : binary;\n};\n","'use strict';\n\nconst fs = require('fs');\nconst shebangCommand = require('shebang-command');\n\nfunction readShebang(command) {\n // Read the first 150 bytes from the file\n const size = 150;\n const buffer = Buffer.alloc(size);\n\n let fd;\n\n try {\n fd = fs.openSync(command, 'r');\n fs.readSync(fd, buffer, 0, size, 0);\n fs.closeSync(fd);\n } catch (e) { /* Empty */ }\n\n // Attempt to extract shebang (null is returned if not a shebang)\n return shebangCommand(buffer.toString());\n}\n\nmodule.exports = readShebang;\n","'use strict';\n\nconst path = require('path');\nconst resolveCommand = require('./util/resolveCommand');\nconst escape = require('./util/escape');\nconst readShebang = require('./util/readShebang');\n\nconst isWin = process.platform === 'win32';\nconst isExecutableRegExp = /\\.(?:com|exe)$/i;\nconst isCmdShimRegExp = /node_modules[\\\\/].bin[\\\\/][^\\\\/]+\\.cmd$/i;\n\nfunction detectShebang(parsed) {\n parsed.file = resolveCommand(parsed);\n\n const shebang = parsed.file && readShebang(parsed.file);\n\n if (shebang) {\n parsed.args.unshift(parsed.file);\n parsed.command = shebang;\n\n return resolveCommand(parsed);\n }\n\n return parsed.file;\n}\n\nfunction parseNonShell(parsed) {\n if (!isWin) {\n return parsed;\n }\n\n // Detect & add support for shebangs\n const commandFile = detectShebang(parsed);\n\n // We don't need a shell if the command filename is an executable\n const needsShell = !isExecutableRegExp.test(commandFile);\n\n // If a shell is required, use cmd.exe and take care of escaping everything correctly\n // Note that `forceShell` is an hidden option used only in tests\n if (parsed.options.forceShell || needsShell) {\n // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`\n // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument\n // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,\n // we need to double escape them\n const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);\n\n // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\\bar)\n // This is necessary otherwise it will always fail with ENOENT in those cases\n parsed.command = path.normalize(parsed.command);\n\n // Escape command & arguments\n parsed.command = escape.command(parsed.command);\n parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));\n\n const shellCommand = [parsed.command].concat(parsed.args).join(' ');\n\n parsed.args = ['/d', '/s', '/c', `\"${shellCommand}\"`];\n parsed.command = process.env.comspec || 'cmd.exe';\n parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped\n }\n\n return parsed;\n}\n\nfunction parse(command, args, options) {\n // Normalize arguments, similar to nodejs\n if (args && !Array.isArray(args)) {\n options = args;\n args = null;\n }\n\n args = args ? args.slice(0) : []; // Clone array to avoid changing the original\n options = Object.assign({}, options); // Clone object to avoid changing the original\n\n // Build our parsed object\n const parsed = {\n command,\n args,\n options,\n file: undefined,\n original: {\n command,\n args,\n },\n };\n\n // Delegate further parsing to shell or non-shell\n return options.shell ? parsed : parseNonShell(parsed);\n}\n\nmodule.exports = parse;\n","'use strict';\n\nconst isWin = process.platform === 'win32';\n\nfunction notFoundError(original, syscall) {\n return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {\n code: 'ENOENT',\n errno: 'ENOENT',\n syscall: `${syscall} ${original.command}`,\n path: original.command,\n spawnargs: original.args,\n });\n}\n\nfunction hookChildProcess(cp, parsed) {\n if (!isWin) {\n return;\n }\n\n const originalEmit = cp.emit;\n\n cp.emit = function (name, arg1) {\n // If emitting \"exit\" event and exit code is 1, we need to check if\n // the command exists and emit an \"error\" instead\n // See https://github.com/IndigoUnited/node-cross-spawn/issues/16\n if (name === 'exit') {\n const err = verifyENOENT(arg1, parsed);\n\n if (err) {\n return originalEmit.call(cp, 'error', err);\n }\n }\n\n return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params\n };\n}\n\nfunction verifyENOENT(status, parsed) {\n if (isWin && status === 1 && !parsed.file) {\n return notFoundError(parsed.original, 'spawn');\n }\n\n return null;\n}\n\nfunction verifyENOENTSync(status, parsed) {\n if (isWin && status === 1 && !parsed.file) {\n return notFoundError(parsed.original, 'spawnSync');\n }\n\n return null;\n}\n\nmodule.exports = {\n hookChildProcess,\n verifyENOENT,\n verifyENOENTSync,\n notFoundError,\n};\n","'use strict';\n\nconst cp = require('child_process');\nconst parse = require('./lib/parse');\nconst enoent = require('./lib/enoent');\n\nfunction spawn(command, args, options) {\n // Parse the arguments\n const parsed = parse(command, args, options);\n\n // Spawn the child process\n const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);\n\n // Hook into child process \"exit\" event to emit an error if the command\n // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n enoent.hookChildProcess(spawned, parsed);\n\n return spawned;\n}\n\nfunction spawnSync(command, args, options) {\n // Parse the arguments\n const parsed = parse(command, args, options);\n\n // Spawn the child process\n const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);\n\n // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);\n\n return result;\n}\n\nmodule.exports = spawn;\nmodule.exports.spawn = spawn;\nmodule.exports.sync = spawnSync;\n\nmodule.exports._parse = parse;\nmodule.exports._enoent = enoent;\n","import { spawn } from 'node:child_process';\nimport * as path from 'node:path';\n\n/**\n * Whether children get their own process group, so that the whole tree can be\n * signalled. Windows has no process groups; `taskkill /T` walks the tree.\n */\nexport const SPAWN_DETACHED = process.platform !== 'win32';\n\n/** Ask a service's process tree to exit (POSIX only; Windows has no equivalent). */\nexport function terminateProcessTree(pid: number): void {\n if (process.platform === 'win32') return;\n _signalGroup(pid, 'SIGTERM');\n}\n\n/** Deliver a POSIX signal to a service's process group. */\nexport function signalProcessGroup(pid: number, signal: NodeJS.Signals): void {\n _signalGroup(pid, signal);\n}\n\n/** Forcefully end a process and all of its descendants. */\nexport function killProcessTree(pid: number): Promise<void> {\n if (process.platform !== 'win32') {\n _signalGroup(pid, 'SIGKILL');\n return Promise.resolve();\n }\n const taskkill = path.join(process.env.SystemRoot ?? 'C:\\\\Windows', 'System32', 'taskkill.exe');\n return new Promise(resolve => {\n const child = spawn(taskkill, ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true });\n child.once('error', () => resolve());\n child.once('exit', () => resolve());\n });\n}\n\nfunction _signalGroup(pid: number, signal: NodeJS.Signals): void {\n try {\n process.kill(-pid, signal);\n } catch {\n try {\n process.kill(pid, signal);\n } catch { /* already gone */ }\n }\n}\n","import * as os from 'node:os';\nimport { StringDecoder } from 'node:string_decoder';\nimport crossSpawn from 'cross-spawn';\nimport type { ConsoleSignal, ConsoleSize } from '@hediet/linkrpc-infra/console';\nimport { killProcessTree, signalProcessGroup, SPAWN_DETACHED } from './processTree';\n\nexport interface ExitInfo {\n readonly code: number | null;\n readonly signal: string | null;\n /** Set when the process never started. */\n readonly error?: string;\n}\n\n/** A spawned service process and its console I/O, over pipes or a pseudoterminal. */\nexport interface ServiceProcess {\n readonly pid: number | undefined;\n /** Resolves once the process runs; never resolves when spawning fails. */\n readonly spawned: Promise<void>;\n readonly exited: Promise<ExitInfo>;\n write(data: Uint8Array): void;\n resize(size: ConsoleSize): void;\n signal(signal: ConsoleSignal): void;\n /** Forcefully end the process tree. */\n kill(): Promise<void>;\n}\n\nexport interface SpawnServiceOptions {\n readonly command: readonly string[];\n readonly env: NodeJS.ProcessEnv;\n readonly cwd?: string;\n readonly onOutput: (stream: 'stdout' | 'stderr' | 'tty', data: Uint8Array) => void;\n readonly onError: (message: string) => void;\n}\n\n/** Signals a service process receives with their usual meaning. */\nexport function processSignals(tty: boolean, platform: NodeJS.Platform = process.platform): ConsoleSignal[] {\n if (platform !== 'win32') return ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGQUIT', 'SIGKILL'];\n // Windows has no signals; only a console (ConPTY) can deliver Ctrl+C, everything else terminates.\n return tty ? ['SIGINT', 'SIGKILL'] : ['SIGKILL'];\n}\n\nexport function spawnPipeProcess(options: SpawnServiceOptions): ServiceProcess {\n const [executable, ...args] = options.command;\n // cross-spawn resolves PATHEXT and escapes arguments for `.cmd` shims, so\n // `command` never goes through a shell's word splitting or metacharacters.\n const child = crossSpawn(executable!, args, {\n env: options.env,\n ...(options.cwd !== undefined ? { cwd: options.cwd } : {}),\n stdio: ['pipe', 'pipe', 'pipe'],\n windowsHide: true,\n detached: SPAWN_DETACHED,\n });\n const exited = new Promise<ExitInfo>(resolve => {\n child.once('close', (code, signal) => resolve({ code, signal }));\n child.once('error', error => {\n if (child.pid === undefined) resolve({ code: null, signal: null, error: error.message });\n else options.onError(`process error: ${error.message}`);\n });\n });\n for (const stream of ['stdout', 'stderr'] as const) {\n child[stream]?.on('data', (chunk: Buffer) => options.onOutput(stream, chunk));\n }\n child.stdin?.on('error', error => options.onError(`stdin failed: ${error.message}`));\n return {\n get pid() { return child.pid; },\n spawned: new Promise(resolve => child.once('spawn', () => resolve())),\n exited,\n write: data => {\n if (!child.stdin?.writable) throw new Error('The process stdin is closed');\n child.stdin.write(data);\n },\n resize: () => {},\n signal: signal => signalProcess(child.pid, signal),\n kill: async () => { if (child.pid !== undefined) await killProcessTree(child.pid); },\n };\n}\n\nexport async function spawnPtyProcess(options: SpawnServiceOptions & { readonly size: ConsoleSize }): Promise<ServiceProcess> {\n const pty = await loadPty();\n const { file, args } = ptyCommand(options.command);\n const env: Record<string, string> = {};\n for (const [key, value] of Object.entries(options.env)) if (value !== undefined) env[key] = value;\n const terminal = pty.spawn(file, args, {\n name: 'xterm-256color',\n cols: options.size.cols,\n rows: options.size.rows,\n cwd: options.cwd ?? process.cwd(),\n env,\n });\n terminal.onData(data => options.onOutput('tty', Buffer.from(data, 'utf8')));\n const exited = new Promise<ExitInfo>(resolve => terminal.onExit(({ exitCode, signal }) => resolve(signal\n ? { code: null, signal: signalName(signal) }\n : { code: exitCode, signal: null })));\n // Input chunks may split multi-byte characters; node-pty writes strings.\n const decoder = new StringDecoder('utf8');\n // ConPTY assigns the process ID asynchronously; node-pty reports 0 until then.\n const pid = () => terminal.pid > 0 ? terminal.pid : undefined;\n const kill = async () => {\n const current = pid();\n if (current !== undefined) await killProcessTree(current);\n // Closing the pseudoconsole reports the exit promptly.\n try { terminal.kill(); } catch { /* already closed */ }\n };\n return {\n get pid() { return pid(); },\n spawned: waitFor(() => pid() !== undefined, exited),\n exited,\n write: data => {\n const text = decoder.write(Buffer.from(data));\n if (text) terminal.write(text);\n },\n resize: size => terminal.resize(size.cols, size.rows),\n signal: signal => {\n // ConPTY turns ETX into a Ctrl+C event for the console's processes.\n if (signal === 'SIGINT' && process.platform === 'win32') terminal.write('\\x03');\n else if (signal === 'SIGKILL') void kill();\n else signalProcess(pid(), signal);\n },\n kill,\n };\n}\n\n/** Resolve once `condition` holds, or once `until` settles. */\nasync function waitFor(condition: () => boolean, until: Promise<unknown>): Promise<void> {\n let settled = false;\n void until.then(() => { settled = true; });\n while (!condition() && !settled) await new Promise(resolve => setTimeout(resolve, 5));\n}\n\nfunction signalProcess(pid: number | undefined, signal: ConsoleSignal): void {\n if (pid === undefined) throw new Error('The process is not running');\n if (signal === 'SIGKILL') void killProcessTree(pid);\n else if (process.platform === 'win32') throw new Error(`${signal} cannot be delivered on Windows`);\n else signalProcessGroup(pid, signal);\n}\n\ntype PtyModule = typeof import('@lydell/node-pty');\nlet ptyModule: Promise<PtyModule> | undefined;\n\nfunction loadPty(): Promise<PtyModule> {\n ptyModule ??= import('@lydell/node-pty').then(\n module => (module as { default?: PtyModule }).default ?? module,\n error => {\n ptyModule = undefined;\n throw new Error(`TTY support is unavailable: ${error instanceof Error ? error.message : String(error)}`);\n },\n );\n return ptyModule;\n}\n\ninterface ParsedCommand {\n readonly command: string;\n readonly args: string[];\n readonly file?: string;\n readonly options: { readonly windowsVerbatimArguments?: boolean };\n}\n\n/** Resolve like {@link spawnPipeProcess}: PATHEXT lookup and escaped `.cmd` shims on Windows. */\nfunction ptyCommand(command: readonly string[]): { file: string; args: string[] | string } {\n const [executable, ...args] = command;\n if (process.platform !== 'win32') return { file: executable!, args };\n const parse = (crossSpawn as unknown as { _parse(command: string, args: string[], options: object): ParsedCommand })._parse;\n const parsed = parse(executable!, args, {});\n // A shim runs through cmd.exe with an already escaped command line.\n if (parsed.options.windowsVerbatimArguments) return { file: parsed.command, args: parsed.args.join(' ') };\n return { file: parsed.file ?? parsed.command, args: parsed.args };\n}\n\nfunction signalName(signal: number): string {\n return Object.entries(os.constants.signals).find(([, value]) => value === signal)?.[0] ?? String(signal);\n}\n","import { StringDecoder } from 'node:string_decoder';\nimport type { ConsoleSignal, ConsoleSize } from '@hediet/linkrpc-infra/console';\nimport type { ParticipantDescriptor } from '@hediet/linkrpc/inspection';\nimport type { ManagedService } from './config';\nimport { LogBuffer } from './logBuffer';\nimport type { LogLine, ServiceState, ServiceStatus } from './managementInterface';\nimport { spawnPipeProcess, spawnPtyProcess, type ExitInfo, type ServiceProcess } from './processIo';\nimport { terminateProcessTree } from './processTree';\n\nconst MIN_BACKOFF_MS = 500;\nconst MAX_BACKOFF_MS = 30_000;\n/** A process that stays up this long resets the backoff. */\nconst STABLE_AFTER_MS = 10_000;\nconst KILL_WAIT_MS = 5_000;\n\n/** The hub-side resources a supervisor needs. */\nexport interface ServiceHost {\n /**\n * Open the private hub socket the service dials (`LINKRPC_ENDPOINT`/`LINKRPC_TOKEN`).\n * `descriptor` describes its peers in the hub's topology; the host picks one by default.\n */\n openSocket(\n name: string,\n service: ManagedService,\n onConnectionCountChanged: (count: number) => void,\n descriptor?: ParticipantDescriptor,\n ): Promise<ServiceSocket>;\n log(name: string, line: string): void;\n output?(name: string, stream: 'stdout' | 'stderr' | 'tty', data: Uint8Array): void;\n /** Supervisor messages, such as exits and restart backoff. */\n notice?(name: string, text: string): void;\n processStarted?(name: string, pid: number | undefined): void;\n processExited?(name: string, exit: { code: number | null; signal: string | null }): void;\n}\n\nexport interface ServiceSocket {\n readonly env: Readonly<Record<string, string>>;\n dispose(): void;\n}\n\n/**\n * Keeps one configured service in its desired state: spawns it with a hub\n * socket, tracks readiness, restarts it with exponential backoff according to\n * its restart policy, and stops it gracefully (hub disconnect, SIGTERM) before\n * killing its process tree. All state transitions are serialized.\n */\nexport class ServiceSupervisor {\n private _service: ManagedService;\n private _state: ServiceState;\n private _since = Date.now();\n private _process: ServiceProcess | undefined;\n private _socket: ServiceSocket | undefined;\n private _connections = 0;\n private _restarts = 0;\n private _consecutiveFailures = 0;\n private _lastExit: ServiceStatus['lastExit'];\n private _error: string | undefined;\n private _stopping = false;\n private _disposed = false;\n private _backoffTimer: ReturnType<typeof setTimeout> | undefined;\n private _startTimer: ReturnType<typeof setTimeout> | undefined;\n private _stableTimer: ReturnType<typeof setTimeout> | undefined;\n private _ops: Promise<void> = Promise.resolve();\n private readonly _logs = new LogBuffer();\n private readonly _decoders = { stdout: new StringDecoder('utf8'), stderr: new StringDecoder('utf8'), tty: new StringDecoder('utf8') };\n private _size: ConsoleSize = { cols: 80, rows: 24 };\n\n constructor(\n public readonly name: string,\n service: ManagedService,\n private readonly _host: ServiceHost,\n private readonly _onDidChange: () => void,\n ) {\n this._service = service;\n this._state = service.enabled ? 'stopped' : 'disabled';\n }\n\n public get service(): ManagedService {\n return this._service;\n }\n\n public status(): ServiceStatus {\n return {\n name: this.name,\n description: this._service.description,\n serviceId: this._service.serviceId,\n enabled: this._service.enabled,\n state: this._state,\n since: this._since,\n pid: this._process?.pid,\n connections: this._connections,\n restarts: this._restarts,\n lastExit: this._lastExit,\n error: this._error,\n };\n }\n\n public logs(limit?: number): LogLine[] {\n return this._logs.lines(limit);\n }\n\n public write(data: Uint8Array): void {\n this._running().write(data);\n }\n\n /** Applies to the running pseudoterminal and to later starts. */\n public resize(size: ConsoleSize): void {\n this._size = size;\n this._process?.resize(size);\n }\n\n public signal(signal: ConsoleSignal): void {\n this._running().signal(signal);\n }\n\n private _running(): ServiceProcess {\n if (!this._process) throw new Error('The process is not running');\n return this._process;\n }\n\n /** Start or stop to match `enabled`. */\n public sync(): Promise<void> {\n return this._enqueue(() => (this._service.enabled ? this._launch() : this._stop('disabled')));\n }\n\n /** Apply a change that keeps the process (see `classifyServiceChange`); only `enabled` starts or stops it. */\n public update(service: ManagedService): Promise<void> {\n const enabledChanged = service.enabled !== this._service.enabled;\n this._service = service;\n if (!enabledChanged) {\n this._onDidChange();\n return Promise.resolve();\n }\n this._logDaemon(service.enabled ? 'enabled' : 'disabled');\n return this.sync();\n }\n\n public restart(): Promise<void> {\n return this._enqueue(async () => {\n if (!this._service.enabled) throw new Error(`service '${this.name}' is disabled`);\n this._logDaemon('restart requested');\n await this._stop('stopped');\n this._consecutiveFailures = 0;\n await this._launch();\n });\n }\n\n /** Stop the service for good. */\n public dispose(): Promise<void> {\n this._disposed = true;\n return this._enqueue(() => this._stop('stopped'), { evenIfDisposed: true });\n }\n\n private _enqueue(op: () => Promise<void>, options: { evenIfDisposed?: boolean; } = {}): Promise<void> {\n const run = this._ops.then(() => (this._disposed && !options.evenIfDisposed ? undefined : op()));\n this._ops = run.catch(error => this._logDaemon(`error: ${_message(error)}`));\n return run;\n }\n\n private async _launch(): Promise<void> {\n if (this._disposed || !this._service.enabled || this._process || this._backoffTimer) return;\n await this._spawn();\n }\n\n private async _spawn(): Promise<void> {\n const service = this._service;\n if (service.command === undefined) throw new Error(`service '${this.name}' has no command`);\n try {\n if (service.rpc) {\n this._socket ??= await this._host.openSocket(this.name, service, count => this._onConnections(count));\n }\n } catch (error) {\n this._error = `cannot connect to the hub: ${_message(error)}`;\n this._logDaemon(this._error);\n this._setState('failed');\n return;\n }\n const env = { ...process.env };\n if (!service.rpc) {\n for (const key of Object.keys(env)) {\n if (/^(LINKRPC|HUBRPC)_(ENDPOINT|TOKEN)$/i.test(key)) delete env[key];\n }\n }\n const options = {\n command: service.command,\n env: { ...env, ...service.env, ...this._socket?.env },\n ...(service.cwd !== undefined ? { cwd: service.cwd } : {}),\n onOutput: (stream: 'stdout' | 'stderr' | 'tty', data: Uint8Array) => this._appendOutput(stream, data),\n onError: (message: string) => this._logDaemon(message),\n };\n let spawned: ServiceProcess;\n try {\n spawned = service.tty ? await spawnPtyProcess({ ...options, size: this._size }) : spawnPipeProcess(options);\n } catch (error) {\n this._onSpawnFailed(_message(error));\n return;\n }\n this._process = spawned;\n this._error = undefined;\n this._setState('starting');\n void spawned.spawned.then(() => {\n if (this._process === spawned) this._host.processStarted?.(this.name, spawned.pid);\n });\n if (!service.rpc || service.readiness === 'spawned') {\n void spawned.spawned.then(() => {\n if (this._process === spawned && this._state === 'starting') this._markRunning();\n });\n } else {\n this._startTimer = setTimeout(() => {\n if (this._process !== spawned || this._state !== 'starting') return;\n this._error = `did not connect to the hub within ${service.startTimeoutMs} ms`;\n this._logDaemon(this._error);\n void spawned.kill();\n }, service.startTimeoutMs);\n }\n void spawned.exited.then(info => this._onExit(spawned, info));\n }\n\n private _onSpawnFailed(error: string): void {\n this._lastExit = { code: null, signal: null, at: Date.now() };\n this._error = `cannot start: ${error}`;\n this._logDaemon(this._error);\n this._releaseSocket();\n this._setState('failed');\n }\n\n private _onExit(process: ServiceProcess, info: ExitInfo): void {\n if (this._process !== process) return;\n this._process = undefined;\n this._clearProcessTimers();\n this._lastExit = { code: info.code, signal: info.signal, at: Date.now() };\n if (info.error === undefined) this._host.processExited?.(this.name, { code: info.code, signal: info.signal });\n if (this._stopping) return;\n\n const failed = info.error !== undefined || info.code !== 0 || info.signal !== null;\n if (info.error !== undefined) this._error = `cannot start: ${info.error}`;\n else if (failed) this._error ??= _describeExit(info);\n const policy = this._service.restart;\n const restart = !this._disposed && this._service.enabled\n && (policy === 'always' || (policy === 'on-failure' && failed));\n if (!restart) {\n this._logDaemon(_describeExit(info));\n this._releaseSocket();\n this._setState(failed ? 'failed' : 'stopped');\n return;\n }\n const delay = Math.min(MAX_BACKOFF_MS, MIN_BACKOFF_MS * 2 ** this._consecutiveFailures);\n this._consecutiveFailures++;\n this._logDaemon(`${_describeExit(info)}; restarting in ${delay} ms`);\n const timer = setTimeout(() => {\n void this._enqueue(async () => {\n if (this._backoffTimer !== timer) return;\n this._backoffTimer = undefined;\n this._restarts++;\n await this._spawn();\n });\n }, delay);\n this._backoffTimer = timer;\n this._setState('backoff');\n }\n\n private async _stop(finalState: 'stopped' | 'disabled'): Promise<void> {\n clearTimeout(this._backoffTimer);\n this._backoffTimer = undefined;\n const running = this._process;\n if (running) {\n this._stopping = true;\n this._setState('stopping');\n try {\n await this._terminate(running);\n } finally {\n this._stopping = false;\n this._process = undefined;\n this._clearProcessTimers();\n }\n }\n this._releaseSocket();\n this._error = undefined;\n this._setState(finalState);\n }\n\n /** Disconnecting from the hub is the portable stop request; POSIX also gets SIGTERM. */\n private async _terminate(running: ServiceProcess): Promise<void> {\n // Windows pipe children without an RPC connection have no graceful stop channel.\n const canStopGracefully = process.platform !== 'win32' || this._connections > 0;\n this._releaseSocket();\n const pid = running.pid;\n if (canStopGracefully) {\n if (pid !== undefined) terminateProcessTree(pid);\n if (await _settlesWithin(running.exited, this._service.stopTimeoutMs)) return;\n this._logDaemon(`did not stop within ${this._service.stopTimeoutMs} ms; killing`);\n }\n await running.kill();\n if (!await _settlesWithin(running.exited, KILL_WAIT_MS)) this._logDaemon('process did not exit after kill');\n }\n\n private _onConnections(count: number): void {\n this._connections = count;\n if (count > 0 && this._state === 'starting' && this._service.readiness === 'connected') {\n this._markRunning();\n } else {\n this._onDidChange();\n }\n }\n\n private _markRunning(): void {\n clearTimeout(this._startTimer);\n this._startTimer = undefined;\n this._stableTimer = setTimeout(() => {\n this._consecutiveFailures = 0;\n }, STABLE_AFTER_MS);\n this._setState('running');\n }\n\n private _releaseSocket(): void {\n this._socket?.dispose();\n this._socket = undefined;\n this._connections = 0;\n }\n\n private _clearProcessTimers(): void {\n clearTimeout(this._startTimer);\n clearTimeout(this._stableTimer);\n this._startTimer = undefined;\n this._stableTimer = undefined;\n }\n\n private _setState(state: ServiceState): void {\n if (this._state !== state) {\n this._state = state;\n this._since = Date.now();\n }\n this._onDidChange();\n }\n\n private _appendOutput(stream: 'stdout' | 'stderr' | 'tty', data: Uint8Array): void {\n this._host.output?.(this.name, stream, data);\n const text = this._decoders[stream].write(Buffer.from(data));\n const logStream = stream === 'stderr' ? 'stderr' : 'stdout';\n for (const line of this._logs.append(logStream, stream === 'tty' ? _stripTerminalControls(text) : text)) {\n this._host.log(this.name, line);\n }\n }\n\n private _logDaemon(text: string): void {\n this._host.notice?.(this.name, text);\n this._logs.append('daemon', text + '\\n');\n this._host.log(this.name, text);\n }\n}\n\n/** Keep TTY log lines readable: drop escape sequences, carriage returns, and other controls. */\nfunction _stripTerminalControls(text: string): string {\n // eslint-disable-next-line no-control-regex\n return text.replace(/\\x1b(?:\\[[0-?]*[ -/]*[@-~]|\\][^\\x07\\x1b]*(?:\\x07|\\x1b\\\\)|[@-Z\\\\-_])|[\\x00-\\x09\\x0b-\\x1f\\x7f]/g, '');\n}\n\nfunction _describeExit(info: ExitInfo): string {\n if (info.error !== undefined) return `failed to start: ${info.error}`;\n if (info.signal !== null) return `killed by ${info.signal}`;\n return `exited with code ${info.code}`;\n}\n\nfunction _settlesWithin(promise: Promise<unknown>, ms: number): Promise<boolean> {\n return new Promise(resolve => {\n const timer = setTimeout(() => resolve(false), ms);\n void promise.then(() => {\n clearTimeout(timer);\n resolve(true);\n });\n });\n}\n\nfunction _message(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","import * as net from 'node:net';\nimport { LinkRpcConnection, type IMessageTransport } from '@hediet/linkrpc';\nimport { connectNdjson, parseEndpointUri, runInitializeHandshake, WebSocketTransport, type ResolvedEndpoint } from '@hediet/linkrpc/node';\nimport { hubGrantedServiceIdInterface } from '@hediet/linkrpc/hub/common';\nimport { spawnCommand } from '@hediet/linkrpc-hub/spawn';\nimport type { ManagedService } from './config';\nimport { LogBuffer } from './logBuffer';\nimport type { LogLine, ServiceStatus } from './managementInterface';\nimport type { ServiceHost, ServiceSocket } from './supervisor';\n\ninterface TransportHandle {\n readonly transport: IMessageTransport;\n readonly closed: Promise<void>;\n dispose(): void;\n}\n\ntype ConnectableEndpoint = Extract<ResolvedEndpoint, { kind: 'socket' | 'ws' | 'cmd-stdio' }>;\n\n/**\n * Keeps a service's `endpoint` connected to the hub: its traffic is relayed\n * through the service's participant socket, so it may serve only the granted\n * `serviceId` and its calls pass the hub's forwarded-call gate. Reconnects with\n * backoff according to the restart policy.\n */\nexport class ConnectionSupervisor {\n private _state: ServiceStatus['state'] = 'stopped';\n private _error: string | undefined;\n private _since = Date.now();\n private _restarts = 0;\n private _generation = 0;\n private _socket: ServiceSocket | undefined;\n private _target: TransportHandle | undefined;\n private _local: TransportHandle | undefined;\n private _timer: ReturnType<typeof setTimeout> | undefined;\n private _pending: Promise<void> | undefined;\n private _service: ManagedService;\n private readonly _endpoint: ConnectableEndpoint;\n private readonly _logs = new LogBuffer();\n\n constructor(\n readonly name: string,\n service: ManagedService,\n private readonly _host: ServiceHost,\n private readonly _changed: () => void,\n ) {\n if (service.endpoint === undefined) throw new Error(`service '${name}' has no endpoint`);\n const endpoint = parseEndpointUri(service.endpoint);\n if (endpoint.kind !== 'socket' && endpoint.kind !== 'ws' && endpoint.kind !== 'cmd-stdio') {\n throw new Error('Managed connections require a LinkRPC socket, WebSocket, or cmd-stdio endpoint');\n }\n this._endpoint = endpoint;\n this._service = service;\n }\n\n get service(): ManagedService { return this._service; }\n status(): ServiceStatus {\n return {\n name: this.name, description: this._service.description, serviceId: this._service.serviceId,\n enabled: this._service.enabled, state: this._state, since: this._since,\n connections: this._state === 'running' ? 1 : 0, restarts: this._restarts, error: this._error,\n };\n }\n logs(limit?: number): LogLine[] {\n return this._logs.lines(limit);\n }\n async sync(): Promise<void> {\n if (!this._service.enabled) return this.dispose();\n if (this._state === 'running' || this._state === 'starting' || this._state === 'backoff') return;\n this._pending = this._connect(++this._generation);\n await this._pending;\n }\n async update(service: ManagedService): Promise<void> {\n const enabledChanged = this._service.enabled !== service.enabled;\n this._service = service;\n if (enabledChanged) await this.sync();\n this._changed();\n }\n input(): never { throw new Error('A connected endpoint has no managed process console'); }\n async restart(): Promise<void> {\n if (!this._service.enabled) throw new Error(`service '${this.name}' is disabled`);\n this._logDaemon('restart requested');\n await this.dispose();\n await this.sync();\n }\n async dispose(): Promise<void> {\n ++this._generation;\n clearTimeout(this._timer);\n this._cleanup();\n await this._pending;\n this._setState('stopped');\n }\n private async _connect(generation: number): Promise<void> {\n this._error = undefined;\n this._setState('starting');\n try {\n const target = await this._openTarget();\n if (generation !== this._generation) { target.dispose(); return; }\n this._target = target;\n this._socket = await this._host.openSocket(this.name, this._service, () => {});\n if (generation !== this._generation) { this._cleanup(); return; }\n const env = this._socket.env;\n const local = await openTransport(parseEndpointUri(env.LINKRPC_ENDPOINT ?? env.HUBRPC_ENDPOINT!), env.LINKRPC_TOKEN ?? env.HUBRPC_TOKEN);\n if (generation !== this._generation) { local.dispose(); this._cleanup(); return; }\n this._local = local;\n // Claims are performed before handing the transport to the remote endpoint.\n const registration = LinkRpcConnection.fromTransport(local.transport);\n await registration.get(hubGrantedServiceIdInterface).register({ serviceId: this._service.serviceId });\n local.transport.setListener(message => target.transport.send(message));\n target.transport.setListener(message => local.transport.send(message));\n this._setState('running');\n void Promise.race([local.closed, target.closed]).then(() => {\n if (generation === this._generation) this._failed(generation, new Error('Endpoint disconnected'));\n });\n } catch (error) {\n if (generation === this._generation) this._failed(generation, error);\n }\n }\n private _failed(generation: number, error: unknown): void {\n this._cleanup();\n this._error = error instanceof Error ? error.message : String(error);\n this._logDaemon(this._error);\n if (this._service.restart === 'never') {\n this._setState('failed');\n } else {\n this._setState('backoff');\n this._timer = setTimeout(() => {\n if (generation !== this._generation) return;\n this._restarts++;\n this._pending = this._connect(generation);\n }, Math.min(30_000, 500 * 2 ** Math.min(this._restarts, 6)));\n }\n }\n private _cleanup(): void {\n this._target?.dispose(); this._target = undefined;\n this._local?.dispose(); this._local = undefined;\n this._socket?.dispose(); this._socket = undefined;\n }\n private _setState(state: ServiceStatus['state']): void {\n this._state = state; this._since = Date.now(); this._changed();\n }\n private _openTarget(): Promise<TransportHandle> {\n if (this._endpoint.kind !== 'cmd-stdio') return openTransport(this._endpoint);\n return openCommandTransport(this._endpoint, line => {\n this._logs.append('stderr', line + '\\n');\n this._host.log(this.name, line);\n });\n }\n private _logDaemon(text: string): void {\n this._host.notice?.(this.name, text);\n this._logs.append('daemon', text + '\\n');\n this._host.log(this.name, text);\n }\n}\n\n/** Spawn the endpoint's command and speak handshake-free newline-delimited JSON-RPC over its stdio. */\nasync function openCommandTransport(\n endpoint: Extract<ConnectableEndpoint, { kind: 'cmd-stdio' }>,\n onStderrLine: (line: string) => void,\n): Promise<TransportHandle> {\n const child = spawnCommand(endpoint.command, {\n stdio: ['pipe', 'pipe', 'pipe'],\n env: { ...process.env, ...endpoint.env },\n windowsHide: true,\n ...(endpoint.cwd !== undefined ? { cwd: endpoint.cwd } : {}),\n });\n const kill = () => { if (child.exitCode === null && !child.killed) child.kill(); };\n const closed = new Promise<void>(resolve => {\n child.once('exit', () => resolve());\n child.once('error', () => resolve());\n });\n let partial = '';\n child.stderr!.setEncoding('utf8');\n child.stderr!.on('data', (chunk: string) => {\n const lines = (partial + chunk).split(/\\r?\\n/);\n partial = lines.pop()!;\n for (const line of lines) if (line.length > 0) onStderrLine(line);\n });\n await new Promise<void>((resolve, reject) => {\n child.once('spawn', resolve);\n child.once('error', reject);\n });\n const { transport } = await connectNdjson({ input: child.stdout!, output: child.stdin!, onClose: kill });\n return { transport, closed, dispose: () => { transport.dispose(); kill(); } };\n}\n\nasync function openTransport(endpoint: ResolvedEndpoint, token?: string): Promise<TransportHandle> {\n if (endpoint.kind === 'socket') {\n const socket = net.createConnection(endpoint.path);\n socket.setTimeout(10_000, () => socket.destroy(new Error('Endpoint initialization timed out')));\n const closed = new Promise<void>(resolve => socket.once('close', () => resolve()));\n try {\n const { transport } = await connectNdjson({\n input: socket, output: socket, onClose: () => socket.destroy(),\n initialize: { kind: 'client', token: token ?? endpoint.token ?? '' },\n });\n socket.setTimeout(0);\n return { transport, closed, dispose: () => socket.destroy() };\n } catch (error) { socket.destroy(); throw error; }\n }\n if (endpoint.kind === 'ws') {\n const ws = new WebSocket(endpoint.url);\n await new Promise<void>((resolve, reject) => {\n const finish = (error?: Error) => {\n clearTimeout(timeout);\n ws.removeEventListener('open', opened);\n ws.removeEventListener('error', failed);\n if (error) { ws.close(); reject(error); } else resolve();\n };\n const opened = () => finish();\n const failed = () => finish(new Error('WebSocket connection failed'));\n const timeout = setTimeout(() => finish(new Error('WebSocket connection timed out')), 10_000);\n ws.addEventListener('open', opened, { once: true });\n ws.addEventListener('error', failed, { once: true });\n });\n const closed = new Promise<void>(resolve => ws.addEventListener('close', () => resolve(), { once: true }));\n const transport = new WebSocketTransport(ws, () => ws.close());\n try {\n await runInitializeHandshake(transport, { kind: 'client', token: token ?? endpoint.token ?? '' });\n return { transport, closed, dispose: () => transport.dispose() };\n } catch (error) { transport.dispose(); throw error; }\n }\n throw new Error('Managed connections require a LinkRPC socket or WebSocket endpoint');\n}\n","import * as headlessModule from '@xterm/headless';\nimport * as serializeModule from '@xterm/addon-serialize';\nimport {\n encodeConsoleData,\n type ConsoleHistory,\n type ConsoleRecord,\n type ConsoleServerMessage,\n type ConsoleSize,\n} from '@hediet/linkrpc-infra/console';\n\n// Node loads these packages as CommonJS (exports on `default`); bundlers may pick their ESM builds.\nconst { Terminal } = commonJsInterop(headlessModule);\nconst { SerializeAddon } = commonJsInterop(serializeModule);\n\n/**\n * Replays a TTY as its current screen and scrollback instead of raw bytes, so\n * that full-screen programs render correctly for attachments that join late.\n */\nexport class ScreenHistory implements ConsoleHistory {\n private readonly _terminal: InstanceType<typeof Terminal>;\n private readonly _serializer = new SerializeAddon();\n\n constructor(size: ConsoleSize, scrollback = 1000) {\n this._terminal = new Terminal({ cols: size.cols, rows: size.rows, scrollback, allowProposedApi: true });\n this._terminal.loadAddon(this._serializer);\n }\n\n append(record: ConsoleRecord): void {\n if (record.type === 'output') this._terminal.write(record.data);\n }\n\n resize(size: ConsoleSize): void {\n this._terminal.resize(size.cols, size.rows);\n }\n\n snapshot(): Promise<readonly ConsoleServerMessage[]> {\n // Writes parse in order: this callback runs after earlier output and before later output.\n return new Promise(resolve => this._terminal.write('', () => {\n const screen = this._serializer.serialize();\n resolve([{ t: 'screen', data: encodeConsoleData(new TextEncoder().encode(screen)) }]);\n }));\n }\n\n dispose(): void {\n this._terminal.dispose();\n }\n}\n\nfunction commonJsInterop<T extends object>(module: T): T {\n return (module as { default?: T }).default ?? module;\n}\n","import { createHash, randomUUID } from 'node:crypto';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport { z } from 'zod';\nimport type { LinkRpcConnection, StreamApi } from '@hediet/linkrpc';\nimport { ConsoleHost, consoleHandlers, type ConsoleClientMessage, type ConsoleExit, type ConsoleSize } from '@hediet/linkrpc-infra/console';\nimport {\n endpointDefinition,\n managedEndpointsInterface,\n type EndpointAddress,\n type EndpointDefinition,\n type EndpointStatus,\n type RunEvent,\n type RunParams,\n type WatchEvent,\n} from './endpointInterface';\nimport { ManagedServiceSchema, type ManagedService } from './config';\nimport { writePrivateJson } from './discovery';\nimport { endpointDescriptor } from './participantDescriptors';\nimport { processSignals } from './processIo';\nimport { ScreenHistory } from './screenHistory';\nimport { ServiceSupervisor, type ServiceHost } from './supervisor';\nimport { ConnectionSupervisor } from './connectionSupervisor';\n\nconst storedEndpoints = z.array(z.object({ definition: endpointDefinition, desired: z.boolean() }));\nconst finishedStates = new Set(['failed', 'stopped', 'disabled']);\n\ninterface Entry {\n definition: EndpointDefinition;\n desired: boolean;\n readonly instanceId: string;\n /** Owned by a `run` call: it is never persisted or restored. */\n readonly owned: boolean;\n readonly supervisor: ServiceSupervisor | ConnectionSupervisor;\n readonly console: ConsoleHost | undefined;\n readonly listeners: Set<() => void>;\n removed: boolean;\n}\n\nexport interface ManagedEndpointsOptions {\n readonly file: string;\n /** Published endpoint service IDs: `<servicePrefix>/<sha256(namespace)>/<id>`. */\n readonly servicePrefix: string;\n readonly host: ServiceHost;\n}\n\nexport class ManagedEndpoints {\n private readonly _entries = new Map<string, Entry>();\n private _ops = Promise.resolve();\n private _closing = false;\n\n constructor(private readonly _options: ManagedEndpointsOptions) {}\n\n snapshot(): { definition: EndpointDefinition; desired: boolean }[] {\n return [...this._entries.values()].filter(entry => !entry.owned)\n .map(entry => ({ definition: entry.definition, desired: entry.desired }));\n }\n\n async restore(snapshot?: ReturnType<ManagedEndpoints['snapshot']>): Promise<void> {\n if (snapshot !== undefined) {\n for (const { definition, desired } of snapshot) await this._restoreEntry(definition, desired);\n return;\n }\n let text: string;\n try { text = fs.readFileSync(this._options.file, 'utf8'); }\n catch (error) {\n if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return;\n throw error;\n }\n for (const { definition, desired } of storedEndpoints.parse(JSON.parse(text))) {\n await this._restoreEntry(definition, desired && definition.restart !== 'never');\n }\n }\n\n private async _restoreEntry(definition: EndpointDefinition, desired: boolean): Promise<void> {\n if (this._entries.has(key(definition))) throw new Error('Duplicate persisted endpoint');\n const entry = this._add(definition, desired, { owned: false });\n if (entry.desired) await entry.supervisor.sync();\n }\n\n register(connection: LinkRpcConnection, serviceId?: string): { dispose(): void } {\n return connection.register(managedEndpointsInterface, {\n consoles: consoleHandlers(address => {\n const console = this._get(address).console;\n if (!console) throw new Error(`Endpoint \"${address.id}\" is a connection and has no console`);\n return console;\n }),\n info: () => ({ hostname: os.hostname(), platform: process.platform, cwd: process.cwd(), servicePrefix: this._options.servicePrefix }),\n list: ({ namespace }) => this.list(namespace),\n create: ({ replace, ...definition }) => this._serialize(async () =>\n this._status(await this._create(definition, { owned: false, replace: replace ?? false }))),\n run: (params, _context, stream) => this._run(params, stream),\n watch: async (address, _context, stream) => {\n await this._watch(this._get(address), stream);\n return {};\n },\n start: address => this._serialize(async () => {\n const entry = this._get(address);\n this._setDesired(entry, true);\n await entry.supervisor.update({ ...entry.supervisor.service, enabled: true });\n await entry.supervisor.sync();\n return this._status(entry);\n }),\n stop: address => this._serialize(async () => {\n const entry = this._get(address);\n this._setDesired(entry, false);\n await entry.supervisor.update({ ...entry.supervisor.service, enabled: false });\n if (!entry.definition.persistent) this._removeEntry(entry);\n return {};\n }),\n remove: address => this._serialize(async () => {\n const entry = this._get(address);\n this._entries.delete(key(entry.definition));\n try { this._save(); } catch (error) { this._entries.set(key(entry.definition), entry); throw error; }\n await entry.supervisor.dispose();\n this._removeEntry(entry);\n return {};\n }),\n configure: params => this._serialize(async () => {\n const entry = this._get(params);\n if (entry.owned && params.persistent) throw new Error('A foreground (owned) endpoint cannot be persistent');\n const definition = {\n ...entry.definition,\n ...(params.persistent === undefined ? {} : { persistent: params.persistent }),\n ...(params.restart === undefined ? {} : { restart: params.restart }),\n };\n const previous = entry.definition;\n entry.definition = definition;\n try { this._save(); } catch (error) { entry.definition = previous; throw error; }\n await entry.supervisor.update({ ...entry.supervisor.service, restart: definition.restart });\n this._changed(entry);\n return this._status(entry);\n }),\n }, serviceId === undefined ? undefined : { serviceId });\n }\n\n list(namespace?: string): EndpointStatus[] {\n return [...this._entries.values()].filter(entry => namespace === undefined || entry.definition.namespace === namespace)\n .map(entry => this._status(entry));\n }\n\n async dispose(): Promise<void> {\n this._closing = true;\n await this._ops;\n await Promise.all([...this._entries.values()].map(entry => entry.supervisor.dispose()));\n for (const entry of this._entries.values()) entry.console?.close();\n }\n\n private async _run(\n { definition, owner = false, replace = false, console: attach }: RunParams,\n stream: StreamApi<ConsoleClientMessage, RunEvent>,\n ): Promise<{ exit: ConsoleExit | null }> {\n if (owner && definition.persistent) throw new Error('A foreground (owned) endpoint cannot be persistent');\n const entry = await this._serialize(async () => {\n stream.signal.throwIfAborted();\n return this._create(definition, { owned: owner, replace, ...(attach.size ? { size: attach.size } : {}) });\n });\n const sendStatus = () => { stream.send({ t: 'status', status: this._status(entry) }).catch(() => {}); };\n entry.listeners.add(sendStatus);\n try {\n sendStatus();\n return await entry.console!.attach(attach, stream);\n } finally {\n entry.listeners.delete(sendStatus);\n // Shutdown already disposes every supervisor. Otherwise cleanup owns\n // this exact instance, never a replacement using the same name.\n if (owner && !this._closing) {\n await this._serialize(async () => {\n await entry.supervisor.dispose();\n this._removeEntry(entry);\n });\n }\n }\n }\n\n private async _create(\n definition: EndpointDefinition,\n options: { readonly owned: boolean; readonly replace: boolean; readonly size?: ConsoleSize },\n ): Promise<Entry> {\n const existing = this._entries.get(key(definition));\n if (existing) {\n if (!options.replace) throw new Error(`Endpoint \"${definition.id}\" already exists in ${definition.namespace}`);\n existing.console?.notice('Replaced by a new launch of the same endpoint.');\n await existing.supervisor.dispose();\n this._removeEntry(existing);\n }\n const entry = this._add(definition, true, options);\n try {\n this._save();\n await entry.supervisor.sync();\n return entry;\n } catch (error) {\n await entry.supervisor.dispose();\n this._removeEntry(entry);\n throw error;\n }\n }\n\n private async _watch(entry: Entry, stream: Pick<StreamApi<never, WatchEvent>, 'signal' | 'send'>): Promise<void> {\n let dirty = true;\n let wake: (() => void) | undefined;\n const notify = () => { dirty = true; wake?.(); };\n entry.listeners.add(notify);\n stream.signal.addEventListener('abort', notify);\n try {\n while (!stream.signal.aborted) {\n dirty = false;\n if (entry.removed) {\n await stream.send({ t: 'removed' });\n return;\n }\n await stream.send({ t: 'status', status: this._status(entry) });\n if (!dirty) await new Promise<void>(resolve => { wake = resolve; if (dirty || stream.signal.aborted) resolve(); });\n wake = undefined;\n }\n } finally {\n entry.listeners.delete(notify);\n stream.signal.removeEventListener('abort', notify);\n }\n }\n\n private _add(definition: EndpointDefinition, desired: boolean, options: { readonly owned: boolean; readonly size?: ConsoleSize }): Entry {\n const digest = createHash('sha256').update(definition.namespace).digest('hex');\n const name = `${digest.slice(0, 16)}-${definition.id}`;\n const serviceId = `${this._options.servicePrefix}/${digest}/${definition.id}`;\n const source = definition.source;\n const service: ManagedService = {\n ...ManagedServiceSchema.parse({\n ...(source.kind === 'process' ? {\n command: source.command, env: source.env, cwd: source.cwd,\n readiness: source.readiness, rpc: source.rpc, tty: source.tty,\n } : { endpoint: source.endpoint }),\n enabled: desired, restart: definition.restart, serviceId,\n }),\n serviceId,\n };\n let entry: Entry;\n const host: ServiceHost = {\n openSocket: (socketName, socketService, onConnectionCountChanged) => this._options.host.openSocket(\n socketName, socketService, onConnectionCountChanged,\n endpointDescriptor(definition.id, definition.namespace, serviceId),\n ),\n log: (...args) => this._options.host.log(...args),\n output: (_name, stream, data) => entry.console?.output(stream, data),\n notice: (_name, text) => entry.console?.notice(text),\n processStarted: (_name, pid) => entry.console?.started(pid),\n processExited: (_name, exit) => entry.console?.exited(exit),\n };\n let supervisor: ServiceSupervisor | ConnectionSupervisor;\n let console: Entry['console'];\n if (source.kind === 'process') {\n const processSupervisor = new ServiceSupervisor(name, service, host, () => this._changed(entry));\n const size = source.tty ? options.size ?? { cols: 80, rows: 24 } : undefined;\n if (size) processSupervisor.resize(size);\n const consoleHost = new ConsoleHost({\n mode: source.tty ? 'tty' : 'pipe',\n signals: processSignals(source.tty),\n backend: processSupervisor,\n ...(size ? { size, history: new ScreenHistory(size) } : {}),\n });\n if (!desired) consoleHost.finish();\n supervisor = processSupervisor;\n console = consoleHost;\n } else {\n supervisor = new ConnectionSupervisor(name, service, host, () => this._changed(entry));\n }\n entry = { definition, desired, owned: options.owned, supervisor, console, instanceId: randomUUID(), listeners: new Set(), removed: false };\n this._entries.set(key(definition), entry);\n return entry;\n }\n\n private _changed(entry: Entry): void {\n for (const listener of entry.listeners) listener();\n if (!finishedStates.has(entry.supervisor.status().state)) return;\n entry.console?.finish();\n if (!this._closing && !entry.removed && !entry.definition.persistent) this._removeEntry(entry);\n }\n\n private _removeEntry(entry: Entry): void {\n if (entry.removed) return;\n if (this._entries.get(key(entry.definition)) === entry) this._entries.delete(key(entry.definition));\n entry.removed = true;\n entry.console?.close();\n for (const listener of entry.listeners) listener();\n }\n\n private _get(address: EndpointAddress): Entry {\n const entry = this._entries.get(key(address));\n if (!entry) throw new Error(`Endpoint \"${address.id}\" not found in ${address.namespace}`);\n return entry;\n }\n\n private _status(entry: Entry): EndpointStatus {\n const source = entry.definition.source;\n return {\n namespace: entry.definition.namespace, id: entry.definition.id, instanceId: entry.instanceId,\n serviceId: entry.supervisor.service.serviceId, persistent: entry.definition.persistent,\n restart: entry.definition.restart, desired: entry.desired, owned: entry.owned, sourceKind: source.kind,\n rpc: source.kind === 'connection' || source.rpc,\n ...(entry.console ? { console: { mode: entry.console.mode } } : {}),\n runtime: entry.supervisor.status(),\n };\n }\n\n private _save(): void {\n writePrivateJson(this._options.file, [...this._entries.values()].filter(entry => entry.definition.persistent)\n .map(entry => ({ definition: entry.definition, desired: entry.desired })));\n }\n\n private _setDesired(entry: Entry, desired: boolean): void {\n const previous = entry.desired;\n entry.desired = desired;\n try { this._save(); } catch (error) { entry.desired = previous; throw error; }\n }\n\n private _serialize<T>(operation: () => Promise<T>): Promise<T> {\n if (this._closing) return Promise.reject(new Error('Daemon is stopping'));\n const result = this._ops.then(operation);\n this._ops = result.then(() => {}, error => this._options.host.log('management', String(error)));\n return result;\n }\n}\n\nfunction key(address: EndpointAddress): string { return JSON.stringify([address.namespace, address.id]); }\n","import { randomBytes, timingSafeEqual } from 'node:crypto';\nimport * as fs from 'node:fs';\nimport { LinkRpcConnection } from '@hediet/linkrpc';\nimport { type HubConfig, runHub, type RunningHub } from '@hediet/linkrpc-hub';\nimport { type NodeSocketTransport, SocketServer } from '@hediet/linkrpc-hub/hub/server/node';\nimport { classifyServiceChange, type DaemonConfig, type ManagedService, parseDaemonConfig, parseDaemonConfigText, setCallLogLevelInText, setServiceEnabledInText, stableKey } from './config';\nimport { CallLog } from './callLog/callLog';\nimport type { CallLogLevel } from './callLog/callRecord';\nimport { ConfigFile } from './configFile';\nimport { DaemonLog } from './daemonLog';\nimport { readEndpointDiscovery, writePrivateJson, type EndpointDiscovery } from './discovery';\nimport { type DaemonStatus, hubDaemonManagementInterface } from './managementInterface';\nimport { packageVersion } from './packageInfo';\nimport { HubHome } from './paths';\nimport { SingleInstanceLock } from './singleInstance';\nimport { type ServiceHost, ServiceSupervisor } from './supervisor';\nimport { ConnectionSupervisor } from './connectionSupervisor';\nimport * as path from 'node:path';\nimport { ManagedEndpoints } from './managedEndpoints';\nimport { serviceDescriptor } from './participantDescriptors';\nimport type { ParticipantDescriptor } from '@hediet/linkrpc/inspection';\n\nexport interface StartHubDaemonOptions {\n readonly home?: HubHome;\n /** Also write the log to stderr. */\n readonly echoLog?: boolean;\n}\n\ninterface LocalEndpoint {\n readonly path: string;\n readonly token: string | undefined;\n}\n\n/**\n * The per-user hub daemon. Runs a LinkRPC hub with a private local endpoint,\n * supervises the configured services, applies config file changes\n * incrementally, and serves the management API.\n *\n * Reconciliation rules: a change to hub-wide settings restarts the hub and\n * every service; otherwise only added, removed, or changed services are\n * touched, and changes to `enabled`, `restart`, timeouts, or `description`\n * keep the process running. An invalid file keeps the running configuration.\n */\nexport class HubDaemon {\n public static async start(options: StartHubDaemonOptions = {}): Promise<HubDaemon> {\n const home = options.home ?? HubHome.resolve();\n _ensurePrivateDirs(home);\n const lock = await SingleInstanceLock.acquire(home.lockEndpoint);\n const log = DaemonLog.open(home.logFile, { echo: options.echoLog ?? false });\n const daemon = new HubDaemon(home, lock, log);\n try {\n await daemon._start();\n return daemon;\n } catch (error) {\n log.line(`startup failed: ${_message(error)}`);\n await daemon.shutdown();\n throw error;\n }\n }\n\n public readonly startedAt = Date.now();\n public readonly version = packageVersion();\n /** Resolves once the daemon has shut down. */\n public readonly done: Promise<void>;\n\n private readonly _configFile: ConfigFile;\n private _appPath: string;\n private readonly _management: LocalEndpoint & { readonly token: string; };\n private readonly _services = new Map<string, ServiceSupervisor | ConnectionSupervisor>();\n private readonly _statusListeners = new Set<() => void>();\n private readonly _serviceHost: ServiceHost;\n private _endpoints: ManagedEndpoints | undefined;\n private readonly _endpointRegistrations = new Map<LinkRpcConnection, { dispose(): void } | undefined>();\n private _managementLink: { dispose(): void } | undefined;\n private _hub: RunningHub | undefined;\n private _hubKey: string | undefined;\n private readonly _callLog: CallLog;\n private _callLogAttachment: { dispose(): void } | undefined;\n private _hubStartedAt = 0;\n private _hubError: string | undefined;\n private _seenRevision: string | undefined;\n private _appliedRevision: string | undefined;\n private _appliedAt: number | undefined;\n private _configError: string | undefined;\n private _reconcile: Promise<void> = Promise.resolve();\n private _managementServer: SocketServer | undefined;\n private _watcher: { dispose(): void; } | undefined;\n private _statusChangeScheduled = false;\n private _stopping = false;\n private _shutdown: Promise<void> | undefined;\n private _resolveDone!: () => void;\n\n private constructor(\n public readonly home: HubHome,\n private readonly _lock: SingleInstanceLock,\n private readonly _log: DaemonLog,\n ) {\n this.done = new Promise(resolve => { this._resolveDone = resolve; });\n this._configFile = new ConfigFile(home.configFile, home.configSchemaFile);\n this._callLog = new CallLog(home.callLogDir, this.startedAt, level => this.setCallLogLevel(level));\n this._appPath = home.defaultAppEndpoint;\n this._management = { path: home.allocEndpoint('management'), token: _token() };\n this._serviceHost = {\n openSocket: (name, service, onConnectionCountChanged, descriptor) =>\n this._openServiceSocket(name, service, onConnectionCountChanged, descriptor ?? serviceDescriptor(name, service.serviceId)),\n log: (name, line) => this._log.line(`[${name}] ${line}`),\n };\n }\n\n public status(): DaemonStatus {\n return {\n pid: process.pid,\n version: this.version,\n startedAt: this.startedAt,\n endpoint: this._appPath,\n configFile: this.home.configFile,\n logFile: this.home.logFile,\n config: { revision: this._appliedRevision, appliedAt: this._appliedAt, error: this._configError },\n hub: {\n startedAt: this._hubStartedAt,\n listeners: this._hub?.listeners.map(({ type, address }) => ({ type, address })) ?? [],\n error: this._hubError,\n },\n callLog: this._callLog.status(),\n services: [...this._services.values()]\n .map(service => service.status())\n .sort((a, b) => a.name.localeCompare(b.name)),\n };\n }\n\n /** Coalesced: fires at most once per microtask turn. */\n public onDidChangeStatus(listener: () => void): { dispose(): void; } {\n this._statusListeners.add(listener);\n return { dispose: () => this._statusListeners.delete(listener) };\n }\n\n /**\n * Re-read the config file and apply what changed. Without `force`, an\n * unchanged file is a no-op; with it, a hub that failed to start is retried.\n */\n public reload(options: { force?: boolean; } = {}): Promise<void> {\n return this._serialize(() => this._reload(options.force ?? false));\n }\n\n public restartService(name: string): Promise<void> {\n return this._service(name).restart();\n }\n\n /** Persist `enabled` in the config file and apply it. */\n public async setServiceEnabled(name: string, enabled: boolean): Promise<void> {\n const document = this._configFile.read();\n this._configFile.write(setServiceEnabledInText(document.text, name, enabled), document.revision);\n await this.reload();\n }\n\n /** Persist `callLog.level` in the config file and apply it; the hub keeps running. */\n public async setCallLogLevel(level: CallLogLevel): Promise<void> {\n const document = this._configFile.read();\n this._configFile.write(setCallLogLevelInText(document.text, level), document.revision);\n await this.reload();\n }\n\n public async setConfig(text: string, expectedRevision: string): Promise<string> {\n const revision = this._configFile.write(text, expectedRevision);\n await this.reload();\n return revision;\n }\n\n public shutdown(): Promise<void> {\n this._shutdown ??= this._doShutdown();\n return this._shutdown;\n }\n\n private async _start(): Promise<void> {\n this._log.line(`starting LinkRPC hub daemon ${this.version} (pid ${process.pid})`);\n this._configFile.ensureExists();\n const document = this._configFile.read();\n this._seenRevision = document.revision;\n let config: DaemonConfig;\n try {\n config = parseDaemonConfigText(document.text);\n this._appliedRevision = document.revision;\n this._appliedAt = Date.now();\n } catch (error) {\n this._configError = _message(error);\n this._log.line(`config is invalid; starting without services: ${this._configError}`);\n config = parseDaemonConfig({});\n }\n await this._serialize(() => this._apply(config));\n await this._startManagementServer();\n writePrivateJson(this.home.managementFile, this._discovery(this._management));\n this._watcher = this._configFile.watch(() => void this.reload());\n this._log.line(`ready: hub endpoint ${this._appPath}`);\n }\n\n private async _reload(force: boolean): Promise<void> {\n if (this._stopping) return;\n const document = this._configFile.read();\n if (!force && document.revision === this._seenRevision) return;\n this._seenRevision = document.revision;\n let config: DaemonConfig;\n try {\n config = parseDaemonConfigText(document.text);\n } catch (error) {\n this._configError = _message(error);\n this._log.line(`config is invalid; keeping the running configuration: ${this._configError}`);\n this._changed();\n return;\n }\n this._configError = undefined;\n await this._apply(config);\n this._appliedRevision = document.revision;\n this._appliedAt = Date.now();\n this._changed();\n }\n\n private async _apply(config: DaemonConfig): Promise<void> {\n // The call log is not a hub setting: it follows the config without a hub restart.\n this._callLog.configure(config.callLog);\n const hubKey = stableKey({ hub: config.hub, localEndpoint: config.localEndpoint });\n if (hubKey !== this._hubKey || !this._hub) {\n if (this._hub) this._log.line('hub settings changed; restarting the hub and all services');\n await this._disposeAllServices();\n const endpointSnapshot = this._endpoints?.snapshot();\n await this._endpoints?.dispose();\n this._endpoints = undefined;\n for (const [connection, registration] of this._endpointRegistrations) {\n registration?.dispose();\n this._endpointRegistrations.set(connection, undefined);\n }\n this._managementLink?.dispose();\n this._callLogAttachment?.dispose();\n this._callLogAttachment = undefined;\n this._hub?.dispose();\n this._hub = undefined;\n fs.rmSync(this.home.discoveryFile, { force: true });\n this._hubKey = hubKey;\n this._appPath = config.localEndpoint.path ?? this.home.defaultAppEndpoint;\n try {\n this._hub = await this._startHub(config);\n this._endpoints = new ManagedEndpoints({\n file: path.join(this.home.stateDir, 'endpoints.json'),\n servicePrefix: `${config.hub.hubServiceId}/services`,\n host: this._serviceHost,\n });\n await this._endpoints.restore(endpointSnapshot);\n for (const connection of this._endpointRegistrations.keys()) {\n this._endpointRegistrations.set(connection, this._endpoints.register(connection));\n }\n const serviceId = `${config.hub.hubServiceId}/daemon`;\n const link = this._hub.hub.attachOut({ routePrefixes: [serviceId] });\n const connection = LinkRpcConnection.fromTransport(link.transport);\n this._endpoints.register(connection, serviceId);\n connection.enableReflection({ serviceId });\n this._managementLink = { dispose: () => { connection.close(); link.dispose(); } };\n this._callLogAttachment = this._callLog.attach(this._hub.inspection, connection, serviceId);\n this._hubStartedAt = Date.now();\n this._hubError = undefined;\n writePrivateJson(this.home.discoveryFile, this._discovery({ path: this._appPath, token: config.localEndpoint.token }));\n } catch (error) {\n this._hubError = _message(error);\n this._log.line(`the hub failed to start: ${this._hubError}`);\n }\n this._changed();\n }\n const removed = [...this._services.keys()].filter(name => !Object.hasOwn(config.services, name));\n // Stop removed services first: a renamed service must release its resources (ports, devices)\n // before its successor starts.\n await Promise.all(removed.map(name => this._removeService(name)));\n await Promise.all(Object.entries(config.services).map(([name, service]) => this._applyService(name, service)));\n }\n\n private async _applyService(name: string, service: ManagedService): Promise<void> {\n const existing = this._services.get(name);\n if (existing) {\n const change = classifyServiceChange(existing.service, service);\n if (change === 'none') return;\n if (change === 'inPlace') {\n await existing.update(service);\n return;\n }\n this._log.line(`[${name}] configuration changed; restarting`);\n await existing.dispose();\n } else {\n this._log.line(`[${name}] added`);\n }\n const supervisor = service.endpoint !== undefined\n ? new ConnectionSupervisor(name, service, this._serviceHost, () => this._changed())\n : new ServiceSupervisor(name, service, this._serviceHost, () => this._changed());\n this._services.set(name, supervisor);\n this._changed();\n await supervisor.sync();\n }\n\n private async _removeService(name: string): Promise<void> {\n const supervisor = this._services.get(name)!;\n this._services.delete(name);\n this._log.line(`[${name}] removed`);\n this._changed();\n await supervisor.dispose();\n }\n\n private async _disposeAllServices(): Promise<void> {\n const services = [...this._services.values()];\n this._services.clear();\n await Promise.all(services.map(service => service.dispose()));\n this._changed();\n }\n\n private _startHub({ hub: hubConfig, localEndpoint }: DaemonConfig): Promise<RunningHub> {\n const config: HubConfig = {\n ...hubConfig,\n listeners: [\n ...hubConfig.listeners,\n {\n type: 'socket',\n path: this._appPath,\n handlers: [localEndpoint.token !== undefined\n ? { token: 'static', value: localEndpoint.token }\n : { token: 'anonymous' }],\n },\n ],\n };\n return runHub({\n config,\n log: line => this._log.line(`[hub] ${line}`),\n identityStoreDir: this.home.identityDir,\n });\n }\n\n private async _openServiceSocket(\n name: string,\n service: ManagedService,\n onConnectionCountChanged: (count: number) => void,\n descriptor: ParticipantDescriptor,\n ) {\n if (!this._hub) throw new Error('the hub is not running');\n return this._hub.openParticipantSocket({\n path: this.home.allocEndpoint(`service-${name}`),\n provision: {\n grantedServiceId: service.serviceId,\n managedIdentity: service.managedIdentity ? { slot: `service:${name}` } : undefined,\n },\n descriptor,\n onConnectionCountChanged,\n });\n }\n\n private async _startManagementServer(): Promise<void> {\n const server = await SocketServer.start({\n endpoint: this._management.path,\n isTokenAccepted: async token => _tokensEqual(token, this._management.token),\n });\n server.setConnectionHandler((transport: NodeSocketTransport) => {\n const connection = LinkRpcConnection.fromTransport(transport);\n this._registerManagement(connection);\n transport.onDidClose(() => {\n this._endpointRegistrations.get(connection)?.dispose();\n this._endpointRegistrations.delete(connection);\n connection.close();\n });\n });\n this._managementServer = server;\n }\n\n private _registerManagement(connection: LinkRpcConnection): void {\n this._endpointRegistrations.set(connection, this._endpoints?.register(connection));\n connection.register(hubDaemonManagementInterface, {\n getStatus: () => this.status(),\n watchStatus: async (_params, _ctx, stream) => {\n await stream.send(this.status());\n const subscription = this.onDidChangeStatus(() => {\n stream.send(this.status()).catch(() => { /* the watcher went away */ });\n });\n try {\n await new Promise<void>(resolve => {\n if (stream.signal.aborted) resolve();\n else stream.signal.addEventListener('abort', () => resolve(), { once: true });\n });\n } finally {\n subscription.dispose();\n }\n return {};\n },\n reloadConfig: async () => {\n await this.reload({ force: true });\n return this.status();\n },\n getConfig: () => this._configFile.read(),\n setConfig: async ({ text, expectedRevision }) => ({ revision: await this.setConfig(text, expectedRevision) }),\n setServiceEnabled: async ({ name, enabled }) => {\n await this.setServiceEnabled(name, enabled);\n return {};\n },\n restartService: async ({ name }) => {\n await this.restartService(name);\n return {};\n },\n getServiceLogs: ({ name, limit }) => ({ lines: this._service(name).logs(limit) }),\n setCallLogLevel: async ({ level }) => {\n await this.setCallLogLevel(level);\n return {};\n },\n queryCalls: async ({ filter, limit }) => {\n const { calls, truncated } = await this._callLog.query(filter ?? {}, limit);\n return { calls: [...calls], truncated };\n },\n watchCalls: async ({ filter }, _ctx, stream) => {\n const subscription = this._callLog.watch(filter ?? {}, record => {\n stream.send(record).catch(() => { /* the watcher went away */ });\n });\n try {\n await new Promise<void>(resolve => {\n if (stream.signal.aborted) resolve();\n else stream.signal.addEventListener('abort', () => resolve(), { once: true });\n });\n } finally {\n subscription.dispose();\n }\n return {};\n },\n shutdown: () => {\n setTimeout(() => void this.shutdown(), 0);\n return {};\n },\n });\n connection.enableReflection();\n }\n\n private _service(name: string): ServiceSupervisor | ConnectionSupervisor {\n const service = this._services.get(name);\n if (!service) throw new Error(`unknown service '${name}'`);\n return service;\n }\n\n private _discovery(endpoint: LocalEndpoint): EndpointDiscovery {\n return {\n version: 1,\n pid: process.pid,\n endpoint: endpoint.path,\n ...(endpoint.token !== undefined ? { token: endpoint.token } : {}),\n };\n }\n\n private _serialize(op: () => Promise<void>): Promise<void> {\n const run = this._reconcile.then(op);\n this._reconcile = run.catch(error => this._log.line(`reconcile failed: ${_message(error)}`));\n return run;\n }\n\n private _changed(): void {\n if (this._statusChangeScheduled) return;\n this._statusChangeScheduled = true;\n queueMicrotask(() => {\n this._statusChangeScheduled = false;\n for (const listener of [...this._statusListeners]) listener();\n });\n }\n\n private async _doShutdown(): Promise<void> {\n this._stopping = true;\n this._log.line('shutting down');\n this._watcher?.dispose();\n await this._reconcile;\n for (const file of [this.home.discoveryFile, this.home.managementFile]) {\n if (readEndpointDiscovery(file)?.pid === process.pid) fs.rmSync(file, { force: true });\n }\n await this._disposeAllServices();\n await this._endpoints?.dispose();\n this._managementLink?.dispose();\n this._callLogAttachment?.dispose();\n this._hub?.dispose();\n this._hub = undefined;\n await this._callLog.close();\n this._managementServer?.dispose();\n this._statusListeners.clear();\n this._log.line('stopped');\n await this._log.close();\n this._lock.dispose();\n this._resolveDone();\n }\n}\n\nfunction _ensurePrivateDirs(home: HubHome): void {\n for (const dir of [home.configDir, home.stateDir, home.runtimeDir]) {\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 });\n }\n if (process.platform !== 'win32') fs.chmodSync(home.runtimeDir, 0o700);\n}\n\nfunction _token(): string {\n return randomBytes(32).toString('base64url');\n}\n\nfunction _tokensEqual(candidate: string | undefined, expected: string): boolean {\n if (candidate === undefined) return false;\n const a = Buffer.from(candidate);\n const b = Buffer.from(expected);\n return a.length === b.length && timingSafeEqual(a, b);\n}\n\nfunction _message(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","import * as net from 'node:net';\nimport { STREAM_METHOD } from '@hediet/linkrpc';\nimport { connectNdjson } from '@hediet/linkrpc/node';\nimport { readEndpointDiscovery } from './discovery';\nimport type { HubHome } from './paths';\n\nexport interface StdioBridgeOptions {\n readonly home: HubHome;\n readonly input: NodeJS.ReadableStream;\n readonly output: NodeJS.WritableStream;\n}\n\n/**\n * Connect a stream pair speaking newline-delimited JSON-RPC (without an\n * initialize handshake) to the local hub as a client: its requests are routed\n * by the hub and responses come back unchanged. Lets hosts that can only spawn\n * stdio services (e.g. the VS Code team-tools hub) route a service ID to this\n * hub. Resolves when either side closes.\n */\nexport async function bridgeStdioToLocalHub(options: StdioBridgeOptions): Promise<void> {\n const discovery = readEndpointDiscovery(options.home.discoveryFile);\n if (!discovery) throw new Error(`The local LinkRPC hub is not running (no ${options.home.discoveryFile}).`);\n const socket = net.connect(discovery.endpoint);\n await new Promise<void>((resolve, reject) => {\n socket.once('connect', resolve);\n socket.once('error', reject);\n });\n let close!: () => void;\n const closed = new Promise<void>(resolve => { close = resolve; });\n socket.on('error', () => close());\n const { transport: hub } = await connectNdjson({\n input: socket,\n output: socket,\n onClose: () => close(),\n initialize: { kind: 'client', token: discovery.token ?? '' },\n });\n const { transport: stdio } = await connectNdjson({\n input: options.input,\n output: options.output,\n onClose: () => close(),\n });\n hub.setListener(message => {\n // Nothing routes service calls to the bridge itself; requests from the hub\n // are participant probes (e.g. inspection), not traffic for the stdio side.\n // Stream frames answer streaming calls made through the bridge and must pass.\n if ('method' in message && message.method !== STREAM_METHOD) {\n if ('id' in message && message.id !== undefined && message.id !== null) {\n void hub.send({ jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'Method not found' } });\n }\n return;\n }\n void stdio.send(message);\n });\n stdio.setListener(message => void hub.send(message));\n await closed;\n hub.dispose();\n stdio.dispose();\n socket.destroy();\n}\n","import { spawn } from 'node:child_process';\n\nconst MIN_RESTART_DELAY_MS = 1_000;\nconst MAX_RESTART_DELAY_MS = 30_000;\n/** A run this long resets the restart delay. */\nconst STABLE_RUN_MS = 60_000;\n\n/**\n * Run the daemon as a child and restart it after crashes, for launchers that\n * do not supervise (Windows login entries, detached starts). Exit code 0 is an\n * intentional stop (or a duplicate daemon) and ends the watchdog too.\n */\nexport async function runWithKeepAlive(\n executable: string,\n args: readonly string[],\n log: (line: string) => void,\n): Promise<number> {\n let delay = MIN_RESTART_DELAY_MS;\n let stopping = false;\n let current: ReturnType<typeof spawn> | undefined;\n const stop = (signal: NodeJS.Signals) => {\n stopping = true;\n current?.kill(signal);\n };\n process.on('SIGINT', stop);\n process.on('SIGTERM', stop);\n try {\n while (true) {\n const startedAt = Date.now();\n const child = spawn(executable, args, { stdio: 'inherit', windowsHide: true });\n current = child;\n const code = await new Promise<number>(resolve => {\n child.once('error', error => {\n log(`cannot start the daemon: ${error.message}`);\n resolve(1);\n });\n child.once('exit', (exitCode, signal) => resolve(exitCode ?? (signal ? 1 : 0)));\n });\n current = undefined;\n if (stopping || code === 0) return code;\n if (Date.now() - startedAt > STABLE_RUN_MS) delay = MIN_RESTART_DELAY_MS;\n log(`the daemon exited with code ${code}; restarting in ${delay} ms`);\n await new Promise(resolve => setTimeout(resolve, delay));\n if (stopping) return code;\n delay = Math.min(delay * 2, MAX_RESTART_DELAY_MS);\n }\n } finally {\n process.off('SIGINT', stop);\n process.off('SIGTERM', stop);\n }\n}\n","#!/usr/bin/env node\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { Command } from 'commander';\nimport { createAutostartManager } from './autostart/autostart';\nimport { nodeDaemonLaunch } from './autostart/launch';\nimport { connectToHubManagement, type HubManagementConnection } from './client';\nimport { daemonConfigJsonSchema, parseDaemonConfigText } from './config';\nimport { queryDaemonStatus, startDaemon, stopDaemon } from './control';\nimport { HubDaemon } from './daemon';\nimport type { DaemonStatus } from './managementInterface';\nimport { HubHome } from './paths';\nimport { AlreadyRunningError } from './singleInstance';\nimport { bridgeStdioToLocalHub } from './stdioBridge';\nimport { runWithKeepAlive } from './watchdog';\n\nconst program = new Command('linkrpc-hub-daemon')\n .description('Run and manage your per-user LinkRPC hub.')\n .option('--home <dir>', 'hub directory (default: the per-user location, or LINKRPC_HUB_HOME)')\n .showHelpAfterError();\n\nfunction home(): HubHome {\n const dir = program.opts<{ home?: string; }>().home;\n return dir !== undefined ? HubHome.at(path.resolve(dir)) : HubHome.resolve();\n}\n\nprogram.command('run')\n .description('run the daemon in the foreground')\n .option('--keep-alive', 'restart the daemon after crashes (for unsupervised launchers)', false)\n .option('--quiet', 'log only to the log file, not to stderr', false)\n .action(async (opts: { keepAlive: boolean; quiet: boolean; }) => {\n const hubHome = home();\n if (opts.keepAlive) {\n const script = fileURLToPath(import.meta.url);\n const args = [...process.execArgv, script, ...process.argv.slice(2).filter(arg => arg !== '--keep-alive')];\n process.exitCode = await runWithKeepAlive(process.execPath, args, line => {\n fs.appendFileSync(hubHome.logFile, `${new Date().toISOString()} [watchdog] ${line}\\n`);\n });\n return;\n }\n let daemon: HubDaemon;\n // Only needed to start Electron's binary as Node.js; services must not inherit it.\n delete process.env.ELECTRON_RUN_AS_NODE;\n try {\n daemon = await HubDaemon.start({ home: hubHome, echoLog: !opts.quiet });\n } catch (error) {\n if (error instanceof AlreadyRunningError) {\n // Exit code 0: no supervisor (launchd, systemd, watchdog) restarts a duplicate.\n console.error(error.message);\n process.exit(0);\n }\n throw error;\n }\n const stop = () => void daemon.shutdown();\n process.once('SIGINT', stop);\n process.once('SIGTERM', stop);\n await daemon.done;\n process.exit(0);\n });\n\nprogram.command('start')\n .description('start the daemon in the background')\n .action(async () => {\n const hubHome = home();\n const result = await startDaemon({\n home: hubHome,\n launch: nodeDaemonLaunch(hubHome),\n autostart: await createAutostartManager({ home: hubHome }),\n });\n console.log(result === 'started' ? 'The hub is running.' : 'The hub is already running.');\n });\n\nprogram.command('stop')\n .description('stop all services and the daemon')\n .action(async () => {\n const result = await stopDaemon(home());\n console.log(result === 'stopped' ? 'The hub stopped.' : 'The hub is not running.');\n });\n\nprogram.command('restart')\n .description('stop and start the daemon')\n .action(async () => {\n const hubHome = home();\n await stopDaemon(hubHome);\n await startDaemon({ home: hubHome, launch: nodeDaemonLaunch(hubHome), autostart: await createAutostartManager({ home: hubHome }) });\n console.log('The hub is running.');\n });\n\nprogram.command('status')\n .description('show the daemon and its services')\n .option('--json', 'print the status as JSON', false)\n .action(async (opts: { json: boolean; }) => {\n const hubHome = home();\n const status = await queryDaemonStatus(hubHome);\n if (opts.json) {\n console.log(JSON.stringify(status ?? null, null, 2));\n } else {\n const autostart = await createAutostartManager({ home: hubHome });\n const enabled = await autostart.isEnabled();\n console.log(_formatStatus(status, hubHome, `${enabled ? 'enabled' : 'disabled'} (${autostart.description})`));\n }\n if (!status) process.exitCode = 1;\n });\n\nprogram.command('reload')\n .description('re-read the config file and apply what changed')\n .action(() => _withManagement(async management => {\n const status = await management.reloadConfig({});\n console.log(status.config.error ? `The config is invalid: ${status.config.error}` : 'Config applied.');\n }));\n\nprogram.command('bridge-stdio')\n .description('pipe newline-delimited JSON-RPC on stdin/stdout (no handshake) to the running hub')\n .action(async () => {\n await bridgeStdioToLocalHub({ home: home(), input: process.stdin, output: process.stdout });\n process.exit(0);\n });\n\nconst autostart = program.command('autostart').description('start the hub at login');\nautostart.command('enable').description('start the hub at login').action(async () => {\n const hubHome = home();\n const manager = await createAutostartManager({ home: hubHome });\n await manager.enable(nodeDaemonLaunch(hubHome));\n console.log(`The hub starts at login (${manager.description}).`);\n});\nautostart.command('disable').description('do not start the hub at login').action(async () => {\n const manager = await createAutostartManager({ home: home() });\n await manager.disable();\n console.log('The hub no longer starts at login.');\n});\nautostart.command('status').description('show whether the hub starts at login').action(async () => {\n const manager = await createAutostartManager({ home: home() });\n console.log(`${await manager.isEnabled() ? 'enabled' : 'disabled'} (${manager.description})`);\n});\n\nconst service = program.command('service').description('control configured services');\nservice.command('enable <name>').description('enable a service (persisted in the config)')\n .action((name: string) => _withManagement(m => m.setServiceEnabled({ name, enabled: true })));\nservice.command('disable <name>').description('disable a service (persisted in the config)')\n .action((name: string) => _withManagement(m => m.setServiceEnabled({ name, enabled: false })));\nservice.command('restart <name>').description('restart a service')\n .action((name: string) => _withManagement(m => m.restartService({ name })));\nservice.command('logs <name>').description('print recent output of a service')\n .option('-n, --lines <n>', 'number of lines', '100')\n .action((name: string, opts: { lines: string; }) => _withManagement(async m => {\n const { lines } = await m.getServiceLogs({ name, limit: Number(opts.lines) });\n for (const line of lines) {\n console.log(`${new Date(line.at).toISOString()} ${line.stream.padEnd(6)} ${line.text}`);\n }\n }));\n\nconst config = program.command('config').description('inspect the config file');\nconfig.command('path').description('print the config file path').action(() => console.log(home().configFile));\nconfig.command('schema').description('print the config JSON Schema').action(() => {\n console.log(JSON.stringify(daemonConfigJsonSchema(), null, 2));\n});\nconfig.command('validate [file]').description('validate a config file (default: the active one)')\n .action((file: string | undefined) => {\n const target = file ?? home().configFile;\n parseDaemonConfigText(fs.readFileSync(target, 'utf8'));\n console.log(`${target} is valid.`);\n });\n\nasync function _withManagement(action: (management: HubManagementConnection['management']) => Promise<unknown>): Promise<void> {\n const connection = await connectToHubManagement(home());\n try {\n await action(connection.management);\n } finally {\n connection.close();\n }\n}\n\nfunction _formatStatus(status: DaemonStatus | undefined, hubHome: HubHome, autostart: string): string {\n if (!status) {\n return [`LinkRPC hub: not running`, `Config: ${hubHome.configFile}`, `Autostart: ${autostart}`].join('\\n');\n }\n const lines = [\n `LinkRPC hub: running (pid ${status.pid}, ${status.version}, up ${_duration(Date.now() - status.startedAt)})`,\n `Endpoint: ${status.endpoint}`,\n `Config: ${status.configFile}${status.config.error ? `\\n error: ${status.config.error}` : ''}`,\n ...(status.hub.error ? [`Hub error: ${status.hub.error}`] : []),\n `Log: ${status.logFile}`,\n `Call log: ${status.callLog.level === 'off' ? 'off' : `${status.callLog.level} → ${status.callLog.directory}`}${status.callLog.error ? `\\n error: ${status.callLog.error}` : ''}`,\n `Autostart: ${autostart}`,\n ];\n if (status.services.length === 0) return [...lines, 'Services: none configured'].join('\\n');\n const rows = status.services.map(s => [\n s.name,\n s.state,\n s.pid?.toString() ?? '-',\n String(s.restarts),\n s.error ?? '',\n ]);\n const header = ['SERVICE', 'STATE', 'PID', 'RESTARTS', 'INFO'];\n const widths = header.map((h, i) => Math.max(h.length, ...rows.map(row => row[i]!.length)));\n const format = (row: string[]) => row.map((cell, i) => cell.padEnd(widths[i]!)).join(' ').trimEnd();\n return [...lines, '', format(header), ...rows.map(format)].join('\\n');\n}\n\nfunction _duration(ms: number): string {\n const s = Math.floor(ms / 1000);\n if (s < 60) return `${s}s`;\n if (s < 3600) return `${Math.floor(s / 60)}m`;\n return `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m`;\n}\n\nprogram.parseAsync(process.argv).catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : String(error));\n process.exit(1);\n});\n"],"x_google_ignoreList":[13,14,15,16,17,18,33,34,35,36,37,38,39,40,41,42,43,44,45],"mappings":";;;;;;;;;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,QAAkB,IAAI,KAAK,MAAM,MAAM,KAAK,OAAO,OAAO,EAAG,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,QAAQ;CACnG,OAAO;EAAC,GAAG;EAAO;EAAI,OAAO,MAAM;EAAG,GAAG,KAAK,IAAI,MAAM;CAAC,CAAC,CAAC,KAAK,IAAI;AACxE;AAEA,SAAS,UAAU,IAAoB;CACnC,MAAM,IAAI,KAAK,MAAM,KAAK,GAAI;CAC9B,IAAI,IAAI,IAAI,OAAO,GAAG,EAAE;CACxB,IAAI,IAAI,MAAM,OAAO,GAAG,KAAK,MAAM,IAAI,EAAE,EAAE;CAC3C,OAAO,GAAG,KAAK,MAAM,IAAI,IAAI,EAAE,IAAI,KAAK,MAAO,IAAI,OAAQ,EAAE,EAAE;AACnE;AAEA,QAAQ,WAAW,QAAQ,IAAI,CAAC,CAAC,OAAO,UAAmB;CACvD,QAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;CACpE,QAAQ,KAAK,CAAC;AAClB,CAAC"}
1
+ {"version":3,"file":"daemon.js","names":["path","fs","fs","fs","path","path","fs","path","path","fs","path","fs","path","path","parse","parser.parse","edit.setProperty","edit.applyEdit","jsonc.parse","jsonc.printParseErrorCode","jsonc.modify","jsonc.applyEdits","path","fs","path","fs","path","fs","fs","fs","path","path","path","crossSpawn","_message","fs","path","path","fs"],"sources":["../../linkrpc-hub-daemon/src/packageInfo.ts","../../linkrpc-hub-daemon/src/autostart/launch.ts","../../linkrpc-hub-daemon/src/autostart/launchd.ts","../../linkrpc-hub-daemon/src/autostart/linux.ts","../../linkrpc-hub-daemon/src/autostart/windows.ts","../../linkrpc-hub-daemon/src/autostart/autostart.ts","../../linkrpc-hub-daemon/src/durableWrite.ts","../../linkrpc-hub-daemon/src/discovery.ts","../../linkrpc-hub-daemon/src/callLog/callQuery.ts","../../linkrpc-hub-daemon/src/callLog/callRecord.ts","../../linkrpc-hub-daemon/src/managementInterface.ts","../../linkrpc-hub-daemon/src/paths.ts","../../linkrpc-hub-daemon/src/endpointInterface.ts","../../linkrpc-hub-daemon/src/client.ts","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/scanner.js","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/string-intern.js","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/format.js","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/parser.js","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/edit.js","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js","../../linkrpc-hub-daemon/src/callLog/callLogConfig.ts","../../linkrpc-hub-daemon/src/config.ts","../../linkrpc-hub-daemon/src/control.ts","../../linkrpc-hub-daemon/src/callLog/callLogService.ts","../../linkrpc-hub-daemon/src/callLog/callLogStore.ts","../../linkrpc-hub-daemon/src/callLog/payloadPolicy.ts","../../linkrpc-hub-daemon/src/callLog/portPeers.ts","../../linkrpc-hub-daemon/src/participantDescriptors.ts","../../linkrpc-hub-daemon/src/callLog/callRecorder.ts","../../linkrpc-hub-daemon/src/callLog/callLog.ts","../../linkrpc-hub-daemon/src/configFile.ts","../../linkrpc-hub-daemon/src/daemonLog.ts","../../linkrpc-hub-daemon/src/singleInstance.ts","../../linkrpc-hub-daemon/src/logBuffer.ts","../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js","../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js","../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js","../../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js","../../../node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js","../../../node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js","../../../node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js","../../linkrpc-hub-daemon/src/processTree.ts","../../linkrpc-hub-daemon/src/processIo.ts","../../linkrpc-hub-daemon/src/supervisor.ts","../../linkrpc-hub-daemon/src/connectionSupervisor.ts","../../linkrpc-hub-daemon/src/screenHistory.ts","../../linkrpc-hub-daemon/src/managedEndpoints.ts","../../linkrpc-hub-daemon/src/daemon.ts","../../linkrpc-hub-daemon/src/stdioBridge.ts","../../linkrpc-hub-daemon/src/watchdog.ts","../../linkrpc-hub-daemon/src/cli.ts"],"sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst PACKAGE_NAME = '@hediet/linkrpc-hub-daemon';\nconst CLI_PACKAGE_NAME = '@hediet/linkrpc-cli';\n\n/** The root directory of this package (works from `src/` and bundled `dist/`). */\nexport function packageRoot(): string {\n let dir = path.dirname(fileURLToPath(import.meta.url));\n while (true) {\n const manifest = path.join(dir, 'package.json');\n if (fs.existsSync(manifest)) {\n const name = JSON.parse(fs.readFileSync(manifest, 'utf8')).name;\n if (name === PACKAGE_NAME || name === CLI_PACKAGE_NAME) return dir;\n }\n const parent = path.dirname(dir);\n if (parent === dir) throw new Error(`cannot locate the ${PACKAGE_NAME} package root`);\n dir = parent;\n }\n}\n\nexport function packageVersion(): string {\n return JSON.parse(fs.readFileSync(path.join(packageRoot(), 'package.json'), 'utf8')).version;\n}\n\n/** The daemon CLI script; `node <cliScript> run` runs the daemon. */\nexport function cliScript(): string {\n const root = packageRoot();\n const { name } = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));\n return path.join(root, 'dist', name === CLI_PACKAGE_NAME ? 'daemon.js' : 'cli.js');\n}\n","import { spawn } from 'node:child_process';\nimport * as fs from 'node:fs';\nimport { cliScript } from '../packageInfo';\nimport type { HubHome } from '../paths';\n\n/** A process to start: executable, arguments, and extra environment. */\nexport interface LaunchCommand {\n readonly executable: string;\n readonly args: readonly string[];\n readonly env: Readonly<Record<string, string>>;\n}\n\n/** How to run the daemon, as registered with the OS. */\nexport interface DaemonLaunch {\n /** The daemon in the foreground, for OS managers that restart it on failure (launchd, systemd). */\n readonly foreground: LaunchCommand;\n /** The daemon under its own crash-restart watchdog, for launchers without supervision. */\n readonly keepAlive: LaunchCommand;\n /** The keep-alive executable opens no console window (a GUI-subsystem binary on Windows). */\n readonly windowless: boolean;\n}\n\n/**\n * Run the daemon with this Node.js runtime and the package's CLI script. The\n * executable is resolved through symlinks: version managers (fnm, nvm, volta)\n * expose per-shell paths that do not survive a logout.\n */\nexport function nodeDaemonLaunch(home: HubHome, executable: string = fs.realpathSync(process.execPath), env: Readonly<Record<string, string>> = {}): DaemonLaunch {\n const run = [cliScript(), ...(home.customDir !== undefined ? ['--home', home.customDir] : []), 'run', '--quiet'];\n return {\n foreground: { executable, args: run, env },\n keepAlive: { executable, args: [...run, '--keep-alive'], env },\n windowless: false,\n };\n}\n\n/** Start `command` detached from this process, without a console window. */\nexport function spawnDetached(command: LaunchCommand): void {\n const child = spawn(command.executable, command.args, {\n detached: true,\n stdio: 'ignore',\n windowsHide: true,\n env: { ...process.env, ...command.env },\n });\n child.on('error', () => { /* surfaced by the readiness wait */ });\n child.unref();\n}\n\nexport interface ExecResult {\n readonly code: number;\n readonly stdout: string;\n readonly stderr: string;\n}\n\nexport type Exec = (file: string, args: readonly string[]) => Promise<ExecResult>;\n\n/** Run a short-lived command and capture its output. Never rejects. */\nexport const execCommand: Exec = (file, args) => new Promise(resolve => {\n const child = spawn(file, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });\n let stdout = '';\n let stderr = '';\n child.stdout.setEncoding('utf8').on('data', (chunk: string) => { stdout += chunk; });\n child.stderr.setEncoding('utf8').on('data', (chunk: string) => { stderr += chunk; });\n child.once('error', error => resolve({ code: -1, stdout, stderr: error.message }));\n child.once('close', code => resolve({ code: code ?? -1, stdout, stderr }));\n});\n\nexport function checkExec(result: ExecResult, what: string): void {\n if (result.code !== 0) throw new Error(`${what} failed (${result.code}): ${(result.stderr || result.stdout).trim()}`);\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { AutostartManager } from './autostart';\nimport { checkExec, type DaemonLaunch, type Exec } from './launch';\n\n/**\n * macOS login autostart through a per-user LaunchAgent. launchd restarts the\n * daemon after crashes but not after an intentional (exit code 0) stop.\n */\nexport class LaunchdAutostart implements AutostartManager {\n public readonly description = 'macOS LaunchAgent';\n\n constructor(\n private readonly _label: string,\n private readonly _plistPath: string,\n private readonly _exec: Exec,\n private readonly _uid: number,\n ) { }\n\n public async isEnabled(): Promise<boolean> {\n return fs.existsSync(this._plistPath);\n }\n\n /** Registers for the next login; does not start the daemon now. */\n public async enable(launch: DaemonLaunch): Promise<void> {\n fs.mkdirSync(path.dirname(this._plistPath), { recursive: true });\n fs.writeFileSync(this._plistPath, launchdPlist(this._label, launch));\n }\n\n /** Unregisters; a running daemon keeps running. */\n public async disable(): Promise<void> {\n fs.rmSync(this._plistPath, { force: true });\n }\n\n public async startManaged(): Promise<boolean> {\n if (!fs.existsSync(this._plistPath)) return false;\n const domain = `gui/${this._uid}`;\n const kickstart = await this._exec('launchctl', ['kickstart', `${domain}/${this._label}`]);\n if (kickstart.code === 0) return true;\n checkExec(await this._exec('launchctl', ['bootstrap', domain, this._plistPath]), 'launchctl bootstrap');\n return true;\n }\n}\n\nexport function launchdPlist(label: string, launch: DaemonLaunch): string {\n const { executable, args, env } = launch.foreground;\n const strings = (values: readonly string[]) => values.map(v => ` <string>${_xml(v)}</string>`).join('\\n');\n const envEntries = Object.entries(env)\n .map(([key, value]) => ` <key>${_xml(key)}</key>\\n <string>${_xml(value)}</string>`)\n .join('\\n');\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>Label</key>\n <string>${_xml(label)}</string>\n <key>ProgramArguments</key>\n <array>\n${strings([executable, ...args])}\n </array>\n <key>EnvironmentVariables</key>\n <dict>\n${envEntries}\n </dict>\n <key>RunAtLoad</key>\n <true/>\n <key>KeepAlive</key>\n <dict>\n <key>SuccessfulExit</key>\n <false/>\n </dict>\n <key>ProcessType</key>\n <string>Background</string>\n</dict>\n</plist>\n`;\n}\n\nfunction _xml(value: string): string {\n return value\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&apos;');\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { AutostartManager } from './autostart';\nimport { checkExec, type DaemonLaunch, type Exec, type LaunchCommand } from './launch';\n\n/**\n * Linux login autostart through a systemd user unit. systemd restarts the\n * daemon after crashes (`Restart=on-failure`) but not after an intentional stop.\n */\nexport class SystemdUserAutostart implements AutostartManager {\n public readonly description = 'systemd user service';\n\n constructor(\n private readonly _unitName: string,\n private readonly _unitPath: string,\n private readonly _exec: Exec,\n ) { }\n\n public async isEnabled(): Promise<boolean> {\n const result = await this._exec('systemctl', ['--user', 'is-enabled', this._unitName]);\n return result.code === 0 && result.stdout.trim() === 'enabled';\n }\n\n /** Registers for the next login; does not start the daemon now. */\n public async enable(launch: DaemonLaunch): Promise<void> {\n fs.mkdirSync(path.dirname(this._unitPath), { recursive: true });\n fs.writeFileSync(this._unitPath, systemdUnit(launch));\n checkExec(await this._exec('systemctl', ['--user', 'daemon-reload']), 'systemctl daemon-reload');\n checkExec(await this._exec('systemctl', ['--user', 'enable', this._unitName]), 'systemctl enable');\n }\n\n /** Unregisters; a running daemon keeps running. */\n public async disable(): Promise<void> {\n await this._exec('systemctl', ['--user', 'disable', this._unitName]);\n fs.rmSync(this._unitPath, { force: true });\n await this._exec('systemctl', ['--user', 'daemon-reload']);\n }\n\n public async startManaged(): Promise<boolean> {\n if (!await this.isEnabled()) return false;\n checkExec(await this._exec('systemctl', ['--user', 'start', this._unitName]), 'systemctl start');\n return true;\n }\n}\n\nexport function systemdUnit(launch: DaemonLaunch): string {\n const { executable, args, env } = launch.foreground;\n const environment = Object.entries(env).map(([key, value]) => `Environment=${_systemdQuote(`${key}=${value}`)}\\n`).join('');\n return `[Unit]\nDescription=LinkRPC user hub\n\n[Service]\nType=simple\nExecStart=${[executable, ...args].map(_systemdQuote).join(' ')}\n${environment}Restart=on-failure\nRestartSec=2\n\n[Install]\nWantedBy=default.target\n`;\n}\n\n/**\n * Linux login autostart through an XDG autostart entry, for desktops without\n * a systemd user instance. Also used for the tray app.\n */\nexport class XdgAutostart implements AutostartManager {\n public readonly description = 'XDG autostart';\n\n constructor(\n private readonly _desktopFile: string,\n private readonly _displayName: string,\n ) { }\n\n public async isEnabled(): Promise<boolean> {\n return fs.existsSync(this._desktopFile);\n }\n\n public async enable(launch: DaemonLaunch): Promise<void> {\n this.enableCommand(launch.keepAlive);\n }\n\n public enableCommand(command: LaunchCommand): void {\n fs.mkdirSync(path.dirname(this._desktopFile), { recursive: true });\n fs.writeFileSync(this._desktopFile, xdgDesktopEntry(this._displayName, command));\n }\n\n public async disable(): Promise<void> {\n fs.rmSync(this._desktopFile, { force: true });\n }\n\n public async startManaged(): Promise<boolean> {\n return false;\n }\n}\n\nexport function xdgDesktopEntry(name: string, command: LaunchCommand): string {\n const env = Object.entries(command.env).map(([key, value]) => `${key}=${value}`);\n const argv = [...(env.length > 0 ? ['env', ...env] : []), command.executable, ...command.args];\n return `[Desktop Entry]\nType=Application\nName=${name}\nExec=${argv.map(_desktopExecQuote).join(' ')}\nTerminal=false\nNoDisplay=true\nX-GNOME-Autostart-enabled=true\n`;\n}\n\nfunction _systemdQuote(arg: string): string {\n const escaped = arg.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"').replace(/%/g, '%%').replace(/\\$/g, '$$$$');\n return `\"${escaped}\"`;\n}\n\n/** Desktop Entry `Exec` quoting, then string-value escaping of backslashes. */\nfunction _desktopExecQuote(arg: string): string {\n const percentEscaped = arg.replace(/%/g, '%%');\n if (/^[A-Za-z0-9_@%+=:,./-]+$/.test(percentEscaped)) return percentEscaped;\n const quoted = `\"${percentEscaped.replace(/([\"`$\\\\])/g, '\\\\$1')}\"`;\n return quoted.replace(/\\\\/g, '\\\\\\\\');\n}\n","import * as path from 'node:path';\nimport { checkExec, type DaemonLaunch, type Exec } from './launch';\nimport type { AutostartManager } from './autostart';\n\nconst RUN_KEY = 'HKCU\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run';\n/** Where Task Manager's \"Startup apps\" toggle records disabled entries. */\nconst STARTUP_APPROVED_KEY = 'HKCU\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\StartupApproved\\\\Run';\n\n/**\n * Windows login autostart through the per-user `Run` key: no elevation, and\n * listed under Task Manager's startup apps. The daemon runs under its own\n * keep-alive watchdog; console executables are hosted by a headless conhost so\n * that no window appears.\n */\nexport class WindowsRunKeyAutostart implements AutostartManager {\n public readonly description = 'Windows login (HKCU Run key)';\n private readonly _reg: string;\n private readonly _conhost: string;\n\n constructor(\n private readonly _valueName: string,\n private readonly _exec: Exec,\n systemRoot: string = process.env.SystemRoot ?? 'C:\\\\Windows',\n ) {\n this._reg = path.win32.join(systemRoot, 'System32', 'reg.exe');\n this._conhost = path.win32.join(systemRoot, 'System32', 'conhost.exe');\n }\n\n public async isEnabled(): Promise<boolean> {\n const registered = await this._exec(this._reg, ['query', RUN_KEY, '/v', this._valueName]);\n if (registered.code !== 0) return false;\n const approval = await this._exec(this._reg, ['query', STARTUP_APPROVED_KEY, '/v', this._valueName]);\n if (approval.code !== 0) return true;\n const flags = /REG_BINARY\\s+([0-9A-F]{2})/i.exec(approval.stdout)?.[1];\n return flags === undefined || (parseInt(flags, 16) & 1) === 0;\n }\n\n public async enable(launch: DaemonLaunch): Promise<void> {\n checkExec(\n await this._exec(this._reg, ['add', RUN_KEY, '/v', this._valueName, '/t', 'REG_SZ', '/d', this.commandLine(launch), '/f']),\n 'registering the login entry',\n );\n await this._exec(this._reg, ['delete', STARTUP_APPROVED_KEY, '/v', this._valueName, '/f']);\n }\n\n public async disable(): Promise<void> {\n await this._exec(this._reg, ['delete', RUN_KEY, '/v', this._valueName, '/f']);\n }\n\n public async startManaged(): Promise<boolean> {\n return false;\n }\n\n /** The `Run` value: keep-alive command line, windowless. */\n public commandLine(launch: DaemonLaunch): string {\n const { executable, args, env } = launch.keepAlive;\n if (Object.keys(env).length > 0) {\n throw new Error('Windows login entries cannot set environment variables; use a launch without env');\n }\n const command = [executable, ...args].map(quoteWindowsArg);\n return (launch.windowless ? command : [quoteWindowsArg(this._conhost), '--headless', ...command]).join(' ');\n }\n}\n\n/** Quote one argument for `CommandLineToArgvW`/MSVCRT parsing. */\nexport function quoteWindowsArg(arg: string): string {\n if (arg !== '' && !/[\\s\"]/.test(arg)) return arg;\n let quoted = '\"';\n let backslashes = 0;\n for (const char of arg) {\n if (char === '\\\\') {\n backslashes++;\n continue;\n }\n quoted += char === '\"' ? '\\\\'.repeat(backslashes * 2 + 1) + '\"' : '\\\\'.repeat(backslashes) + char;\n backslashes = 0;\n }\n return quoted + '\\\\'.repeat(backslashes * 2) + '\"';\n}\n","import * as os from 'node:os';\nimport * as path from 'node:path';\nimport type { HubHome } from '../paths';\nimport { type DaemonLaunch, type Exec, execCommand } from './launch';\nimport { LaunchdAutostart } from './launchd';\nimport { SystemdUserAutostart, XdgAutostart } from './linux';\nimport { WindowsRunKeyAutostart } from './windows';\n\n/**\n * Registers the daemon to start at user login. Enabling or disabling never\n * starts or stops a running daemon.\n */\nexport interface AutostartManager {\n /** Human-readable mechanism, e.g. \"systemd user service\". */\n readonly description: string;\n isEnabled(): Promise<boolean>;\n enable(launch: DaemonLaunch): Promise<void>;\n disable(): Promise<void>;\n /**\n * Start the daemon through the OS manager, so that it supervises this\n * instance too. Resolves `false` when the mechanism cannot (or is not\n * registered to) start it; the caller then starts it directly.\n */\n startManaged(): Promise<boolean>;\n}\n\nexport interface AutostartOptions {\n readonly home: HubHome;\n readonly platform?: NodeJS.Platform;\n readonly exec?: Exec;\n readonly homedir?: string;\n readonly env?: NodeJS.ProcessEnv;\n}\n\n/** The login-autostart mechanism of this platform. */\nexport async function createAutostartManager(options: AutostartOptions): Promise<AutostartManager> {\n const platform = options.platform ?? process.platform;\n const exec = options.exec ?? execCommand;\n const homedir = options.homedir ?? os.homedir();\n const env = options.env ?? process.env;\n const name = options.home.instanceName;\n if (platform === 'win32') return new WindowsRunKeyAutostart(name, exec);\n if (platform === 'darwin') {\n const label = `dev.hediet.${name}`;\n const uid = process.getuid?.() ?? 0;\n return new LaunchdAutostart(label, path.posix.join(homedir, 'Library', 'LaunchAgents', `${label}.plist`), exec, uid);\n }\n const configHome = env.XDG_CONFIG_HOME || path.posix.join(homedir, '.config');\n if ((await exec('systemctl', ['--user', 'show-environment'])).code === 0) {\n return new SystemdUserAutostart(`${name}.service`, path.posix.join(configHome, 'systemd', 'user', `${name}.service`), exec);\n }\n return new XdgAutostart(path.posix.join(configHome, 'autostart', `${name}.desktop`), 'LinkRPC Hub');\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\n/**\n * Atomically replace `file` with `data`, durably: after a crash or power loss,\n * the file holds either the old or the new content.\n *\n * A rename alone is not enough: file systems journal the rename (metadata)\n * but may not have written the data yet, which leaves a file of the new size\n * filled with zeros. The data is therefore flushed before the rename, and the\n * directory entry after it (POSIX; Windows cannot open directories as files).\n */\nexport function writeFileDurably(file: string, data: string, options: { mode?: number; } = {}): void {\n const tmp = `${file}.${process.pid}.tmp`;\n try {\n const fd = fs.openSync(tmp, 'w', options.mode);\n try {\n fs.writeFileSync(fd, data);\n fs.fsyncSync(fd);\n } finally {\n fs.closeSync(fd);\n }\n fs.renameSync(tmp, file);\n } catch (error) {\n fs.rmSync(tmp, { force: true });\n throw error;\n }\n if (process.platform !== 'win32') _fsyncDirectory(path.dirname(file));\n}\n\nfunction _fsyncDirectory(dir: string): void {\n const fd = fs.openSync(dir, 'r');\n try {\n fs.fsyncSync(fd);\n } catch (error) {\n // Some file systems do not support syncing directories; the data itself is already durable.\n if (!['EINVAL', 'ENOTSUP', 'EISDIR'].includes((error as NodeJS.ErrnoException).code ?? '')) throw error;\n } finally {\n fs.closeSync(fd);\n }\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { z } from 'zod';\nimport { writeFileDurably } from './durableWrite';\n\n/**\n * How to reach one daemon endpoint. The daemon writes one file for\n * applications ({@link HubHome.discoveryFile}) and one for management\n * ({@link HubHome.managementFile}); both are private to the user.\n */\nexport const EndpointDiscoverySchema = z.object({\n version: z.literal(1),\n pid: z.number().int(),\n /** Named pipe (Windows) or Unix socket path. */\n endpoint: z.string().min(1),\n /** Absent when the endpoint requires no token. */\n token: z.string().min(1).optional(),\n});\nexport type EndpointDiscovery = z.infer<typeof EndpointDiscoverySchema>;\n\n/** The published endpoint, or `undefined` when absent or unreadable. */\nexport function readEndpointDiscovery(file: string): EndpointDiscovery | undefined {\n let text: string;\n try {\n text = fs.readFileSync(file, 'utf8');\n } catch {\n return undefined;\n }\n try {\n const parsed = EndpointDiscoverySchema.safeParse(JSON.parse(text));\n return parsed.success ? parsed.data : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Atomically and durably write a JSON file readable only by the current user. */\nexport function writePrivateJson(file: string, value: unknown): void {\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });\n writeFileDurably(file, JSON.stringify(value, null, 2) + '\\n', { mode: 0o600 });\n}\n","/**\n * The call-log query language, shared by the daemon (which filters) and UIs\n * (which build terms). Dependency-free so sandboxed renderers can bundle it.\n *\n * A query is a list of space-separated terms that must all match:\n * - `text`: case-insensitive substring of the method, caller, target,\n * principal, or error message. Quote terms with spaces: `\"no route\"`.\n * - `method:<glob>`: matches `service::interface::member` (the service is\n * empty for root-form calls); `*` matches any characters.\n * - `service:<name>`: the call came from or went to that configured daemon\n * service (e.g. `service:devtunnel`); case-insensitive, no wildcards.\n * - `-<term>` negates a term, e.g. `-method:hediet/devbox::*`.\n */\nimport type { CallRecord } from './callRecord';\n\n/** A call's method split at its parts. */\nexport interface CallTarget {\n /** Absent for root-form calls (`interface::member`). */\n readonly serviceId: string | undefined;\n readonly interfaceId: string | undefined;\n readonly member: string;\n}\n\nexport function callTargetOf(record: Pick<CallRecord, 'method' | 'serviceId'>): CallTarget {\n const { serviceId } = record;\n const rest = serviceId !== undefined && record.method.startsWith(`${serviceId}::`)\n ? record.method.slice(serviceId.length + 2)\n : record.method.replace(/^::/, '');\n const separator = rest.lastIndexOf('::');\n return separator < 0\n ? { serviceId, interfaceId: undefined, member: rest }\n : { serviceId, interfaceId: rest.slice(0, separator), member: rest.slice(separator + 2) };\n}\n\n/**\n * A `method:` glob for the given parts; omitted parts match anything, e.g.\n * `{ serviceId: 'a' }` → `a::*`, `{ interfaceId: 'i', member: 'm' }` → `*::i::m`.\n */\nexport function methodPattern(target: Partial<CallTarget>): string {\n const parts = [target.serviceId ?? '*', target.interfaceId ?? '*', target.member ?? '*'];\n while (parts.length > 1 && parts.at(-1) === '*' && parts.at(-2) === '*') parts.pop();\n return parts.join('::');\n}\n\n/** The term that excludes calls matching `methodPattern(target)`. */\nexport function excludeMethodTerm(target: Partial<CallTarget>): string {\n return `-method:${methodPattern(target)}`;\n}\n\n/** The term that limits the log to calls through a configured daemon service. */\nexport function serviceTerm(name: string): string {\n return `service:${name}`;\n}\n\ninterface Term {\n readonly negated: boolean;\n readonly test: (record: CallRecord) => boolean;\n}\n\nconst TERM = /(-?)(?:(method|service):)?(\"[^\"]*\"?|\\S+)/g;\n\nexport class CallQuery {\n public static parse(text: string): CallQuery {\n const terms: Term[] = [];\n for (const [, negation, qualifier, raw] of text.matchAll(TERM)) {\n const value = _unquote(raw!);\n if (value === '') continue;\n terms.push({\n negated: negation === '-',\n test: qualifier === 'method' ? _methodTest(value)\n : qualifier === 'service' ? _serviceTest(value.toLowerCase())\n : _textTest(value.toLowerCase()),\n });\n }\n return new CallQuery(terms);\n }\n\n /** `text` with `term` appended, unless an equal term is already present. */\n public static appendTerm(text: string, term: string): string {\n const existing = [...text.matchAll(TERM)].map(match => match[0]);\n return existing.includes(term) ? text : [text.trim(), term].filter(part => part !== '').join(' ');\n }\n\n private constructor(private readonly _terms: readonly Term[]) { }\n\n public matches(record: CallRecord): boolean {\n return this._terms.every(term => term.test(record) !== term.negated);\n }\n}\n\nfunction _textTest(needle: string): (record: CallRecord) => boolean {\n return record => [record.method, record.from.label, record.to?.label, record.principal, record.error?.message]\n .some(value => value?.toLowerCase().includes(needle));\n}\n\nfunction _serviceTest(name: string): (record: CallRecord) => boolean {\n return record => [record.from.service, record.to?.service].some(service => service?.toLowerCase() === name);\n}\n\nfunction _methodTest(glob: string): (record: CallRecord) => boolean {\n const escaped = glob.split('*').map(part => part.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')).join('.*');\n const pattern = new RegExp(`^${escaped}$`, 'i');\n return record => {\n const { serviceId, interfaceId, member } = callTargetOf(record);\n return pattern.test([serviceId ?? '', interfaceId ?? '', member].join('::'));\n };\n}\n\nfunction _unquote(raw: string): string {\n return raw.startsWith('\"') ? raw.slice(1, raw.endsWith('\"') && raw.length > 1 ? -1 : undefined) : raw;\n}\n","/**\n * The persisted call-log record and its filter. Schema-only (no Node.js APIs)\n * so management clients and UIs can share it.\n */\nimport { logLevelSchema } from '@hediet/linkrpc-infra/logging';\nimport { z } from 'zod';\nimport { CallQuery } from './callQuery';\n\n/** `linkrpc.logging` levels. A threshold records calls at or above it. */\nexport const CallLogLevelSchema = z.enum(logLevelSchema.options);\nexport type CallLogLevel = z.infer<typeof CallLogLevelSchema>;\n\n/**\n * The level of a recorded call: failures are `error`, requests `info`,\n * notifications `debug`, and stream frames reported apart from their request\n * `trace`. `warn` records the same calls as `error`.\n */\nexport const CallRecordLevelSchema = z.enum(['error', 'info', 'debug', 'trace']);\nexport type CallRecordLevel = z.infer<typeof CallRecordLevelSchema>;\n\n/** One side of a call at the hub: the port's friendly label and its transport. */\nexport const CallPeerSchema = z.object({\n /** The port's claimed prefix (e.g. `hediet/devbox`) or an edge id (`e12`). */\n label: z.string(),\n /** E.g. `named-pipe \\\\.\\pipe\\linkrpc-hub-user` or `websocket 10.0.0.2:51234`. */\n transport: z.string().optional(),\n /** The configured daemon service connected through this port, e.g. `devtunnel`. */\n service: z.string().optional(),\n});\nexport type CallPeer = z.infer<typeof CallPeerSchema>;\n\n/**\n * One NDJSON line. A call still in flight is written as `pending` and written\n * again under the same `id` when it settles; readers keep the newest record per id.\n */\nexport const CallRecordSchema = z.object({\n v: z.literal(1),\n id: z.string(),\n /** Start, epoch ms. */\n at: z.number(),\n level: CallRecordLevelSchema,\n kind: z.enum(['request', 'notification', 'stream']),\n status: z.enum(['pending', 'completed', 'failed', 'unroutable', 'dropped']),\n durationMs: z.number(),\n /** The wire method, e.g. `hediet/pc2/compute::linkrpc.compute::exec`. */\n method: z.string(),\n serviceId: z.string().optional(),\n /** Where the call entered the hub. */\n from: CallPeerSchema,\n /** Where the hub forwarded it; absent when the hub consumed or dropped it. */\n to: CallPeerSchema.optional(),\n /** `$hubrpc.principal` of a signed call; verified when the hub checks forwarded calls. */\n principal: z.string().optional(),\n error: z.object({ code: z.number(), message: z.string() }).optional(),\n /** UTF-8 size of the application params (without `$hubrpc*` meta). */\n paramsBytes: z.number().int().optional(),\n resultBytes: z.number().int().optional(),\n /** Redacted and truncated per the `callLog.payloads` policy; absent for `mode: \"none\"`. */\n params: z.unknown().optional(),\n result: z.unknown().optional(),\n /** Stream frames folded into this record (frames shortly after the request starts). */\n streamFrames: z.number().int().optional(),\n});\nexport type CallRecord = z.infer<typeof CallRecordSchema>;\n\nexport const CallFilterSchema = z.object({\n /** A {@link CallQuery}: space-separated terms, `-term` to exclude, `method:<glob>` for methods. */\n text: z.string().optional(),\n /** Only records at or above this level, e.g. `error` for failures. */\n minLevel: CallRecordLevelSchema.optional(),\n /** Start time bounds, epoch ms (inclusive). */\n since: z.number().optional(),\n until: z.number().optional(),\n});\nexport type CallFilter = z.infer<typeof CallFilterSchema>;\n\nconst SEVERITY: Readonly<Record<CallLogLevel, number>> = { trace: 0, debug: 1, info: 2, warn: 3, error: 4, off: 5 };\n\n/** Whether a record at `level` is recorded or shown at `threshold`. */\nexport function isCallLevelEnabled(level: CallRecordLevel, threshold: CallLogLevel): boolean {\n return SEVERITY[level] >= SEVERITY[threshold];\n}\n\n/** Parses `filter` once; the result tests records against it. */\nexport function createCallMatcher(filter: CallFilter): (record: CallRecord) => boolean {\n const query = filter.text ? CallQuery.parse(filter.text) : undefined;\n return record => {\n if (filter.minLevel !== undefined && !isCallLevelEnabled(record.level, filter.minLevel)) return false;\n if (filter.since !== undefined && record.at < filter.since) return false;\n if (filter.until !== undefined && record.at > filter.until) return false;\n return query?.matches(record) ?? true;\n };\n}\n","import { defineInterface, requestType } from '@hediet/linkrpc';\nimport { z } from 'zod';\nimport { CallFilterSchema, CallLogLevelSchema, CallRecordSchema } from './callLog/callRecord';\n\nexport const ServiceStateSchema = z.enum([\n /** `enabled: false` in the config. */\n 'disabled',\n /** Exited without a pending restart. */\n 'stopped',\n /** Spawned, waiting for readiness (hub connection or spawn). */\n 'starting',\n 'running',\n /** Exited; restarting after a delay. */\n 'backoff',\n 'stopping',\n /** Exited abnormally and the restart policy gave up. */\n 'failed',\n]);\nexport type ServiceState = z.infer<typeof ServiceStateSchema>;\n\nexport const ServiceStatusSchema = z.object({\n name: z.string(),\n description: z.string().optional(),\n /** Namespace the service may claim on the hub. */\n serviceId: z.string(),\n enabled: z.boolean(),\n state: ServiceStateSchema,\n /** Epoch ms of the last state change. */\n since: z.number(),\n pid: z.number().int().optional(),\n /** Open hub connections of this service. */\n connections: z.number().int(),\n /** Restarts since the service was (re)configured. */\n restarts: z.number().int(),\n lastExit: z.object({\n code: z.number().int().nullable(),\n signal: z.string().nullable(),\n at: z.number(),\n }).optional(),\n error: z.string().optional(),\n});\nexport type ServiceStatus = z.infer<typeof ServiceStatusSchema>;\n\nexport const DaemonStatusSchema = z.object({\n pid: z.number().int(),\n version: z.string(),\n startedAt: z.number(),\n /** Application endpoint (named pipe or Unix socket). */\n endpoint: z.string(),\n configFile: z.string(),\n logFile: z.string(),\n config: z.object({\n /** Revision of the applied config file. */\n revision: z.string().optional(),\n appliedAt: z.number().optional(),\n /** Why the current file is not applied; the previous config keeps running. */\n error: z.string().optional(),\n }),\n hub: z.object({\n startedAt: z.number(),\n listeners: z.array(z.object({ type: z.string(), address: z.string() })),\n error: z.string().optional(),\n }),\n callLog: z.object({\n level: CallLogLevelSchema,\n /** Directory of the NDJSON call-log files. */\n directory: z.string(),\n /** Where the log is served as `linkrpc.logging` while the hub runs. */\n serviceId: z.string().optional(),\n error: z.string().optional(),\n }),\n services: z.array(ServiceStatusSchema),\n});\nexport type DaemonStatus = z.infer<typeof DaemonStatusSchema>;\n\nexport const LogLineSchema = z.object({\n at: z.number(),\n stream: z.enum(['stdout', 'stderr', 'daemon']),\n text: z.string(),\n});\nexport type LogLine = z.infer<typeof LogLineSchema>;\n\nexport const ConfigDocumentSchema = z.object({\n path: z.string(),\n text: z.string(),\n /** Opaque content revision; pass it back to `setConfig`. */\n revision: z.string(),\n});\nexport type ConfigDocument = z.infer<typeof ConfigDocumentSchema>;\n\n/** Management API of the local hub daemon, served on its management endpoint. */\nexport const hubDaemonManagementInterface = defineInterface(\n { id: 'linkrpc.hubDaemon', description: 'Manage the local LinkRPC hub daemon.' },\n {\n getStatus: requestType(z.object({}), DaemonStatusSchema),\n /** Streams the status on every change until cancelled. */\n watchStatus: requestType(z.object({}), z.object({})).withStream({ server: DaemonStatusSchema }),\n /** Re-read the config file and apply what changed. */\n reloadConfig: requestType(z.object({}), DaemonStatusSchema),\n getConfig: requestType(z.object({}), ConfigDocumentSchema),\n /** Validate, write, and apply; rejects when the file changed since `expectedRevision`. */\n setConfig: requestType(\n z.object({ text: z.string(), expectedRevision: z.string() }),\n z.object({ revision: z.string() }),\n ),\n /** Persistently enable or disable a service in the config file. */\n setServiceEnabled: requestType(z.object({ name: z.string(), enabled: z.boolean() }), z.object({})),\n restartService: requestType(z.object({ name: z.string() }), z.object({})),\n getServiceLogs: requestType(\n z.object({ name: z.string(), limit: z.number().int().positive().optional() }),\n z.object({ lines: z.array(LogLineSchema) }),\n ),\n /** Persist `callLog.level` in the config file and apply it (`off` stops recording). */\n setCallLogLevel: requestType(z.object({ level: CallLogLevelSchema }), z.object({})),\n /** Read recorded calls from the call-log files, newest first. */\n queryCalls: requestType(\n z.object({ filter: CallFilterSchema.optional(), limit: z.number().int().positive().max(5_000).optional() }),\n z.object({ calls: z.array(CallRecordSchema), truncated: z.boolean() }),\n ),\n /** Streams matching records as they are written, until cancelled. */\n watchCalls: requestType(z.object({ filter: CallFilterSchema.optional() }), z.object({}))\n .withStream({ server: CallRecordSchema }),\n /** Stop all services and exit. Intentional: autostart managers do not restart it. */\n shutdown: requestType(z.object({}), z.object({})),\n },\n);\n","import { createHash, randomUUID } from 'node:crypto';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\n\n/** Overrides every hub location with one directory (tests, portable installs). */\nexport const LINKRPC_HUB_HOME_VAR = 'LINKRPC_HUB_HOME';\n\n/** Unix domain socket paths longer than this fail to bind on macOS. */\nconst MAX_UNIX_SOCKET_PATH = 103;\n\n/**\n * Where one per-user hub keeps its configuration, state, and local sockets.\n * All daemon, CLI, and desktop processes of a user resolve the same home.\n */\nexport class HubHome {\n /**\n * The per-user default:\n * - Windows: `%LOCALAPPDATA%\\linkrpc\\hub`\n * - macOS: `~/Library/Application Support/linkrpc/hub`\n * - Linux: `$XDG_CONFIG_HOME/linkrpc/hub` (config), `$XDG_STATE_HOME/linkrpc/hub`\n * (state), `$XDG_RUNTIME_DIR/linkrpc-hub` (sockets)\n *\n * `LINKRPC_HUB_HOME` places everything under one directory instead.\n */\n public static resolve(\n env: NodeJS.ProcessEnv = process.env,\n platform: NodeJS.Platform = process.platform,\n homedir: string = os.homedir(),\n ): HubHome {\n const p = platform === 'win32' ? path.win32 : path.posix;\n const override = env[LINKRPC_HUB_HOME_VAR];\n if (override) return HubHome.at(override, platform);\n if (platform === 'win32') {\n const base = p.join(env.LOCALAPPDATA ?? p.join(homedir, 'AppData', 'Local'), 'linkrpc', 'hub');\n return new HubHome(p.join(base, 'config.json'), base, p.join(base, 'run'), platform, undefined);\n }\n if (platform === 'darwin') {\n const base = p.join(homedir, 'Library', 'Application Support', 'linkrpc', 'hub');\n return new HubHome(p.join(base, 'config.json'), base, p.join(base, 'run'), platform, undefined);\n }\n const configDir = p.join(env.XDG_CONFIG_HOME || p.join(homedir, '.config'), 'linkrpc', 'hub');\n const stateDir = p.join(env.XDG_STATE_HOME || p.join(homedir, '.local', 'state'), 'linkrpc', 'hub');\n const runtimeDir = env.XDG_RUNTIME_DIR ? p.join(env.XDG_RUNTIME_DIR, 'linkrpc-hub') : p.join(stateDir, 'run');\n return new HubHome(p.join(configDir, 'config.json'), stateDir, runtimeDir, platform, undefined);\n }\n\n /** A custom home with config, state, and sockets all below `dir`. */\n public static at(dir: string, platform: NodeJS.Platform = process.platform): HubHome {\n const p = platform === 'win32' ? path.win32 : path.posix;\n return new HubHome(p.join(dir, 'config.json'), dir, p.join(dir, 'run'), platform, dir);\n }\n\n private constructor(\n public readonly configFile: string,\n public readonly stateDir: string,\n /** Private (0700) directory for Unix sockets. Unused on Windows. */\n public readonly runtimeDir: string,\n private readonly _platform: NodeJS.Platform,\n /** The directory of a custom home (`--home`, `LINKRPC_HUB_HOME`); `undefined` for the default. */\n public readonly customDir: string | undefined,\n ) { }\n\n private get _path(): path.PlatformPath {\n return this._platform === 'win32' ? path.win32 : path.posix;\n }\n\n public get configDir(): string {\n return this._path.dirname(this.configFile);\n }\n\n /** JSON Schema written next to the config for editor validation. */\n public get configSchemaFile(): string {\n return this._path.join(this.configDir, 'config.schema.json');\n }\n\n /** Endpoint + token for applications; present while the daemon runs. */\n public get discoveryFile(): string {\n return this._path.join(this.stateDir, 'hub.json');\n }\n\n /** Endpoint + token for the management API; present while the daemon runs. */\n public get managementFile(): string {\n return this._path.join(this.stateDir, 'management.json');\n }\n\n public get logFile(): string {\n return this._path.join(this.stateDir, 'daemon.log');\n }\n\n /** NDJSON call-log files (`callLog` in the config). */\n public get callLogDir(): string {\n return this._path.join(this.stateDir, 'calls');\n }\n\n /** Persistent managed identities of services. */\n public get identityDir(): string {\n return this._path.join(this.stateDir, 'identities');\n }\n\n /** Distinguishes OS registrations (autostart entries) of custom homes from the default one. */\n public get instanceName(): string {\n if (this.customDir === undefined) return 'linkrpc-hub';\n return `linkrpc-hub-${createHash('sha256').update(this.customDir).digest('hex').slice(0, 8)}`;\n }\n\n /**\n * The fixed application endpoint unless `localEndpoint.path` overrides it.\n * Windows pipes share one machine-wide namespace, so the name includes the\n * user; Unix sockets live in the user's private runtime directory.\n */\n public get defaultAppEndpoint(): string {\n if (this._platform === 'win32') {\n const user = os.userInfo().username.replace(/[^A-Za-z0-9._-]/g, '_');\n return `\\\\\\\\.\\\\pipe\\\\${this.instanceName}-${user}`;\n }\n return this._unixSocketPath('hub.sock');\n }\n\n /**\n * The single-instance lock endpoint. Fixed per home so that a second daemon\n * for the same home fails to bind it.\n */\n public get lockEndpoint(): string {\n if (this._platform === 'win32') {\n const key = createHash('sha256').update(this.stateDir.toLowerCase()).digest('hex').slice(0, 24);\n return `\\\\\\\\.\\\\pipe\\\\linkrpc-hub-lock-${key}`;\n }\n return this._unixSocketPath('daemon.lock');\n }\n\n /**\n * A fresh endpoint for a daemon listener. Windows pipe names are random\n * (pipes are a global namespace); Unix sockets live in the private runtime dir.\n */\n public allocEndpoint(name: string): string {\n if (this._platform === 'win32') return `\\\\\\\\.\\\\pipe\\\\linkrpc-hub-${name}-${randomUUID()}`;\n return this._unixSocketPath(`${name}.sock`);\n }\n\n private _unixSocketPath(name: string): string {\n const socketPath = this._path.join(this.runtimeDir, name);\n if (Buffer.byteLength(socketPath) > MAX_UNIX_SOCKET_PATH) {\n throw new Error(`socket path is too long for this platform: ${socketPath}`);\n }\n return socketPath;\n }\n}\n","import { defineInterface, requestType } from '@hediet/linkrpc';\nimport {\n ConsoleTemplate,\n consoleAttachParamsSchema,\n consoleClientMessageSchema,\n consoleExitSchema,\n consoleModeSchema,\n consoleServerMessageSchema,\n} from '@hediet/linkrpc-infra/console';\nimport { z } from 'zod';\nimport { ServiceStatusSchema } from './managementInterface';\n\nexport const endpointAddress = z.object({\n namespace: z.string().min(1),\n id: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).default('main'),\n});\nexport const processSource = z.object({\n kind: z.literal('process'),\n command: z.array(z.string().min(1)).min(1),\n cwd: z.string().optional(),\n env: z.record(z.string(), z.string()).default({}),\n rpc: z.boolean().default(true),\n /** Run in a pseudoterminal: stdout and stderr merge, and attachments can resize it. */\n tty: z.boolean().default(false),\n readiness: z.enum(['connected', 'spawned']).default('connected'),\n});\nexport const endpointDefinition = endpointAddress.extend({\n source: z.discriminatedUnion('kind', [\n processSource,\n z.object({ kind: z.literal('connection'), endpoint: z.string().min(1) }),\n ]),\n persistent: z.boolean().default(false),\n restart: z.enum(['never', 'on-failure', 'always']).default('never'),\n});\nexport type EndpointDefinition = z.infer<typeof endpointDefinition>;\nexport type EndpointAddress = z.infer<typeof endpointAddress>;\nexport const endpointStatus = endpointAddress.extend({\n instanceId: z.string(),\n serviceId: z.string(),\n persistent: z.boolean(),\n restart: endpointDefinition.shape.restart,\n desired: z.boolean(),\n /** Owned by a `run` call that stops and removes it when the call ends. */\n owned: z.boolean(),\n sourceKind: z.enum(['process', 'connection']),\n rpc: z.boolean(),\n /** Process endpoints have a console, reachable through the `consoles` template instance. */\n console: z.object({ mode: consoleModeSchema }).optional(),\n runtime: ServiceStatusSchema,\n});\nexport type EndpointStatus = z.infer<typeof endpointStatus>;\n\nconst replace = z.boolean().optional()\n .describe('Stop and remove an existing endpoint with the same address first, including persistent and owned ones.');\nexport const runParams = z.object({\n definition: endpointDefinition.extend({ source: processSource }),\n /** The call owns the endpoint: ending it (cancellation, disconnect, or completion) stops and removes it. */\n owner: z.boolean().optional(),\n replace,\n console: consoleAttachParamsSchema,\n});\nexport type RunParams = z.infer<typeof runParams>;\nexport const runEvent = z.union([\n consoleServerMessageSchema,\n z.object({ t: z.literal('status'), status: endpointStatus }),\n]);\nexport type RunEvent = z.infer<typeof runEvent>;\nexport const watchEvent = z.discriminatedUnion('t', [\n z.object({ t: z.literal('status'), status: endpointStatus }),\n z.object({ t: z.literal('removed') }),\n]);\nexport type WatchEvent = z.infer<typeof watchEvent>;\n\n/** Console template parameters: the endpoint whose process console to use. */\nexport const consoleAddress = z.object({ namespace: z.string().min(1), id: z.string().min(1) });\n\nexport const managedEndpointsInterface = defineInterface({\n id: 'linkrpc.managedEndpoints',\n description: 'Manage named processes and connections on this execution host. Starting endpoints executes with this host user\\'s privileges. '\n + 'Process consoles are served by the `consoles` instance of the `linkrpc.console.v1` template, with the endpoint address as params.',\n}, {\n consoles: ConsoleTemplate({ params: consoleAddress }).mapMembers({ info: 'consoleInfo', attach: 'attachConsole' }),\n info: requestType(z.object({}), z.object({ hostname: z.string(), platform: z.string(), cwd: z.string(), servicePrefix: z.string() })),\n list: requestType(z.object({ namespace: z.string().optional() }), z.array(endpointStatus)),\n create: requestType(endpointDefinition.extend({ replace }), endpointStatus),\n run: requestType(runParams, z.object({ exit: z.nullable(consoleExitSchema) }), {\n description: 'Create a process endpoint and attach to its console in one call. The stream carries the '\n + '`linkrpc.console` attach protocol plus `status` events. Without `owner`, cancelling detaches.',\n }).withStream({ client: consoleClientMessageSchema, server: runEvent }),\n watch: requestType(endpointAddress, z.object({})).withStream({ server: watchEvent }),\n start: requestType(endpointAddress, endpointStatus),\n stop: requestType(endpointAddress, z.object({})),\n remove: requestType(endpointAddress, z.object({})),\n configure: requestType(endpointAddress.extend({\n persistent: z.boolean().optional(),\n restart: z.enum(['never', 'on-failure', 'always']).optional(),\n }), endpointStatus),\n});\n","/**\n * Client entry point: connect applications and management tools to the\n * user's local hub daemon. Free of hub-server dependencies.\n */\nimport type { InterfaceClient } from '@hediet/linkrpc';\nimport { connectToHub, LINKRPC_ENDPOINT_VAR, type ConnectToHubOptions, type HubClientHandle } from '@hediet/linkrpc/node';\nimport { readEndpointDiscovery } from './discovery';\nimport { hubDaemonManagementInterface } from './managementInterface';\nimport { HubHome } from './paths';\n\nexport * from './managementInterface';\nexport * from './callLog/callRecord';\nexport * from './callLog/callQuery';\nexport * from './endpointInterface';\nexport { type EndpointDiscovery, readEndpointDiscovery } from './discovery';\nexport { HubHome, LINKRPC_HUB_HOME_VAR } from './paths';\n\nexport interface ConnectToLocalHubOptions extends ConnectToHubOptions {\n readonly home?: HubHome;\n}\n\n/**\n * Connect to the local hub. Resolution order: explicit `endpoint`,\n * `LINKRPC_ENDPOINT` (set for services the daemon manages), then the running\n * daemon's discovery file.\n */\nexport async function connectToLocalHub(options: ConnectToLocalHubOptions = {}): Promise<HubClientHandle> {\n const { home, ...connectOptions } = options;\n if (connectOptions.endpoint !== undefined || process.env[LINKRPC_ENDPOINT_VAR]) {\n return connectToHub(connectOptions);\n }\n const resolvedHome = home ?? HubHome.resolve();\n const discovery = readEndpointDiscovery(resolvedHome.discoveryFile);\n if (!discovery) {\n throw new Error(`The local LinkRPC hub is not running (no ${resolvedHome.discoveryFile}).`);\n }\n return connectToHub({ ...connectOptions, endpoint: discovery.endpoint, token: discovery.token ?? '' });\n}\n\nexport interface HubManagementConnection {\n readonly management: InterfaceClient<typeof hubDaemonManagementInterface>;\n onClose(listener: () => void): { dispose(): void; };\n close(): void;\n}\n\n/** Connect to the daemon's management API. Rejects when the daemon is not running. */\nexport async function connectToHubManagement(home: HubHome = HubHome.resolve()): Promise<HubManagementConnection> {\n const discovery = readEndpointDiscovery(home.managementFile);\n if (!discovery) {\n throw new Error(`The local LinkRPC hub is not running (no ${home.managementFile}).`);\n }\n const handle = await connectToHub({ endpoint: discovery.endpoint, token: discovery.token ?? '' });\n return {\n management: handle.connection.get(hubDaemonManagementInterface),\n onClose: listener => handle.onClose(listener),\n close: () => handle.close(),\n };\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'use strict';\n/**\n * Creates a JSON scanner on the given text.\n * If ignoreTrivia is set, whitespaces or comments are ignored.\n */\nexport function createScanner(text, ignoreTrivia = false) {\n const len = text.length;\n let pos = 0, value = '', tokenOffset = 0, token = 16 /* SyntaxKind.Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* ScanError.None */;\n function scanHexDigits(count, exact) {\n let digits = 0;\n let value = 0;\n while (digits < count || !exact) {\n let ch = text.charCodeAt(pos);\n if (ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */) {\n value = value * 16 + ch - 48 /* CharacterCodes._0 */;\n }\n else if (ch >= 65 /* CharacterCodes.A */ && ch <= 70 /* CharacterCodes.F */) {\n value = value * 16 + ch - 65 /* CharacterCodes.A */ + 10;\n }\n else if (ch >= 97 /* CharacterCodes.a */ && ch <= 102 /* CharacterCodes.f */) {\n value = value * 16 + ch - 97 /* CharacterCodes.a */ + 10;\n }\n else {\n break;\n }\n pos++;\n digits++;\n }\n if (digits < count) {\n value = -1;\n }\n return value;\n }\n function setPosition(newPosition) {\n pos = newPosition;\n value = '';\n tokenOffset = 0;\n token = 16 /* SyntaxKind.Unknown */;\n scanError = 0 /* ScanError.None */;\n }\n function scanNumber() {\n let start = pos;\n if (text.charCodeAt(pos) === 48 /* CharacterCodes._0 */) {\n pos++;\n }\n else {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n }\n if (pos < text.length && text.charCodeAt(pos) === 46 /* CharacterCodes.dot */) {\n pos++;\n if (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n }\n else {\n scanError = 3 /* ScanError.UnexpectedEndOfNumber */;\n return text.substring(start, pos);\n }\n }\n let end = pos;\n if (pos < text.length && (text.charCodeAt(pos) === 69 /* CharacterCodes.E */ || text.charCodeAt(pos) === 101 /* CharacterCodes.e */)) {\n pos++;\n if (pos < text.length && text.charCodeAt(pos) === 43 /* CharacterCodes.plus */ || text.charCodeAt(pos) === 45 /* CharacterCodes.minus */) {\n pos++;\n }\n if (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n end = pos;\n }\n else {\n scanError = 3 /* ScanError.UnexpectedEndOfNumber */;\n }\n }\n return text.substring(start, end);\n }\n function scanString() {\n let result = '', start = pos;\n while (true) {\n if (pos >= len) {\n result += text.substring(start, pos);\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n const ch = text.charCodeAt(pos);\n if (ch === 34 /* CharacterCodes.doubleQuote */) {\n result += text.substring(start, pos);\n pos++;\n break;\n }\n if (ch === 92 /* CharacterCodes.backslash */) {\n result += text.substring(start, pos);\n pos++;\n if (pos >= len) {\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n const ch2 = text.charCodeAt(pos++);\n switch (ch2) {\n case 34 /* CharacterCodes.doubleQuote */:\n result += '\\\"';\n break;\n case 92 /* CharacterCodes.backslash */:\n result += '\\\\';\n break;\n case 47 /* CharacterCodes.slash */:\n result += '/';\n break;\n case 98 /* CharacterCodes.b */:\n result += '\\b';\n break;\n case 102 /* CharacterCodes.f */:\n result += '\\f';\n break;\n case 110 /* CharacterCodes.n */:\n result += '\\n';\n break;\n case 114 /* CharacterCodes.r */:\n result += '\\r';\n break;\n case 116 /* CharacterCodes.t */:\n result += '\\t';\n break;\n case 117 /* CharacterCodes.u */:\n const ch3 = scanHexDigits(4, true);\n if (ch3 >= 0) {\n result += String.fromCharCode(ch3);\n }\n else {\n scanError = 4 /* ScanError.InvalidUnicode */;\n }\n break;\n default:\n scanError = 5 /* ScanError.InvalidEscapeCharacter */;\n }\n start = pos;\n continue;\n }\n if (ch >= 0 && ch <= 0x1f) {\n if (isLineBreak(ch)) {\n result += text.substring(start, pos);\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n else {\n scanError = 6 /* ScanError.InvalidCharacter */;\n // mark as error but continue with string\n }\n }\n pos++;\n }\n return result;\n }\n function scanNext() {\n value = '';\n scanError = 0 /* ScanError.None */;\n tokenOffset = pos;\n lineStartOffset = lineNumber;\n prevTokenLineStartOffset = tokenLineStartOffset;\n if (pos >= len) {\n // at the end\n tokenOffset = len;\n return token = 17 /* SyntaxKind.EOF */;\n }\n let code = text.charCodeAt(pos);\n // trivia: whitespace\n if (isWhiteSpace(code)) {\n do {\n pos++;\n value += String.fromCharCode(code);\n code = text.charCodeAt(pos);\n } while (isWhiteSpace(code));\n return token = 15 /* SyntaxKind.Trivia */;\n }\n // trivia: newlines\n if (isLineBreak(code)) {\n pos++;\n value += String.fromCharCode(code);\n if (code === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) {\n pos++;\n value += '\\n';\n }\n lineNumber++;\n tokenLineStartOffset = pos;\n return token = 14 /* SyntaxKind.LineBreakTrivia */;\n }\n switch (code) {\n // tokens: []{}:,\n case 123 /* CharacterCodes.openBrace */:\n pos++;\n return token = 1 /* SyntaxKind.OpenBraceToken */;\n case 125 /* CharacterCodes.closeBrace */:\n pos++;\n return token = 2 /* SyntaxKind.CloseBraceToken */;\n case 91 /* CharacterCodes.openBracket */:\n pos++;\n return token = 3 /* SyntaxKind.OpenBracketToken */;\n case 93 /* CharacterCodes.closeBracket */:\n pos++;\n return token = 4 /* SyntaxKind.CloseBracketToken */;\n case 58 /* CharacterCodes.colon */:\n pos++;\n return token = 6 /* SyntaxKind.ColonToken */;\n case 44 /* CharacterCodes.comma */:\n pos++;\n return token = 5 /* SyntaxKind.CommaToken */;\n // strings\n case 34 /* CharacterCodes.doubleQuote */:\n pos++;\n value = scanString();\n return token = 10 /* SyntaxKind.StringLiteral */;\n // comments\n case 47 /* CharacterCodes.slash */:\n const start = pos - 1;\n // Single-line comment\n if (text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) {\n pos += 2;\n while (pos < len) {\n if (isLineBreak(text.charCodeAt(pos))) {\n break;\n }\n pos++;\n }\n value = text.substring(start, pos);\n return token = 12 /* SyntaxKind.LineCommentTrivia */;\n }\n // Multi-line comment\n if (text.charCodeAt(pos + 1) === 42 /* CharacterCodes.asterisk */) {\n pos += 2;\n const safeLength = len - 1; // For lookahead.\n let commentClosed = false;\n while (pos < safeLength) {\n const ch = text.charCodeAt(pos);\n if (ch === 42 /* CharacterCodes.asterisk */ && text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) {\n pos += 2;\n commentClosed = true;\n break;\n }\n pos++;\n if (isLineBreak(ch)) {\n if (ch === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) {\n pos++;\n }\n lineNumber++;\n tokenLineStartOffset = pos;\n }\n }\n if (!commentClosed) {\n pos++;\n scanError = 1 /* ScanError.UnexpectedEndOfComment */;\n }\n value = text.substring(start, pos);\n return token = 13 /* SyntaxKind.BlockCommentTrivia */;\n }\n // just a single slash\n value += String.fromCharCode(code);\n pos++;\n return token = 16 /* SyntaxKind.Unknown */;\n // numbers\n case 45 /* CharacterCodes.minus */:\n value += String.fromCharCode(code);\n pos++;\n if (pos === len || !isDigit(text.charCodeAt(pos))) {\n return token = 16 /* SyntaxKind.Unknown */;\n }\n // found a minus, followed by a number so\n // we fall through to proceed with scanning\n // numbers\n case 48 /* CharacterCodes._0 */:\n case 49 /* CharacterCodes._1 */:\n case 50 /* CharacterCodes._2 */:\n case 51 /* CharacterCodes._3 */:\n case 52 /* CharacterCodes._4 */:\n case 53 /* CharacterCodes._5 */:\n case 54 /* CharacterCodes._6 */:\n case 55 /* CharacterCodes._7 */:\n case 56 /* CharacterCodes._8 */:\n case 57 /* CharacterCodes._9 */:\n value += scanNumber();\n return token = 11 /* SyntaxKind.NumericLiteral */;\n // literals and unknown symbols\n default:\n // is a literal? Read the full word.\n while (pos < len && isUnknownContentCharacter(code)) {\n pos++;\n code = text.charCodeAt(pos);\n }\n if (tokenOffset !== pos) {\n value = text.substring(tokenOffset, pos);\n // keywords: true, false, null\n switch (value) {\n case 'true': return token = 8 /* SyntaxKind.TrueKeyword */;\n case 'false': return token = 9 /* SyntaxKind.FalseKeyword */;\n case 'null': return token = 7 /* SyntaxKind.NullKeyword */;\n }\n return token = 16 /* SyntaxKind.Unknown */;\n }\n // some\n value += String.fromCharCode(code);\n pos++;\n return token = 16 /* SyntaxKind.Unknown */;\n }\n }\n function isUnknownContentCharacter(code) {\n if (isWhiteSpace(code) || isLineBreak(code)) {\n return false;\n }\n switch (code) {\n case 125 /* CharacterCodes.closeBrace */:\n case 93 /* CharacterCodes.closeBracket */:\n case 123 /* CharacterCodes.openBrace */:\n case 91 /* CharacterCodes.openBracket */:\n case 34 /* CharacterCodes.doubleQuote */:\n case 58 /* CharacterCodes.colon */:\n case 44 /* CharacterCodes.comma */:\n case 47 /* CharacterCodes.slash */:\n return false;\n }\n return true;\n }\n function scanNextNonTrivia() {\n let result;\n do {\n result = scanNext();\n } while (result >= 12 /* SyntaxKind.LineCommentTrivia */ && result <= 15 /* SyntaxKind.Trivia */);\n return result;\n }\n return {\n setPosition: setPosition,\n getPosition: () => pos,\n scan: ignoreTrivia ? scanNextNonTrivia : scanNext,\n getToken: () => token,\n getTokenValue: () => value,\n getTokenOffset: () => tokenOffset,\n getTokenLength: () => pos - tokenOffset,\n getTokenStartLine: () => lineStartOffset,\n getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset,\n getTokenError: () => scanError,\n };\n}\nfunction isWhiteSpace(ch) {\n return ch === 32 /* CharacterCodes.space */ || ch === 9 /* CharacterCodes.tab */;\n}\nfunction isLineBreak(ch) {\n return ch === 10 /* CharacterCodes.lineFeed */ || ch === 13 /* CharacterCodes.carriageReturn */;\n}\nfunction isDigit(ch) {\n return ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */;\n}\nvar CharacterCodes;\n(function (CharacterCodes) {\n CharacterCodes[CharacterCodes[\"lineFeed\"] = 10] = \"lineFeed\";\n CharacterCodes[CharacterCodes[\"carriageReturn\"] = 13] = \"carriageReturn\";\n CharacterCodes[CharacterCodes[\"space\"] = 32] = \"space\";\n CharacterCodes[CharacterCodes[\"_0\"] = 48] = \"_0\";\n CharacterCodes[CharacterCodes[\"_1\"] = 49] = \"_1\";\n CharacterCodes[CharacterCodes[\"_2\"] = 50] = \"_2\";\n CharacterCodes[CharacterCodes[\"_3\"] = 51] = \"_3\";\n CharacterCodes[CharacterCodes[\"_4\"] = 52] = \"_4\";\n CharacterCodes[CharacterCodes[\"_5\"] = 53] = \"_5\";\n CharacterCodes[CharacterCodes[\"_6\"] = 54] = \"_6\";\n CharacterCodes[CharacterCodes[\"_7\"] = 55] = \"_7\";\n CharacterCodes[CharacterCodes[\"_8\"] = 56] = \"_8\";\n CharacterCodes[CharacterCodes[\"_9\"] = 57] = \"_9\";\n CharacterCodes[CharacterCodes[\"a\"] = 97] = \"a\";\n CharacterCodes[CharacterCodes[\"b\"] = 98] = \"b\";\n CharacterCodes[CharacterCodes[\"c\"] = 99] = \"c\";\n CharacterCodes[CharacterCodes[\"d\"] = 100] = \"d\";\n CharacterCodes[CharacterCodes[\"e\"] = 101] = \"e\";\n CharacterCodes[CharacterCodes[\"f\"] = 102] = \"f\";\n CharacterCodes[CharacterCodes[\"g\"] = 103] = \"g\";\n CharacterCodes[CharacterCodes[\"h\"] = 104] = \"h\";\n CharacterCodes[CharacterCodes[\"i\"] = 105] = \"i\";\n CharacterCodes[CharacterCodes[\"j\"] = 106] = \"j\";\n CharacterCodes[CharacterCodes[\"k\"] = 107] = \"k\";\n CharacterCodes[CharacterCodes[\"l\"] = 108] = \"l\";\n CharacterCodes[CharacterCodes[\"m\"] = 109] = \"m\";\n CharacterCodes[CharacterCodes[\"n\"] = 110] = \"n\";\n CharacterCodes[CharacterCodes[\"o\"] = 111] = \"o\";\n CharacterCodes[CharacterCodes[\"p\"] = 112] = \"p\";\n CharacterCodes[CharacterCodes[\"q\"] = 113] = \"q\";\n CharacterCodes[CharacterCodes[\"r\"] = 114] = \"r\";\n CharacterCodes[CharacterCodes[\"s\"] = 115] = \"s\";\n CharacterCodes[CharacterCodes[\"t\"] = 116] = \"t\";\n CharacterCodes[CharacterCodes[\"u\"] = 117] = \"u\";\n CharacterCodes[CharacterCodes[\"v\"] = 118] = \"v\";\n CharacterCodes[CharacterCodes[\"w\"] = 119] = \"w\";\n CharacterCodes[CharacterCodes[\"x\"] = 120] = \"x\";\n CharacterCodes[CharacterCodes[\"y\"] = 121] = \"y\";\n CharacterCodes[CharacterCodes[\"z\"] = 122] = \"z\";\n CharacterCodes[CharacterCodes[\"A\"] = 65] = \"A\";\n CharacterCodes[CharacterCodes[\"B\"] = 66] = \"B\";\n CharacterCodes[CharacterCodes[\"C\"] = 67] = \"C\";\n CharacterCodes[CharacterCodes[\"D\"] = 68] = \"D\";\n CharacterCodes[CharacterCodes[\"E\"] = 69] = \"E\";\n CharacterCodes[CharacterCodes[\"F\"] = 70] = \"F\";\n CharacterCodes[CharacterCodes[\"G\"] = 71] = \"G\";\n CharacterCodes[CharacterCodes[\"H\"] = 72] = \"H\";\n CharacterCodes[CharacterCodes[\"I\"] = 73] = \"I\";\n CharacterCodes[CharacterCodes[\"J\"] = 74] = \"J\";\n CharacterCodes[CharacterCodes[\"K\"] = 75] = \"K\";\n CharacterCodes[CharacterCodes[\"L\"] = 76] = \"L\";\n CharacterCodes[CharacterCodes[\"M\"] = 77] = \"M\";\n CharacterCodes[CharacterCodes[\"N\"] = 78] = \"N\";\n CharacterCodes[CharacterCodes[\"O\"] = 79] = \"O\";\n CharacterCodes[CharacterCodes[\"P\"] = 80] = \"P\";\n CharacterCodes[CharacterCodes[\"Q\"] = 81] = \"Q\";\n CharacterCodes[CharacterCodes[\"R\"] = 82] = \"R\";\n CharacterCodes[CharacterCodes[\"S\"] = 83] = \"S\";\n CharacterCodes[CharacterCodes[\"T\"] = 84] = \"T\";\n CharacterCodes[CharacterCodes[\"U\"] = 85] = \"U\";\n CharacterCodes[CharacterCodes[\"V\"] = 86] = \"V\";\n CharacterCodes[CharacterCodes[\"W\"] = 87] = \"W\";\n CharacterCodes[CharacterCodes[\"X\"] = 88] = \"X\";\n CharacterCodes[CharacterCodes[\"Y\"] = 89] = \"Y\";\n CharacterCodes[CharacterCodes[\"Z\"] = 90] = \"Z\";\n CharacterCodes[CharacterCodes[\"asterisk\"] = 42] = \"asterisk\";\n CharacterCodes[CharacterCodes[\"backslash\"] = 92] = \"backslash\";\n CharacterCodes[CharacterCodes[\"closeBrace\"] = 125] = \"closeBrace\";\n CharacterCodes[CharacterCodes[\"closeBracket\"] = 93] = \"closeBracket\";\n CharacterCodes[CharacterCodes[\"colon\"] = 58] = \"colon\";\n CharacterCodes[CharacterCodes[\"comma\"] = 44] = \"comma\";\n CharacterCodes[CharacterCodes[\"dot\"] = 46] = \"dot\";\n CharacterCodes[CharacterCodes[\"doubleQuote\"] = 34] = \"doubleQuote\";\n CharacterCodes[CharacterCodes[\"minus\"] = 45] = \"minus\";\n CharacterCodes[CharacterCodes[\"openBrace\"] = 123] = \"openBrace\";\n CharacterCodes[CharacterCodes[\"openBracket\"] = 91] = \"openBracket\";\n CharacterCodes[CharacterCodes[\"plus\"] = 43] = \"plus\";\n CharacterCodes[CharacterCodes[\"slash\"] = 47] = \"slash\";\n CharacterCodes[CharacterCodes[\"formFeed\"] = 12] = \"formFeed\";\n CharacterCodes[CharacterCodes[\"tab\"] = 9] = \"tab\";\n})(CharacterCodes || (CharacterCodes = {}));\n","export const cachedSpaces = new Array(20).fill(0).map((_, index) => {\n return ' '.repeat(index);\n});\nconst maxCachedValues = 200;\nexport const cachedBreakLinesWithSpaces = {\n ' ': {\n '\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\n' + ' '.repeat(index);\n }),\n '\\r': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r' + ' '.repeat(index);\n }),\n '\\r\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r\\n' + ' '.repeat(index);\n }),\n },\n '\\t': {\n '\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\n' + '\\t'.repeat(index);\n }),\n '\\r': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r' + '\\t'.repeat(index);\n }),\n '\\r\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r\\n' + '\\t'.repeat(index);\n }),\n }\n};\nexport const supportedEols = ['\\n', '\\r', '\\r\\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'use strict';\nimport { createScanner } from './scanner';\nimport { cachedSpaces, cachedBreakLinesWithSpaces, supportedEols } from './string-intern';\nexport function format(documentText, range, options) {\n let initialIndentLevel;\n let formatText;\n let formatTextStart;\n let rangeStart;\n let rangeEnd;\n if (range) {\n rangeStart = range.offset;\n rangeEnd = rangeStart + range.length;\n formatTextStart = rangeStart;\n while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {\n formatTextStart--;\n }\n let endOffset = rangeEnd;\n while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {\n endOffset++;\n }\n formatText = documentText.substring(formatTextStart, endOffset);\n initialIndentLevel = computeIndentLevel(formatText, options);\n }\n else {\n formatText = documentText;\n initialIndentLevel = 0;\n formatTextStart = 0;\n rangeStart = 0;\n rangeEnd = documentText.length;\n }\n const eol = getEOL(options, documentText);\n const eolFastPathSupported = supportedEols.includes(eol);\n let numberLineBreaks = 0;\n let indentLevel = 0;\n let indentValue;\n if (options.insertSpaces) {\n indentValue = cachedSpaces[options.tabSize || 4] ?? repeat(cachedSpaces[1], options.tabSize || 4);\n }\n else {\n indentValue = '\\t';\n }\n const indentType = indentValue === '\\t' ? '\\t' : ' ';\n let scanner = createScanner(formatText, false);\n let hasError = false;\n function newLinesAndIndent() {\n if (numberLineBreaks > 1) {\n return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel);\n }\n const amountOfSpaces = indentValue.length * (initialIndentLevel + indentLevel);\n if (!eolFastPathSupported || amountOfSpaces > cachedBreakLinesWithSpaces[indentType][eol].length) {\n return eol + repeat(indentValue, initialIndentLevel + indentLevel);\n }\n if (amountOfSpaces <= 0) {\n return eol;\n }\n return cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces];\n }\n function scanNext() {\n let token = scanner.scan();\n numberLineBreaks = 0;\n while (token === 15 /* SyntaxKind.Trivia */ || token === 14 /* SyntaxKind.LineBreakTrivia */) {\n if (token === 14 /* SyntaxKind.LineBreakTrivia */ && options.keepLines) {\n numberLineBreaks += 1;\n }\n else if (token === 14 /* SyntaxKind.LineBreakTrivia */) {\n numberLineBreaks = 1;\n }\n token = scanner.scan();\n }\n hasError = token === 16 /* SyntaxKind.Unknown */ || scanner.getTokenError() !== 0 /* ScanError.None */;\n return token;\n }\n const editOperations = [];\n function addEdit(text, startOffset, endOffset) {\n if (!hasError && (!range || (startOffset < rangeEnd && endOffset > rangeStart)) && documentText.substring(startOffset, endOffset) !== text) {\n editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });\n }\n }\n let firstToken = scanNext();\n if (options.keepLines && numberLineBreaks > 0) {\n addEdit(repeat(eol, numberLineBreaks), 0, 0);\n }\n if (firstToken !== 17 /* SyntaxKind.EOF */) {\n let firstTokenStart = scanner.getTokenOffset() + formatTextStart;\n let initialIndent = (indentValue.length * initialIndentLevel < 20) && options.insertSpaces\n ? cachedSpaces[indentValue.length * initialIndentLevel]\n : repeat(indentValue, initialIndentLevel);\n addEdit(initialIndent, formatTextStart, firstTokenStart);\n }\n while (firstToken !== 17 /* SyntaxKind.EOF */) {\n let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;\n let secondToken = scanNext();\n let replaceContent = '';\n let needsLineBreak = false;\n while (numberLineBreaks === 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) {\n let commentTokenStart = scanner.getTokenOffset() + formatTextStart;\n addEdit(cachedSpaces[1], firstTokenEnd, commentTokenStart);\n firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;\n needsLineBreak = secondToken === 12 /* SyntaxKind.LineCommentTrivia */;\n replaceContent = needsLineBreak ? newLinesAndIndent() : '';\n secondToken = scanNext();\n }\n if (secondToken === 2 /* SyntaxKind.CloseBraceToken */) {\n if (firstToken !== 1 /* SyntaxKind.OpenBraceToken */) {\n indentLevel--;\n }\n ;\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1 /* SyntaxKind.OpenBraceToken */) {\n replaceContent = newLinesAndIndent();\n }\n else if (options.keepLines) {\n replaceContent = cachedSpaces[1];\n }\n }\n else if (secondToken === 4 /* SyntaxKind.CloseBracketToken */) {\n if (firstToken !== 3 /* SyntaxKind.OpenBracketToken */) {\n indentLevel--;\n }\n ;\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3 /* SyntaxKind.OpenBracketToken */) {\n replaceContent = newLinesAndIndent();\n }\n else if (options.keepLines) {\n replaceContent = cachedSpaces[1];\n }\n }\n else {\n switch (firstToken) {\n case 3 /* SyntaxKind.OpenBracketToken */:\n case 1 /* SyntaxKind.OpenBraceToken */:\n indentLevel++;\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {\n replaceContent = newLinesAndIndent();\n }\n else {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 5 /* SyntaxKind.CommaToken */:\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {\n replaceContent = newLinesAndIndent();\n }\n else {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 12 /* SyntaxKind.LineCommentTrivia */:\n replaceContent = newLinesAndIndent();\n break;\n case 13 /* SyntaxKind.BlockCommentTrivia */:\n if (numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else if (!needsLineBreak) {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 6 /* SyntaxKind.ColonToken */:\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else if (!needsLineBreak) {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 10 /* SyntaxKind.StringLiteral */:\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else if (secondToken === 6 /* SyntaxKind.ColonToken */ && !needsLineBreak) {\n replaceContent = '';\n }\n break;\n case 7 /* SyntaxKind.NullKeyword */:\n case 8 /* SyntaxKind.TrueKeyword */:\n case 9 /* SyntaxKind.FalseKeyword */:\n case 11 /* SyntaxKind.NumericLiteral */:\n case 2 /* SyntaxKind.CloseBraceToken */:\n case 4 /* SyntaxKind.CloseBracketToken */:\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else {\n if ((secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */) && !needsLineBreak) {\n replaceContent = cachedSpaces[1];\n }\n else if (secondToken !== 5 /* SyntaxKind.CommaToken */ && secondToken !== 17 /* SyntaxKind.EOF */) {\n hasError = true;\n }\n }\n break;\n case 16 /* SyntaxKind.Unknown */:\n hasError = true;\n break;\n }\n if (numberLineBreaks > 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) {\n replaceContent = newLinesAndIndent();\n }\n }\n if (secondToken === 17 /* SyntaxKind.EOF */) {\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else {\n replaceContent = options.insertFinalNewline ? eol : '';\n }\n }\n const secondTokenStart = scanner.getTokenOffset() + formatTextStart;\n addEdit(replaceContent, firstTokenEnd, secondTokenStart);\n firstToken = secondToken;\n }\n return editOperations;\n}\nfunction repeat(s, count) {\n let result = '';\n for (let i = 0; i < count; i++) {\n result += s;\n }\n return result;\n}\nfunction computeIndentLevel(content, options) {\n let i = 0;\n let nChars = 0;\n const tabSize = options.tabSize || 4;\n while (i < content.length) {\n let ch = content.charAt(i);\n if (ch === cachedSpaces[1]) {\n nChars++;\n }\n else if (ch === '\\t') {\n nChars += tabSize;\n }\n else {\n break;\n }\n i++;\n }\n return Math.floor(nChars / tabSize);\n}\nfunction getEOL(options, text) {\n for (let i = 0; i < text.length; i++) {\n const ch = text.charAt(i);\n if (ch === '\\r') {\n if (i + 1 < text.length && text.charAt(i + 1) === '\\n') {\n return '\\r\\n';\n }\n return '\\r';\n }\n else if (ch === '\\n') {\n return '\\n';\n }\n }\n return (options && options.eol) || '\\n';\n}\nexport function isEOL(text, offset) {\n return '\\r\\n'.indexOf(text.charAt(offset)) !== -1;\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'use strict';\nimport { createScanner } from './scanner';\nvar ParseOptions;\n(function (ParseOptions) {\n ParseOptions.DEFAULT = {\n allowTrailingComma: false\n };\n})(ParseOptions || (ParseOptions = {}));\n/**\n * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.\n */\nexport function getLocation(text, position) {\n const segments = []; // strings or numbers\n const earlyReturnException = new Object();\n let previousNode = undefined;\n const previousNodeInst = {\n value: {},\n offset: 0,\n length: 0,\n type: 'object',\n parent: undefined\n };\n let isAtPropertyKey = false;\n function setPreviousNode(value, offset, length, type) {\n previousNodeInst.value = value;\n previousNodeInst.offset = offset;\n previousNodeInst.length = length;\n previousNodeInst.type = type;\n previousNodeInst.colonOffset = undefined;\n previousNode = previousNodeInst;\n }\n try {\n visit(text, {\n onObjectBegin: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n isAtPropertyKey = position > offset;\n segments.push(''); // push a placeholder (will be replaced)\n },\n onObjectProperty: (name, offset, length) => {\n if (position < offset) {\n throw earlyReturnException;\n }\n setPreviousNode(name, offset, length, 'property');\n segments[segments.length - 1] = name;\n if (position <= offset + length) {\n throw earlyReturnException;\n }\n },\n onObjectEnd: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.pop();\n },\n onArrayBegin: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.push(0);\n },\n onArrayEnd: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.pop();\n },\n onLiteralValue: (value, offset, length) => {\n if (position < offset) {\n throw earlyReturnException;\n }\n setPreviousNode(value, offset, length, getNodeType(value));\n if (position <= offset + length) {\n throw earlyReturnException;\n }\n },\n onSeparator: (sep, offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n if (sep === ':' && previousNode && previousNode.type === 'property') {\n previousNode.colonOffset = offset;\n isAtPropertyKey = false;\n previousNode = undefined;\n }\n else if (sep === ',') {\n const last = segments[segments.length - 1];\n if (typeof last === 'number') {\n segments[segments.length - 1] = last + 1;\n }\n else {\n isAtPropertyKey = true;\n segments[segments.length - 1] = '';\n }\n previousNode = undefined;\n }\n }\n });\n }\n catch (e) {\n if (e !== earlyReturnException) {\n throw e;\n }\n }\n return {\n path: segments,\n previousNode,\n isAtPropertyKey,\n matches: (pattern) => {\n let k = 0;\n for (let i = 0; k < pattern.length && i < segments.length; i++) {\n if (pattern[k] === segments[i] || pattern[k] === '*') {\n k++;\n }\n else if (pattern[k] !== '**') {\n return false;\n }\n }\n return k === pattern.length;\n }\n };\n}\n/**\n * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n * Therefore always check the errors list to find out if the input was valid.\n */\nexport function parse(text, errors = [], options = ParseOptions.DEFAULT) {\n let currentProperty = null;\n let currentParent = [];\n const previousParents = [];\n function onValue(value) {\n if (Array.isArray(currentParent)) {\n currentParent.push(value);\n }\n else if (currentProperty !== null) {\n currentParent[currentProperty] = value;\n }\n }\n const visitor = {\n onObjectBegin: () => {\n const object = {};\n onValue(object);\n previousParents.push(currentParent);\n currentParent = object;\n currentProperty = null;\n },\n onObjectProperty: (name) => {\n currentProperty = name;\n },\n onObjectEnd: () => {\n currentParent = previousParents.pop();\n },\n onArrayBegin: () => {\n const array = [];\n onValue(array);\n previousParents.push(currentParent);\n currentParent = array;\n currentProperty = null;\n },\n onArrayEnd: () => {\n currentParent = previousParents.pop();\n },\n onLiteralValue: onValue,\n onError: (error, offset, length) => {\n errors.push({ error, offset, length });\n }\n };\n visit(text, visitor, options);\n return currentParent[0];\n}\n/**\n * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n */\nexport function parseTree(text, errors = [], options = ParseOptions.DEFAULT) {\n let currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root\n function ensurePropertyComplete(endOffset) {\n if (currentParent.type === 'property') {\n currentParent.length = endOffset - currentParent.offset;\n currentParent = currentParent.parent;\n }\n }\n function onValue(valueNode) {\n currentParent.children.push(valueNode);\n return valueNode;\n }\n const visitor = {\n onObjectBegin: (offset) => {\n currentParent = onValue({ type: 'object', offset, length: -1, parent: currentParent, children: [] });\n },\n onObjectProperty: (name, offset, length) => {\n currentParent = onValue({ type: 'property', offset, length: -1, parent: currentParent, children: [] });\n currentParent.children.push({ type: 'string', value: name, offset, length, parent: currentParent });\n },\n onObjectEnd: (offset, length) => {\n ensurePropertyComplete(offset + length); // in case of a missing value for a property: make sure property is complete\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onArrayBegin: (offset, length) => {\n currentParent = onValue({ type: 'array', offset, length: -1, parent: currentParent, children: [] });\n },\n onArrayEnd: (offset, length) => {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onLiteralValue: (value, offset, length) => {\n onValue({ type: getNodeType(value), offset, length, parent: currentParent, value });\n ensurePropertyComplete(offset + length);\n },\n onSeparator: (sep, offset, length) => {\n if (currentParent.type === 'property') {\n if (sep === ':') {\n currentParent.colonOffset = offset;\n }\n else if (sep === ',') {\n ensurePropertyComplete(offset);\n }\n }\n },\n onError: (error, offset, length) => {\n errors.push({ error, offset, length });\n }\n };\n visit(text, visitor, options);\n const result = currentParent.children[0];\n if (result) {\n delete result.parent;\n }\n return result;\n}\n/**\n * Finds the node at the given path in a JSON DOM.\n */\nexport function findNodeAtLocation(root, path) {\n if (!root) {\n return undefined;\n }\n let node = root;\n for (let segment of path) {\n if (typeof segment === 'string') {\n if (node.type !== 'object' || !Array.isArray(node.children)) {\n return undefined;\n }\n let found = false;\n for (const propertyNode of node.children) {\n if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {\n node = propertyNode.children[1];\n found = true;\n break;\n }\n }\n if (!found) {\n return undefined;\n }\n }\n else {\n const index = segment;\n if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {\n return undefined;\n }\n node = node.children[index];\n }\n }\n return node;\n}\n/**\n * Gets the JSON path of the given JSON DOM node\n */\nexport function getNodePath(node) {\n if (!node.parent || !node.parent.children) {\n return [];\n }\n const path = getNodePath(node.parent);\n if (node.parent.type === 'property') {\n const key = node.parent.children[0].value;\n path.push(key);\n }\n else if (node.parent.type === 'array') {\n const index = node.parent.children.indexOf(node);\n if (index !== -1) {\n path.push(index);\n }\n }\n return path;\n}\n/**\n * Evaluates the JavaScript object of the given JSON DOM node\n */\nexport function getNodeValue(node) {\n switch (node.type) {\n case 'array':\n return node.children.map(getNodeValue);\n case 'object':\n const obj = Object.create(null);\n for (let prop of node.children) {\n const valueNode = prop.children[1];\n if (valueNode) {\n obj[prop.children[0].value] = getNodeValue(valueNode);\n }\n }\n return obj;\n case 'null':\n case 'string':\n case 'number':\n case 'boolean':\n return node.value;\n default:\n return undefined;\n }\n}\nexport function contains(node, offset, includeRightBound = false) {\n return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length));\n}\n/**\n * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.\n */\nexport function findNodeAtOffset(node, offset, includeRightBound = false) {\n if (contains(node, offset, includeRightBound)) {\n const children = node.children;\n if (Array.isArray(children)) {\n for (let i = 0; i < children.length && children[i].offset <= offset; i++) {\n const item = findNodeAtOffset(children[i], offset, includeRightBound);\n if (item) {\n return item;\n }\n }\n }\n return node;\n }\n return undefined;\n}\n/**\n * Parses the given text and invokes the visitor functions for each object, array and literal reached.\n */\nexport function visit(text, visitor, options = ParseOptions.DEFAULT) {\n const _scanner = createScanner(text, false);\n // Important: Only pass copies of this to visitor functions to prevent accidental modification, and\n // to not affect visitor functions which stored a reference to a previous JSONPath\n const _jsonPath = [];\n // Depth of onXXXBegin() callbacks suppressed. onXXXEnd() decrements this if it isn't 0 already.\n // Callbacks are only called when this value is 0.\n let suppressedCallbacks = 0;\n function toNoArgVisit(visitFunction) {\n return visitFunction ? () => suppressedCallbacks === 0 && visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;\n }\n function toOneArgVisit(visitFunction) {\n return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;\n }\n function toOneArgVisitWithPath(visitFunction) {\n return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;\n }\n function toBeginVisit(visitFunction) {\n return visitFunction ?\n () => {\n if (suppressedCallbacks > 0) {\n suppressedCallbacks++;\n }\n else {\n let cbReturn = visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice());\n if (cbReturn === false) {\n suppressedCallbacks = 1;\n }\n }\n }\n : () => true;\n }\n function toEndVisit(visitFunction) {\n return visitFunction ?\n () => {\n if (suppressedCallbacks > 0) {\n suppressedCallbacks--;\n }\n if (suppressedCallbacks === 0) {\n visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter());\n }\n }\n : () => true;\n }\n const onObjectBegin = toBeginVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toEndVisit(visitor.onObjectEnd), onArrayBegin = toBeginVisit(visitor.onArrayBegin), onArrayEnd = toEndVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);\n const disallowComments = options && options.disallowComments;\n const allowTrailingComma = options && options.allowTrailingComma;\n function scanNext() {\n while (true) {\n const token = _scanner.scan();\n switch (_scanner.getTokenError()) {\n case 4 /* ScanError.InvalidUnicode */:\n handleError(14 /* ParseErrorCode.InvalidUnicode */);\n break;\n case 5 /* ScanError.InvalidEscapeCharacter */:\n handleError(15 /* ParseErrorCode.InvalidEscapeCharacter */);\n break;\n case 3 /* ScanError.UnexpectedEndOfNumber */:\n handleError(13 /* ParseErrorCode.UnexpectedEndOfNumber */);\n break;\n case 1 /* ScanError.UnexpectedEndOfComment */:\n if (!disallowComments) {\n handleError(11 /* ParseErrorCode.UnexpectedEndOfComment */);\n }\n break;\n case 2 /* ScanError.UnexpectedEndOfString */:\n handleError(12 /* ParseErrorCode.UnexpectedEndOfString */);\n break;\n case 6 /* ScanError.InvalidCharacter */:\n handleError(16 /* ParseErrorCode.InvalidCharacter */);\n break;\n }\n switch (token) {\n case 12 /* SyntaxKind.LineCommentTrivia */:\n case 13 /* SyntaxKind.BlockCommentTrivia */:\n if (disallowComments) {\n handleError(10 /* ParseErrorCode.InvalidCommentToken */);\n }\n else {\n onComment();\n }\n break;\n case 16 /* SyntaxKind.Unknown */:\n handleError(1 /* ParseErrorCode.InvalidSymbol */);\n break;\n case 15 /* SyntaxKind.Trivia */:\n case 14 /* SyntaxKind.LineBreakTrivia */:\n break;\n default:\n return token;\n }\n }\n }\n function handleError(error, skipUntilAfter = [], skipUntil = []) {\n onError(error);\n if (skipUntilAfter.length + skipUntil.length > 0) {\n let token = _scanner.getToken();\n while (token !== 17 /* SyntaxKind.EOF */) {\n if (skipUntilAfter.indexOf(token) !== -1) {\n scanNext();\n break;\n }\n else if (skipUntil.indexOf(token) !== -1) {\n break;\n }\n token = scanNext();\n }\n }\n }\n function parseString(isValue) {\n const value = _scanner.getTokenValue();\n if (isValue) {\n onLiteralValue(value);\n }\n else {\n onObjectProperty(value);\n // add property name afterwards\n _jsonPath.push(value);\n }\n scanNext();\n return true;\n }\n function parseLiteral() {\n switch (_scanner.getToken()) {\n case 11 /* SyntaxKind.NumericLiteral */:\n const tokenValue = _scanner.getTokenValue();\n let value = Number(tokenValue);\n if (isNaN(value)) {\n handleError(2 /* ParseErrorCode.InvalidNumberFormat */);\n value = 0;\n }\n onLiteralValue(value);\n break;\n case 7 /* SyntaxKind.NullKeyword */:\n onLiteralValue(null);\n break;\n case 8 /* SyntaxKind.TrueKeyword */:\n onLiteralValue(true);\n break;\n case 9 /* SyntaxKind.FalseKeyword */:\n onLiteralValue(false);\n break;\n default:\n return false;\n }\n scanNext();\n return true;\n }\n function parseProperty() {\n if (_scanner.getToken() !== 10 /* SyntaxKind.StringLiteral */) {\n handleError(3 /* ParseErrorCode.PropertyNameExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n return false;\n }\n parseString(false);\n if (_scanner.getToken() === 6 /* SyntaxKind.ColonToken */) {\n onSeparator(':');\n scanNext(); // consume colon\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n }\n else {\n handleError(5 /* ParseErrorCode.ColonExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n _jsonPath.pop(); // remove processed property name\n return true;\n }\n function parseObject() {\n onObjectBegin();\n scanNext(); // consume open brace\n let needsComma = false;\n while (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) {\n if (!needsComma) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n }\n onSeparator(',');\n scanNext(); // consume comma\n if (_scanner.getToken() === 2 /* SyntaxKind.CloseBraceToken */ && allowTrailingComma) {\n break;\n }\n }\n else if (needsComma) {\n handleError(6 /* ParseErrorCode.CommaExpected */, [], []);\n }\n if (!parseProperty()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n needsComma = true;\n }\n onObjectEnd();\n if (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */) {\n handleError(7 /* ParseErrorCode.CloseBraceExpected */, [2 /* SyntaxKind.CloseBraceToken */], []);\n }\n else {\n scanNext(); // consume close brace\n }\n return true;\n }\n function parseArray() {\n onArrayBegin();\n scanNext(); // consume open bracket\n let isFirstElement = true;\n let needsComma = false;\n while (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) {\n if (!needsComma) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n }\n onSeparator(',');\n scanNext(); // consume comma\n if (_scanner.getToken() === 4 /* SyntaxKind.CloseBracketToken */ && allowTrailingComma) {\n break;\n }\n }\n else if (needsComma) {\n handleError(6 /* ParseErrorCode.CommaExpected */, [], []);\n }\n if (isFirstElement) {\n _jsonPath.push(0);\n isFirstElement = false;\n }\n else {\n _jsonPath[_jsonPath.length - 1]++;\n }\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [4 /* SyntaxKind.CloseBracketToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n needsComma = true;\n }\n onArrayEnd();\n if (!isFirstElement) {\n _jsonPath.pop(); // remove array index\n }\n if (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */) {\n handleError(8 /* ParseErrorCode.CloseBracketExpected */, [4 /* SyntaxKind.CloseBracketToken */], []);\n }\n else {\n scanNext(); // consume close bracket\n }\n return true;\n }\n function parseValue() {\n switch (_scanner.getToken()) {\n case 3 /* SyntaxKind.OpenBracketToken */:\n return parseArray();\n case 1 /* SyntaxKind.OpenBraceToken */:\n return parseObject();\n case 10 /* SyntaxKind.StringLiteral */:\n return parseString(true);\n default:\n return parseLiteral();\n }\n }\n scanNext();\n if (_scanner.getToken() === 17 /* SyntaxKind.EOF */) {\n if (options.allowEmptyContent) {\n return true;\n }\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n return false;\n }\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n return false;\n }\n if (_scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n handleError(9 /* ParseErrorCode.EndOfFileExpected */, [], []);\n }\n return true;\n}\n/**\n * Takes JSON with JavaScript-style comments and remove\n * them. Optionally replaces every none-newline character\n * of comments with a replaceCharacter\n */\nexport function stripComments(text, replaceCh) {\n let _scanner = createScanner(text), parts = [], kind, offset = 0, pos;\n do {\n pos = _scanner.getPosition();\n kind = _scanner.scan();\n switch (kind) {\n case 12 /* SyntaxKind.LineCommentTrivia */:\n case 13 /* SyntaxKind.BlockCommentTrivia */:\n case 17 /* SyntaxKind.EOF */:\n if (offset !== pos) {\n parts.push(text.substring(offset, pos));\n }\n if (replaceCh !== undefined) {\n parts.push(_scanner.getTokenValue().replace(/[^\\r\\n]/g, replaceCh));\n }\n offset = _scanner.getPosition();\n break;\n }\n } while (kind !== 17 /* SyntaxKind.EOF */);\n return parts.join('');\n}\nexport function getNodeType(value) {\n switch (typeof value) {\n case 'boolean': return 'boolean';\n case 'number': return 'number';\n case 'string': return 'string';\n case 'object': {\n if (!value) {\n return 'null';\n }\n else if (Array.isArray(value)) {\n return 'array';\n }\n return 'object';\n }\n default: return 'null';\n }\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'use strict';\nimport { format, isEOL } from './format';\nimport { parseTree, findNodeAtLocation } from './parser';\nexport function removeProperty(text, path, options) {\n return setProperty(text, path, void 0, options);\n}\nexport function setProperty(text, originalPath, value, options) {\n const path = originalPath.slice();\n const errors = [];\n const root = parseTree(text, errors);\n let parent = void 0;\n let lastSegment = void 0;\n while (path.length > 0) {\n lastSegment = path.pop();\n parent = findNodeAtLocation(root, path);\n if (parent === void 0 && value !== void 0) {\n if (typeof lastSegment === 'string') {\n value = { [lastSegment]: value };\n }\n else {\n value = [value];\n }\n }\n else {\n break;\n }\n }\n if (!parent) {\n // empty document\n if (value === void 0) { // delete\n throw new Error('Can not delete in empty document');\n }\n return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options);\n }\n else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) {\n const existing = findNodeAtLocation(parent, [lastSegment]);\n if (existing !== void 0) {\n if (value === void 0) { // delete\n if (!existing.parent) {\n throw new Error('Malformed AST');\n }\n const propertyIndex = parent.children.indexOf(existing.parent);\n let removeBegin;\n let removeEnd = existing.parent.offset + existing.parent.length;\n if (propertyIndex > 0) {\n // remove the comma of the previous node\n let previous = parent.children[propertyIndex - 1];\n removeBegin = previous.offset + previous.length;\n }\n else {\n removeBegin = parent.offset + 1;\n if (parent.children.length > 1) {\n // remove the comma of the next node\n let next = parent.children[1];\n removeEnd = next.offset;\n }\n }\n return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, options);\n }\n else {\n // set value of existing property\n return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options);\n }\n }\n else {\n if (value === void 0) { // delete\n return []; // property does not exist, nothing to do\n }\n const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;\n const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map(p => p.children[0].value)) : parent.children.length;\n let edit;\n if (index > 0) {\n let previous = parent.children[index - 1];\n edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };\n }\n else if (parent.children.length === 0) {\n edit = { offset: parent.offset + 1, length: 0, content: newProperty };\n }\n else {\n edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' };\n }\n return withFormatting(text, edit, options);\n }\n }\n else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) {\n const insertIndex = lastSegment;\n if (insertIndex === -1) {\n // Insert\n const newProperty = `${JSON.stringify(value)}`;\n let edit;\n if (parent.children.length === 0) {\n edit = { offset: parent.offset + 1, length: 0, content: newProperty };\n }\n else {\n const previous = parent.children[parent.children.length - 1];\n edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };\n }\n return withFormatting(text, edit, options);\n }\n else if (value === void 0 && parent.children.length >= 0) {\n // Removal\n const removalIndex = lastSegment;\n const toRemove = parent.children[removalIndex];\n let edit;\n if (parent.children.length === 1) {\n // only item\n edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' };\n }\n else if (parent.children.length - 1 === removalIndex) {\n // last item\n let previous = parent.children[removalIndex - 1];\n let offset = previous.offset + previous.length;\n let parentEndOffset = parent.offset + parent.length;\n edit = { offset, length: parentEndOffset - 2 - offset, content: '' };\n }\n else {\n edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' };\n }\n return withFormatting(text, edit, options);\n }\n else if (value !== void 0) {\n let edit;\n const newProperty = `${JSON.stringify(value)}`;\n if (!options.isArrayInsertion && parent.children.length > lastSegment) {\n const toModify = parent.children[lastSegment];\n edit = { offset: toModify.offset, length: toModify.length, content: newProperty };\n }\n else if (parent.children.length === 0 || lastSegment === 0) {\n edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + ',' };\n }\n else {\n const index = lastSegment > parent.children.length ? parent.children.length : lastSegment;\n const previous = parent.children[index - 1];\n edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };\n }\n return withFormatting(text, edit, options);\n }\n else {\n throw new Error(`Can not ${value === void 0 ? 'remove' : (options.isArrayInsertion ? 'insert' : 'modify')} Array index ${insertIndex} as length is not sufficient`);\n }\n }\n else {\n throw new Error(`Can not add ${typeof lastSegment !== 'number' ? 'index' : 'property'} to parent of type ${parent.type}`);\n }\n}\nfunction withFormatting(text, edit, options) {\n if (!options.formattingOptions) {\n return [edit];\n }\n // apply the edit\n let newText = applyEdit(text, edit);\n // format the new text\n let begin = edit.offset;\n let end = edit.offset + edit.content.length;\n if (edit.length === 0 || edit.content.length === 0) { // insert or remove\n while (begin > 0 && !isEOL(newText, begin - 1)) {\n begin--;\n }\n while (end < newText.length && !isEOL(newText, end)) {\n end++;\n }\n }\n const edits = format(newText, { offset: begin, length: end - begin }, { ...options.formattingOptions, keepLines: false });\n // apply the formatting edits and track the begin and end offsets of the changes\n for (let i = edits.length - 1; i >= 0; i--) {\n const edit = edits[i];\n newText = applyEdit(newText, edit);\n begin = Math.min(begin, edit.offset);\n end = Math.max(end, edit.offset + edit.length);\n end += edit.content.length - edit.length;\n }\n // create a single edit with all changes\n const editLength = text.length - (newText.length - end) - begin;\n return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];\n}\nexport function applyEdit(text, edit) {\n return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);\n}\nexport function isWS(text, offset) {\n return '\\r\\n \\t'.indexOf(text.charAt(offset)) !== -1;\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'use strict';\nimport * as formatter from './impl/format';\nimport * as edit from './impl/edit';\nimport * as scanner from './impl/scanner';\nimport * as parser from './impl/parser';\n/**\n * Creates a JSON scanner on the given text.\n * If ignoreTrivia is set, whitespaces or comments are ignored.\n */\nexport const createScanner = scanner.createScanner;\nexport var ScanError;\n(function (ScanError) {\n ScanError[ScanError[\"None\"] = 0] = \"None\";\n ScanError[ScanError[\"UnexpectedEndOfComment\"] = 1] = \"UnexpectedEndOfComment\";\n ScanError[ScanError[\"UnexpectedEndOfString\"] = 2] = \"UnexpectedEndOfString\";\n ScanError[ScanError[\"UnexpectedEndOfNumber\"] = 3] = \"UnexpectedEndOfNumber\";\n ScanError[ScanError[\"InvalidUnicode\"] = 4] = \"InvalidUnicode\";\n ScanError[ScanError[\"InvalidEscapeCharacter\"] = 5] = \"InvalidEscapeCharacter\";\n ScanError[ScanError[\"InvalidCharacter\"] = 6] = \"InvalidCharacter\";\n})(ScanError || (ScanError = {}));\nexport var SyntaxKind;\n(function (SyntaxKind) {\n SyntaxKind[SyntaxKind[\"OpenBraceToken\"] = 1] = \"OpenBraceToken\";\n SyntaxKind[SyntaxKind[\"CloseBraceToken\"] = 2] = \"CloseBraceToken\";\n SyntaxKind[SyntaxKind[\"OpenBracketToken\"] = 3] = \"OpenBracketToken\";\n SyntaxKind[SyntaxKind[\"CloseBracketToken\"] = 4] = \"CloseBracketToken\";\n SyntaxKind[SyntaxKind[\"CommaToken\"] = 5] = \"CommaToken\";\n SyntaxKind[SyntaxKind[\"ColonToken\"] = 6] = \"ColonToken\";\n SyntaxKind[SyntaxKind[\"NullKeyword\"] = 7] = \"NullKeyword\";\n SyntaxKind[SyntaxKind[\"TrueKeyword\"] = 8] = \"TrueKeyword\";\n SyntaxKind[SyntaxKind[\"FalseKeyword\"] = 9] = \"FalseKeyword\";\n SyntaxKind[SyntaxKind[\"StringLiteral\"] = 10] = \"StringLiteral\";\n SyntaxKind[SyntaxKind[\"NumericLiteral\"] = 11] = \"NumericLiteral\";\n SyntaxKind[SyntaxKind[\"LineCommentTrivia\"] = 12] = \"LineCommentTrivia\";\n SyntaxKind[SyntaxKind[\"BlockCommentTrivia\"] = 13] = \"BlockCommentTrivia\";\n SyntaxKind[SyntaxKind[\"LineBreakTrivia\"] = 14] = \"LineBreakTrivia\";\n SyntaxKind[SyntaxKind[\"Trivia\"] = 15] = \"Trivia\";\n SyntaxKind[SyntaxKind[\"Unknown\"] = 16] = \"Unknown\";\n SyntaxKind[SyntaxKind[\"EOF\"] = 17] = \"EOF\";\n})(SyntaxKind || (SyntaxKind = {}));\n/**\n * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.\n */\nexport const getLocation = parser.getLocation;\n/**\n * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n * Therefore, always check the errors list to find out if the input was valid.\n */\nexport const parse = parser.parse;\n/**\n * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n */\nexport const parseTree = parser.parseTree;\n/**\n * Finds the node at the given path in a JSON DOM.\n */\nexport const findNodeAtLocation = parser.findNodeAtLocation;\n/**\n * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.\n */\nexport const findNodeAtOffset = parser.findNodeAtOffset;\n/**\n * Gets the JSON path of the given JSON DOM node\n */\nexport const getNodePath = parser.getNodePath;\n/**\n * Evaluates the JavaScript object of the given JSON DOM node\n */\nexport const getNodeValue = parser.getNodeValue;\n/**\n * Parses the given text and invokes the visitor functions for each object, array and literal reached.\n */\nexport const visit = parser.visit;\n/**\n * Takes JSON with JavaScript-style comments and remove\n * them. Optionally replaces every none-newline character\n * of comments with a replaceCharacter\n */\nexport const stripComments = parser.stripComments;\nexport var ParseErrorCode;\n(function (ParseErrorCode) {\n ParseErrorCode[ParseErrorCode[\"InvalidSymbol\"] = 1] = \"InvalidSymbol\";\n ParseErrorCode[ParseErrorCode[\"InvalidNumberFormat\"] = 2] = \"InvalidNumberFormat\";\n ParseErrorCode[ParseErrorCode[\"PropertyNameExpected\"] = 3] = \"PropertyNameExpected\";\n ParseErrorCode[ParseErrorCode[\"ValueExpected\"] = 4] = \"ValueExpected\";\n ParseErrorCode[ParseErrorCode[\"ColonExpected\"] = 5] = \"ColonExpected\";\n ParseErrorCode[ParseErrorCode[\"CommaExpected\"] = 6] = \"CommaExpected\";\n ParseErrorCode[ParseErrorCode[\"CloseBraceExpected\"] = 7] = \"CloseBraceExpected\";\n ParseErrorCode[ParseErrorCode[\"CloseBracketExpected\"] = 8] = \"CloseBracketExpected\";\n ParseErrorCode[ParseErrorCode[\"EndOfFileExpected\"] = 9] = \"EndOfFileExpected\";\n ParseErrorCode[ParseErrorCode[\"InvalidCommentToken\"] = 10] = \"InvalidCommentToken\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfComment\"] = 11] = \"UnexpectedEndOfComment\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfString\"] = 12] = \"UnexpectedEndOfString\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfNumber\"] = 13] = \"UnexpectedEndOfNumber\";\n ParseErrorCode[ParseErrorCode[\"InvalidUnicode\"] = 14] = \"InvalidUnicode\";\n ParseErrorCode[ParseErrorCode[\"InvalidEscapeCharacter\"] = 15] = \"InvalidEscapeCharacter\";\n ParseErrorCode[ParseErrorCode[\"InvalidCharacter\"] = 16] = \"InvalidCharacter\";\n})(ParseErrorCode || (ParseErrorCode = {}));\nexport function printParseErrorCode(code) {\n switch (code) {\n case 1 /* ParseErrorCode.InvalidSymbol */: return 'InvalidSymbol';\n case 2 /* ParseErrorCode.InvalidNumberFormat */: return 'InvalidNumberFormat';\n case 3 /* ParseErrorCode.PropertyNameExpected */: return 'PropertyNameExpected';\n case 4 /* ParseErrorCode.ValueExpected */: return 'ValueExpected';\n case 5 /* ParseErrorCode.ColonExpected */: return 'ColonExpected';\n case 6 /* ParseErrorCode.CommaExpected */: return 'CommaExpected';\n case 7 /* ParseErrorCode.CloseBraceExpected */: return 'CloseBraceExpected';\n case 8 /* ParseErrorCode.CloseBracketExpected */: return 'CloseBracketExpected';\n case 9 /* ParseErrorCode.EndOfFileExpected */: return 'EndOfFileExpected';\n case 10 /* ParseErrorCode.InvalidCommentToken */: return 'InvalidCommentToken';\n case 11 /* ParseErrorCode.UnexpectedEndOfComment */: return 'UnexpectedEndOfComment';\n case 12 /* ParseErrorCode.UnexpectedEndOfString */: return 'UnexpectedEndOfString';\n case 13 /* ParseErrorCode.UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber';\n case 14 /* ParseErrorCode.InvalidUnicode */: return 'InvalidUnicode';\n case 15 /* ParseErrorCode.InvalidEscapeCharacter */: return 'InvalidEscapeCharacter';\n case 16 /* ParseErrorCode.InvalidCharacter */: return 'InvalidCharacter';\n }\n return '<unknown ParseErrorCode>';\n}\n/**\n * Computes the edit operations needed to format a JSON document.\n *\n * @param documentText The input text\n * @param range The range to format or `undefined` to format the full content\n * @param options The formatting options\n * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}.\n * To apply the edit operations to the input, use {@linkcode applyEdits}.\n */\nexport function format(documentText, range, options) {\n return formatter.format(documentText, range, options);\n}\n/**\n * Computes the edit operations needed to modify a value in the JSON document.\n *\n * @param documentText The input text\n * @param path The path of the value to change. The path represents either to the document root, a property or an array item.\n * If the path points to an non-existing property or item, it will be created.\n * @param value The new value for the specified property or item. If the value is undefined,\n * the property or item will be removed.\n * @param options Options\n * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}.\n * To apply the edit operations to the input, use {@linkcode applyEdits}.\n */\nexport function modify(text, path, value, options) {\n return edit.setProperty(text, path, value, options);\n}\n/**\n * Applies edits to an input string.\n * @param text The input text\n * @param edits Edit operations following the format described in {@linkcode EditResult}.\n * @returns The text with the applied edits.\n * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}.\n */\nexport function applyEdits(text, edits) {\n let sortedEdits = edits.slice(0).sort((a, b) => {\n const diff = a.offset - b.offset;\n if (diff === 0) {\n return a.length - b.length;\n }\n return diff;\n });\n let lastModifiedOffset = text.length;\n for (let i = sortedEdits.length - 1; i >= 0; i--) {\n let e = sortedEdits[i];\n if (e.offset + e.length <= lastModifiedOffset) {\n text = edit.applyEdit(text, e);\n }\n else {\n throw new Error('Overlapping edit');\n }\n lastModifiedOffset = e.offset;\n }\n return text;\n}\n","import { z } from 'zod';\nimport { CallLogLevelSchema } from './callRecord';\n\n/** Keys whose values are replaced by `[redacted]`; matched case-insensitively, ignoring `_`/`-`, as substrings. */\nexport const DEFAULT_REDACT_KEYS: readonly string[] = [\n 'password', 'passwd', 'secret', 'token', 'apikey', 'privatekey', 'authorization', 'cookie', 'credential',\n];\n\nconst PayloadPolicySchema = z.object({\n /**\n * `none` records only sizes; `truncated` (default) cuts long strings,\n * arrays, and deep nesting per property; `full` records payloads as sent.\n * Redaction applies to `truncated` and `full`.\n */\n mode: z.enum(['none', 'truncated', 'full']).default('truncated'),\n maxStringLength: z.number().int().positive().default(256),\n maxArrayItems: z.number().int().positive().default(50),\n maxDepth: z.number().int().positive().default(8),\n /** `[]` turns redaction off. */\n redactKeys: z.array(z.string().min(1)).default([...DEFAULT_REDACT_KEYS]),\n}).strict().prefault({});\n\nexport type PayloadPolicy = z.output<typeof PayloadPolicySchema>;\n\nconst RotationSchema = z.object({\n /** Start a new file once the current one reaches this size. */\n maxFileSizeMb: z.number().positive().default(10),\n /** Delete the oldest files beyond this count. */\n maxFiles: z.number().int().positive().default(20),\n /** Delete files last written longer ago than this. */\n maxAgeDays: z.number().positive().default(14),\n}).strict().prefault({});\n\nexport type CallLogRotation = z.output<typeof RotationSchema>;\n\n/**\n * Persistent log of the calls routed through the hub, written as NDJSON to\n * `<state dir>/calls`. Changes apply without restarting the hub.\n */\nexport const CallLogConfigSchema = z.object({\n /**\n * `off` (default) records nothing; `error`/`warn` failed calls; `info`\n * every request; `debug` also notifications; `trace` also stream frames.\n */\n level: CallLogLevelSchema.default('off'),\n payloads: PayloadPolicySchema,\n rotation: RotationSchema,\n}).strict().prefault({});\n\nexport type CallLogConfig = z.output<typeof CallLogConfigSchema>;\n","import { type HubConfig, hubConfigJsonSchema, parseHubConfig } from '@hediet/linkrpc-hub';\nimport * as jsonc from 'jsonc-parser';\nimport { z } from 'zod';\nimport { type CallLogConfig, CallLogConfigSchema } from './callLog/callLogConfig';\nimport type { CallLogLevel } from './callLog/callRecord';\n\nconst SERVICE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\n/** A process the daemon starts and supervises, or a LinkRPC endpoint it connects, optionally connected to the hub. */\nexport const ManagedServiceSchema = z.object({\n description: z.string().optional(),\n /** Executable and arguments (no shell). `.cmd`/`.bat` shims work on Windows. Set exactly one of `command` and `endpoint`. */\n command: z.array(z.string().min(1)).min(1).optional(),\n /**\n * A LinkRPC endpoint URI to connect instead of starting a process, for\n * example another hub reached through\n * `cmd-stdio:?argv=ssh&argv=vm&argv=linkrpc-hub-daemon&argv=bridge-stdio`,\n * or `unix:`/`npipe:`/`ws:`. The endpoint joins this hub like a service:\n * it may serve only `serviceId`, and its own calls pass the hub's\n * forwarded-call checks.\n */\n endpoint: z.string().min(1).optional(),\n /** Extra environment. RPC services also receive `LINKRPC_ENDPOINT`/`LINKRPC_TOKEN`. */\n env: z.record(z.string(), z.string()).default({}),\n cwd: z.string().optional(),\n /** `false` keeps the service configured but stopped. */\n enabled: z.boolean().default(true),\n restart: z.enum(['always', 'on-failure', 'never']).default('on-failure'),\n /** `false` runs a plain stdio process without a participant socket or identity. */\n rpc: z.boolean().default(true),\n /** Run in a pseudoterminal: stdout and stderr merge, and attachments can resize it. */\n tty: z.boolean().default(false),\n /**\n * When the service counts as running: after it connects to the hub\n * (`connected`, for LinkRPC services) or as soon as it spawned.\n * Plain stdio processes (`rpc: false`) always use spawned readiness.\n */\n readiness: z.enum(['connected', 'spawned']).default('connected'),\n /**\n * Namespace the service may claim on the hub. Defaults to\n * `<hubServiceId>/<name>`, so one prefix addresses the whole hub.\n */\n serviceId: z.string().min(1).optional(),\n /** Provision a persistent managed identity (slot `service:<name>`). */\n managedIdentity: z.boolean().default(true),\n /** A `connected` service that does not connect in time is restarted. */\n startTimeoutMs: z.number().int().positive().default(30_000),\n /** Grace period after disconnecting (and SIGTERM on POSIX) before killing the process tree. */\n stopTimeoutMs: z.number().int().positive().default(5_000),\n}).strict().superRefine((service, context) => {\n if ((service.command === undefined) === (service.endpoint === undefined)) {\n context.addIssue({ code: 'custom', message: 'set exactly one of \"command\" and \"endpoint\"' });\n }\n if (service.endpoint === undefined) return;\n const processOnly = [\n Object.keys(service.env).length > 0 && 'env',\n service.cwd !== undefined && 'cwd',\n !service.rpc && 'rpc',\n service.tty && 'tty',\n service.readiness !== 'connected' && 'readiness',\n ].filter(field => field !== false);\n if (processOnly.length > 0) {\n context.addIssue({ code: 'custom', message: `\"${processOnly.join('\", \"')}\" only apply to \"command\" services` });\n }\n});\n\nexport type ManagedService = z.output<typeof ManagedServiceSchema> & { readonly serviceId: string; };\n\nconst ServicesSchema = z.record(\n z.string().regex(SERVICE_NAME, 'service names use letters, digits, \".\", \"_\", and \"-\"'),\n ManagedServiceSchema,\n).default({});\n\n/** The daemon's application endpoint (named pipe / Unix socket). */\nconst LocalEndpointSchema = z.object({\n /**\n * Named pipe (Windows, `\\\\.\\pipe\\name`) or Unix socket path. Defaults to a\n * fixed per-user name (see `linkrpc-hub-daemon status`).\n */\n path: z.string().min(1).optional(),\n /**\n * Token clients must present. By default there is none: the endpoint is\n * reachable only by the OS user (pipe ACL / private socket directory).\n */\n token: z.string().min(1).optional(),\n}).strict().default({});\n\nexport type LocalEndpointConfig = z.output<typeof LocalEndpointSchema>;\n\n/** The daemon config file: a hub config plus supervised `services`. */\nexport interface DaemonConfig {\n readonly hub: HubConfig;\n readonly localEndpoint: LocalEndpointConfig;\n readonly callLog: CallLogConfig;\n readonly services: Readonly<Record<string, ManagedService>>;\n}\n\n/**\n * Parse a config file's text. Comments and trailing commas are allowed.\n * Throws a readable error on invalid input.\n */\nexport function parseDaemonConfigText(text: string): DaemonConfig {\n if (text.trim() === '') return parseDaemonConfig({});\n const errors: jsonc.ParseError[] = [];\n const raw: unknown = jsonc.parse(text, errors, { allowTrailingComma: true });\n if (errors.length > 0) {\n const first = errors[0]!;\n const { line, column } = _position(text, first.offset);\n throw new Error(`invalid JSON at ${line}:${column}: ${jsonc.printParseErrorCode(first.error)}`);\n }\n return parseDaemonConfig(raw);\n}\n\n/**\n * Validate a parsed config. Unlike a standalone hub, the per-user hub defaults\n * to `forwardChecking: false`: the OS user is the trust boundary of its\n * private endpoints.\n */\nexport function parseDaemonConfig(raw: unknown): DaemonConfig {\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {\n throw new Error('config must be a JSON object');\n }\n const record = raw as Record<string, unknown>;\n let hub: HubConfig;\n let localEndpoint: LocalEndpointConfig;\n let callLog: CallLogConfig;\n let parsedServices: Record<string, z.output<typeof ManagedServiceSchema>>;\n try {\n const { $schema: _editorSchema, ...hubFields } = parseHubConfig({ ...record, forwardChecking: record.forwardChecking ?? false });\n hub = hubFields;\n localEndpoint = LocalEndpointSchema.parse(record.localEndpoint);\n callLog = CallLogConfigSchema.parse(record.callLog);\n parsedServices = ServicesSchema.parse(record.services);\n } catch (error) {\n if (error instanceof z.ZodError) throw new Error(z.prettifyError(error));\n throw error;\n }\n const services: Record<string, ManagedService> = {};\n const owners = new Map<string, string>();\n for (const [name, service] of Object.entries(parsedServices)) {\n const serviceId = service.serviceId ?? `${hub.hubServiceId}/${name}`;\n const owner = owners.get(serviceId);\n if (owner !== undefined) {\n throw new Error(`services '${owner}' and '${name}' both claim serviceId '${serviceId}'`);\n }\n owners.set(serviceId, name);\n services[name] = { ...service, serviceId };\n }\n return { hub, localEndpoint, callLog, services };\n}\n\n/** How applying `next` over a running `previous` service must proceed. */\nexport type ServiceChange = 'none' | 'inPlace' | 'restart';\n\nconst IN_PLACE_FIELDS = ['description', 'enabled', 'restart', 'startTimeoutMs', 'stopTimeoutMs'] as const;\n\nexport function classifyServiceChange(previous: ManagedService, next: ManagedService): ServiceChange {\n if (stableKey(_withoutInPlaceFields(previous)) !== stableKey(_withoutInPlaceFields(next))) return 'restart';\n return stableKey(previous) === stableKey(next) ? 'none' : 'inPlace';\n}\n\n/** A canonical serialization: equal for semantically equal JSON values. */\nexport function stableKey(value: unknown): string {\n return JSON.stringify(value, (_key, v: unknown) => {\n if (v === null || typeof v !== 'object' || Array.isArray(v)) return v;\n return Object.fromEntries(\n Object.entries(v as Record<string, unknown>)\n .filter(([, entry]) => entry !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n );\n });\n}\n\n/**\n * Persistently enable or disable `name` with a minimal text edit, keeping the\n * file's comments and formatting. Enabling removes the key (the default).\n */\nexport function setServiceEnabledInText(text: string, name: string, enabled: boolean): string {\n const config = parseDaemonConfigText(text);\n if (!(name in config.services)) throw new Error(`unknown service '${name}'`);\n return _modify(text, ['services', name, 'enabled'], enabled ? undefined : false);\n}\n\n/** Persist `callLog.level` with a minimal text edit. `off` removes the key (the default), and `callLog` once empty. */\nexport function setCallLogLevelInText(text: string, level: CallLogLevel): string {\n parseDaemonConfigText(text);\n const edited = _modify(text, ['callLog', 'level'], level === 'off' ? undefined : level);\n const callLog: unknown = jsonc.parse(edited, [], { allowTrailingComma: true })?.callLog;\n const empty = callLog !== null && typeof callLog === 'object' && Object.keys(callLog).length === 0;\n return empty ? _modify(edited, ['callLog'], undefined) : edited;\n}\n\nfunction _modify(text: string, path: jsonc.JSONPath, value: unknown): string {\n const edits = jsonc.modify(text, path, value, {\n formattingOptions: { insertSpaces: true, tabSize: 4, eol: text.includes('\\r\\n') ? '\\r\\n' : '\\n' },\n });\n return jsonc.applyEdits(text, edits);\n}\n\n/** JSON Schema of the config file, for editor validation. */\nexport function daemonConfigJsonSchema(): unknown {\n const hubSchema = hubConfigJsonSchema() as { properties?: Record<string, Record<string, unknown>>; };\n const servicesSchema = z.toJSONSchema(\n z.object({ services: ServicesSchema, localEndpoint: LocalEndpointSchema, callLog: CallLogConfigSchema }),\n { target: 'draft-2020-12', io: 'input' },\n ) as { properties: Record<string, unknown>; };\n const forwardChecking = hubSchema.properties?.forwardChecking;\n return {\n ...hubSchema,\n properties: {\n ...hubSchema.properties,\n ...(forwardChecking ? { forwardChecking: { ...forwardChecking, default: false } } : {}),\n localEndpoint: servicesSchema.properties.localEndpoint,\n callLog: servicesSchema.properties.callLog,\n services: servicesSchema.properties.services,\n },\n };\n}\n\n/** The config written on first start. */\nexport const DEFAULT_CONFIG_TEXT = `{\n \"$schema\": \"./config.schema.json\",\n // Services the hub starts at login and keeps running. RPC-enabled services get\n // LINKRPC_ENDPOINT and LINKRPC_TOKEN and may claim the service ID\n // <hubServiceId>/<name> (default hub/<name>). Saving this file applies\n // changes; only changed services restart.\n \"services\": {\n // \"example\": {\n // \"command\": [\"node\", \"/path/to/service.js\"],\n // \"env\": { \"LOG_LEVEL\": \"info\" }\n // }\n }\n}\n`;\n\nfunction _withoutInPlaceFields(service: ManagedService): Record<string, unknown> {\n const copy: Record<string, unknown> = { ...service };\n for (const field of IN_PLACE_FIELDS) delete copy[field];\n return copy;\n}\n\nfunction _position(text: string, offset: number): { line: number; column: number; } {\n const before = text.slice(0, offset).split('\\n');\n return { line: before.length, column: before[before.length - 1]!.length + 1 };\n}\n","import { connectToHubManagement } from './client';\nimport type { AutostartManager } from './autostart/autostart';\nimport { type DaemonLaunch, spawnDetached } from './autostart/launch';\nimport { readEndpointDiscovery } from './discovery';\nimport type { DaemonStatus } from './managementInterface';\nimport type { HubHome } from './paths';\n\nconst POLL_MS = 200;\n\n/** The running daemon's status, or `undefined` when it does not answer. */\nexport async function queryDaemonStatus(home: HubHome, timeoutMs = 3_000): Promise<DaemonStatus | undefined> {\n let connection: Awaited<ReturnType<typeof connectToHubManagement>> | undefined;\n const attempt = (async () => {\n connection = await connectToHubManagement(home);\n return await connection.management.getStatus({});\n })();\n const timeout = new Promise<undefined>(resolve => setTimeout(() => resolve(undefined), timeoutMs).unref());\n try {\n return await Promise.race([attempt, timeout]);\n } catch {\n return undefined;\n } finally {\n attempt.catch(() => undefined).finally(() => connection?.close());\n }\n}\n\nexport interface StartDaemonOptions {\n readonly home: HubHome;\n readonly launch: DaemonLaunch;\n /** Start through the OS manager when it is registered there. */\n readonly autostart?: AutostartManager;\n readonly timeoutMs?: number;\n}\n\n/** Start the daemon in the background and wait until it answers. */\nexport async function startDaemon(options: StartDaemonOptions): Promise<'started' | 'already-running'> {\n if (await queryDaemonStatus(options.home)) return 'already-running';\n if (!await options.autostart?.startManaged()) spawnDetached(options.launch.keepAlive);\n const deadline = Date.now() + (options.timeoutMs ?? 20_000);\n while (Date.now() < deadline) {\n if (await queryDaemonStatus(options.home)) return 'started';\n await _sleep(POLL_MS);\n }\n throw new Error(`the hub daemon did not start; see ${options.home.logFile}`);\n}\n\n/** Ask the daemon to stop all services and exit, and wait until its process is gone. */\nexport async function stopDaemon(home: HubHome, timeoutMs = 30_000): Promise<'stopped' | 'not-running'> {\n const pid = readEndpointDiscovery(home.managementFile)?.pid;\n let connection: Awaited<ReturnType<typeof connectToHubManagement>>;\n try {\n connection = await connectToHubManagement(home);\n } catch (error) {\n if (pid === undefined) return 'not-running';\n if (error instanceof Error && 'code' in error && (error.code === 'ENOENT' || error.code === 'ECONNREFUSED') && !_isProcessAlive(pid)) {\n return 'not-running';\n }\n throw error;\n }\n try {\n await connection.management.shutdown({});\n } finally {\n connection.close();\n }\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (pid === undefined ? !await queryDaemonStatus(home) : !_isProcessAlive(pid)) return 'stopped';\n await _sleep(POLL_MS);\n }\n throw new Error(`the hub daemon did not stop within ${timeoutMs} ms`);\n}\n\nfunction _isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'EPERM';\n }\n}\n\nfunction _sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n","import type { JsonValue, LinkRpcConnection } from '@hediet/linkrpc';\nimport { type FlowSummary, formatFlowSummary } from '@hediet/linkrpc-hub';\nimport type { JsonDocumentEdit } from '@hediet/linkrpc-infra/json-document';\nimport { type LogDocument, type LogEntry, type LogLevel, type LogStreamEvent, loggingInterface } from '@hediet/linkrpc-infra/logging';\nimport { stableKey } from '../config';\nimport type { CallLogStore } from './callLogStore';\nimport type { CallRecord } from './callRecord';\n\n/** How many of the latest calls the `linkrpc.logging` document holds. */\nexport const CALL_LOG_WINDOW = 200;\n\n/**\n * The call log as a revisioned `linkrpc.logging` document: the latest\n * {@link CALL_LOG_WINDOW} calls (oldest first) plus the log's state. A call\n * that settles replaces its pending entry in place.\n */\nexport class CallLogDocument {\n private _entries: Array<{ readonly id: string; readonly entry: LogEntry; }> = [];\n private _state: Readonly<Record<string, unknown>>;\n private _revision = 0;\n private _loaded = false;\n private readonly _patchListeners = new Set<(event: LogStreamEvent) => void>();\n private readonly _subscription: { dispose(): void; };\n /** Resolves once the window holds the latest calls from disk. */\n public readonly ready: Promise<void>;\n\n constructor(\n private readonly _service: string,\n private readonly _startedAt: number,\n store: CallLogStore,\n state: Readonly<Record<string, unknown>>,\n ) {\n this._state = state;\n const early: CallRecord[] = [];\n this._subscription = store.onRecord(record => this._loaded ? this._add(record) : early.push(record));\n this.ready = store.query({}, CALL_LOG_WINDOW)\n .catch(() => ({ calls: [] }))\n .then(({ calls }) => {\n this._entries = [...calls].reverse().map(record => ({ id: record.id, entry: _toLogEntry(record) }));\n this._loaded = true;\n for (const record of early) this._add(record);\n });\n }\n\n public snapshot(): { revision: number; document: LogDocument; } {\n return {\n revision: this._revision,\n document: {\n schemaVersion: 1,\n service: this._service,\n startedAt: new Date(this._startedAt).toISOString(),\n state: this._state,\n entries: this._entries.map(({ entry }) => entry),\n },\n };\n }\n\n public setState(state: Readonly<Record<string, unknown>>): void {\n if (stableKey(state) === stableKey(this._state)) return;\n this._state = state;\n this._publish([{ op: 'set', path: '/state', value: state }]);\n }\n\n public onPatch(listener: (event: LogStreamEvent) => void): { dispose(): void; } {\n this._patchListeners.add(listener);\n return { dispose: () => this._patchListeners.delete(listener) };\n }\n\n public dispose(): void {\n this._subscription.dispose();\n this._patchListeners.clear();\n }\n\n private _add(record: CallRecord): void {\n const entry = _toLogEntry(record);\n const index = this._entries.findIndex(existing => existing.id === record.id);\n if (index >= 0) {\n this._entries[index] = { id: record.id, entry };\n this._publish([{ op: 'set', path: `/entries/${index}`, value: entry }]);\n return;\n }\n const edits: JsonDocumentEdit[] = [{ op: 'insert', path: '/entries', index: this._entries.length, value: entry }];\n this._entries.push({ id: record.id, entry });\n if (this._entries.length > CALL_LOG_WINDOW) {\n this._entries.shift();\n edits.push({ op: 'remove', path: '/entries/0' });\n }\n this._publish(edits);\n }\n\n private _publish(edits: JsonDocumentEdit[]): void {\n this._revision++;\n const event: LogStreamEvent = { type: 'patch', revision: this._revision, edits };\n for (const listener of [...this._patchListeners]) listener(event);\n }\n}\n\nexport interface CallLogLevelControl {\n level(): LogLevel;\n /** Persists the level in the daemon config. */\n setLevel(level: LogLevel): Promise<void>;\n}\n\n/** Serve `document` as `linkrpc.logging` under `serviceId`. */\nexport function registerCallLogService(\n connection: LinkRpcConnection,\n serviceId: string,\n document: CallLogDocument,\n control: CallLogLevelControl,\n): { dispose(): void; } {\n return connection.register(loggingInterface, {\n getLogLevel: () => ({ level: control.level() }),\n setLogLevel: async ({ level }) => {\n await control.setLevel(level);\n return {};\n },\n getLogSnapshot: async () => {\n await document.ready;\n return document.snapshot();\n },\n watchLog: async (_params, _ctx, stream) => {\n await document.ready;\n const send = (event: LogStreamEvent) => stream.send(event).catch(() => { /* the watcher went away */ });\n void send({ type: 'snapshot', ...document.snapshot() });\n const subscription = document.onPatch(event => void send(event));\n try {\n await new Promise<void>(resolve => {\n if (stream.signal.aborted) resolve();\n else stream.signal.addEventListener('abort', () => resolve(), { once: true });\n });\n } finally {\n subscription.dispose();\n }\n return {};\n },\n }, { serviceId });\n}\n\nfunction _toLogEntry(record: CallRecord): LogEntry {\n return {\n timestamp: new Date(record.at).toISOString(),\n level: record.level,\n message: formatFlowSummary(_asFlowSummary(record), 120),\n durationMs: record.durationMs,\n ...(record.error !== undefined ? { error: { name: 'RpcError', message: `${record.error.message} (code ${record.error.code})` } } : {}),\n attributes: record,\n };\n}\n\n/** Render a record like the hub's flow log (`--log-messages`, `hub traffic`). */\nfunction _asFlowSummary(record: CallRecord): FlowSummary {\n const params = record.params as JsonValue | undefined;\n const frame = record.kind === 'stream' ? params as { dir?: string; control?: string; payload?: JsonValue; } | undefined : undefined;\n return {\n id: record.id,\n kind: record.kind,\n method: record.method,\n params: frame ? undefined : params,\n status: record.status,\n result: record.result as JsonValue | undefined,\n error: record.error,\n startTs: record.at,\n endTs: record.status === 'pending' ? undefined : record.at + record.durationMs,\n durationMs: record.durationMs,\n path: [record.from.label, ...(record.to ? [record.to.label] : [])],\n partial: record.status === 'pending',\n ...(frame ? {\n stream: [{\n timeMs: record.at + record.durationMs,\n dir: frame.dir === 'toCallee' ? 'toCallee' : 'toCaller',\n ...(frame.control !== undefined ? { control: frame.control } : {}),\n ...(frame.payload !== undefined ? { payload: frame.payload } : {}),\n }],\n } : {}),\n };\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { CallLogRotation } from './callLogConfig';\nimport { type CallFilter, type CallRecord, createCallMatcher } from './callRecord';\n\nconst SEGMENT = /^calls-[0-9TZ-]+\\.ndjson$/;\nconst DAY_MS = 24 * 60 * 60_000;\n\nexport interface CallQueryResult {\n /** Newest first; one record per call id (the latest one written). */\n readonly calls: readonly CallRecord[];\n /** More records match beyond `limit`. */\n readonly truncated: boolean;\n}\n\n/**\n * The call log on disk: NDJSON segments `calls-<UTC start>.ndjson` in one\n * directory. Appends are buffered and written in order; a segment is closed\n * at `maxFileSizeMb`, and old segments beyond `maxFiles` or `maxAgeDays` are\n * deleted. The files are the source of truth for queries.\n */\nexport class CallLogStore {\n private readonly _queue: string[] = [];\n private readonly _listeners = new Set<(record: CallRecord) => void>();\n private _segment: { readonly file: string; readonly handle: fs.promises.FileHandle; size: number; } | undefined;\n private _drain: Promise<void> | undefined;\n private _lastStamp = 0;\n private _error: string | undefined;\n\n constructor(\n public readonly directory: string,\n private _rotation: CallLogRotation,\n private readonly _now: () => number = Date.now,\n ) { }\n\n /** The last write failure, if the latest write failed. */\n public get error(): string | undefined {\n return this._error;\n }\n\n public setRotation(rotation: CallLogRotation): void {\n this._rotation = rotation;\n }\n\n /** Queue `record` for writing and notify live listeners. */\n public append(record: CallRecord): void {\n this._queue.push(`${JSON.stringify(record)}\\n`);\n this._schedule();\n for (const listener of [...this._listeners]) listener(record);\n }\n\n public onRecord(listener: (record: CallRecord) => void): { dispose(): void; } {\n this._listeners.add(listener);\n return { dispose: () => this._listeners.delete(listener) };\n }\n\n /** Resolves once every appended record is written. */\n public async flush(): Promise<void> {\n while (this._drain) await this._drain;\n }\n\n public async query(filter: CallFilter = {}, limit = 200): Promise<CallQueryResult> {\n await this.flush();\n const matches = createCallMatcher(filter);\n const calls: CallRecord[] = [];\n const seen = new Set<string>();\n for (const name of (await this._segments()).reverse()) {\n const file = path.join(this.directory, name);\n let text: string;\n try {\n if (filter.since !== undefined && (await fs.promises.stat(file)).mtimeMs < filter.since) break;\n text = await fs.promises.readFile(file, 'utf8');\n } catch {\n continue; // deleted by retention meanwhile\n }\n const lines = text.split('\\n');\n for (let i = lines.length - 1; i >= 0; i--) {\n const record = _parseLine(lines[i]!);\n if (!record || seen.has(record.id)) continue;\n seen.add(record.id);\n if (!matches(record)) continue;\n if (calls.length === limit) return { calls, truncated: true };\n calls.push(record);\n }\n }\n return { calls, truncated: false };\n }\n\n public async close(): Promise<void> {\n await this.flush();\n this._listeners.clear();\n await this._closeSegment();\n }\n\n private _schedule(): void {\n this._drain ??= this._write().finally(() => {\n this._drain = undefined;\n if (this._queue.length > 0) this._schedule();\n });\n }\n\n private async _write(): Promise<void> {\n while (this._queue.length > 0) {\n const chunk = this._queue.splice(0).join('');\n try {\n const segment = this._segment ?? await this._openSegment();\n await segment.handle.write(chunk);\n segment.size += Buffer.byteLength(chunk);\n if (segment.size >= this._rotation.maxFileSizeMb * 1024 * 1024) await this._closeSegment();\n this._error = undefined;\n } catch (error) {\n this._error = `cannot write the call log: ${error instanceof Error ? error.message : String(error)}`;\n await this._closeSegment().catch(() => { /* reopened on the next write */ });\n }\n }\n }\n\n /** Continue the newest segment while it has room; otherwise start one and apply retention. */\n private async _openSegment(): Promise<NonNullable<CallLogStore['_segment']>> {\n await fs.promises.mkdir(this.directory, { recursive: true, mode: 0o700 });\n const newest = (await this._segments()).at(-1);\n if (newest !== undefined) {\n const file = path.join(this.directory, newest);\n const { size } = await fs.promises.stat(file);\n if (size < this._rotation.maxFileSizeMb * 1024 * 1024) {\n this._segment = { file, handle: await fs.promises.open(file, 'a', 0o600), size };\n return this._segment;\n }\n }\n const file = path.join(this.directory, `calls-${this._stamp()}.ndjson`);\n this._segment = { file, handle: await fs.promises.open(file, 'a', 0o600), size: 0 };\n await this._prune(file);\n return this._segment;\n }\n\n private async _closeSegment(): Promise<void> {\n const segment = this._segment;\n this._segment = undefined;\n await segment?.handle.close();\n }\n\n private async _prune(current: string): Promise<void> {\n const names = await this._segments();\n const expired = this._now() - this._rotation.maxAgeDays * DAY_MS;\n for (const [index, name] of names.entries()) {\n const file = path.join(this.directory, name);\n if (file === current) continue;\n const beyondCount = index < names.length - this._rotation.maxFiles;\n try {\n if (beyondCount || (await fs.promises.stat(file)).mtimeMs < expired) await fs.promises.rm(file, { force: true });\n } catch { /* already gone */ }\n }\n }\n\n /** Segment names, oldest first. */\n private async _segments(): Promise<string[]> {\n try {\n return (await fs.promises.readdir(this.directory)).filter(name => SEGMENT.test(name)).sort();\n } catch {\n return [];\n }\n }\n\n /** Sortable and unique: `2026-10-21T12-37-35-123Z`. */\n private _stamp(): string {\n this._lastStamp = Math.max(this._now(), this._lastStamp + 1);\n return new Date(this._lastStamp).toISOString().replace(/[:.]/g, '-');\n }\n}\n\nfunction _parseLine(line: string): CallRecord | undefined {\n if (line === '') return undefined;\n try {\n const value: unknown = JSON.parse(line);\n if (value === null || typeof value !== 'object' || !('v' in value) || value.v !== 1) return undefined;\n return value as CallRecord;\n } catch {\n return undefined; // a line cut short by a crash\n }\n}\n","import type { PayloadPolicy } from './callLogConfig';\n\nexport const REDACTED = '[redacted]';\n\n/**\n * Apply the payload policy to an application payload (`$hubrpc*` meta already\n * stripped): redact values under sensitive keys and, in `truncated` mode, cut\n * long strings, long arrays, and deep nesting per property. Returns\n * `undefined` for `mode: \"none\"`.\n */\nexport function shapePayload(value: unknown, policy: PayloadPolicy): unknown {\n if (policy.mode === 'none' || value === undefined) return undefined;\n const redactKeys = policy.redactKeys.map(_normalizeKey);\n const truncate = policy.mode === 'truncated';\n const shape = (current: unknown, depth: number): unknown => {\n if (typeof current === 'string') {\n if (!truncate || current.length <= policy.maxStringLength) return current;\n return `${current.slice(0, policy.maxStringLength)}…(+${current.length - policy.maxStringLength} chars)`;\n }\n if (current === null || typeof current !== 'object') return current;\n if (truncate && depth >= policy.maxDepth) return Array.isArray(current) ? '[…]' : '{…}';\n if (Array.isArray(current)) {\n const kept = truncate ? current.slice(0, policy.maxArrayItems) : current;\n const items = kept.map(item => shape(item, depth + 1));\n if (kept.length < current.length) items.push(`…(+${current.length - kept.length} items)`);\n return items;\n }\n return Object.fromEntries(Object.entries(current).map(([key, entry]) => {\n const normalized = _normalizeKey(key);\n return [key, redactKeys.some(redact => normalized.includes(redact)) ? REDACTED : shape(entry, depth + 1)];\n }));\n };\n return shape(value, 0);\n}\n\n/** UTF-8 size of the JSON encoding; `undefined` for absent payloads. */\nexport function payloadBytes(value: unknown): number | undefined {\n if (value === undefined) return undefined;\n const json = JSON.stringify(value);\n return json === undefined ? undefined : Buffer.byteLength(json);\n}\n\nfunction _normalizeKey(key: string): string {\n return key.toLowerCase().replace(/[_-]/g, '');\n}\n","import type { ParticipantDescriptor, TopologyGraph, TopologyTransportInfo } from '@hediet/linkrpc/inspection';\n\nconst MAX_HOPS = 3;\n/** Ports are never reused, so entries stay valid; the oldest are forgotten beyond this. */\nconst MAX_ENTRIES = 4_096;\n\n/** What the hub's topology graph says about the peer behind one of its ports. */\nexport interface PortPeer {\n /** How it is connected, e.g. `named-pipe \\\\.\\pipe\\…` or `websocket 10.0.0.2:5000`. */\n readonly transport?: string;\n /** The attacher's description of it, e.g. which managed service it is. */\n readonly descriptor?: ParticipantDescriptor;\n}\n\n/**\n * Describes the peer behind a hub port from the hub's topology graph: the\n * nearest link (within a few hops, not crossing the hub) that reports a\n * transport, and the nearest node with an attacher descriptor. A participant's\n * transport sits on its overlay's participant link, and its descriptor on the\n * node at the far end, two hops from the hub port.\n *\n * Call {@link observe} while the port's connection is open (when a call\n * enters): short-lived clients are gone from the topology by the time their\n * call is recorded.\n */\nexport class PortPeers {\n private readonly _known = new Map<string, PortPeer>();\n\n constructor(private readonly _readGraph: () => TopologyGraph) { }\n\n /** Resolve and remember `portId`'s peer; reads the graph only for unknown ports. */\n public observe(portId: string): void {\n if (this._known.has(portId)) return;\n for (const [port, peer] of _peersByHubPort(this._readGraph())) {\n if (!this._known.has(port)) this._remember(port, peer);\n }\n if (!this._known.has(portId)) this._remember(portId, {});\n }\n\n public describe(portId: string): PortPeer {\n return this._known.get(portId) ?? {};\n }\n\n private _remember(portId: string, peer: PortPeer): void {\n this._known.set(portId, peer);\n if (this._known.size > MAX_ENTRIES) this._known.delete(this._known.keys().next().value!);\n }\n}\n\nfunction _peersByHubPort(graph: TopologyGraph): Map<string, PortPeer> {\n const linksOf = new Map<string, TopologyGraph['links']>();\n for (const link of graph.links) {\n for (const nodeId of new Set([link.from.nodeId, link.to.nodeId])) {\n linksOf.set(nodeId, [...linksOf.get(nodeId) ?? [], link]);\n }\n }\n const nodes = new Map(graph.nodes.map(node => [node.nodeId, node]));\n const result = new Map<string, PortPeer>();\n for (const port of nodes.get(graph.entryNodeId)?.ports ?? []) {\n result.set(port.portId, _peerOf(graph.entryNodeId, port.portId, linksOf, nodes));\n }\n return result;\n}\n\nfunction _peerOf(\n hubNodeId: string,\n portId: string,\n linksOf: ReadonlyMap<string, TopologyGraph['links']>,\n nodes: ReadonlyMap<string, TopologyGraph['nodes'][number]>,\n): PortPeer {\n const isHubPort = (end: { nodeId: string; portId: string; }) => end.nodeId === hubNodeId && end.portId === portId;\n let frontier = (linksOf.get(hubNodeId) ?? []).filter(link => isHubPort(link.from) || isHubPort(link.to));\n const visited = new Set<string>([hubNodeId]);\n let transport: TopologyTransportInfo | undefined;\n let descriptor: ParticipantDescriptor | undefined;\n for (let hop = 0; hop < MAX_HOPS && frontier.length > 0 && (!transport || !descriptor); hop++) {\n transport ??= frontier.find(link => link.transport !== undefined)?.transport;\n const next: TopologyGraph['links'] = [];\n for (const link of frontier) {\n for (const nodeId of [link.from.nodeId, link.to.nodeId]) {\n if (visited.has(nodeId)) continue;\n visited.add(nodeId);\n descriptor ??= nodes.get(nodeId)?.descriptors?.find(source => source.source === 'attacher')?.descriptor;\n next.push(...(linksOf.get(nodeId) ?? []).filter(candidate => candidate !== link));\n }\n }\n frontier = next;\n }\n return {\n ...(transport !== undefined ? { transport: _format(transport) } : {}),\n ...(descriptor !== undefined ? { descriptor } : {}),\n };\n}\n\nfunction _format(transport: TopologyTransportInfo): string {\n const remote = transport.remote;\n const where = transport.path\n ?? (remote?.address !== undefined ? `${remote.address}${remote.port !== undefined ? `:${remote.port}` : ''}` : undefined);\n const forwardedFor = transport.metadata?.forwardedFor;\n return [transport.type, where, forwardedFor !== undefined ? `(for ${String(forwardedFor)})` : undefined]\n .filter(part => part !== undefined)\n .join(' ');\n}\n","/**\n * How the daemon describes the participants it connects to its hub: an\n * `attacher` descriptor on their topology node. Diagnostic only; the call log\n * and UIs use it to attribute traffic to configured services.\n */\nimport type { ParticipantDescriptor } from '@hediet/linkrpc/inspection';\n\nconst SERVICE_TYPE = 'linkrpc.hubDaemon.service';\nconst ENDPOINT_TYPE = 'linkrpc.hubDaemon.endpoint';\n\n/** A service configured under `services` in the daemon config. */\nexport function serviceDescriptor(name: string, serviceId: string): ParticipantDescriptor {\n return { type: SERVICE_TYPE, label: name, metadata: { serviceId } };\n}\n\n/** An endpoint managed through `linkrpc.managedEndpoints` (e.g. started by the CLI). */\nexport function endpointDescriptor(id: string, namespace: string, serviceId: string): ParticipantDescriptor {\n return { type: ENDPOINT_TYPE, label: id, metadata: { namespace, serviceId } };\n}\n\n/** The configured service a descriptor names, if it is one of ours. */\nexport function serviceNameOf(descriptor: ParticipantDescriptor | undefined): string | undefined {\n return descriptor?.type === SERVICE_TYPE ? descriptor.label : undefined;\n}\n","import { randomBytes } from 'node:crypto';\nimport { HUBRPC_META_KEY, parseMethodName, stripLinkRpcWireMeta } from '@hediet/linkrpc';\nimport type { InspectionHost } from '@hediet/linkrpc/inspection';\nimport { type FlowSummary, TrafficFlowAggregator } from '@hediet/linkrpc-hub';\nimport type { CallLogConfig } from './callLogConfig';\nimport { type CallPeer, type CallRecord, type CallRecordLevel, isCallLevelEnabled } from './callRecord';\nimport { payloadBytes, shapePayload } from './payloadPolicy';\nimport { PortPeers } from './portPeers';\nimport { serviceNameOf } from '../participantDescriptors';\n\n/** How long an unsettled call (e.g. a watch stream) is tracked before it is forgotten. */\nconst GIVE_UP_MS = 24 * 60 * 60_000;\n\nexport interface CallRecorderOptions {\n readonly inspection: InspectionHost;\n /** Read for every call, so level and payload changes apply immediately. */\n readonly config: () => CallLogConfig;\n readonly onRecord: (record: CallRecord) => void;\n /** Calls to this method prefix (the call log's own `linkrpc.logging`) are recorded without results or stream frames. */\n readonly ownMethodPrefix: string;\n}\n\n/**\n * Records the calls routed through a hub: observes its inspection traffic,\n * coalesces transits into flows with {@link TrafficFlowAggregator}, and turns\n * each flow into a {@link CallRecord}. Calls the hub itself originates\n * (peer discovery, ...) are not recorded.\n */\nexport class CallRecorder {\n private readonly _idPrefix = randomBytes(4).toString('hex');\n private readonly _aggregator: TrafficFlowAggregator;\n private readonly _peers: PortPeers;\n private readonly _observation: { dispose(): void; };\n\n constructor(private readonly _options: CallRecorderOptions) {\n this._peers = new PortPeers(() => _options.inspection.getGraph(''));\n this._aggregator = new TrafficFlowAggregator({ onFlow: flow => this._onFlow(flow), giveUpMs: GIVE_UP_MS });\n this._observation = _options.inspection.observeTraffic(transit => {\n if (transit.kind === 'request' || transit.kind === 'notification') {\n if (transit.in) this._peers.observe(transit.in.portId);\n if (transit.out) this._peers.observe(transit.out.portId);\n }\n this._aggregator.add(transit);\n });\n }\n\n public dispose(): void {\n this._observation.dispose();\n this._aggregator.dispose();\n }\n\n private _onFlow(flow: FlowSummary): void {\n const record = this._toRecord(flow, this._options.config());\n if (record) this._options.onRecord(record);\n }\n\n private _toRecord(flow: FlowSummary, config: CallLogConfig): CallRecord | undefined {\n if (flow.entryPortId === undefined || flow.method === undefined) return undefined;\n // The log never stores its own content: snapshots would copy earlier records into new ones.\n const ownCall = flow.method.startsWith(this._options.ownMethodPrefix);\n if (ownCall && flow.kind === 'stream') return undefined;\n const parsed = parseMethodName(flow.method);\n const serviceId = parsed?.kind === 'full' ? parsed.serviceId : undefined;\n const level = _levelOf(flow);\n if (!isCallLevelEnabled(level, config.level)) return undefined;\n\n const frame = flow.kind === 'stream' ? flow.stream?.[0] : undefined;\n const params = frame !== undefined\n ? { dir: frame.dir, ...(frame.control !== undefined ? { control: frame.control } : {}), payload: frame.payload }\n : stripLinkRpcWireMeta(flow.params);\n const principal = _principalOf(flow.params);\n const shapedParams = shapePayload(params, config.payloads);\n const shapedResult = ownCall ? undefined : shapePayload(flow.result, config.payloads);\n const paramsSize = payloadBytes(params);\n const resultSize = payloadBytes(flow.result);\n return {\n v: 1,\n id: `${this._idPrefix}-${flow.id}`,\n at: flow.startTs,\n level,\n kind: flow.kind === 'response' ? 'request' : flow.kind,\n status: flow.status,\n durationMs: flow.durationMs,\n method: flow.method,\n ...(serviceId !== undefined ? { serviceId } : {}),\n from: this._peer(flow.entryPortId),\n ...(flow.exitPortId !== undefined ? { to: this._peer(flow.exitPortId) } : {}),\n ...(principal !== undefined ? { principal } : {}),\n ...(flow.error !== undefined ? { error: { code: flow.error.code, message: flow.error.message } } : {}),\n ...(paramsSize !== undefined ? { paramsBytes: paramsSize } : {}),\n ...(resultSize !== undefined ? { resultBytes: resultSize } : {}),\n ...(shapedParams !== undefined ? { params: shapedParams } : {}),\n ...(shapedResult !== undefined ? { result: shapedResult } : {}),\n ...(frame === undefined && flow.stream !== undefined ? { streamFrames: flow.stream.length } : {}),\n };\n }\n\n private _peer(portId: string): CallPeer {\n const { transport, descriptor } = this._peers.describe(portId);\n const service = serviceNameOf(descriptor);\n return {\n label: this._aggregator.portLabel(portId),\n ...(transport !== undefined ? { transport } : {}),\n ...(service !== undefined ? { service } : {}),\n };\n }\n}\n\nfunction _levelOf(flow: FlowSummary): CallRecordLevel {\n if (flow.status === 'failed' || flow.status === 'unroutable' || flow.status === 'dropped') return 'error';\n if (flow.kind === 'stream') return 'trace';\n return flow.kind === 'notification' ? 'debug' : 'info';\n}\n\nfunction _principalOf(wireParams: unknown): string | undefined {\n if (wireParams === null || typeof wireParams !== 'object' || !(HUBRPC_META_KEY in wireParams)) return undefined;\n const meta: unknown = (wireParams as Record<string, unknown>)[HUBRPC_META_KEY];\n if (meta === null || typeof meta !== 'object' || !('principal' in meta)) return undefined;\n return typeof meta.principal === 'string' ? meta.principal : undefined;\n}\n","import type { LinkRpcConnection } from '@hediet/linkrpc';\nimport type { InspectionHost } from '@hediet/linkrpc/inspection';\nimport { loggingInterface } from '@hediet/linkrpc-infra/logging';\nimport { type CallLogConfig, CallLogConfigSchema } from './callLogConfig';\nimport { CallLogDocument, registerCallLogService } from './callLogService';\nimport { type CallQueryResult, CallLogStore } from './callLogStore';\nimport { type CallFilter, type CallLogLevel, type CallRecord, createCallMatcher } from './callRecord';\nimport { CallRecorder } from './callRecorder';\n\nexport interface CallLogStatus {\n readonly level: CallLogLevel;\n readonly directory: string;\n /** `<hubServiceId>/daemon` while the hub runs. */\n readonly serviceId?: string;\n readonly error?: string;\n}\n\ninterface AttachedHub {\n readonly inspection: InspectionHost;\n readonly serviceId: string;\n}\n\n/**\n * The daemon's persistent call log. Owns the files and the `linkrpc.logging`\n * document across hub restarts; records the attached hub's calls while the\n * configured level is not `off`. Configuration changes apply immediately.\n */\nexport class CallLog {\n private _config: CallLogConfig = CallLogConfigSchema.parse(undefined);\n private readonly _store: CallLogStore;\n private _document: CallLogDocument | undefined;\n private _hub: AttachedHub | undefined;\n private _recorder: CallRecorder | undefined;\n\n constructor(\n directory: string,\n private readonly _startedAt: number,\n /** Persists a level set over `linkrpc.logging` in the config file. */\n private readonly _persistLevel: (level: CallLogLevel) => Promise<void>,\n ) {\n this._store = new CallLogStore(directory, this._config.rotation);\n }\n\n public status(): CallLogStatus {\n return {\n level: this._config.level,\n directory: this._store.directory,\n ...(this._hub !== undefined ? { serviceId: this._hub.serviceId } : {}),\n ...(this._store.error !== undefined ? { error: this._store.error } : {}),\n };\n }\n\n public configure(config: CallLogConfig): void {\n this._config = config;\n this._store.setRotation(config.rotation);\n this._document?.setState(this._documentState());\n this._syncRecorder();\n }\n\n /**\n * Record the calls of a (re)started hub and serve the log as\n * `linkrpc.logging` under `serviceId` on `connection`.\n */\n public attach(inspection: InspectionHost, connection: LinkRpcConnection, serviceId: string): { dispose(): void; } {\n const hub: AttachedHub = { inspection, serviceId };\n this._hub = hub;\n this._recorder?.dispose();\n this._recorder = undefined;\n this._document?.dispose();\n const document = new CallLogDocument(serviceId, this._startedAt, this._store, this._documentState());\n this._document = document;\n const service = registerCallLogService(connection, serviceId, document, {\n level: () => this._config.level,\n setLevel: level => this._persistLevel(level),\n });\n this._syncRecorder();\n return {\n dispose: () => {\n service.dispose();\n if (this._hub !== hub) return;\n this._hub = undefined;\n this._document = undefined;\n document.dispose();\n this._syncRecorder();\n },\n };\n }\n\n public query(filter: CallFilter, limit?: number): Promise<CallQueryResult> {\n return this._store.query(filter, limit);\n }\n\n /** Live records matching `filter`, as they are written. */\n public watch(filter: CallFilter, listener: (record: CallRecord) => void): { dispose(): void; } {\n const matches = createCallMatcher(filter);\n return this._store.onRecord(record => {\n if (matches(record)) listener(record);\n });\n }\n\n public async close(): Promise<void> {\n this._recorder?.dispose();\n this._recorder = undefined;\n this._document?.dispose();\n await this._store.close();\n }\n\n private _syncRecorder(): void {\n const hub = this._hub;\n const record = hub !== undefined && this._config.level !== 'off';\n if (record && this._recorder === undefined) {\n this._recorder = new CallRecorder({\n inspection: hub.inspection,\n config: () => this._config,\n onRecord: call => this._store.append(call),\n ownMethodPrefix: `${hub.serviceId}::${loggingInterface.info.id}::`,\n });\n } else if (!record && this._recorder !== undefined) {\n this._recorder.dispose();\n this._recorder = undefined;\n }\n }\n\n private _documentState(): Readonly<Record<string, unknown>> {\n return { level: this._config.level, directory: this._store.directory, payloads: this._config.payloads.mode };\n }\n}\n","import { createHash } from 'node:crypto';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { daemonConfigJsonSchema, DEFAULT_CONFIG_TEXT, parseDaemonConfigText } from './config';\nimport { writeFileDurably } from './durableWrite';\nimport type { ConfigDocument } from './managementInterface';\n\n/** Debounce for editors that save via several file operations. */\nconst WATCH_DEBOUNCE_MS = 150;\n\nexport class ConfigConflictError extends Error {\n constructor(file: string) {\n super(`${file} changed since it was read; reload and try again`);\n }\n}\n\n/** The daemon config file: revisioned reads, validated atomic and durable writes, and change watching. */\nexport class ConfigFile {\n constructor(\n public readonly path: string,\n private readonly _schemaPath: string,\n ) { }\n\n /** Create the config (if missing) and refresh the JSON Schema beside it. */\n public ensureExists(): void {\n fs.mkdirSync(path.dirname(this.path), { recursive: true });\n fs.writeFileSync(this._schemaPath, JSON.stringify(daemonConfigJsonSchema(), null, 2) + '\\n');\n try {\n fs.writeFileSync(this.path, DEFAULT_CONFIG_TEXT, { flag: 'wx' });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n }\n }\n\n public read(): ConfigDocument {\n let text: string;\n try {\n text = fs.readFileSync(this.path, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n text = '';\n }\n return { path: this.path, text, revision: configRevision(text) };\n }\n\n /**\n * Replace the file if it still has `expectedRevision`. Invalid configs are\n * rejected before anything is written. Returns the new revision.\n */\n public write(text: string, expectedRevision: string): string {\n parseDaemonConfigText(text);\n if (this.read().revision !== expectedRevision) throw new ConfigConflictError(this.path);\n writeFileDurably(this.path, text);\n return configRevision(text);\n }\n\n /** Invoke `onChange` (debounced) whenever the file may have changed. */\n public watch(onChange: () => void): { dispose(): void; } {\n const name = path.basename(this.path);\n let timer: ReturnType<typeof setTimeout> | undefined;\n const watcher = fs.watch(path.dirname(this.path), (_event, filename) => {\n if (filename !== null && filename !== name) return;\n clearTimeout(timer);\n timer = setTimeout(onChange, WATCH_DEBOUNCE_MS);\n });\n watcher.on('error', () => { /* the next explicit reload re-reads the file */ });\n return {\n dispose: () => {\n clearTimeout(timer);\n watcher.close();\n },\n };\n }\n}\n\nexport function configRevision(text: string): string {\n return createHash('sha256').update(text).digest('hex').slice(0, 16);\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nconst MAX_LOG_BYTES = 5 * 1024 * 1024;\n\n/** The daemon's log file (rotated once at startup when large), optionally echoed to stderr. */\nexport class DaemonLog {\n public static open(file: string, options: { echo: boolean; }): DaemonLog {\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });\n try {\n if (fs.statSync(file).size > MAX_LOG_BYTES) fs.renameSync(file, `${file}.1`);\n } catch { /* no previous log */ }\n return new DaemonLog(fs.createWriteStream(file, { flags: 'a', mode: 0o600 }), options.echo);\n }\n\n private constructor(\n private readonly _stream: fs.WriteStream,\n private readonly _echo: boolean,\n ) { }\n\n public line(text: string): void {\n const line = `${new Date().toISOString()} ${text}\\n`;\n this._stream.write(line);\n if (this._echo) process.stderr.write(line);\n }\n\n public close(): Promise<void> {\n return new Promise(resolve => this._stream.end(resolve));\n }\n}\n","import * as fs from 'node:fs';\nimport * as net from 'node:net';\n\nexport class AlreadyRunningError extends Error {\n constructor() {\n super('The LinkRPC hub daemon is already running.');\n }\n}\n\n/**\n * Process-lifetime mutex: a bound local socket. The OS releases it when the\n * process dies, so no stale lock survives a crash (a stale Unix socket file is\n * detected by a refused probe connection and replaced).\n */\nexport class SingleInstanceLock {\n public static async acquire(endpoint: string): Promise<SingleInstanceLock> {\n try {\n return new SingleInstanceLock(await _listen(endpoint), endpoint);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EADDRINUSE') throw error;\n }\n if (process.platform === 'win32' || await _isAlive(endpoint)) throw new AlreadyRunningError();\n fs.rmSync(endpoint, { force: true });\n try {\n return new SingleInstanceLock(await _listen(endpoint), endpoint);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'EADDRINUSE') throw new AlreadyRunningError();\n throw error;\n }\n }\n\n private constructor(\n private readonly _server: net.Server,\n private readonly _endpoint: string,\n ) { }\n\n public dispose(): void {\n this._server.close();\n if (process.platform !== 'win32') fs.rmSync(this._endpoint, { force: true });\n }\n}\n\nfunction _listen(endpoint: string): Promise<net.Server> {\n return new Promise((resolve, reject) => {\n const server = net.createServer(socket => socket.destroy());\n server.once('error', reject);\n server.listen(endpoint, () => {\n server.off('error', reject);\n resolve(server);\n });\n });\n}\n\nfunction _isAlive(endpoint: string): Promise<boolean> {\n return new Promise(resolve => {\n const socket = net.connect(endpoint);\n socket.once('connect', () => {\n socket.destroy();\n resolve(true);\n });\n socket.once('error', () => resolve(false));\n });\n}\n","import type { LogLine } from './managementInterface';\n\n/** Output without a newline is cut into lines of at most this length. */\nconst MAX_LINE_LENGTH = 8_192;\n\n/** A bounded, line-oriented log of one service's output. */\nexport class LogBuffer {\n private readonly _lines: LogLine[] = [];\n private readonly _partial = new Map<LogLine['stream'], string>();\n\n constructor(private readonly _capacity = 1000) { }\n\n /** Append a chunk; returns the completed lines. Partial lines wait for their newline (up to a length limit). */\n public append(stream: LogLine['stream'], chunk: string): string[] {\n const parts = ((this._partial.get(stream) ?? '') + chunk).split(/\\r?\\n/);\n let partial = parts.pop()!;\n while (partial.length > MAX_LINE_LENGTH) {\n parts.push(partial.slice(0, MAX_LINE_LENGTH));\n partial = partial.slice(MAX_LINE_LENGTH);\n }\n this._partial.set(stream, partial);\n for (const text of parts) this._push({ at: Date.now(), stream, text });\n return parts;\n }\n\n public lines(limit = this._capacity): LogLine[] {\n return this._lines.slice(-limit);\n }\n\n private _push(line: LogLine): void {\n this._lines.push(line);\n if (this._lines.length > this._capacity) this._lines.splice(0, this._lines.length - this._capacity);\n }\n}\n","module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction checkPathExt (path, options) {\n var pathext = options.pathExt !== undefined ?\n options.pathExt : process.env.PATHEXT\n\n if (!pathext) {\n return true\n }\n\n pathext = pathext.split(';')\n if (pathext.indexOf('') !== -1) {\n return true\n }\n for (var i = 0; i < pathext.length; i++) {\n var p = pathext[i].toLowerCase()\n if (p && path.substr(-p.length).toLowerCase() === p) {\n return true\n }\n }\n return false\n}\n\nfunction checkStat (stat, path, options) {\n if (!stat.isSymbolicLink() && !stat.isFile()) {\n return false\n }\n return checkPathExt(path, options)\n}\n\nfunction isexe (path, options, cb) {\n fs.stat(path, function (er, stat) {\n cb(er, er ? false : checkStat(stat, path, options))\n })\n}\n\nfunction sync (path, options) {\n return checkStat(fs.statSync(path), path, options)\n}\n","module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction isexe (path, options, cb) {\n fs.stat(path, function (er, stat) {\n cb(er, er ? false : checkStat(stat, options))\n })\n}\n\nfunction sync (path, options) {\n return checkStat(fs.statSync(path), options)\n}\n\nfunction checkStat (stat, options) {\n return stat.isFile() && checkMode(stat, options)\n}\n\nfunction checkMode (stat, options) {\n var mod = stat.mode\n var uid = stat.uid\n var gid = stat.gid\n\n var myUid = options.uid !== undefined ?\n options.uid : process.getuid && process.getuid()\n var myGid = options.gid !== undefined ?\n options.gid : process.getgid && process.getgid()\n\n var u = parseInt('100', 8)\n var g = parseInt('010', 8)\n var o = parseInt('001', 8)\n var ug = u | g\n\n var ret = (mod & o) ||\n (mod & g) && gid === myGid ||\n (mod & u) && uid === myUid ||\n (mod & ug) && myUid === 0\n\n return ret\n}\n","var fs = require('fs')\nvar core\nif (process.platform === 'win32' || global.TESTING_WINDOWS) {\n core = require('./windows.js')\n} else {\n core = require('./mode.js')\n}\n\nmodule.exports = isexe\nisexe.sync = sync\n\nfunction isexe (path, options, cb) {\n if (typeof options === 'function') {\n cb = options\n options = {}\n }\n\n if (!cb) {\n if (typeof Promise !== 'function') {\n throw new TypeError('callback not provided')\n }\n\n return new Promise(function (resolve, reject) {\n isexe(path, options || {}, function (er, is) {\n if (er) {\n reject(er)\n } else {\n resolve(is)\n }\n })\n })\n }\n\n core(path, options || {}, function (er, is) {\n // ignore EACCES because that just means we aren't allowed to run it\n if (er) {\n if (er.code === 'EACCES' || options && options.ignoreErrors) {\n er = null\n is = false\n }\n }\n cb(er, is)\n })\n}\n\nfunction sync (path, options) {\n // my kingdom for a filtered catch\n try {\n return core.sync(path, options || {})\n } catch (er) {\n if (options && options.ignoreErrors || er.code === 'EACCES') {\n return false\n } else {\n throw er\n }\n }\n}\n","const isWindows = process.platform === 'win32' ||\n process.env.OSTYPE === 'cygwin' ||\n process.env.OSTYPE === 'msys'\n\nconst path = require('path')\nconst COLON = isWindows ? ';' : ':'\nconst isexe = require('isexe')\n\nconst getNotFoundError = (cmd) =>\n Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })\n\nconst getPathInfo = (cmd, opt) => {\n const colon = opt.colon || COLON\n\n // If it has a slash, then we don't bother searching the pathenv.\n // just check the file itself, and that's it.\n const pathEnv = cmd.match(/\\//) || isWindows && cmd.match(/\\\\/) ? ['']\n : (\n [\n // windows always checks the cwd first\n ...(isWindows ? [process.cwd()] : []),\n ...(opt.path || process.env.PATH ||\n /* istanbul ignore next: very unusual */ '').split(colon),\n ]\n )\n const pathExtExe = isWindows\n ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'\n : ''\n const pathExt = isWindows ? pathExtExe.split(colon) : ['']\n\n if (isWindows) {\n if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')\n pathExt.unshift('')\n }\n\n return {\n pathEnv,\n pathExt,\n pathExtExe,\n }\n}\n\nconst which = (cmd, opt, cb) => {\n if (typeof opt === 'function') {\n cb = opt\n opt = {}\n }\n if (!opt)\n opt = {}\n\n const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n const found = []\n\n const step = i => new Promise((resolve, reject) => {\n if (i === pathEnv.length)\n return opt.all && found.length ? resolve(found)\n : reject(getNotFoundError(cmd))\n\n const ppRaw = pathEnv[i]\n const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n const pCmd = path.join(pathPart, cmd)\n const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n : pCmd\n\n resolve(subStep(p, i, 0))\n })\n\n const subStep = (p, i, ii) => new Promise((resolve, reject) => {\n if (ii === pathExt.length)\n return resolve(step(i + 1))\n const ext = pathExt[ii]\n isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {\n if (!er && is) {\n if (opt.all)\n found.push(p + ext)\n else\n return resolve(p + ext)\n }\n return resolve(subStep(p, i, ii + 1))\n })\n })\n\n return cb ? step(0).then(res => cb(null, res), cb) : step(0)\n}\n\nconst whichSync = (cmd, opt) => {\n opt = opt || {}\n\n const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n const found = []\n\n for (let i = 0; i < pathEnv.length; i ++) {\n const ppRaw = pathEnv[i]\n const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n const pCmd = path.join(pathPart, cmd)\n const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n : pCmd\n\n for (let j = 0; j < pathExt.length; j ++) {\n const cur = p + pathExt[j]\n try {\n const is = isexe.sync(cur, { pathExt: pathExtExe })\n if (is) {\n if (opt.all)\n found.push(cur)\n else\n return cur\n }\n } catch (ex) {}\n }\n }\n\n if (opt.all && found.length)\n return found\n\n if (opt.nothrow)\n return null\n\n throw getNotFoundError(cmd)\n}\n\nmodule.exports = which\nwhich.sync = whichSync\n","'use strict';\n\nconst pathKey = (options = {}) => {\n\tconst environment = options.env || process.env;\n\tconst platform = options.platform || process.platform;\n\n\tif (platform !== 'win32') {\n\t\treturn 'PATH';\n\t}\n\n\treturn Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';\n};\n\nmodule.exports = pathKey;\n// TODO: Remove this for the next major release\nmodule.exports.default = pathKey;\n","'use strict';\n\nconst path = require('path');\nconst which = require('which');\nconst getPathKey = require('path-key');\n\nfunction resolveCommandAttempt(parsed, withoutPathExt) {\n const env = parsed.options.env || process.env;\n const cwd = process.cwd();\n const hasCustomCwd = parsed.options.cwd != null;\n // Worker threads do not have process.chdir()\n const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;\n\n // If a custom `cwd` was specified, we need to change the process cwd\n // because `which` will do stat calls but does not support a custom cwd\n if (shouldSwitchCwd) {\n try {\n process.chdir(parsed.options.cwd);\n } catch (err) {\n /* Empty */\n }\n }\n\n let resolved;\n\n try {\n resolved = which.sync(parsed.command, {\n path: env[getPathKey({ env })],\n pathExt: withoutPathExt ? path.delimiter : undefined,\n });\n } catch (e) {\n /* Empty */\n } finally {\n if (shouldSwitchCwd) {\n process.chdir(cwd);\n }\n }\n\n // If we successfully resolved, ensure that an absolute path is returned\n // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it\n if (resolved) {\n resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);\n }\n\n return resolved;\n}\n\nfunction resolveCommand(parsed) {\n return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);\n}\n\nmodule.exports = resolveCommand;\n","'use strict';\n\n// See http://www.robvanderwoude.com/escapechars.php\nconst metaCharsRegExp = /([()\\][%!^\"`<>&|;, *?])/g;\n\nfunction escapeCommand(arg) {\n // Escape meta chars\n arg = arg.replace(metaCharsRegExp, '^$1');\n\n return arg;\n}\n\nfunction escapeArgument(arg, doubleEscapeMetaChars) {\n // Convert to string\n arg = `${arg}`;\n\n // Algorithm below is based on https://qntm.org/cmd\n // It's slightly altered to disable JS backtracking to avoid hanging on specially crafted input\n // Please see https://github.com/moxystudio/node-cross-spawn/pull/160 for more information\n\n // Sequence of backslashes followed by a double quote:\n // double up all the backslashes and escape the double quote\n arg = arg.replace(/(?=(\\\\+?)?)\\1\"/g, '$1$1\\\\\"');\n\n // Sequence of backslashes followed by the end of the string\n // (which will become a double quote later):\n // double up all the backslashes\n arg = arg.replace(/(?=(\\\\+?)?)\\1$/, '$1$1');\n\n // All other backslashes occur literally\n\n // Quote the whole thing:\n arg = `\"${arg}\"`;\n\n // Escape meta chars\n arg = arg.replace(metaCharsRegExp, '^$1');\n\n // Double escape meta chars if necessary\n if (doubleEscapeMetaChars) {\n arg = arg.replace(metaCharsRegExp, '^$1');\n }\n\n return arg;\n}\n\nmodule.exports.command = escapeCommand;\nmodule.exports.argument = escapeArgument;\n","'use strict';\nmodule.exports = /^#!(.*)/;\n","'use strict';\nconst shebangRegex = require('shebang-regex');\n\nmodule.exports = (string = '') => {\n\tconst match = string.match(shebangRegex);\n\n\tif (!match) {\n\t\treturn null;\n\t}\n\n\tconst [path, argument] = match[0].replace(/#! ?/, '').split(' ');\n\tconst binary = path.split('/').pop();\n\n\tif (binary === 'env') {\n\t\treturn argument;\n\t}\n\n\treturn argument ? `${binary} ${argument}` : binary;\n};\n","'use strict';\n\nconst fs = require('fs');\nconst shebangCommand = require('shebang-command');\n\nfunction readShebang(command) {\n // Read the first 150 bytes from the file\n const size = 150;\n const buffer = Buffer.alloc(size);\n\n let fd;\n\n try {\n fd = fs.openSync(command, 'r');\n fs.readSync(fd, buffer, 0, size, 0);\n fs.closeSync(fd);\n } catch (e) { /* Empty */ }\n\n // Attempt to extract shebang (null is returned if not a shebang)\n return shebangCommand(buffer.toString());\n}\n\nmodule.exports = readShebang;\n","'use strict';\n\nconst path = require('path');\nconst resolveCommand = require('./util/resolveCommand');\nconst escape = require('./util/escape');\nconst readShebang = require('./util/readShebang');\n\nconst isWin = process.platform === 'win32';\nconst isExecutableRegExp = /\\.(?:com|exe)$/i;\nconst isCmdShimRegExp = /node_modules[\\\\/].bin[\\\\/][^\\\\/]+\\.cmd$/i;\n\nfunction detectShebang(parsed) {\n parsed.file = resolveCommand(parsed);\n\n const shebang = parsed.file && readShebang(parsed.file);\n\n if (shebang) {\n parsed.args.unshift(parsed.file);\n parsed.command = shebang;\n\n return resolveCommand(parsed);\n }\n\n return parsed.file;\n}\n\nfunction parseNonShell(parsed) {\n if (!isWin) {\n return parsed;\n }\n\n // Detect & add support for shebangs\n const commandFile = detectShebang(parsed);\n\n // We don't need a shell if the command filename is an executable\n const needsShell = !isExecutableRegExp.test(commandFile);\n\n // If a shell is required, use cmd.exe and take care of escaping everything correctly\n // Note that `forceShell` is an hidden option used only in tests\n if (parsed.options.forceShell || needsShell) {\n // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`\n // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument\n // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,\n // we need to double escape them\n const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);\n\n // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\\bar)\n // This is necessary otherwise it will always fail with ENOENT in those cases\n parsed.command = path.normalize(parsed.command);\n\n // Escape command & arguments\n parsed.command = escape.command(parsed.command);\n parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));\n\n const shellCommand = [parsed.command].concat(parsed.args).join(' ');\n\n parsed.args = ['/d', '/s', '/c', `\"${shellCommand}\"`];\n parsed.command = process.env.comspec || 'cmd.exe';\n parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped\n }\n\n return parsed;\n}\n\nfunction parse(command, args, options) {\n // Normalize arguments, similar to nodejs\n if (args && !Array.isArray(args)) {\n options = args;\n args = null;\n }\n\n args = args ? args.slice(0) : []; // Clone array to avoid changing the original\n options = Object.assign({}, options); // Clone object to avoid changing the original\n\n // Build our parsed object\n const parsed = {\n command,\n args,\n options,\n file: undefined,\n original: {\n command,\n args,\n },\n };\n\n // Delegate further parsing to shell or non-shell\n return options.shell ? parsed : parseNonShell(parsed);\n}\n\nmodule.exports = parse;\n","'use strict';\n\nconst isWin = process.platform === 'win32';\n\nfunction notFoundError(original, syscall) {\n return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {\n code: 'ENOENT',\n errno: 'ENOENT',\n syscall: `${syscall} ${original.command}`,\n path: original.command,\n spawnargs: original.args,\n });\n}\n\nfunction hookChildProcess(cp, parsed) {\n if (!isWin) {\n return;\n }\n\n const originalEmit = cp.emit;\n\n cp.emit = function (name, arg1) {\n // If emitting \"exit\" event and exit code is 1, we need to check if\n // the command exists and emit an \"error\" instead\n // See https://github.com/IndigoUnited/node-cross-spawn/issues/16\n if (name === 'exit') {\n const err = verifyENOENT(arg1, parsed);\n\n if (err) {\n return originalEmit.call(cp, 'error', err);\n }\n }\n\n return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params\n };\n}\n\nfunction verifyENOENT(status, parsed) {\n if (isWin && status === 1 && !parsed.file) {\n return notFoundError(parsed.original, 'spawn');\n }\n\n return null;\n}\n\nfunction verifyENOENTSync(status, parsed) {\n if (isWin && status === 1 && !parsed.file) {\n return notFoundError(parsed.original, 'spawnSync');\n }\n\n return null;\n}\n\nmodule.exports = {\n hookChildProcess,\n verifyENOENT,\n verifyENOENTSync,\n notFoundError,\n};\n","'use strict';\n\nconst cp = require('child_process');\nconst parse = require('./lib/parse');\nconst enoent = require('./lib/enoent');\n\nfunction spawn(command, args, options) {\n // Parse the arguments\n const parsed = parse(command, args, options);\n\n // Spawn the child process\n const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);\n\n // Hook into child process \"exit\" event to emit an error if the command\n // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n enoent.hookChildProcess(spawned, parsed);\n\n return spawned;\n}\n\nfunction spawnSync(command, args, options) {\n // Parse the arguments\n const parsed = parse(command, args, options);\n\n // Spawn the child process\n const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);\n\n // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);\n\n return result;\n}\n\nmodule.exports = spawn;\nmodule.exports.spawn = spawn;\nmodule.exports.sync = spawnSync;\n\nmodule.exports._parse = parse;\nmodule.exports._enoent = enoent;\n","import { spawn } from 'node:child_process';\nimport * as path from 'node:path';\n\n/**\n * Whether children get their own process group, so that the whole tree can be\n * signalled. Windows has no process groups; `taskkill /T` walks the tree.\n */\nexport const SPAWN_DETACHED = process.platform !== 'win32';\n\n/** Ask a service's process tree to exit (POSIX only; Windows has no equivalent). */\nexport function terminateProcessTree(pid: number): void {\n if (process.platform === 'win32') return;\n _signalGroup(pid, 'SIGTERM');\n}\n\n/** Deliver a POSIX signal to a service's process group. */\nexport function signalProcessGroup(pid: number, signal: NodeJS.Signals): void {\n _signalGroup(pid, signal);\n}\n\n/** Forcefully end a process and all of its descendants. */\nexport function killProcessTree(pid: number): Promise<void> {\n if (process.platform !== 'win32') {\n _signalGroup(pid, 'SIGKILL');\n return Promise.resolve();\n }\n const taskkill = path.join(process.env.SystemRoot ?? 'C:\\\\Windows', 'System32', 'taskkill.exe');\n return new Promise(resolve => {\n const child = spawn(taskkill, ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true });\n child.once('error', () => resolve());\n child.once('exit', () => resolve());\n });\n}\n\nfunction _signalGroup(pid: number, signal: NodeJS.Signals): void {\n try {\n process.kill(-pid, signal);\n } catch {\n try {\n process.kill(pid, signal);\n } catch { /* already gone */ }\n }\n}\n","import * as os from 'node:os';\nimport { StringDecoder } from 'node:string_decoder';\nimport crossSpawn from 'cross-spawn';\nimport type { ConsoleSignal, ConsoleSize } from '@hediet/linkrpc-infra/console';\nimport { killProcessTree, signalProcessGroup, SPAWN_DETACHED } from './processTree';\n\nexport interface ExitInfo {\n readonly code: number | null;\n readonly signal: string | null;\n /** Set when the process never started. */\n readonly error?: string;\n}\n\n/** A spawned service process and its console I/O, over pipes or a pseudoterminal. */\nexport interface ServiceProcess {\n readonly pid: number | undefined;\n /** Resolves once the process runs; never resolves when spawning fails. */\n readonly spawned: Promise<void>;\n readonly exited: Promise<ExitInfo>;\n write(data: Uint8Array): void;\n resize(size: ConsoleSize): void;\n signal(signal: ConsoleSignal): void;\n /** Forcefully end the process tree. */\n kill(): Promise<void>;\n}\n\nexport interface SpawnServiceOptions {\n readonly command: readonly string[];\n readonly env: NodeJS.ProcessEnv;\n readonly cwd?: string;\n readonly onOutput: (stream: 'stdout' | 'stderr' | 'tty', data: Uint8Array) => void;\n readonly onError: (message: string) => void;\n}\n\n/** Signals a service process receives with their usual meaning. */\nexport function processSignals(tty: boolean, platform: NodeJS.Platform = process.platform): ConsoleSignal[] {\n if (platform !== 'win32') return ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGQUIT', 'SIGKILL'];\n // Windows has no signals; only a console (ConPTY) can deliver Ctrl+C, everything else terminates.\n return tty ? ['SIGINT', 'SIGKILL'] : ['SIGKILL'];\n}\n\nexport function spawnPipeProcess(options: SpawnServiceOptions): ServiceProcess {\n const [executable, ...args] = options.command;\n // cross-spawn resolves PATHEXT and escapes arguments for `.cmd` shims, so\n // `command` never goes through a shell's word splitting or metacharacters.\n const child = crossSpawn(executable!, args, {\n env: options.env,\n ...(options.cwd !== undefined ? { cwd: options.cwd } : {}),\n stdio: ['pipe', 'pipe', 'pipe'],\n windowsHide: true,\n detached: SPAWN_DETACHED,\n });\n const exited = new Promise<ExitInfo>(resolve => {\n child.once('close', (code, signal) => resolve({ code, signal }));\n child.once('error', error => {\n if (child.pid === undefined) resolve({ code: null, signal: null, error: error.message });\n else options.onError(`process error: ${error.message}`);\n });\n });\n for (const stream of ['stdout', 'stderr'] as const) {\n child[stream]?.on('data', (chunk: Buffer) => options.onOutput(stream, chunk));\n }\n child.stdin?.on('error', error => options.onError(`stdin failed: ${error.message}`));\n return {\n get pid() { return child.pid; },\n spawned: new Promise(resolve => child.once('spawn', () => resolve())),\n exited,\n write: data => {\n if (!child.stdin?.writable) throw new Error('The process stdin is closed');\n child.stdin.write(data);\n },\n resize: () => {},\n signal: signal => signalProcess(child.pid, signal),\n kill: async () => { if (child.pid !== undefined) await killProcessTree(child.pid); },\n };\n}\n\nexport async function spawnPtyProcess(options: SpawnServiceOptions & { readonly size: ConsoleSize }): Promise<ServiceProcess> {\n const pty = await loadPty();\n const { file, args } = ptyCommand(options.command);\n const env: Record<string, string> = {};\n for (const [key, value] of Object.entries(options.env)) if (value !== undefined) env[key] = value;\n const terminal = pty.spawn(file, args, {\n name: 'xterm-256color',\n cols: options.size.cols,\n rows: options.size.rows,\n cwd: options.cwd ?? process.cwd(),\n env,\n });\n terminal.onData(data => options.onOutput('tty', Buffer.from(data, 'utf8')));\n const exited = new Promise<ExitInfo>(resolve => terminal.onExit(({ exitCode, signal }) => resolve(signal\n ? { code: null, signal: signalName(signal) }\n : { code: exitCode, signal: null })));\n // Input chunks may split multi-byte characters; node-pty writes strings.\n const decoder = new StringDecoder('utf8');\n // ConPTY assigns the process ID asynchronously; node-pty reports 0 until then.\n const pid = () => terminal.pid > 0 ? terminal.pid : undefined;\n const kill = async () => {\n const current = pid();\n if (current !== undefined) await killProcessTree(current);\n // Closing the pseudoconsole reports the exit promptly.\n try { terminal.kill(); } catch { /* already closed */ }\n };\n return {\n get pid() { return pid(); },\n spawned: waitFor(() => pid() !== undefined, exited),\n exited,\n write: data => {\n const text = decoder.write(Buffer.from(data));\n if (text) terminal.write(text);\n },\n resize: size => terminal.resize(size.cols, size.rows),\n signal: signal => {\n // ConPTY turns ETX into a Ctrl+C event for the console's processes.\n if (signal === 'SIGINT' && process.platform === 'win32') terminal.write('\\x03');\n else if (signal === 'SIGKILL') void kill();\n else signalProcess(pid(), signal);\n },\n kill,\n };\n}\n\n/** Resolve once `condition` holds, or once `until` settles. */\nasync function waitFor(condition: () => boolean, until: Promise<unknown>): Promise<void> {\n let settled = false;\n void until.then(() => { settled = true; });\n while (!condition() && !settled) await new Promise(resolve => setTimeout(resolve, 5));\n}\n\nfunction signalProcess(pid: number | undefined, signal: ConsoleSignal): void {\n if (pid === undefined) throw new Error('The process is not running');\n if (signal === 'SIGKILL') void killProcessTree(pid);\n else if (process.platform === 'win32') throw new Error(`${signal} cannot be delivered on Windows`);\n else signalProcessGroup(pid, signal);\n}\n\ntype PtyModule = typeof import('@lydell/node-pty');\nlet ptyModule: Promise<PtyModule> | undefined;\n\nfunction loadPty(): Promise<PtyModule> {\n ptyModule ??= import('@lydell/node-pty').then(\n module => (module as { default?: PtyModule }).default ?? module,\n error => {\n ptyModule = undefined;\n throw new Error(`TTY support is unavailable: ${error instanceof Error ? error.message : String(error)}`);\n },\n );\n return ptyModule;\n}\n\ninterface ParsedCommand {\n readonly command: string;\n readonly args: string[];\n readonly file?: string;\n readonly options: { readonly windowsVerbatimArguments?: boolean };\n}\n\n/** Resolve like {@link spawnPipeProcess}: PATHEXT lookup and escaped `.cmd` shims on Windows. */\nfunction ptyCommand(command: readonly string[]): { file: string; args: string[] | string } {\n const [executable, ...args] = command;\n if (process.platform !== 'win32') return { file: executable!, args };\n const parse = (crossSpawn as unknown as { _parse(command: string, args: string[], options: object): ParsedCommand })._parse;\n const parsed = parse(executable!, args, {});\n // A shim runs through cmd.exe with an already escaped command line.\n if (parsed.options.windowsVerbatimArguments) return { file: parsed.command, args: parsed.args.join(' ') };\n return { file: parsed.file ?? parsed.command, args: parsed.args };\n}\n\nfunction signalName(signal: number): string {\n return Object.entries(os.constants.signals).find(([, value]) => value === signal)?.[0] ?? String(signal);\n}\n","import { StringDecoder } from 'node:string_decoder';\nimport type { ConsoleSignal, ConsoleSize } from '@hediet/linkrpc-infra/console';\nimport type { ParticipantDescriptor } from '@hediet/linkrpc/inspection';\nimport type { ManagedService } from './config';\nimport { LogBuffer } from './logBuffer';\nimport type { LogLine, ServiceState, ServiceStatus } from './managementInterface';\nimport { spawnPipeProcess, spawnPtyProcess, type ExitInfo, type ServiceProcess } from './processIo';\nimport { terminateProcessTree } from './processTree';\n\nconst MIN_BACKOFF_MS = 500;\nconst MAX_BACKOFF_MS = 30_000;\n/** A process that stays up this long resets the backoff. */\nconst STABLE_AFTER_MS = 10_000;\nconst KILL_WAIT_MS = 5_000;\n\n/** The hub-side resources a supervisor needs. */\nexport interface ServiceHost {\n /**\n * Open the private hub socket the service dials (`LINKRPC_ENDPOINT`/`LINKRPC_TOKEN`).\n * `descriptor` describes its peers in the hub's topology; the host picks one by default.\n */\n openSocket(\n name: string,\n service: ManagedService,\n onConnectionCountChanged: (count: number) => void,\n descriptor?: ParticipantDescriptor,\n ): Promise<ServiceSocket>;\n log(name: string, line: string): void;\n output?(name: string, stream: 'stdout' | 'stderr' | 'tty', data: Uint8Array): void;\n /** Supervisor messages, such as exits and restart backoff. */\n notice?(name: string, text: string): void;\n processStarted?(name: string, pid: number | undefined): void;\n processExited?(name: string, exit: { code: number | null; signal: string | null }): void;\n}\n\nexport interface ServiceSocket {\n readonly env: Readonly<Record<string, string>>;\n dispose(): void;\n}\n\n/**\n * Keeps one configured service in its desired state: spawns it with a hub\n * socket, tracks readiness, restarts it with exponential backoff according to\n * its restart policy, and stops it gracefully (hub disconnect, SIGTERM) before\n * killing its process tree. All state transitions are serialized.\n */\nexport class ServiceSupervisor {\n private _service: ManagedService;\n private _state: ServiceState;\n private _since = Date.now();\n private _process: ServiceProcess | undefined;\n private _socket: ServiceSocket | undefined;\n private _connections = 0;\n private _restarts = 0;\n private _consecutiveFailures = 0;\n private _lastExit: ServiceStatus['lastExit'];\n private _error: string | undefined;\n private _stopping = false;\n private _disposed = false;\n private _backoffTimer: ReturnType<typeof setTimeout> | undefined;\n private _startTimer: ReturnType<typeof setTimeout> | undefined;\n private _stableTimer: ReturnType<typeof setTimeout> | undefined;\n private _ops: Promise<void> = Promise.resolve();\n private readonly _logs = new LogBuffer();\n private readonly _decoders = { stdout: new StringDecoder('utf8'), stderr: new StringDecoder('utf8'), tty: new StringDecoder('utf8') };\n private _size: ConsoleSize = { cols: 80, rows: 24 };\n\n constructor(\n public readonly name: string,\n service: ManagedService,\n private readonly _host: ServiceHost,\n private readonly _onDidChange: () => void,\n ) {\n this._service = service;\n this._state = service.enabled ? 'stopped' : 'disabled';\n }\n\n public get service(): ManagedService {\n return this._service;\n }\n\n public status(): ServiceStatus {\n return {\n name: this.name,\n description: this._service.description,\n serviceId: this._service.serviceId,\n enabled: this._service.enabled,\n state: this._state,\n since: this._since,\n pid: this._process?.pid,\n connections: this._connections,\n restarts: this._restarts,\n lastExit: this._lastExit,\n error: this._error,\n };\n }\n\n public logs(limit?: number): LogLine[] {\n return this._logs.lines(limit);\n }\n\n public write(data: Uint8Array): void {\n this._running().write(data);\n }\n\n /** Applies to the running pseudoterminal and to later starts. */\n public resize(size: ConsoleSize): void {\n this._size = size;\n this._process?.resize(size);\n }\n\n public signal(signal: ConsoleSignal): void {\n this._running().signal(signal);\n }\n\n private _running(): ServiceProcess {\n if (!this._process) throw new Error('The process is not running');\n return this._process;\n }\n\n /** Start or stop to match `enabled`. */\n public sync(): Promise<void> {\n return this._enqueue(() => (this._service.enabled ? this._launch() : this._stop('disabled')));\n }\n\n /** Apply a change that keeps the process (see `classifyServiceChange`); only `enabled` starts or stops it. */\n public update(service: ManagedService): Promise<void> {\n const enabledChanged = service.enabled !== this._service.enabled;\n this._service = service;\n if (!enabledChanged) {\n this._onDidChange();\n return Promise.resolve();\n }\n this._logDaemon(service.enabled ? 'enabled' : 'disabled');\n return this.sync();\n }\n\n public restart(): Promise<void> {\n return this._enqueue(async () => {\n if (!this._service.enabled) throw new Error(`service '${this.name}' is disabled`);\n this._logDaemon('restart requested');\n await this._stop('stopped');\n this._consecutiveFailures = 0;\n await this._launch();\n });\n }\n\n /** Stop the service for good. */\n public dispose(): Promise<void> {\n this._disposed = true;\n return this._enqueue(() => this._stop('stopped'), { evenIfDisposed: true });\n }\n\n private _enqueue(op: () => Promise<void>, options: { evenIfDisposed?: boolean; } = {}): Promise<void> {\n const run = this._ops.then(() => (this._disposed && !options.evenIfDisposed ? undefined : op()));\n this._ops = run.catch(error => this._logDaemon(`error: ${_message(error)}`));\n return run;\n }\n\n private async _launch(): Promise<void> {\n if (this._disposed || !this._service.enabled || this._process || this._backoffTimer) return;\n await this._spawn();\n }\n\n private async _spawn(): Promise<void> {\n const service = this._service;\n if (service.command === undefined) throw new Error(`service '${this.name}' has no command`);\n try {\n if (service.rpc) {\n this._socket ??= await this._host.openSocket(this.name, service, count => this._onConnections(count));\n }\n } catch (error) {\n this._error = `cannot connect to the hub: ${_message(error)}`;\n this._logDaemon(this._error);\n this._setState('failed');\n return;\n }\n const env = { ...process.env };\n if (!service.rpc) {\n for (const key of Object.keys(env)) {\n if (/^(LINKRPC|HUBRPC)_(ENDPOINT|TOKEN)$/i.test(key)) delete env[key];\n }\n }\n const options = {\n command: service.command,\n env: { ...env, ...service.env, ...this._socket?.env },\n ...(service.cwd !== undefined ? { cwd: service.cwd } : {}),\n onOutput: (stream: 'stdout' | 'stderr' | 'tty', data: Uint8Array) => this._appendOutput(stream, data),\n onError: (message: string) => this._logDaemon(message),\n };\n let spawned: ServiceProcess;\n try {\n spawned = service.tty ? await spawnPtyProcess({ ...options, size: this._size }) : spawnPipeProcess(options);\n } catch (error) {\n this._onSpawnFailed(_message(error));\n return;\n }\n this._process = spawned;\n this._error = undefined;\n this._setState('starting');\n void spawned.spawned.then(() => {\n if (this._process === spawned) this._host.processStarted?.(this.name, spawned.pid);\n });\n if (!service.rpc || service.readiness === 'spawned') {\n void spawned.spawned.then(() => {\n if (this._process === spawned && this._state === 'starting') this._markRunning();\n });\n } else {\n this._startTimer = setTimeout(() => {\n if (this._process !== spawned || this._state !== 'starting') return;\n this._error = `did not connect to the hub within ${service.startTimeoutMs} ms`;\n this._logDaemon(this._error);\n void spawned.kill();\n }, service.startTimeoutMs);\n }\n void spawned.exited.then(info => this._onExit(spawned, info));\n }\n\n private _onSpawnFailed(error: string): void {\n this._lastExit = { code: null, signal: null, at: Date.now() };\n this._error = `cannot start: ${error}`;\n this._logDaemon(this._error);\n this._releaseSocket();\n this._setState('failed');\n }\n\n private _onExit(process: ServiceProcess, info: ExitInfo): void {\n if (this._process !== process) return;\n this._process = undefined;\n this._clearProcessTimers();\n this._lastExit = { code: info.code, signal: info.signal, at: Date.now() };\n if (info.error === undefined) this._host.processExited?.(this.name, { code: info.code, signal: info.signal });\n if (this._stopping) return;\n\n const failed = info.error !== undefined || info.code !== 0 || info.signal !== null;\n if (info.error !== undefined) this._error = `cannot start: ${info.error}`;\n else if (failed) this._error ??= _describeExit(info);\n const policy = this._service.restart;\n const restart = !this._disposed && this._service.enabled\n && (policy === 'always' || (policy === 'on-failure' && failed));\n if (!restart) {\n this._logDaemon(_describeExit(info));\n this._releaseSocket();\n this._setState(failed ? 'failed' : 'stopped');\n return;\n }\n const delay = Math.min(MAX_BACKOFF_MS, MIN_BACKOFF_MS * 2 ** this._consecutiveFailures);\n this._consecutiveFailures++;\n this._logDaemon(`${_describeExit(info)}; restarting in ${delay} ms`);\n const timer = setTimeout(() => {\n void this._enqueue(async () => {\n if (this._backoffTimer !== timer) return;\n this._backoffTimer = undefined;\n this._restarts++;\n await this._spawn();\n });\n }, delay);\n this._backoffTimer = timer;\n this._setState('backoff');\n }\n\n private async _stop(finalState: 'stopped' | 'disabled'): Promise<void> {\n clearTimeout(this._backoffTimer);\n this._backoffTimer = undefined;\n const running = this._process;\n if (running) {\n this._stopping = true;\n this._setState('stopping');\n try {\n await this._terminate(running);\n } finally {\n this._stopping = false;\n this._process = undefined;\n this._clearProcessTimers();\n }\n }\n this._releaseSocket();\n this._error = undefined;\n this._setState(finalState);\n }\n\n /** Disconnecting from the hub is the portable stop request; POSIX also gets SIGTERM. */\n private async _terminate(running: ServiceProcess): Promise<void> {\n // Windows pipe children without an RPC connection have no graceful stop channel.\n const canStopGracefully = process.platform !== 'win32' || this._connections > 0;\n this._releaseSocket();\n const pid = running.pid;\n if (canStopGracefully) {\n if (pid !== undefined) terminateProcessTree(pid);\n if (await _settlesWithin(running.exited, this._service.stopTimeoutMs)) return;\n this._logDaemon(`did not stop within ${this._service.stopTimeoutMs} ms; killing`);\n }\n await running.kill();\n if (!await _settlesWithin(running.exited, KILL_WAIT_MS)) this._logDaemon('process did not exit after kill');\n }\n\n private _onConnections(count: number): void {\n this._connections = count;\n if (count > 0 && this._state === 'starting' && this._service.readiness === 'connected') {\n this._markRunning();\n } else {\n this._onDidChange();\n }\n }\n\n private _markRunning(): void {\n clearTimeout(this._startTimer);\n this._startTimer = undefined;\n this._stableTimer = setTimeout(() => {\n this._consecutiveFailures = 0;\n }, STABLE_AFTER_MS);\n this._setState('running');\n }\n\n private _releaseSocket(): void {\n this._socket?.dispose();\n this._socket = undefined;\n this._connections = 0;\n }\n\n private _clearProcessTimers(): void {\n clearTimeout(this._startTimer);\n clearTimeout(this._stableTimer);\n this._startTimer = undefined;\n this._stableTimer = undefined;\n }\n\n private _setState(state: ServiceState): void {\n if (this._state !== state) {\n this._state = state;\n this._since = Date.now();\n }\n this._onDidChange();\n }\n\n private _appendOutput(stream: 'stdout' | 'stderr' | 'tty', data: Uint8Array): void {\n this._host.output?.(this.name, stream, data);\n const text = this._decoders[stream].write(Buffer.from(data));\n const logStream = stream === 'stderr' ? 'stderr' : 'stdout';\n for (const line of this._logs.append(logStream, stream === 'tty' ? _stripTerminalControls(text) : text)) {\n this._host.log(this.name, line);\n }\n }\n\n private _logDaemon(text: string): void {\n this._host.notice?.(this.name, text);\n this._logs.append('daemon', text + '\\n');\n this._host.log(this.name, text);\n }\n}\n\n/** Keep TTY log lines readable: drop escape sequences, carriage returns, and other controls. */\nfunction _stripTerminalControls(text: string): string {\n // eslint-disable-next-line no-control-regex\n return text.replace(/\\x1b(?:\\[[0-?]*[ -/]*[@-~]|\\][^\\x07\\x1b]*(?:\\x07|\\x1b\\\\)|[@-Z\\\\-_])|[\\x00-\\x09\\x0b-\\x1f\\x7f]/g, '');\n}\n\nfunction _describeExit(info: ExitInfo): string {\n if (info.error !== undefined) return `failed to start: ${info.error}`;\n if (info.signal !== null) return `killed by ${info.signal}`;\n return `exited with code ${info.code}`;\n}\n\nfunction _settlesWithin(promise: Promise<unknown>, ms: number): Promise<boolean> {\n return new Promise(resolve => {\n const timer = setTimeout(() => resolve(false), ms);\n void promise.then(() => {\n clearTimeout(timer);\n resolve(true);\n });\n });\n}\n\nfunction _message(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","import * as net from 'node:net';\nimport { LinkRpcConnection, type IMessageTransport } from '@hediet/linkrpc';\nimport { connectNdjson, parseEndpointUri, runInitializeHandshake, WebSocketTransport, type ResolvedEndpoint } from '@hediet/linkrpc/node';\nimport { hubGrantedServiceIdInterface } from '@hediet/linkrpc/hub/common';\nimport { spawnCommand } from '@hediet/linkrpc-hub/spawn';\nimport type { ManagedService } from './config';\nimport { LogBuffer } from './logBuffer';\nimport type { LogLine, ServiceStatus } from './managementInterface';\nimport type { ServiceHost, ServiceSocket } from './supervisor';\n\ninterface TransportHandle {\n readonly transport: IMessageTransport;\n readonly closed: Promise<void>;\n dispose(): void;\n}\n\ntype ConnectableEndpoint = Extract<ResolvedEndpoint, { kind: 'socket' | 'ws' | 'cmd-stdio' }>;\n\n/**\n * Keeps a service's `endpoint` connected to the hub: its traffic is relayed\n * through the service's participant socket, so it may serve only the granted\n * `serviceId` and its calls pass the hub's forwarded-call gate. Reconnects with\n * backoff according to the restart policy.\n */\nexport class ConnectionSupervisor {\n private _state: ServiceStatus['state'] = 'stopped';\n private _error: string | undefined;\n private _since = Date.now();\n private _restarts = 0;\n private _generation = 0;\n private _socket: ServiceSocket | undefined;\n private _target: TransportHandle | undefined;\n private _local: TransportHandle | undefined;\n private _timer: ReturnType<typeof setTimeout> | undefined;\n private _pending: Promise<void> | undefined;\n private _service: ManagedService;\n private readonly _endpoint: ConnectableEndpoint;\n private readonly _logs = new LogBuffer();\n\n constructor(\n readonly name: string,\n service: ManagedService,\n private readonly _host: ServiceHost,\n private readonly _changed: () => void,\n ) {\n if (service.endpoint === undefined) throw new Error(`service '${name}' has no endpoint`);\n const endpoint = parseEndpointUri(service.endpoint);\n if (endpoint.kind !== 'socket' && endpoint.kind !== 'ws' && endpoint.kind !== 'cmd-stdio') {\n throw new Error('Managed connections require a LinkRPC socket, WebSocket, or cmd-stdio endpoint');\n }\n this._endpoint = endpoint;\n this._service = service;\n }\n\n get service(): ManagedService { return this._service; }\n status(): ServiceStatus {\n return {\n name: this.name, description: this._service.description, serviceId: this._service.serviceId,\n enabled: this._service.enabled, state: this._state, since: this._since,\n connections: this._state === 'running' ? 1 : 0, restarts: this._restarts, error: this._error,\n };\n }\n logs(limit?: number): LogLine[] {\n return this._logs.lines(limit);\n }\n async sync(): Promise<void> {\n if (!this._service.enabled) return this.dispose();\n if (this._state === 'running' || this._state === 'starting' || this._state === 'backoff') return;\n this._pending = this._connect(++this._generation);\n await this._pending;\n }\n async update(service: ManagedService): Promise<void> {\n const enabledChanged = this._service.enabled !== service.enabled;\n this._service = service;\n if (enabledChanged) await this.sync();\n this._changed();\n }\n input(): never { throw new Error('A connected endpoint has no managed process console'); }\n async restart(): Promise<void> {\n if (!this._service.enabled) throw new Error(`service '${this.name}' is disabled`);\n this._logDaemon('restart requested');\n await this.dispose();\n await this.sync();\n }\n async dispose(): Promise<void> {\n ++this._generation;\n clearTimeout(this._timer);\n this._cleanup();\n await this._pending;\n this._setState('stopped');\n }\n private async _connect(generation: number): Promise<void> {\n this._error = undefined;\n this._setState('starting');\n try {\n const target = await this._openTarget();\n if (generation !== this._generation) { target.dispose(); return; }\n this._target = target;\n this._socket = await this._host.openSocket(this.name, this._service, () => {});\n if (generation !== this._generation) { this._cleanup(); return; }\n const env = this._socket.env;\n const local = await openTransport(parseEndpointUri(env.LINKRPC_ENDPOINT ?? env.HUBRPC_ENDPOINT!), env.LINKRPC_TOKEN ?? env.HUBRPC_TOKEN);\n if (generation !== this._generation) { local.dispose(); this._cleanup(); return; }\n this._local = local;\n // Claims are performed before handing the transport to the remote endpoint.\n const registration = LinkRpcConnection.fromTransport(local.transport);\n await registration.get(hubGrantedServiceIdInterface).register({ serviceId: this._service.serviceId });\n local.transport.setListener(message => target.transport.send(message));\n target.transport.setListener(message => local.transport.send(message));\n this._setState('running');\n void Promise.race([local.closed, target.closed]).then(() => {\n if (generation === this._generation) this._failed(generation, new Error('Endpoint disconnected'));\n });\n } catch (error) {\n if (generation === this._generation) this._failed(generation, error);\n }\n }\n private _failed(generation: number, error: unknown): void {\n this._cleanup();\n this._error = error instanceof Error ? error.message : String(error);\n this._logDaemon(this._error);\n if (this._service.restart === 'never') {\n this._setState('failed');\n } else {\n this._setState('backoff');\n this._timer = setTimeout(() => {\n if (generation !== this._generation) return;\n this._restarts++;\n this._pending = this._connect(generation);\n }, Math.min(30_000, 500 * 2 ** Math.min(this._restarts, 6)));\n }\n }\n private _cleanup(): void {\n this._target?.dispose(); this._target = undefined;\n this._local?.dispose(); this._local = undefined;\n this._socket?.dispose(); this._socket = undefined;\n }\n private _setState(state: ServiceStatus['state']): void {\n this._state = state; this._since = Date.now(); this._changed();\n }\n private _openTarget(): Promise<TransportHandle> {\n if (this._endpoint.kind !== 'cmd-stdio') return openTransport(this._endpoint);\n return openCommandTransport(this._endpoint, line => {\n this._logs.append('stderr', line + '\\n');\n this._host.log(this.name, line);\n });\n }\n private _logDaemon(text: string): void {\n this._host.notice?.(this.name, text);\n this._logs.append('daemon', text + '\\n');\n this._host.log(this.name, text);\n }\n}\n\n/** Spawn the endpoint's command and speak handshake-free newline-delimited JSON-RPC over its stdio. */\nasync function openCommandTransport(\n endpoint: Extract<ConnectableEndpoint, { kind: 'cmd-stdio' }>,\n onStderrLine: (line: string) => void,\n): Promise<TransportHandle> {\n const child = spawnCommand(endpoint.command, {\n stdio: ['pipe', 'pipe', 'pipe'],\n env: { ...process.env, ...endpoint.env },\n windowsHide: true,\n ...(endpoint.cwd !== undefined ? { cwd: endpoint.cwd } : {}),\n });\n const kill = () => { if (child.exitCode === null && !child.killed) child.kill(); };\n const closed = new Promise<void>(resolve => {\n child.once('exit', () => resolve());\n child.once('error', () => resolve());\n });\n let partial = '';\n child.stderr!.setEncoding('utf8');\n child.stderr!.on('data', (chunk: string) => {\n const lines = (partial + chunk).split(/\\r?\\n/);\n partial = lines.pop()!;\n for (const line of lines) if (line.length > 0) onStderrLine(line);\n });\n await new Promise<void>((resolve, reject) => {\n child.once('spawn', resolve);\n child.once('error', reject);\n });\n const { transport } = await connectNdjson({ input: child.stdout!, output: child.stdin!, onClose: kill });\n return { transport, closed, dispose: () => { transport.dispose(); kill(); } };\n}\n\nasync function openTransport(endpoint: ResolvedEndpoint, token?: string): Promise<TransportHandle> {\n if (endpoint.kind === 'socket') {\n const socket = net.createConnection(endpoint.path);\n socket.setTimeout(10_000, () => socket.destroy(new Error('Endpoint initialization timed out')));\n const closed = new Promise<void>(resolve => socket.once('close', () => resolve()));\n try {\n const { transport } = await connectNdjson({\n input: socket, output: socket, onClose: () => socket.destroy(),\n initialize: { kind: 'client', token: token ?? endpoint.token ?? '' },\n });\n socket.setTimeout(0);\n return { transport, closed, dispose: () => socket.destroy() };\n } catch (error) { socket.destroy(); throw error; }\n }\n if (endpoint.kind === 'ws') {\n const ws = new WebSocket(endpoint.url);\n await new Promise<void>((resolve, reject) => {\n const finish = (error?: Error) => {\n clearTimeout(timeout);\n ws.removeEventListener('open', opened);\n ws.removeEventListener('error', failed);\n if (error) { ws.close(); reject(error); } else resolve();\n };\n const opened = () => finish();\n const failed = () => finish(new Error('WebSocket connection failed'));\n const timeout = setTimeout(() => finish(new Error('WebSocket connection timed out')), 10_000);\n ws.addEventListener('open', opened, { once: true });\n ws.addEventListener('error', failed, { once: true });\n });\n const closed = new Promise<void>(resolve => ws.addEventListener('close', () => resolve(), { once: true }));\n const transport = new WebSocketTransport(ws, () => ws.close());\n try {\n await runInitializeHandshake(transport, { kind: 'client', token: token ?? endpoint.token ?? '' });\n return { transport, closed, dispose: () => transport.dispose() };\n } catch (error) { transport.dispose(); throw error; }\n }\n throw new Error('Managed connections require a LinkRPC socket or WebSocket endpoint');\n}\n","import * as headlessModule from '@xterm/headless';\nimport * as serializeModule from '@xterm/addon-serialize';\nimport {\n encodeConsoleData,\n type ConsoleHistory,\n type ConsoleRecord,\n type ConsoleServerMessage,\n type ConsoleSize,\n} from '@hediet/linkrpc-infra/console';\n\n// Node loads these packages as CommonJS (exports on `default`); bundlers may pick their ESM builds.\nconst { Terminal } = commonJsInterop(headlessModule);\nconst { SerializeAddon } = commonJsInterop(serializeModule);\n\n/**\n * Replays a TTY as its current screen and scrollback instead of raw bytes, so\n * that full-screen programs render correctly for attachments that join late.\n */\nexport class ScreenHistory implements ConsoleHistory {\n private readonly _terminal: InstanceType<typeof Terminal>;\n private readonly _serializer = new SerializeAddon();\n\n constructor(size: ConsoleSize, scrollback = 1000) {\n this._terminal = new Terminal({ cols: size.cols, rows: size.rows, scrollback, allowProposedApi: true });\n this._terminal.loadAddon(this._serializer);\n }\n\n append(record: ConsoleRecord): void {\n if (record.type === 'output') this._terminal.write(record.data);\n }\n\n resize(size: ConsoleSize): void {\n this._terminal.resize(size.cols, size.rows);\n }\n\n snapshot(): Promise<readonly ConsoleServerMessage[]> {\n // Writes parse in order: this callback runs after earlier output and before later output.\n return new Promise(resolve => this._terminal.write('', () => {\n const screen = this._serializer.serialize();\n resolve([{ t: 'screen', data: encodeConsoleData(new TextEncoder().encode(screen)) }]);\n }));\n }\n\n dispose(): void {\n this._terminal.dispose();\n }\n}\n\nfunction commonJsInterop<T extends object>(module: T): T {\n return (module as { default?: T }).default ?? module;\n}\n","import { createHash, randomUUID } from 'node:crypto';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport { z } from 'zod';\nimport type { LinkRpcConnection, StreamApi } from '@hediet/linkrpc';\nimport { ConsoleHost, consoleHandlers, type ConsoleClientMessage, type ConsoleExit, type ConsoleSize } from '@hediet/linkrpc-infra/console';\nimport {\n endpointDefinition,\n managedEndpointsInterface,\n type EndpointAddress,\n type EndpointDefinition,\n type EndpointStatus,\n type RunEvent,\n type RunParams,\n type WatchEvent,\n} from './endpointInterface';\nimport { ManagedServiceSchema, type ManagedService } from './config';\nimport { writePrivateJson } from './discovery';\nimport { endpointDescriptor } from './participantDescriptors';\nimport { processSignals } from './processIo';\nimport { ScreenHistory } from './screenHistory';\nimport { ServiceSupervisor, type ServiceHost } from './supervisor';\nimport { ConnectionSupervisor } from './connectionSupervisor';\n\nconst storedEndpoints = z.array(z.object({ definition: endpointDefinition, desired: z.boolean() }));\nconst finishedStates = new Set(['failed', 'stopped', 'disabled']);\n\ninterface Entry {\n definition: EndpointDefinition;\n desired: boolean;\n readonly instanceId: string;\n /** Owned by a `run` call: it is never persisted or restored. */\n readonly owned: boolean;\n readonly supervisor: ServiceSupervisor | ConnectionSupervisor;\n readonly console: ConsoleHost | undefined;\n readonly listeners: Set<() => void>;\n removed: boolean;\n}\n\nexport interface ManagedEndpointsOptions {\n readonly file: string;\n /** Published endpoint service IDs: `<servicePrefix>/<sha256(namespace)>/<id>`. */\n readonly servicePrefix: string;\n readonly host: ServiceHost;\n}\n\nexport class ManagedEndpoints {\n private readonly _entries = new Map<string, Entry>();\n private _ops = Promise.resolve();\n private _closing = false;\n\n constructor(private readonly _options: ManagedEndpointsOptions) {}\n\n snapshot(): { definition: EndpointDefinition; desired: boolean }[] {\n return [...this._entries.values()].filter(entry => !entry.owned)\n .map(entry => ({ definition: entry.definition, desired: entry.desired }));\n }\n\n async restore(snapshot?: ReturnType<ManagedEndpoints['snapshot']>): Promise<void> {\n if (snapshot !== undefined) {\n for (const { definition, desired } of snapshot) await this._restoreEntry(definition, desired);\n return;\n }\n let text: string;\n try { text = fs.readFileSync(this._options.file, 'utf8'); }\n catch (error) {\n if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return;\n throw error;\n }\n for (const { definition, desired } of storedEndpoints.parse(JSON.parse(text))) {\n await this._restoreEntry(definition, desired && definition.restart !== 'never');\n }\n }\n\n private async _restoreEntry(definition: EndpointDefinition, desired: boolean): Promise<void> {\n if (this._entries.has(key(definition))) throw new Error('Duplicate persisted endpoint');\n const entry = this._add(definition, desired, { owned: false });\n if (entry.desired) await entry.supervisor.sync();\n }\n\n register(connection: LinkRpcConnection, serviceId?: string): { dispose(): void } {\n return connection.register(managedEndpointsInterface, {\n consoles: consoleHandlers(address => {\n const console = this._get(address).console;\n if (!console) throw new Error(`Endpoint \"${address.id}\" is a connection and has no console`);\n return console;\n }),\n info: () => ({ hostname: os.hostname(), platform: process.platform, cwd: process.cwd(), servicePrefix: this._options.servicePrefix }),\n list: ({ namespace }) => this.list(namespace),\n create: ({ replace, ...definition }) => this._serialize(async () =>\n this._status(await this._create(definition, { owned: false, replace: replace ?? false }))),\n run: (params, _context, stream) => this._run(params, stream),\n watch: async (address, _context, stream) => {\n await this._watch(this._get(address), stream);\n return {};\n },\n start: address => this._serialize(async () => {\n const entry = this._get(address);\n this._setDesired(entry, true);\n await entry.supervisor.update({ ...entry.supervisor.service, enabled: true });\n await entry.supervisor.sync();\n return this._status(entry);\n }),\n stop: address => this._serialize(async () => {\n const entry = this._get(address);\n this._setDesired(entry, false);\n await entry.supervisor.update({ ...entry.supervisor.service, enabled: false });\n if (!entry.definition.persistent) this._removeEntry(entry);\n return {};\n }),\n remove: address => this._serialize(async () => {\n const entry = this._get(address);\n this._entries.delete(key(entry.definition));\n try { this._save(); } catch (error) { this._entries.set(key(entry.definition), entry); throw error; }\n await entry.supervisor.dispose();\n this._removeEntry(entry);\n return {};\n }),\n configure: params => this._serialize(async () => {\n const entry = this._get(params);\n if (entry.owned && params.persistent) throw new Error('A foreground (owned) endpoint cannot be persistent');\n const definition = {\n ...entry.definition,\n ...(params.persistent === undefined ? {} : { persistent: params.persistent }),\n ...(params.restart === undefined ? {} : { restart: params.restart }),\n };\n const previous = entry.definition;\n entry.definition = definition;\n try { this._save(); } catch (error) { entry.definition = previous; throw error; }\n await entry.supervisor.update({ ...entry.supervisor.service, restart: definition.restart });\n this._changed(entry);\n return this._status(entry);\n }),\n }, serviceId === undefined ? undefined : { serviceId });\n }\n\n list(namespace?: string): EndpointStatus[] {\n return [...this._entries.values()].filter(entry => namespace === undefined || entry.definition.namespace === namespace)\n .map(entry => this._status(entry));\n }\n\n async dispose(): Promise<void> {\n this._closing = true;\n await this._ops;\n await Promise.all([...this._entries.values()].map(entry => entry.supervisor.dispose()));\n for (const entry of this._entries.values()) entry.console?.close();\n }\n\n private async _run(\n { definition, owner = false, replace = false, console: attach }: RunParams,\n stream: StreamApi<ConsoleClientMessage, RunEvent>,\n ): Promise<{ exit: ConsoleExit | null }> {\n if (owner && definition.persistent) throw new Error('A foreground (owned) endpoint cannot be persistent');\n const entry = await this._serialize(async () => {\n stream.signal.throwIfAborted();\n return this._create(definition, { owned: owner, replace, ...(attach.size ? { size: attach.size } : {}) });\n });\n const sendStatus = () => { stream.send({ t: 'status', status: this._status(entry) }).catch(() => {}); };\n entry.listeners.add(sendStatus);\n try {\n sendStatus();\n return await entry.console!.attach(attach, stream);\n } finally {\n entry.listeners.delete(sendStatus);\n // Shutdown already disposes every supervisor. Otherwise cleanup owns\n // this exact instance, never a replacement using the same name.\n if (owner && !this._closing) {\n await this._serialize(async () => {\n await entry.supervisor.dispose();\n this._removeEntry(entry);\n });\n }\n }\n }\n\n private async _create(\n definition: EndpointDefinition,\n options: { readonly owned: boolean; readonly replace: boolean; readonly size?: ConsoleSize },\n ): Promise<Entry> {\n const existing = this._entries.get(key(definition));\n if (existing) {\n if (!options.replace) throw new Error(`Endpoint \"${definition.id}\" already exists in ${definition.namespace}`);\n existing.console?.notice('Replaced by a new launch of the same endpoint.');\n await existing.supervisor.dispose();\n this._removeEntry(existing);\n }\n const entry = this._add(definition, true, options);\n try {\n this._save();\n await entry.supervisor.sync();\n return entry;\n } catch (error) {\n await entry.supervisor.dispose();\n this._removeEntry(entry);\n throw error;\n }\n }\n\n private async _watch(entry: Entry, stream: Pick<StreamApi<never, WatchEvent>, 'signal' | 'send'>): Promise<void> {\n let dirty = true;\n let wake: (() => void) | undefined;\n const notify = () => { dirty = true; wake?.(); };\n entry.listeners.add(notify);\n stream.signal.addEventListener('abort', notify);\n try {\n while (!stream.signal.aborted) {\n dirty = false;\n if (entry.removed) {\n await stream.send({ t: 'removed' });\n return;\n }\n await stream.send({ t: 'status', status: this._status(entry) });\n if (!dirty) await new Promise<void>(resolve => { wake = resolve; if (dirty || stream.signal.aborted) resolve(); });\n wake = undefined;\n }\n } finally {\n entry.listeners.delete(notify);\n stream.signal.removeEventListener('abort', notify);\n }\n }\n\n private _add(definition: EndpointDefinition, desired: boolean, options: { readonly owned: boolean; readonly size?: ConsoleSize }): Entry {\n const digest = createHash('sha256').update(definition.namespace).digest('hex');\n const name = `${digest.slice(0, 16)}-${definition.id}`;\n const serviceId = `${this._options.servicePrefix}/${digest}/${definition.id}`;\n const source = definition.source;\n const service: ManagedService = {\n ...ManagedServiceSchema.parse({\n ...(source.kind === 'process' ? {\n command: source.command, env: source.env, cwd: source.cwd,\n readiness: source.readiness, rpc: source.rpc, tty: source.tty,\n } : { endpoint: source.endpoint }),\n enabled: desired, restart: definition.restart, serviceId,\n }),\n serviceId,\n };\n let entry: Entry;\n const host: ServiceHost = {\n openSocket: (socketName, socketService, onConnectionCountChanged) => this._options.host.openSocket(\n socketName, socketService, onConnectionCountChanged,\n endpointDescriptor(definition.id, definition.namespace, serviceId),\n ),\n log: (...args) => this._options.host.log(...args),\n output: (_name, stream, data) => entry.console?.output(stream, data),\n notice: (_name, text) => entry.console?.notice(text),\n processStarted: (_name, pid) => entry.console?.started(pid),\n processExited: (_name, exit) => entry.console?.exited(exit),\n };\n let supervisor: ServiceSupervisor | ConnectionSupervisor;\n let console: Entry['console'];\n if (source.kind === 'process') {\n const processSupervisor = new ServiceSupervisor(name, service, host, () => this._changed(entry));\n const size = source.tty ? options.size ?? { cols: 80, rows: 24 } : undefined;\n if (size) processSupervisor.resize(size);\n const consoleHost = new ConsoleHost({\n mode: source.tty ? 'tty' : 'pipe',\n signals: processSignals(source.tty),\n backend: processSupervisor,\n ...(size ? { size, history: new ScreenHistory(size) } : {}),\n });\n if (!desired) consoleHost.finish();\n supervisor = processSupervisor;\n console = consoleHost;\n } else {\n supervisor = new ConnectionSupervisor(name, service, host, () => this._changed(entry));\n }\n entry = { definition, desired, owned: options.owned, supervisor, console, instanceId: randomUUID(), listeners: new Set(), removed: false };\n this._entries.set(key(definition), entry);\n return entry;\n }\n\n private _changed(entry: Entry): void {\n for (const listener of entry.listeners) listener();\n if (!finishedStates.has(entry.supervisor.status().state)) return;\n entry.console?.finish();\n if (!this._closing && !entry.removed && !entry.definition.persistent) this._removeEntry(entry);\n }\n\n private _removeEntry(entry: Entry): void {\n if (entry.removed) return;\n if (this._entries.get(key(entry.definition)) === entry) this._entries.delete(key(entry.definition));\n entry.removed = true;\n entry.console?.close();\n for (const listener of entry.listeners) listener();\n }\n\n private _get(address: EndpointAddress): Entry {\n const entry = this._entries.get(key(address));\n if (!entry) throw new Error(`Endpoint \"${address.id}\" not found in ${address.namespace}`);\n return entry;\n }\n\n private _status(entry: Entry): EndpointStatus {\n const source = entry.definition.source;\n return {\n namespace: entry.definition.namespace, id: entry.definition.id, instanceId: entry.instanceId,\n serviceId: entry.supervisor.service.serviceId, persistent: entry.definition.persistent,\n restart: entry.definition.restart, desired: entry.desired, owned: entry.owned, sourceKind: source.kind,\n rpc: source.kind === 'connection' || source.rpc,\n ...(entry.console ? { console: { mode: entry.console.mode } } : {}),\n runtime: entry.supervisor.status(),\n };\n }\n\n private _save(): void {\n writePrivateJson(this._options.file, [...this._entries.values()].filter(entry => entry.definition.persistent)\n .map(entry => ({ definition: entry.definition, desired: entry.desired })));\n }\n\n private _setDesired(entry: Entry, desired: boolean): void {\n const previous = entry.desired;\n entry.desired = desired;\n try { this._save(); } catch (error) { entry.desired = previous; throw error; }\n }\n\n private _serialize<T>(operation: () => Promise<T>): Promise<T> {\n if (this._closing) return Promise.reject(new Error('Daemon is stopping'));\n const result = this._ops.then(operation);\n this._ops = result.then(() => {}, error => this._options.host.log('management', String(error)));\n return result;\n }\n}\n\nfunction key(address: EndpointAddress): string { return JSON.stringify([address.namespace, address.id]); }\n","import { randomBytes, timingSafeEqual } from 'node:crypto';\nimport * as fs from 'node:fs';\nimport { LinkRpcConnection } from '@hediet/linkrpc';\nimport { type HubConfig, runHub, type RunningHub } from '@hediet/linkrpc-hub';\nimport { type NodeSocketTransport, SocketServer } from '@hediet/linkrpc-hub/hub/server/node';\nimport { classifyServiceChange, type DaemonConfig, type ManagedService, parseDaemonConfig, parseDaemonConfigText, setCallLogLevelInText, setServiceEnabledInText, stableKey } from './config';\nimport { CallLog } from './callLog/callLog';\nimport type { CallLogLevel } from './callLog/callRecord';\nimport { ConfigFile } from './configFile';\nimport { DaemonLog } from './daemonLog';\nimport { readEndpointDiscovery, writePrivateJson, type EndpointDiscovery } from './discovery';\nimport { type DaemonStatus, hubDaemonManagementInterface } from './managementInterface';\nimport { packageVersion } from './packageInfo';\nimport { HubHome } from './paths';\nimport { SingleInstanceLock } from './singleInstance';\nimport { type ServiceHost, ServiceSupervisor } from './supervisor';\nimport { ConnectionSupervisor } from './connectionSupervisor';\nimport * as path from 'node:path';\nimport { ManagedEndpoints } from './managedEndpoints';\nimport { serviceDescriptor } from './participantDescriptors';\nimport type { ParticipantDescriptor } from '@hediet/linkrpc/inspection';\n\nexport interface StartHubDaemonOptions {\n readonly home?: HubHome;\n /** Also write the log to stderr. */\n readonly echoLog?: boolean;\n}\n\ninterface LocalEndpoint {\n readonly path: string;\n readonly token: string | undefined;\n}\n\n/**\n * The per-user hub daemon. Runs a LinkRPC hub with a private local endpoint,\n * supervises the configured services, applies config file changes\n * incrementally, and serves the management API.\n *\n * Reconciliation rules: a change to hub-wide settings restarts the hub and\n * every service; otherwise only added, removed, or changed services are\n * touched, and changes to `enabled`, `restart`, timeouts, or `description`\n * keep the process running. An invalid file keeps the running configuration.\n */\nexport class HubDaemon {\n public static async start(options: StartHubDaemonOptions = {}): Promise<HubDaemon> {\n const home = options.home ?? HubHome.resolve();\n _ensurePrivateDirs(home);\n const lock = await SingleInstanceLock.acquire(home.lockEndpoint);\n const log = DaemonLog.open(home.logFile, { echo: options.echoLog ?? false });\n const daemon = new HubDaemon(home, lock, log);\n try {\n await daemon._start();\n return daemon;\n } catch (error) {\n log.line(`startup failed: ${_message(error)}`);\n await daemon.shutdown();\n throw error;\n }\n }\n\n public readonly startedAt = Date.now();\n public readonly version = packageVersion();\n /** Resolves once the daemon has shut down. */\n public readonly done: Promise<void>;\n\n private readonly _configFile: ConfigFile;\n private _appPath: string;\n private readonly _management: LocalEndpoint & { readonly token: string; };\n private readonly _services = new Map<string, ServiceSupervisor | ConnectionSupervisor>();\n private readonly _statusListeners = new Set<() => void>();\n private readonly _serviceHost: ServiceHost;\n private _endpoints: ManagedEndpoints | undefined;\n private readonly _endpointRegistrations = new Map<LinkRpcConnection, { dispose(): void } | undefined>();\n private _managementLink: { dispose(): void } | undefined;\n private _hub: RunningHub | undefined;\n private _hubKey: string | undefined;\n private readonly _callLog: CallLog;\n private _callLogAttachment: { dispose(): void } | undefined;\n private _hubStartedAt = 0;\n private _hubError: string | undefined;\n private _seenRevision: string | undefined;\n private _appliedRevision: string | undefined;\n private _appliedAt: number | undefined;\n private _configError: string | undefined;\n private _reconcile: Promise<void> = Promise.resolve();\n private _managementServer: SocketServer | undefined;\n private _watcher: { dispose(): void; } | undefined;\n private _statusChangeScheduled = false;\n private _stopping = false;\n /** While the hub restarts, its services are stopped and not yet re-added. */\n private _restartingHub = false;\n private _shutdown: Promise<void> | undefined;\n private _resolveDone!: () => void;\n\n private constructor(\n public readonly home: HubHome,\n private readonly _lock: SingleInstanceLock,\n private readonly _log: DaemonLog,\n ) {\n this.done = new Promise(resolve => { this._resolveDone = resolve; });\n this._configFile = new ConfigFile(home.configFile, home.configSchemaFile);\n this._callLog = new CallLog(home.callLogDir, this.startedAt, level => this.setCallLogLevel(level));\n this._appPath = home.defaultAppEndpoint;\n this._management = { path: home.allocEndpoint('management'), token: _token() };\n this._serviceHost = {\n openSocket: (name, service, onConnectionCountChanged, descriptor) =>\n this._openServiceSocket(name, service, onConnectionCountChanged, descriptor ?? serviceDescriptor(name, service.serviceId)),\n log: (name, line) => this._log.line(`[${name}] ${line}`),\n };\n }\n\n public status(): DaemonStatus {\n return {\n pid: process.pid,\n version: this.version,\n startedAt: this.startedAt,\n endpoint: this._appPath,\n configFile: this.home.configFile,\n logFile: this.home.logFile,\n config: { revision: this._appliedRevision, appliedAt: this._appliedAt, error: this._configError },\n hub: {\n startedAt: this._hubStartedAt,\n listeners: this._hub?.listeners.map(({ type, address }) => ({ type, address })) ?? [],\n error: this._hubError,\n },\n callLog: this._callLog.status(),\n services: [...this._services.values()]\n .map(service => service.status())\n .sort((a, b) => a.name.localeCompare(b.name)),\n };\n }\n\n /** Coalesced: fires at most once per microtask turn. */\n public onDidChangeStatus(listener: () => void): { dispose(): void; } {\n this._statusListeners.add(listener);\n return { dispose: () => this._statusListeners.delete(listener) };\n }\n\n /**\n * Re-read the config file and apply what changed. Without `force`, an\n * unchanged file is a no-op; with it, a hub that failed to start is retried.\n */\n public reload(options: { force?: boolean; } = {}): Promise<void> {\n return this._serialize(() => this._reload(options.force ?? false));\n }\n\n public restartService(name: string): Promise<void> {\n return this._service(name).restart();\n }\n\n /** Persist `enabled` in the config file and apply it. */\n public async setServiceEnabled(name: string, enabled: boolean): Promise<void> {\n const document = this._configFile.read();\n this._configFile.write(setServiceEnabledInText(document.text, name, enabled), document.revision);\n await this.reload();\n }\n\n /** Persist `callLog.level` in the config file and apply it; the hub keeps running. */\n public async setCallLogLevel(level: CallLogLevel): Promise<void> {\n const document = this._configFile.read();\n this._configFile.write(setCallLogLevelInText(document.text, level), document.revision);\n await this.reload();\n }\n\n public async setConfig(text: string, expectedRevision: string): Promise<string> {\n const revision = this._configFile.write(text, expectedRevision);\n await this.reload();\n return revision;\n }\n\n public shutdown(): Promise<void> {\n this._shutdown ??= this._doShutdown();\n return this._shutdown;\n }\n\n private async _start(): Promise<void> {\n this._log.line(`starting LinkRPC hub daemon ${this.version} (pid ${process.pid})`);\n this._configFile.ensureExists();\n const document = this._configFile.read();\n this._seenRevision = document.revision;\n let config: DaemonConfig;\n try {\n config = parseDaemonConfigText(document.text);\n this._appliedRevision = document.revision;\n this._appliedAt = Date.now();\n } catch (error) {\n this._configError = _message(error);\n this._log.line(`config is invalid; starting without services: ${this._configError}`);\n config = parseDaemonConfig({});\n }\n await this._serialize(() => this._apply(config));\n await this._startManagementServer();\n writePrivateJson(this.home.managementFile, this._discovery(this._management));\n this._watcher = this._configFile.watch(() => void this.reload());\n this._log.line(`ready: hub endpoint ${this._appPath}`);\n }\n\n private async _reload(force: boolean): Promise<void> {\n if (this._stopping) return;\n const document = this._configFile.read();\n if (!force && document.revision === this._seenRevision) return;\n this._seenRevision = document.revision;\n let config: DaemonConfig;\n try {\n config = parseDaemonConfigText(document.text);\n } catch (error) {\n this._configError = _message(error);\n this._log.line(`config is invalid; keeping the running configuration: ${this._configError}`);\n this._changed();\n return;\n }\n this._configError = undefined;\n await this._apply(config);\n this._appliedRevision = document.revision;\n this._appliedAt = Date.now();\n this._changed();\n }\n\n private async _apply(config: DaemonConfig): Promise<void> {\n // The call log is not a hub setting: it follows the config without a hub restart.\n this._callLog.configure(config.callLog);\n const hubKey = stableKey({ hub: config.hub, localEndpoint: config.localEndpoint });\n if (hubKey !== this._hubKey || !this._hub) {\n if (this._hub) this._log.line('hub settings changed; restarting the hub and all services');\n this._restartingHub = true;\n await this._disposeAllServices();\n const endpointSnapshot = this._endpoints?.snapshot();\n await this._endpoints?.dispose();\n this._endpoints = undefined;\n for (const [connection, registration] of this._endpointRegistrations) {\n registration?.dispose();\n this._endpointRegistrations.set(connection, undefined);\n }\n this._managementLink?.dispose();\n this._callLogAttachment?.dispose();\n this._callLogAttachment = undefined;\n this._hub?.dispose();\n this._hub = undefined;\n fs.rmSync(this.home.discoveryFile, { force: true });\n this._hubKey = hubKey;\n this._appPath = config.localEndpoint.path ?? this.home.defaultAppEndpoint;\n try {\n this._hub = await this._startHub(config);\n this._endpoints = new ManagedEndpoints({\n file: path.join(this.home.stateDir, 'endpoints.json'),\n servicePrefix: `${config.hub.hubServiceId}/services`,\n host: this._serviceHost,\n });\n await this._endpoints.restore(endpointSnapshot);\n for (const connection of this._endpointRegistrations.keys()) {\n this._endpointRegistrations.set(connection, this._endpoints.register(connection));\n }\n const serviceId = `${config.hub.hubServiceId}/daemon`;\n const link = this._hub.hub.attachOut({ routePrefixes: [serviceId] });\n const connection = LinkRpcConnection.fromTransport(link.transport);\n this._endpoints.register(connection, serviceId);\n connection.enableReflection({ serviceId });\n this._managementLink = { dispose: () => { connection.close(); link.dispose(); } };\n this._callLogAttachment = this._callLog.attach(this._hub.inspection, connection, serviceId);\n this._hubStartedAt = Date.now();\n this._hubError = undefined;\n writePrivateJson(this.home.discoveryFile, this._discovery({ path: this._appPath, token: config.localEndpoint.token }));\n } catch (error) {\n this._hubError = _message(error);\n this._log.line(`the hub failed to start: ${this._hubError}`);\n }\n this._changed();\n }\n const removed = [...this._services.keys()].filter(name => !Object.hasOwn(config.services, name));\n // Stop removed services first: a renamed service must release its resources (ports, devices)\n // before its successor starts.\n await Promise.all(removed.map(name => this._removeService(name)));\n // New services are added synchronously, so lookups see them from here on.\n this._restartingHub = false;\n await Promise.all(Object.entries(config.services).map(([name, service]) => this._applyService(name, service)));\n }\n\n private async _applyService(name: string, service: ManagedService): Promise<void> {\n const existing = this._services.get(name);\n if (existing) {\n const change = classifyServiceChange(existing.service, service);\n if (change === 'none') return;\n if (change === 'inPlace') {\n await existing.update(service);\n return;\n }\n this._log.line(`[${name}] configuration changed; restarting`);\n await existing.dispose();\n } else {\n this._log.line(`[${name}] added`);\n }\n const supervisor = service.endpoint !== undefined\n ? new ConnectionSupervisor(name, service, this._serviceHost, () => this._changed())\n : new ServiceSupervisor(name, service, this._serviceHost, () => this._changed());\n this._services.set(name, supervisor);\n this._changed();\n await supervisor.sync();\n }\n\n private async _removeService(name: string): Promise<void> {\n const supervisor = this._services.get(name)!;\n this._services.delete(name);\n this._log.line(`[${name}] removed`);\n this._changed();\n await supervisor.dispose();\n }\n\n private async _disposeAllServices(): Promise<void> {\n const services = [...this._services.values()];\n this._services.clear();\n await Promise.all(services.map(service => service.dispose()));\n this._changed();\n }\n\n private _startHub({ hub: hubConfig, localEndpoint }: DaemonConfig): Promise<RunningHub> {\n const config: HubConfig = {\n ...hubConfig,\n listeners: [\n ...hubConfig.listeners,\n {\n type: 'socket',\n path: this._appPath,\n handlers: [localEndpoint.token !== undefined\n ? { token: 'static', value: localEndpoint.token }\n : { token: 'anonymous' }],\n },\n ],\n };\n return runHub({\n config,\n log: line => this._log.line(`[hub] ${line}`),\n identityStoreDir: this.home.identityDir,\n });\n }\n\n private async _openServiceSocket(\n name: string,\n service: ManagedService,\n onConnectionCountChanged: (count: number) => void,\n descriptor: ParticipantDescriptor,\n ) {\n if (!this._hub) throw new Error('the hub is not running');\n return this._hub.openParticipantSocket({\n path: this.home.allocEndpoint(`service-${name}`),\n provision: {\n grantedServiceId: service.serviceId,\n managedIdentity: service.managedIdentity ? { slot: `service:${name}` } : undefined,\n },\n descriptor,\n onConnectionCountChanged,\n });\n }\n\n private async _startManagementServer(): Promise<void> {\n const server = await SocketServer.start({\n endpoint: this._management.path,\n isTokenAccepted: async token => _tokensEqual(token, this._management.token),\n });\n server.setConnectionHandler((transport: NodeSocketTransport) => {\n const connection = LinkRpcConnection.fromTransport(transport);\n this._registerManagement(connection);\n transport.onDidClose(() => {\n this._endpointRegistrations.get(connection)?.dispose();\n this._endpointRegistrations.delete(connection);\n connection.close();\n });\n });\n this._managementServer = server;\n }\n\n private _registerManagement(connection: LinkRpcConnection): void {\n this._endpointRegistrations.set(connection, this._endpoints?.register(connection));\n connection.register(hubDaemonManagementInterface, {\n getStatus: () => this.status(),\n watchStatus: async (_params, _ctx, stream) => {\n await stream.send(this.status());\n const subscription = this.onDidChangeStatus(() => {\n stream.send(this.status()).catch(() => { /* the watcher went away */ });\n });\n try {\n await new Promise<void>(resolve => {\n if (stream.signal.aborted) resolve();\n else stream.signal.addEventListener('abort', () => resolve(), { once: true });\n });\n } finally {\n subscription.dispose();\n }\n return {};\n },\n reloadConfig: async () => {\n await this.reload({ force: true });\n return this.status();\n },\n getConfig: () => this._configFile.read(),\n setConfig: async ({ text, expectedRevision }) => ({ revision: await this.setConfig(text, expectedRevision) }),\n setServiceEnabled: async ({ name, enabled }) => {\n await this.setServiceEnabled(name, enabled);\n return {};\n },\n restartService: async ({ name }) => {\n await this.restartService(name);\n return {};\n },\n getServiceLogs: ({ name, limit }) => ({ lines: this._service(name).logs(limit) }),\n setCallLogLevel: async ({ level }) => {\n await this.setCallLogLevel(level);\n return {};\n },\n queryCalls: async ({ filter, limit }) => {\n const { calls, truncated } = await this._callLog.query(filter ?? {}, limit);\n return { calls: [...calls], truncated };\n },\n watchCalls: async ({ filter }, _ctx, stream) => {\n const subscription = this._callLog.watch(filter ?? {}, record => {\n stream.send(record).catch(() => { /* the watcher went away */ });\n });\n try {\n await new Promise<void>(resolve => {\n if (stream.signal.aborted) resolve();\n else stream.signal.addEventListener('abort', () => resolve(), { once: true });\n });\n } finally {\n subscription.dispose();\n }\n return {};\n },\n shutdown: () => {\n setTimeout(() => void this.shutdown(), 0);\n return {};\n },\n });\n connection.enableReflection();\n }\n\n private _service(name: string): ServiceSupervisor | ConnectionSupervisor {\n const service = this._services.get(name);\n if (service) return service;\n // Both stop all services before the management API goes away; the service is not unknown.\n if (this._stopping) throw new Error('the hub daemon is shutting down');\n if (this._restartingHub) throw new Error('the hub is restarting; try again shortly');\n throw new Error(`unknown service '${name}'`);\n }\n\n private _discovery(endpoint: LocalEndpoint): EndpointDiscovery {\n return {\n version: 1,\n pid: process.pid,\n endpoint: endpoint.path,\n ...(endpoint.token !== undefined ? { token: endpoint.token } : {}),\n };\n }\n\n private _serialize(op: () => Promise<void>): Promise<void> {\n const run = this._reconcile.then(op);\n this._reconcile = run.catch(error => this._log.line(`reconcile failed: ${_message(error)}`));\n return run;\n }\n\n private _changed(): void {\n if (this._statusChangeScheduled) return;\n this._statusChangeScheduled = true;\n queueMicrotask(() => {\n this._statusChangeScheduled = false;\n for (const listener of [...this._statusListeners]) listener();\n });\n }\n\n private async _doShutdown(): Promise<void> {\n this._stopping = true;\n this._log.line('shutting down');\n this._watcher?.dispose();\n await this._reconcile;\n for (const file of [this.home.discoveryFile, this.home.managementFile]) {\n if (readEndpointDiscovery(file)?.pid === process.pid) fs.rmSync(file, { force: true });\n }\n await this._disposeAllServices();\n await this._endpoints?.dispose();\n this._managementLink?.dispose();\n this._callLogAttachment?.dispose();\n this._hub?.dispose();\n this._hub = undefined;\n await this._callLog.close();\n this._managementServer?.dispose();\n this._statusListeners.clear();\n this._log.line('stopped');\n await this._log.close();\n this._lock.dispose();\n this._resolveDone();\n }\n}\n\nfunction _ensurePrivateDirs(home: HubHome): void {\n for (const dir of [home.configDir, home.stateDir, home.runtimeDir]) {\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 });\n }\n if (process.platform !== 'win32') fs.chmodSync(home.runtimeDir, 0o700);\n}\n\nfunction _token(): string {\n return randomBytes(32).toString('base64url');\n}\n\nfunction _tokensEqual(candidate: string | undefined, expected: string): boolean {\n if (candidate === undefined) return false;\n const a = Buffer.from(candidate);\n const b = Buffer.from(expected);\n return a.length === b.length && timingSafeEqual(a, b);\n}\n\nfunction _message(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","import * as net from 'node:net';\nimport { STREAM_METHOD } from '@hediet/linkrpc';\nimport { connectNdjson } from '@hediet/linkrpc/node';\nimport { readEndpointDiscovery } from './discovery';\nimport type { HubHome } from './paths';\n\nexport interface StdioBridgeOptions {\n readonly home: HubHome;\n readonly input: NodeJS.ReadableStream;\n readonly output: NodeJS.WritableStream;\n}\n\n/**\n * Connect a stream pair speaking newline-delimited JSON-RPC (without an\n * initialize handshake) to the local hub as a client: its requests are routed\n * by the hub and responses come back unchanged. Lets hosts that can only spawn\n * stdio services (e.g. the VS Code team-tools hub) route a service ID to this\n * hub. Resolves when either side closes.\n */\nexport async function bridgeStdioToLocalHub(options: StdioBridgeOptions): Promise<void> {\n const discovery = readEndpointDiscovery(options.home.discoveryFile);\n if (!discovery) throw new Error(`The local LinkRPC hub is not running (no ${options.home.discoveryFile}).`);\n const socket = net.connect(discovery.endpoint);\n await new Promise<void>((resolve, reject) => {\n socket.once('connect', resolve);\n socket.once('error', reject);\n });\n let close!: () => void;\n const closed = new Promise<void>(resolve => { close = resolve; });\n socket.on('error', () => close());\n const { transport: hub } = await connectNdjson({\n input: socket,\n output: socket,\n onClose: () => close(),\n initialize: { kind: 'client', token: discovery.token ?? '' },\n });\n const { transport: stdio } = await connectNdjson({\n input: options.input,\n output: options.output,\n onClose: () => close(),\n });\n hub.setListener(message => {\n // Nothing routes service calls to the bridge itself; requests from the hub\n // are participant probes (e.g. inspection), not traffic for the stdio side.\n // Stream frames answer streaming calls made through the bridge and must pass.\n if ('method' in message && message.method !== STREAM_METHOD) {\n if ('id' in message && message.id !== undefined && message.id !== null) {\n void hub.send({ jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'Method not found' } });\n }\n return;\n }\n void stdio.send(message);\n });\n stdio.setListener(message => void hub.send(message));\n await closed;\n hub.dispose();\n stdio.dispose();\n socket.destroy();\n}\n","import { spawn } from 'node:child_process';\n\nconst MIN_RESTART_DELAY_MS = 1_000;\nconst MAX_RESTART_DELAY_MS = 30_000;\n/** A run this long resets the restart delay. */\nconst STABLE_RUN_MS = 60_000;\n\n/**\n * Run the daemon as a child and restart it after crashes, for launchers that\n * do not supervise (Windows login entries, detached starts). Exit code 0 is an\n * intentional stop (or a duplicate daemon) and ends the watchdog too.\n */\nexport async function runWithKeepAlive(\n executable: string,\n args: readonly string[],\n log: (line: string) => void,\n): Promise<number> {\n let delay = MIN_RESTART_DELAY_MS;\n let stopping = false;\n let current: ReturnType<typeof spawn> | undefined;\n const stop = (signal: NodeJS.Signals) => {\n stopping = true;\n current?.kill(signal);\n };\n process.on('SIGINT', stop);\n process.on('SIGTERM', stop);\n try {\n while (true) {\n const startedAt = Date.now();\n const child = spawn(executable, args, { stdio: 'inherit', windowsHide: true });\n current = child;\n const code = await new Promise<number>(resolve => {\n child.once('error', error => {\n log(`cannot start the daemon: ${error.message}`);\n resolve(1);\n });\n child.once('exit', (exitCode, signal) => resolve(exitCode ?? (signal ? 1 : 0)));\n });\n current = undefined;\n if (stopping || code === 0) return code;\n if (Date.now() - startedAt > STABLE_RUN_MS) delay = MIN_RESTART_DELAY_MS;\n log(`the daemon exited with code ${code}; restarting in ${delay} ms`);\n await new Promise(resolve => setTimeout(resolve, delay));\n if (stopping) return code;\n delay = Math.min(delay * 2, MAX_RESTART_DELAY_MS);\n }\n } finally {\n process.off('SIGINT', stop);\n process.off('SIGTERM', stop);\n }\n}\n","#!/usr/bin/env node\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { Command } from 'commander';\nimport { createAutostartManager } from './autostart/autostart';\nimport { nodeDaemonLaunch } from './autostart/launch';\nimport { connectToHubManagement, type HubManagementConnection } from './client';\nimport { daemonConfigJsonSchema, parseDaemonConfigText } from './config';\nimport { queryDaemonStatus, startDaemon, stopDaemon } from './control';\nimport { HubDaemon } from './daemon';\nimport type { DaemonStatus } from './managementInterface';\nimport { HubHome } from './paths';\nimport { AlreadyRunningError } from './singleInstance';\nimport { bridgeStdioToLocalHub } from './stdioBridge';\nimport { runWithKeepAlive } from './watchdog';\n\nconst program = new Command('linkrpc-hub-daemon')\n .description('Run and manage your per-user LinkRPC hub.')\n .option('--home <dir>', 'hub directory (default: the per-user location, or LINKRPC_HUB_HOME)')\n .showHelpAfterError();\n\nfunction home(): HubHome {\n const dir = program.opts<{ home?: string; }>().home;\n return dir !== undefined ? HubHome.at(path.resolve(dir)) : HubHome.resolve();\n}\n\nprogram.command('run')\n .description('run the daemon in the foreground')\n .option('--keep-alive', 'restart the daemon after crashes (for unsupervised launchers)', false)\n .option('--quiet', 'log only to the log file, not to stderr', false)\n .action(async (opts: { keepAlive: boolean; quiet: boolean; }) => {\n const hubHome = home();\n if (opts.keepAlive) {\n const script = fileURLToPath(import.meta.url);\n const args = [...process.execArgv, script, ...process.argv.slice(2).filter(arg => arg !== '--keep-alive')];\n process.exitCode = await runWithKeepAlive(process.execPath, args, line => {\n fs.appendFileSync(hubHome.logFile, `${new Date().toISOString()} [watchdog] ${line}\\n`);\n });\n return;\n }\n let daemon: HubDaemon;\n // Only needed to start Electron's binary as Node.js; services must not inherit it.\n delete process.env.ELECTRON_RUN_AS_NODE;\n try {\n daemon = await HubDaemon.start({ home: hubHome, echoLog: !opts.quiet });\n } catch (error) {\n if (error instanceof AlreadyRunningError) {\n // Exit code 0: no supervisor (launchd, systemd, watchdog) restarts a duplicate.\n console.error(error.message);\n process.exit(0);\n }\n throw error;\n }\n const stop = () => void daemon.shutdown();\n process.once('SIGINT', stop);\n process.once('SIGTERM', stop);\n await daemon.done;\n process.exit(0);\n });\n\nprogram.command('start')\n .description('start the daemon in the background')\n .action(async () => {\n const hubHome = home();\n const result = await startDaemon({\n home: hubHome,\n launch: nodeDaemonLaunch(hubHome),\n autostart: await createAutostartManager({ home: hubHome }),\n });\n console.log(result === 'started' ? 'The hub is running.' : 'The hub is already running.');\n });\n\nprogram.command('stop')\n .description('stop all services and the daemon')\n .action(async () => {\n const result = await stopDaemon(home());\n console.log(result === 'stopped' ? 'The hub stopped.' : 'The hub is not running.');\n });\n\nprogram.command('restart')\n .description('stop and start the daemon')\n .action(async () => {\n const hubHome = home();\n await stopDaemon(hubHome);\n await startDaemon({ home: hubHome, launch: nodeDaemonLaunch(hubHome), autostart: await createAutostartManager({ home: hubHome }) });\n console.log('The hub is running.');\n });\n\nprogram.command('status')\n .description('show the daemon and its services')\n .option('--json', 'print the status as JSON', false)\n .action(async (opts: { json: boolean; }) => {\n const hubHome = home();\n const status = await queryDaemonStatus(hubHome);\n if (opts.json) {\n console.log(JSON.stringify(status ?? null, null, 2));\n } else {\n const autostart = await createAutostartManager({ home: hubHome });\n const enabled = await autostart.isEnabled();\n console.log(_formatStatus(status, hubHome, `${enabled ? 'enabled' : 'disabled'} (${autostart.description})`));\n }\n if (!status) process.exitCode = 1;\n });\n\nprogram.command('reload')\n .description('re-read the config file and apply what changed')\n .action(() => _withManagement(async management => {\n const status = await management.reloadConfig({});\n console.log(status.config.error ? `The config is invalid: ${status.config.error}` : 'Config applied.');\n }));\n\nprogram.command('bridge-stdio')\n .description('pipe newline-delimited JSON-RPC on stdin/stdout (no handshake) to the running hub')\n .action(async () => {\n await bridgeStdioToLocalHub({ home: home(), input: process.stdin, output: process.stdout });\n process.exit(0);\n });\n\nconst autostart = program.command('autostart').description('start the hub at login');\nautostart.command('enable').description('start the hub at login').action(async () => {\n const hubHome = home();\n const manager = await createAutostartManager({ home: hubHome });\n await manager.enable(nodeDaemonLaunch(hubHome));\n console.log(`The hub starts at login (${manager.description}).`);\n});\nautostart.command('disable').description('do not start the hub at login').action(async () => {\n const manager = await createAutostartManager({ home: home() });\n await manager.disable();\n console.log('The hub no longer starts at login.');\n});\nautostart.command('status').description('show whether the hub starts at login').action(async () => {\n const manager = await createAutostartManager({ home: home() });\n console.log(`${await manager.isEnabled() ? 'enabled' : 'disabled'} (${manager.description})`);\n});\n\nconst service = program.command('service').description('control configured services');\nservice.command('enable <name>').description('enable a service (persisted in the config)')\n .action((name: string) => _withManagement(m => m.setServiceEnabled({ name, enabled: true })));\nservice.command('disable <name>').description('disable a service (persisted in the config)')\n .action((name: string) => _withManagement(m => m.setServiceEnabled({ name, enabled: false })));\nservice.command('restart <name>').description('restart a service')\n .action((name: string) => _withManagement(m => m.restartService({ name })));\nservice.command('logs <name>').description('print recent output of a service')\n .option('-n, --lines <n>', 'number of lines', '100')\n .action((name: string, opts: { lines: string; }) => _withManagement(async m => {\n const { lines } = await m.getServiceLogs({ name, limit: Number(opts.lines) });\n for (const line of lines) {\n console.log(`${new Date(line.at).toISOString()} ${line.stream.padEnd(6)} ${line.text}`);\n }\n }));\n\nconst config = program.command('config').description('inspect the config file');\nconfig.command('path').description('print the config file path').action(() => console.log(home().configFile));\nconfig.command('schema').description('print the config JSON Schema').action(() => {\n console.log(JSON.stringify(daemonConfigJsonSchema(), null, 2));\n});\nconfig.command('validate [file]').description('validate a config file (default: the active one)')\n .action((file: string | undefined) => {\n const target = file ?? home().configFile;\n parseDaemonConfigText(fs.readFileSync(target, 'utf8'));\n console.log(`${target} is valid.`);\n });\n\nasync function _withManagement(action: (management: HubManagementConnection['management']) => Promise<unknown>): Promise<void> {\n const connection = await connectToHubManagement(home());\n try {\n await action(connection.management);\n } finally {\n connection.close();\n }\n}\n\nfunction _formatStatus(status: DaemonStatus | undefined, hubHome: HubHome, autostart: string): string {\n if (!status) {\n return [`LinkRPC hub: not running`, `Config: ${hubHome.configFile}`, `Autostart: ${autostart}`].join('\\n');\n }\n const lines = [\n `LinkRPC hub: running (pid ${status.pid}, ${status.version}, up ${_duration(Date.now() - status.startedAt)})`,\n `Endpoint: ${status.endpoint}`,\n `Config: ${status.configFile}${status.config.error ? `\\n error: ${status.config.error}` : ''}`,\n ...(status.hub.error ? [`Hub error: ${status.hub.error}`] : []),\n `Log: ${status.logFile}`,\n `Call log: ${status.callLog.level === 'off' ? 'off' : `${status.callLog.level} → ${status.callLog.directory}`}${status.callLog.error ? `\\n error: ${status.callLog.error}` : ''}`,\n `Autostart: ${autostart}`,\n ];\n if (status.services.length === 0) return [...lines, 'Services: none configured'].join('\\n');\n const rows = status.services.map(s => [\n s.name,\n s.state,\n s.pid?.toString() ?? '-',\n String(s.restarts),\n s.error ?? '',\n ]);\n const header = ['SERVICE', 'STATE', 'PID', 'RESTARTS', 'INFO'];\n const widths = header.map((h, i) => Math.max(h.length, ...rows.map(row => row[i]!.length)));\n const format = (row: string[]) => row.map((cell, i) => cell.padEnd(widths[i]!)).join(' ').trimEnd();\n return [...lines, '', format(header), ...rows.map(format)].join('\\n');\n}\n\nfunction _duration(ms: number): string {\n const s = Math.floor(ms / 1000);\n if (s < 60) return `${s}s`;\n if (s < 3600) return `${Math.floor(s / 60)}m`;\n return `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m`;\n}\n\nprogram.parseAsync(process.argv).catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : String(error));\n process.exit(1);\n});\n"],"x_google_ignoreList":[14,15,16,17,18,19,34,35,36,37,38,39,40,41,42,43,44,45,46],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,MAAM,eAAe;AACrB,MAAM,mBAAmB;;AAGzB,SAAgB,cAAsB;CAClC,IAAI,MAAMA,OAAK,QAAQ,cAAc,YAAY,GAAG,CAAC;CACrD,OAAO,MAAM;EACT,MAAM,WAAWA,OAAK,KAAK,KAAK,cAAc;EAC9C,IAAIC,KAAG,WAAW,QAAQ,GAAG;GACzB,MAAM,OAAO,KAAK,MAAMA,KAAG,aAAa,UAAU,MAAM,CAAC,CAAC,CAAC;GAC3D,IAAI,SAAS,gBAAgB,SAAS,kBAAkB,OAAO;EACnE;EACA,MAAM,SAASD,OAAK,QAAQ,GAAG;EAC/B,IAAI,WAAW,KAAK,MAAM,IAAI,MAAM,qBAAqB,aAAa,cAAc;EACpF,MAAM;CACV;AACJ;AAEA,SAAgB,iBAAyB;CACrC,OAAO,KAAK,MAAMC,KAAG,aAAaD,OAAK,KAAK,YAAY,GAAG,cAAc,GAAG,MAAM,CAAC,CAAC,CAAC;AACzF;;AAGA,SAAgB,YAAoB;CAChC,MAAM,OAAO,YAAY;CACzB,MAAM,EAAE,SAAS,KAAK,MAAMC,KAAG,aAAaD,OAAK,KAAK,MAAM,cAAc,GAAG,MAAM,CAAC;CACpF,OAAOA,OAAK,KAAK,MAAM,QAAQ,SAAS,mBAAmB,cAAc,QAAQ;AACrF;;;;;;;;ACJA,SAAgB,iBAAiB,MAAe,aAAqBE,KAAG,aAAa,QAAQ,QAAQ,GAAG,MAAwC,CAAC,GAAiB;CAC9J,MAAM,MAAM;EAAC,UAAU;EAAG,GAAI,KAAK,cAAc,KAAA,IAAY,CAAC,UAAU,KAAK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