@saptools/cf-debugger 0.3.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +72 -16
- package/dist/{chunk-QBB4N2WN.js → chunk-4UAIE7V6.js} +176 -88
- package/dist/chunk-4UAIE7V6.js.map +1 -0
- package/dist/cli.js +15 -1
- package/dist/cli.js.map +1 -1
- package/dist/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-QBB4N2WN.js.map +0 -1
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../../core/src/package-metadata.ts","../../core/src/records.ts","../../core/src/saptools-paths.ts","../../core/src/self-update/reexec.ts","../../core/src/self-update/policy.ts","../../core/src/self-update/run.ts","../../core/src/self-update/install-location.ts","../../core/src/self-update/installer.ts","../../core/src/self-update/registry.ts","../../core/src/self-update/semver.ts","../../core/src/self-update/state.ts","../../core/src/self-update/commander.ts","../src/cli-input.ts","../src/package-version.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport nodeProcess from \"node:process\";\n\nimport { attachSelfUpdate, registerSelfUpdateCommand } from \"@saptools/core\";\nimport { Command } from \"commander\";\n\nimport { readCurrentCfTarget, requireCurrentCfRegion } from \"./cf.js\";\nimport type { CurrentCfTargetReadOptions } from \"./cf.js\";\nimport {\n CLEANUP_FAILURE_EXIT_CODE,\n cliErrorExitCode,\n hasTunnelTerminationFailure,\n stopAllExitCode,\n} from \"./cli-errors.js\";\nimport {\n parseOptionalInteger,\n parseSeconds,\n readRequiredOption,\n} from \"./cli-input.js\";\nimport {\n DEFAULT_NODE_INSPECTOR_PORT,\n resolveNodeTarget,\n} from \"./cloud-foundry/node-process.js\";\nimport { runDoctor } from \"./debug-session/doctor.js\";\nimport { getDebuggerHandleTunnelError } from \"./debug-session/lifecycle.js\";\nimport { startDebuggerWithinDeadline } from \"./debug-session/start.js\";\nimport {\n createStartupDeadline,\n remainingStartupMs,\n resolveStartupTimeoutMs,\n startupTimeoutError,\n} from \"./debug-session/startup-deadline.js\";\nimport {\n getSession,\n listSessions,\n stopAllDebuggers,\n stopDebugger,\n} from \"./debugger.js\";\nimport { readPackageVersion } from \"./package-version.js\";\nimport { validateApiEndpointOverride } from \"./regions.js\";\nimport { parseRestartEnvironment } from \"./restart-policy.js\";\nimport type {\n DebuggerHandle,\n ResolvedSessionKey,\n SessionStatus,\n StartDebuggerOptions,\n} from \"./types.js\";\nimport { CfDebuggerError } from \"./types.js\";\n\ninterface TargetCommandOptions {\n readonly process?: string;\n readonly instance?: string;\n readonly nodePid?: string;\n readonly apiEndpoint?: string;\n}\n\ninterface StartCommandOptions extends TargetCommandOptions {\n readonly region?: string;\n readonly org?: string;\n readonly space?: string;\n readonly app?: string;\n readonly port?: string;\n readonly remotePort?: string;\n readonly timeout?: string;\n readonly startupTimeout?: string;\n readonly allowSshEnableRestart?: boolean;\n readonly sshEnableRestart?: boolean;\n readonly verbose?: boolean;\n}\n\ninterface StopCommandOptions extends TargetCommandOptions {\n readonly region?: string;\n readonly org?: string;\n readonly space?: string;\n readonly app?: string;\n readonly sessionId?: string;\n readonly all?: boolean;\n readonly force?: boolean;\n}\n\ntype StatusCommandOptions = Omit<StopCommandOptions, \"all\" | \"force\">;\nconst STOP_SCOPE_OPTION_NAMES = [\n \"apiEndpoint\",\n \"app\",\n \"instance\",\n \"nodePid\",\n \"org\",\n \"process\",\n \"region\",\n \"sessionId\",\n \"space\",\n] as const;\n\nfunction logStatus(verbose: boolean, status: SessionStatus, message?: string): void {\n if (!verbose) {\n return;\n }\n const suffix = message === undefined ? \"\" : `: ${message}`;\n nodeProcess.stdout.write(`[cf-debugger] ${status}${suffix}\\n`);\n}\n\nfunction mergeSelector<\n T extends { region?: string; org?: string; space?: string; app?: string },\n>(selector: string | undefined, options: T): T {\n if (selector === undefined) {\n return options;\n }\n const parts = selector.split(\"/\");\n if (parts.length === 1 && parts[0]?.length !== 0) {\n return { ...options, app: options.app ?? parts[0] };\n }\n if (parts.length === 4 && parts.every((part) => part.length > 0)) {\n return {\n ...options,\n region: options.region ?? parts[0],\n org: options.org ?? parts[1],\n space: options.space ?? parts[2],\n app: options.app ?? parts[3],\n };\n }\n throw new CfDebuggerError(\n \"UNSAFE_INPUT\",\n \"Invalid app selector. Expected <app> or non-empty <region>/<org>/<space>/<app> segments.\",\n );\n}\n\ninterface StartupAbort {\n readonly signal: AbortSignal;\n requestedExitCode(): number | undefined;\n dispose(): void;\n}\n\nfunction startupAbort(app: string): StartupAbort {\n const controller = new AbortController();\n let requestedExitCode: number | undefined;\n const handler = (exitCode: number) => (): void => {\n requestedExitCode ??= exitCode;\n controller.abort();\n nodeProcess.stderr.write(`\\nAborting startup for ${app}...\\n`);\n };\n const onSigint = handler(130);\n const onSigterm = handler(143);\n nodeProcess.on(\"SIGINT\", onSigint);\n nodeProcess.on(\"SIGTERM\", onSigterm);\n return {\n signal: controller.signal,\n requestedExitCode: (): number | undefined => requestedExitCode,\n dispose: (): void => {\n nodeProcess.off(\"SIGINT\", onSigint);\n nodeProcess.off(\"SIGTERM\", onSigterm);\n },\n };\n}\n\nfunction writeReady(\n app: string,\n key: ResolvedSessionKey,\n handle: DebuggerHandle,\n): void {\n nodeProcess.stdout.write(\n `Debugger ready for ${app} (${key.region}/${key.org}/${key.space}).\\n` +\n ` Process: ${key.process}\\n` +\n ` Instance: ${key.instance.toString()}\\n` +\n ` Local port: ${handle.session.localPort.toString()}\\n` +\n ` Remote port: ${handle.session.remotePort.toString()}\\n` +\n ` Session id: ${handle.session.sessionId}\\n` +\n ` Tunnel PID: ${handle.session.pid.toString()}\\n` +\n ` Node PID: ${handle.session.remoteNodePid?.toString() ?? \"unknown\"}\\n` +\n \"Press Ctrl+C to stop.\\n\",\n );\n}\n\nfunction writeCleanupError(error: unknown): void {\n const message = error instanceof Error ? error.message : String(error);\n nodeProcess.stderr.write(`Error during stop: ${message}\\n`);\n}\n\nasync function waitForHandle(\n app: string,\n handle: DebuggerHandle,\n): Promise<void> {\n let pendingDispose: Promise<void> | undefined;\n let requestedExitCode: number | undefined;\n const dispose = (): Promise<void> => {\n pendingDispose ??= (async (): Promise<void> => {\n nodeProcess.stdout.write(`\\nStopping debugger for ${app}...\\n`);\n await handle.dispose();\n })();\n return pendingDispose;\n };\n const stop = (exitCode: number) => (): void => {\n requestedExitCode = exitCode;\n void dispose()\n .catch((error: unknown) => {\n writeCleanupError(error);\n nodeProcess.exit(CLEANUP_FAILURE_EXIT_CODE);\n });\n };\n nodeProcess.on(\"SIGINT\", stop(130));\n nodeProcess.on(\"SIGTERM\", stop(143));\n const code = await handle.waitForExit();\n const tunnelError = getDebuggerHandleTunnelError(handle);\n if (tunnelError !== undefined) {\n nodeProcess.stderr.write(\n `Error [${tunnelError.code}]: ${tunnelError.message}\\n`,\n );\n if (tunnelError.stderr !== undefined && tunnelError.stderr.trim().length > 0) {\n nodeProcess.stderr.write(`[cf-debugger transport]\\n${tunnelError.stderr.trim()}\\n`);\n }\n }\n try {\n await dispose();\n } catch (error: unknown) {\n writeCleanupError(error);\n nodeProcess.exit(CLEANUP_FAILURE_EXIT_CODE);\n }\n nodeProcess.exit(requestedExitCode ?? code ?? 0);\n}\n\nfunction buildStartOptions(\n options: StartCommandOptions,\n key: ResolvedSessionKey,\n app: string,\n signal: AbortSignal,\n startupTimeoutMs: number,\n): StartDebuggerOptions {\n const preferredPort = parseOptionalInteger(options.port, \"port\", 1, 65_535);\n const remotePort = parseOptionalInteger(options.remotePort, \"remotePort\", 1, 65_535);\n const nodePid = parseOptionalInteger(options.nodePid, \"nodePid\", 1);\n const tunnelReadyTimeoutMs = parseSeconds(options.timeout, \"timeout\");\n const restartEnvironment = parseRestartEnvironment(\n nodeProcess.env[\"CF_DEBUGGER_ALLOW_RESTART\"],\n );\n const allowSshEnableRestart =\n options.sshEnableRestart !== false &&\n restartEnvironment !== \"forbid\" &&\n (options.allowSshEnableRestart === true || restartEnvironment === \"allow\");\n return {\n region: key.region,\n org: key.org,\n space: key.space,\n app,\n process: key.process,\n instance: key.instance,\n signal,\n allowSshEnableRestart,\n ...(options.apiEndpoint === undefined ? {} : { apiEndpoint: options.apiEndpoint }),\n ...(preferredPort === undefined ? {} : { preferredPort }),\n ...(remotePort === undefined ? {} : { remotePort }),\n ...(nodePid === undefined ? {} : { nodePid }),\n ...(tunnelReadyTimeoutMs === undefined ? {} : { tunnelReadyTimeoutMs }),\n startupTimeoutMs,\n };\n}\n\nfunction deadlineTimedOut(\n deadline: ReturnType<typeof createStartupDeadline>,\n): boolean {\n return remainingStartupMs(deadline.expiresAt) === 0 ||\n (\n deadline.signal.reason instanceof CfDebuggerError &&\n deadline.signal.reason.code === \"STARTUP_TIMEOUT\"\n );\n}\n\nfunction validateStartEndpoint(options: StartCommandOptions): StartCommandOptions {\n return options.apiEndpoint === undefined\n ? options\n : {\n ...options,\n apiEndpoint: validateApiEndpointOverride(options.apiEndpoint),\n };\n}\n\nasync function handleStart(\n selector: string | undefined,\n rawOptions: StartCommandOptions,\n): Promise<void> {\n const options = validateStartEndpoint(mergeSelector(selector, rawOptions));\n const app = readRequiredOption(options.app, \"--app or selector\");\n const verbose = options.verbose ?? false;\n const startupTimeoutMs = resolveStartupTimeoutMs(\n parseSeconds(options.startupTimeout, \"startupTimeout\"),\n );\n const abort = startupAbort(app);\n const deadline = createStartupDeadline(startupTimeoutMs, abort.signal);\n let handle;\n let phase = \"current CF target discovery\";\n let key: ResolvedSessionKey;\n try {\n key = await resolveSessionKey({ ...options, app }, deadline.signal);\n if (deadlineTimedOut(deadline)) {\n throw startupTimeoutError(startupTimeoutMs, phase);\n }\n phase = \"startup\";\n handle = await startDebuggerWithinDeadline({\n ...buildStartOptions(options, key, app, deadline.signal, startupTimeoutMs),\n verbose,\n onStatus: (status, message): void => {\n logStatus(verbose, status, message);\n },\n }, deadline);\n } catch (error: unknown) {\n const normalized = deadlineTimedOut(deadline) &&\n !(error instanceof CfDebuggerError && error.code === \"STARTUP_TIMEOUT\")\n ? startupTimeoutError(startupTimeoutMs, phase)\n : error;\n const exitCode = abort.requestedExitCode();\n if (exitCode !== undefined && typeof normalized === \"object\" && normalized !== null) {\n Reflect.set(normalized, \"cliExitCode\", exitCode);\n }\n throw normalized;\n } finally {\n deadline.dispose();\n abort.dispose();\n }\n writeReady(app, key, handle);\n await waitForHandle(app, handle);\n}\n\nfunction optionalText(value: string | undefined): string | undefined {\n const trimmed = value?.trim();\n return trimmed === undefined || trimmed.length === 0 ? undefined : trimmed;\n}\n\nfunction currentCfOptions(signal?: AbortSignal): CurrentCfTargetReadOptions | undefined {\n const command = nodeProcess.env[\"CF_DEBUGGER_CF_BIN\"];\n if (command === undefined && signal === undefined) {\n return undefined;\n }\n return {\n ...(command === undefined ? {} : { command }),\n ...(signal === undefined ? {} : { signal }),\n };\n}\n\ninterface ResolvedCfScope {\n readonly region: string;\n readonly org: string;\n readonly space: string;\n}\n\nfunction currentTargetReadError(error: unknown): CfDebuggerError {\n return new CfDebuggerError(\n \"CF_TARGET_FAILED\",\n \"No current CF target. Run `cf target -o <org> -s <space>` or pass --region/--org/--space.\",\n error instanceof Error ? error.message : String(error),\n );\n}\n\nfunction missingCurrentTargetError(): CfDebuggerError {\n return new CfDebuggerError(\n \"CF_TARGET_FAILED\",\n \"No current CF target. Run `cf target -o <org> -s <space>` or pass --region/--org/--space.\",\n );\n}\n\nasync function resolveCfScope(\n region: string | undefined,\n org: string | undefined,\n space: string | undefined,\n signal?: AbortSignal,\n): Promise<ResolvedCfScope> {\n if (region !== undefined && org !== undefined && space !== undefined) {\n return { region, org, space };\n }\n const current = await readCurrentCfTarget(currentCfOptions(signal)).catch((error: unknown) => {\n if (\n error instanceof CfDebuggerError &&\n (error.code === \"ABORTED\" || error.code === \"STARTUP_TIMEOUT\")\n ) {\n throw error;\n }\n throw currentTargetReadError(error);\n });\n if (current === undefined) {\n throw missingCurrentTargetError();\n }\n return {\n region: region ?? requireCurrentCfRegion(current),\n org: org ?? current.org,\n space: space ?? current.space,\n };\n}\n\nasync function resolveSessionKey(\n options: StopCommandOptions,\n signal?: AbortSignal,\n): Promise<ResolvedSessionKey> {\n const app = readRequiredOption(options.app, \"--app or selector\");\n const region = optionalText(options.region);\n const org = optionalText(options.org);\n const space = optionalText(options.space);\n const nodePid = parseOptionalInteger(options.nodePid, \"nodePid\", 1);\n const instance = parseOptionalInteger(options.instance, \"instance\", 0);\n const target = resolveNodeTarget({\n ...(options.process === undefined ? {} : { process: options.process }),\n ...(instance === undefined ? {} : { instance }),\n ...(nodePid === undefined ? {} : { nodePid }),\n });\n const scope = await resolveCfScope(region, org, space, signal);\n return {\n ...scope,\n app,\n process: target.process,\n instance: target.instance,\n ...(options.apiEndpoint === undefined ? {} : { apiEndpoint: options.apiEndpoint }),\n ...(target.nodePid === undefined ? {} : { nodePid: target.nodePid }),\n };\n}\n\nasync function resolveOptionalSessionKey(\n options: StopCommandOptions,\n): Promise<ResolvedSessionKey | undefined> {\n if (optionalText(options.app) === undefined) {\n if (\n optionalText(options.region) !== undefined ||\n optionalText(options.org) !== undefined ||\n optionalText(options.space) !== undefined\n ) {\n readRequiredOption(options.app, \"--app or selector\");\n }\n return undefined;\n }\n return await resolveSessionKey(options);\n}\n\nfunction writeStopResult(result: Awaited<ReturnType<typeof stopDebugger>>): void {\n if (result === undefined) {\n return;\n }\n if (result.warning !== undefined) {\n nodeProcess.stderr.write(`[cf-debugger] warning: ${result.warning}\\n`);\n }\n if (result.pending) {\n nodeProcess.stdout.write(\n `Stop requested for session ${result.sessionId} (${result.app}, phase ${result.status}).\\n`,\n );\n } else if (result.stale) {\n nodeProcess.stdout.write(\n `Removed ${result.forced ? \"forced \" : \"\"}stale session ${result.sessionId} ` +\n `(${result.app}, port ${result.localPort.toString()}).\\n`,\n );\n } else {\n nodeProcess.stdout.write(\n `Stopped session ${result.sessionId} (${result.app}, port ${result.localPort.toString()}).\\n`,\n );\n }\n}\n\nfunction rejectScopedStopAll(\n selector: string | undefined,\n options: StopCommandOptions,\n command: Command,\n): void {\n if (\n options.all === true &&\n (\n selector !== undefined ||\n STOP_SCOPE_OPTION_NAMES.some((name) => command.getOptionValueSource(name) === \"cli\")\n )\n ) {\n throw new CfDebuggerError(\n \"UNSAFE_INPUT\",\n \"--all cannot be combined with a selector, --session-id, or target selector options.\",\n );\n }\n}\n\nasync function handleStopAll(force: boolean): Promise<void> {\n const summary = await stopAllDebuggers(force);\n for (const outcome of summary.outcomes) {\n if (outcome.error === undefined) {\n writeStopResult(outcome.result);\n } else {\n nodeProcess.stderr.write(\n `Failed ${outcome.sessionId} (${outcome.app}): ${outcome.error.message}\\n`,\n );\n }\n }\n nodeProcess.stdout.write(\n `Stop summary: ${summary.stopped.toString()} stopped, ${summary.forced.toString()} forced, ` +\n `${summary.stale.toString()} stale, ` +\n `${summary.pending.toString()} pending, ${summary.failed.toString()} failed.\\n`,\n );\n const exitCode = stopAllExitCode(\n summary.outcomes.flatMap((outcome) =>\n outcome.error === undefined ? [] : [outcome.error]),\n );\n if (exitCode !== undefined) {\n nodeProcess.exitCode = exitCode;\n }\n}\n\nasync function handleStop(\n selector: string | undefined,\n rawOptions: StopCommandOptions,\n command: Command,\n): Promise<void> {\n rejectScopedStopAll(selector, rawOptions, command);\n const options = mergeSelector(selector, rawOptions);\n if (options.all === true) {\n await handleStopAll(options.force === true);\n return;\n }\n const key = await resolveOptionalSessionKey(options);\n const result = await stopDebugger({\n ...(options.sessionId === undefined ? {} : { sessionId: options.sessionId }),\n ...(key === undefined ? {} : { key }),\n force: options.force === true,\n });\n if (result === undefined) {\n throw new CfDebuggerError(\n \"SESSION_NOT_FOUND\",\n \"No matching session. Use `cf-debugger list` and pass --session-id or an exact key.\",\n );\n }\n writeStopResult(result);\n}\n\nasync function handleList(): Promise<void> {\n nodeProcess.stdout.write(`${JSON.stringify(await listSessions(), null, 2)}\\n`);\n}\n\nasync function handleStatus(\n selector: string | undefined,\n rawOptions: StatusCommandOptions,\n): Promise<void> {\n const options = mergeSelector(selector, rawOptions);\n const session = options.sessionId === undefined\n ? await getSession(await resolveSessionKey(options))\n : (await listSessions()).find((candidate) => candidate.sessionId === options.sessionId);\n nodeProcess.stdout.write(`${JSON.stringify(session ?? null, null, 2)}\\n`);\n}\n\nasync function handleDoctor(cleanup: boolean): Promise<void> {\n const report = await runDoctor({ cleanup });\n nodeProcess.stdout.write(`${JSON.stringify(report, null, 2)}\\n`);\n}\n\nfunction registerStartCommand(program: Command): void {\n program\n .command(\"start\")\n .description(\"Open a debug tunnel for one app\")\n .argument(\"[selector]\", \"Optional <app> or <region>/<org>/<space>/<app>\")\n .option(\"--region <key>\", \"CF region key (default: current cf target)\")\n .option(\"--api-endpoint <url>\", \"Absolute HTTPS CF API endpoint override\")\n .option(\"--org <name>\", \"CF org (default: current cf target)\")\n .option(\"--space <name>\", \"CF space (default: current cf target)\")\n .option(\"--app <name>\", \"CF app name\")\n .option(\"--process <name>\", \"CF process name\", \"web\")\n .option(\"-i, --instance <index>\", \"CF process instance\", \"0\")\n .option(\"--node-pid <pid>\", \"Explicit remote Node.js PID\")\n .option(\"--port <number>\", \"Preferred local port\")\n .option(\n \"--remote-port <number>\",\n \"Port where cf-debugger looks for an existing remote inspector\",\n DEFAULT_NODE_INSPECTOR_PORT.toString(),\n )\n .option(\"--timeout <seconds>\", \"Tunnel/inspector readiness timeout\", \"180\")\n .option(\"--startup-timeout <seconds>\", \"Overall startup deadline\", \"300\")\n .option(\n \"--allow-ssh-enable-restart\",\n \"Allow app-level SSH enablement and an app restart (opt-in)\",\n )\n .option(\n \"--no-ssh-enable-restart\",\n \"Forbid app-level SSH enablement and restart, overriding flag/environment\",\n )\n .option(\"--verbose\", \"Print status transitions and tunnel diagnostics\", false)\n .action(async (selector: string | undefined, options: StartCommandOptions): Promise<void> => {\n await handleStart(selector, options);\n });\n}\n\nfunction addKeyOptions(command: Command): Command {\n return command\n .option(\"--region <key>\")\n .option(\"--api-endpoint <url>\", \"Exact API endpoint selector\")\n .option(\"--org <name>\")\n .option(\"--space <name>\")\n .option(\"--app <name>\")\n .option(\"--process <name>\", \"CF process name\", \"web\")\n .option(\"-i, --instance <index>\", \"CF process instance\", \"0\")\n .option(\"--node-pid <pid>\", \"Exact remote Node PID selector\");\n}\n\nfunction registerStopCommand(program: Command): void {\n addKeyOptions(\n program\n .command(\"stop\")\n .description(\"Stop one session by exact key/id, or every session with --all\")\n .argument(\"[selector]\", \"Optional <app> or <region>/<org>/<space>/<app>\"),\n )\n .option(\"--session-id <id>\")\n .option(\n \"--all\",\n \"Attempt every active session; cannot be combined with session selectors\",\n false,\n )\n .option(\n \"--force\",\n \"Forget unverifiable state first; best-effort remove its exact owned CF home; \" +\n \"never signal an unverified process\",\n false,\n )\n .action(\n async (\n selector: string | undefined,\n options: StopCommandOptions,\n command: Command,\n ): Promise<void> => {\n await handleStop(selector, options, command);\n },\n );\n}\n\nfunction registerReadCommands(program: Command): void {\n program\n .command(\"list\")\n .description(\"Print every active debugger session as JSON\")\n .action(async (): Promise<void> => {\n await handleList();\n });\n addKeyOptions(\n program\n .command(\"status\")\n .description(\"Print one exact session as JSON; null only when no session matches\")\n .argument(\"[selector]\", \"Optional <app> or <region>/<org>/<space>/<app>\"),\n )\n .option(\"--session-id <id>\", \"Exact session ID selector\")\n .action(async (selector: string | undefined, options: StatusCommandOptions): Promise<void> => {\n await handleStatus(selector, options);\n });\n program\n .command(\"doctor\")\n .description(\"Report session health, orphan homes/ports, temp files, and legacy credentials\")\n .option(\"--cleanup\", \"Remove only safe orphan v2 homes and stale v2 temp/lock files\", false)\n .action(async (options: { readonly cleanup?: boolean }): Promise<void> => {\n await handleDoctor(options.cleanup === true);\n });\n}\n\nexport async function main(argv: readonly string[]): Promise<void> {\n const version = readPackageVersion();\n // Every command first checks npm (at most once an hour) and re-runs itself on a newer release; see `@saptools/core`.\n const selfUpdate = { packageName: \"@saptools/cf-debugger\", currentVersion: version, binName: \"cf-debugger\", envPrefix: \"CF_DEBUGGER\" };\n const program = new Command()\n .name(\"cf-debugger\")\n .description(\"Open an SSH debug tunnel to a SAP BTP Cloud Foundry Node.js inspector\")\n .version(version);\n attachSelfUpdate(program, selfUpdate);\n registerStartCommand(program);\n registerStopCommand(program);\n registerReadCommands(program);\n registerSelfUpdateCommand(program, selfUpdate);\n await program.parseAsync([...argv]);\n}\n\nfunction writeTopLevelError(error: unknown): void {\n if (error instanceof CfDebuggerError) {\n if (error.code === \"ABORTED\") {\n nodeProcess.stderr.write(`Aborted: ${error.message}\\n`);\n nodeProcess.exit(cliErrorExitCode(error));\n }\n nodeProcess.stderr.write(`Error [${error.code}]: ${error.message}\\n`);\n if (error.stderr !== undefined && error.stderr.trim().length > 0) {\n nodeProcess.stderr.write(`[cf-debugger transport]\\n${error.stderr.trim()}\\n`);\n }\n nodeProcess.exit(cliErrorExitCode(error));\n }\n if (hasTunnelTerminationFailure(error)) {\n const message = error instanceof Error ? error.message : String(error);\n nodeProcess.stderr.write(`Error during cleanup: ${message}\\n`);\n nodeProcess.exit(CLEANUP_FAILURE_EXIT_CODE);\n }\n const message = error instanceof Error ? error.message : String(error);\n nodeProcess.stderr.write(`Error: ${message}\\n`);\n nodeProcess.exit(cliErrorExitCode(error));\n}\n\ntry {\n await main(nodeProcess.argv);\n} catch (error: unknown) {\n writeTopLevelError(error);\n}\n","import { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { isRecord, readString } from \"./records.js\";\n\nexport interface PackageMetadata {\n readonly name: string;\n readonly version: string;\n /** Directory that holds the package.json. */\n readonly directory: string;\n}\n\n/**\n * A bundled CLI lives at `<package>/dist/cli.js`; a source file under test at\n * `<package>/src/...`; tsup chunks one level deeper. Six levels covers every\n * layout in this repo with room to spare while still failing fast on a stray\n * file outside any package.\n */\nconst MAX_WALK_UP = 6;\n\n/** Parse `<directory>/package.json`; undefined when missing, unreadable, or not a manifest with name and version. */\nexport function readPackageManifest(directory: string): PackageMetadata | undefined {\n let raw: string;\n try {\n raw = readFileSync(join(directory, \"package.json\"), \"utf8\");\n } catch {\n return;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return;\n }\n if (!isRecord(parsed)) {\n return;\n }\n const name = readString(parsed, \"name\");\n const version = readString(parsed, \"version\");\n if (name === undefined || version === undefined) {\n return;\n }\n return { name, version, directory };\n}\n\n/** Walk up from `startDirectory` to the nearest package.json whose `name` is `expectedName`. */\nexport function findPackageMetadata(startDirectory: string, expectedName: string): PackageMetadata | undefined {\n let current = startDirectory;\n for (let depth = 0; depth < MAX_WALK_UP; depth += 1) {\n const manifest = readPackageManifest(current);\n if (manifest?.name === expectedName) {\n return manifest;\n }\n const parent = dirname(current);\n if (parent === current) {\n return;\n }\n current = parent;\n }\n return;\n}\n\n/**\n * Version and name of the package that owns the calling module, read from its\n * package.json at runtime so `--version` and the self-updater can never drift\n * from the manifest the way a hand-maintained constant does. Throws when the\n * manifest cannot be found: a broken install should fail loudly, not report\n * \"0.0.0\".\n */\nexport function readPackageMetadata(importMetaUrl: string, expectedName: string): PackageMetadata {\n const startDirectory = dirname(fileURLToPath(importMetaUrl));\n const found = findPackageMetadata(startDirectory, expectedName);\n if (found === undefined) {\n throw new Error(`Cannot find the package.json of ${expectedName} above ${startDirectory}`);\n }\n return found;\n}\n","export function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** A non-empty string field of a parsed JSON object, or undefined when absent or of another type. */\nexport function readString(record: Record<string, unknown>, key: string): string | undefined {\n const value = record[key];\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n","import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport const SAPTOOLS_DIR_NAME = \".saptools\";\n/** Relocates every saptools state file at once; packages may still offer their own narrower override. */\nexport const SAPTOOLS_ROOT_ENV = \"SAPTOOLS_ROOT\";\n\nexport function resolveSaptoolsRoot(explicit?: string, env: NodeJS.ProcessEnv = process.env): string {\n if (explicit !== undefined && explicit.length > 0) {\n return explicit;\n }\n const fromEnv = env[SAPTOOLS_ROOT_ENV];\n if (fromEnv !== undefined && fromEnv.length > 0) {\n return fromEnv;\n }\n return join(homedir(), SAPTOOLS_DIR_NAME);\n}\n\n/**\n * Create `directory` (and missing parents) readable by the current user only.\n * Only the leaf has its mode enforced: parents such as `~/.saptools` itself\n * belong to every tool and keep whatever mode they already have.\n */\nexport function ensurePrivateDirectorySync(directory: string): void {\n mkdirSync(directory, { recursive: true, mode: 0o700 });\n try {\n chmodSync(directory, 0o700);\n } catch {\n // Filesystems without POSIX modes (some network mounts, Windows) reject chmod; the directory still exists.\n }\n}\n\n/**\n * Replace `path` atomically: write a sibling temp file with `mode`, then\n * rename it over the target, so a concurrent reader never sees a half-written\n * file and a crash never leaves a truncated one behind.\n */\nexport function writeFileAtomicSync(path: string, data: string, mode = 0o600): void {\n const temp = `${path}.${String(process.pid)}.${Math.random().toString(36).slice(2, 8)}.tmp`;\n try {\n writeFileSync(temp, data, { encoding: \"utf8\", mode });\n try {\n chmodSync(temp, mode);\n } catch {\n // Same as above: best effort where modes are unsupported.\n }\n renameSync(temp, path);\n } catch (error) {\n rmSync(temp, { force: true });\n throw error;\n }\n}\n\n/** Parse a JSON file; a missing or malformed file reads as undefined so corrupt state can never break a command. */\nexport function readJsonFileSync(path: string): unknown {\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch {\n return;\n }\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n return;\n }\n}\n","import { spawn } from \"node:child_process\";\nimport { constants } from \"node:os\";\n\nimport type { SpawnLike } from \"./process-types.js\";\n\n/** Set on the re-executed process so it can never start a second update. */\nexport const REEXEC_MARKER_ENV = \"SAPTOOLS_SELF_UPDATE_REEXEC\";\n\nexport interface ReexecRequest {\n readonly execPath: string;\n readonly execArgv: readonly string[];\n readonly binPath: string;\n readonly args: readonly string[];\n readonly env: NodeJS.ProcessEnv;\n}\n\n/** Resolves only when the re-executed command has finished and the replacement failed to end this process itself. */\nexport type ReexecImpl = (request: ReexecRequest) => Promise<void>;\n\ntype ExecveLike = (file: string, args: readonly string[], env: NodeJS.ProcessEnv) => never;\n\nexport interface ReexecRuntime {\n readonly platform: NodeJS.Platform;\n readonly execve: ExecveLike | undefined;\n readonly spawnImpl: SpawnLike;\n readonly onSignal: (signal: NodeJS.Signals, handler: (signal: NodeJS.Signals) => void) => void;\n readonly offSignal: (signal: NodeJS.Signals, handler: (signal: NodeJS.Signals) => void) => void;\n readonly kill: (pid: number, signal: NodeJS.Signals) => void;\n readonly exit: (code: number) => void;\n}\n\nconst FORWARDED_SIGNALS: readonly NodeJS.Signals[] = [\"SIGINT\", \"SIGTERM\", \"SIGHUP\"];\n\nfunction nativeExecve(): ExecveLike | undefined {\n return process.execve?.bind(process);\n}\n\nfunction defaultRuntime(): ReexecRuntime {\n return {\n platform: process.platform,\n execve: nativeExecve(),\n spawnImpl: spawn,\n onSignal: (signal, handler): void => {\n process.on(signal, handler);\n },\n offSignal: (signal, handler): void => {\n process.off(signal, handler);\n },\n kill: (pid, signal): void => {\n process.kill(pid, signal);\n },\n exit: (code): void => {\n process.exit(code);\n },\n };\n}\n\nexport function buildReexecArgv(request: ReexecRequest): string[] {\n return [...request.execArgv, request.binPath, ...request.args];\n}\n\nexport function reexecEnvironment(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n return { ...env, [REEXEC_MARKER_ENV]: \"1\" };\n}\n\nfunction signalExitCode(signal: NodeJS.Signals): number {\n const number = constants.signals[signal];\n return 128 + number;\n}\n\n/**\n * Run the same command again on the freshly installed version. On POSIX with\n * Node >= 22.15 the process image is replaced outright (`execve`), so stdin,\n * stdout, the exit code and signals all belong to the new version with no\n * wrapper left behind. Elsewhere a child inherits our stdio, terminal signals\n * are forwarded to it, and we mirror its exit code or signal.\n */\nexport async function reexecProcess(request: ReexecRequest, runtimeOverrides: Partial<ReexecRuntime> = {}): Promise<void> {\n const runtime: ReexecRuntime = { ...defaultRuntime(), ...runtimeOverrides };\n const argv = buildReexecArgv(request);\n const env = reexecEnvironment(request.env);\n\n if (runtime.platform !== \"win32\" && runtime.execve !== undefined) {\n try {\n runtime.execve(request.execPath, [request.execPath, ...argv], env);\n } catch {\n // execve refused (for example EACCES on an odd mount): the child-process route below still works.\n }\n }\n\n await new Promise<void>((resolve, reject) => {\n const child = runtime.spawnImpl(request.execPath, argv, { stdio: \"inherit\", env });\n const forward = (signal: NodeJS.Signals): void => {\n child.kill(signal);\n };\n for (const signal of FORWARDED_SIGNALS) {\n runtime.onSignal(signal, forward);\n }\n const detach = (): void => {\n for (const signal of FORWARDED_SIGNALS) {\n runtime.offSignal(signal, forward);\n }\n };\n child.once(\"error\", (error) => {\n detach();\n reject(error);\n });\n child.once(\"exit\", (code, signal) => {\n detach();\n if (signal === null) {\n runtime.exit(code ?? 1);\n } else {\n runtime.kill(process.pid, signal);\n runtime.exit(signalExitCode(signal));\n }\n resolve();\n });\n });\n}\n","import type { InstallLocation } from \"./install-location.js\";\nimport { REEXEC_MARKER_ENV } from \"./reexec.js\";\n\nexport type UpdatePolicy = \"on\" | \"notify\" | \"off\";\n\nexport const POLICY_ENV = \"SAPTOOLS_AUTO_UPDATE\";\nexport const INTERVAL_ENV = \"SAPTOOLS_UPDATE_INTERVAL_MINUTES\";\nexport const DEBUG_ENV = \"SAPTOOLS_UPDATE_DEBUG\";\nexport const DEFAULT_CHECK_INTERVAL_MINUTES = 60;\nexport const SELF_UPDATE_COMMAND = \"self-update\";\n\nexport interface PolicyDecision {\n readonly policy: UpdatePolicy;\n readonly reason: string;\n /** True when the user set the policy through the environment rather than relying on the default. */\n readonly explicit: boolean;\n}\n\nexport interface ResolvePolicyInput {\n readonly env: NodeJS.ProcessEnv;\n readonly envPrefix?: string;\n readonly location: InstallLocation;\n /** Space-joined command path being run, e.g. `credential list`; empty for the root action. */\n readonly commandPath?: string;\n readonly skipCommands?: readonly string[];\n /** The explicit `self-update` command: ignore the exclusions and CI/test gates, but never the install-location facts. */\n readonly manual?: boolean;\n}\n\nexport function parsePolicy(raw: string | undefined): UpdatePolicy | undefined {\n if (raw === undefined) {\n return;\n }\n const value = raw.trim().toLowerCase();\n if ([\"on\", \"1\", \"true\", \"yes\", \"auto\", \"always\"].includes(value)) {\n return \"on\";\n }\n if ([\"notify\", \"check\"].includes(value)) {\n return \"notify\";\n }\n if ([\"off\", \"0\", \"false\", \"no\", \"never\", \"disabled\"].includes(value)) {\n return \"off\";\n }\n return;\n}\n\n/** `CI=true`, `CI=1`, even `CI=yes` count; `CI=0`, `CI=false` and an empty value do not. */\nexport function isTruthyFlag(raw: string | undefined): boolean {\n return raw !== undefined && ![\"\", \"0\", \"false\", \"no\", \"off\"].includes(raw.trim().toLowerCase());\n}\n\nfunction readExplicitPolicy(env: NodeJS.ProcessEnv, envPrefix: string | undefined): UpdatePolicy | undefined {\n const perPackage = envPrefix === undefined ? undefined : parsePolicy(env[`${envPrefix}_AUTO_UPDATE`]);\n return perPackage ?? parsePolicy(env[POLICY_ENV]);\n}\n\nfunction off(reason: string, explicit: boolean): PolicyDecision {\n return { policy: \"off\", reason, explicit };\n}\n\nfunction notify(reason: string, explicit: boolean): PolicyDecision {\n return { policy: \"notify\", reason, explicit };\n}\n\nfunction locationDecision(location: InstallLocation, explicit: boolean): PolicyDecision | undefined {\n switch (location.kind) {\n case \"local\":\n return off(\"running from a source checkout or linked package, not a package-manager install\", explicit);\n case \"npx\":\n return off(\"running through npx or dlx, which resolves the version on its own\", explicit);\n case \"unknown\":\n return notify(`install location not recognized (${location.detail})`, explicit);\n case \"npm-global\":\n case \"pnpm-global\":\n case \"yarn-global\":\n case \"bun-global\":\n case \"volta\":\n return;\n }\n}\n\n/**\n * Decide what this invocation may do. Order matters: the re-exec marker and\n * the command exclusions are absolute, an explicit `off` wins next, then the\n * environment defaults (CI, test runs) that only an explicit setting\n * overrides, and only then the facts about the install: a checkout can never\n * be upgraded by npm, a read-only prefix can only be announced.\n */\nexport function resolveUpdatePolicy(input: ResolvePolicyInput): PolicyDecision {\n const { env, location } = input;\n const manual = input.manual === true;\n const explicit = readExplicitPolicy(env, input.envPrefix);\n\n if (!manual && isTruthyFlag(env[REEXEC_MARKER_ENV])) {\n return off(\"already re-executed after an update\", false);\n }\n const commandPath = input.commandPath ?? \"\";\n if (!manual && (commandPath === SELF_UPDATE_COMMAND || (input.skipCommands ?? []).includes(commandPath))) {\n return off(`the \"${commandPath}\" command is excluded from automatic updates`, false);\n }\n if (!manual && explicit === \"off\") {\n return off(`${POLICY_ENV} is off`, true);\n }\n if (!manual && explicit === undefined) {\n if (isTruthyFlag(env[\"NO_UPDATE_NOTIFIER\"])) {\n return off(\"NO_UPDATE_NOTIFIER is set\", false);\n }\n if (isTruthyFlag(env[\"CI\"])) {\n return off(\"running in CI\", false);\n }\n if (env[\"NODE_ENV\"] === \"test\") {\n return off(\"NODE_ENV is test\", false);\n }\n }\n const byLocation = locationDecision(location, explicit !== undefined);\n if (byLocation !== undefined) {\n return byLocation;\n }\n if (!location.writable) {\n return notify(\"the install directory is not writable by this user\", explicit !== undefined);\n }\n if (manual) {\n return { policy: \"on\", reason: \"requested explicitly\", explicit: true };\n }\n return explicit === undefined\n ? { policy: \"on\", reason: \"default\", explicit: false }\n : { policy: explicit, reason: `${POLICY_ENV} is ${explicit}`, explicit: true };\n}\n\n/** Minutes between registry checks; `0` checks on every run. Invalid values fall back to the default. */\nexport function resolveCheckIntervalMs(env: NodeJS.ProcessEnv): number {\n const raw = env[INTERVAL_ENV];\n if (raw === undefined) {\n return DEFAULT_CHECK_INTERVAL_MINUTES * 60_000;\n }\n const minutes = Number(raw.trim());\n if (!Number.isFinite(minutes) || minutes < 0) {\n return DEFAULT_CHECK_INTERVAL_MINUTES * 60_000;\n }\n return Math.round(minutes * 60_000);\n}\n","import { spawn } from \"node:child_process\";\nimport { homedir } from \"node:os\";\n\nimport { readPackageManifest } from \"../package-metadata.js\";\nimport { errorMessage } from \"../records.js\";\nimport { resolveSaptoolsRoot } from \"../saptools-paths.js\";\n\nimport { detectInstallLocation } from \"./install-location.js\";\nimport type { InstallLocation } from \"./install-location.js\";\nimport { buildInstallCommand, DEFAULT_INSTALL_TIMEOUT_MS, manualInstallCommand, runInstall } from \"./installer.js\";\nimport { DEBUG_ENV, isTruthyFlag, resolveCheckIntervalMs, resolveUpdatePolicy } from \"./policy.js\";\nimport type { PolicyDecision } from \"./policy.js\";\nimport type { SpawnLike } from \"./process-types.js\";\nimport { reexecProcess } from \"./reexec.js\";\nimport type { ReexecImpl } from \"./reexec.js\";\nimport { DEFAULT_CHECK_TIMEOUT_MS, fetchLatestVersion, readUserNpmrc, resolveRegistryUrl } from \"./registry.js\";\nimport { isNewerRelease } from \"./semver.js\";\nimport {\n acquireUpdateLock,\n clearFailure,\n EMPTY_UPDATE_STATE,\n readUpdateState,\n updateLockPath,\n updateStatePath,\n writeUpdateState,\n} from \"./state.js\";\nimport type { UpdateState } from \"./state.js\";\n\nexport interface SelfUpdateOptions {\n /** npm package name, e.g. `@saptools/cf-metrics`. */\n readonly packageName: string;\n /** The running version, read from package.json (see readPackageMetadata). */\n readonly currentVersion: string;\n /** Executable name used as the prefix of every notice, e.g. `cf-metrics`. */\n readonly binName: string;\n /** Per-package override namespace: `CF_METRICS` honours `CF_METRICS_AUTO_UPDATE`. */\n readonly envPrefix?: string;\n /** Space-joined command paths that must never trigger an update (internal workers, daemons). */\n readonly skipCommands?: readonly string[];\n /** The command being run, supplied by the commander hook. */\n readonly commandPath?: string;\n readonly saptoolsRoot?: string;\n /** Where notices go; defaults to `<binName>: <line>` on stderr. Never stdout. */\n readonly notice?: (line: string) => void;\n /** The explicit `self-update` command: ignore the check interval, backoffs and policy gates. */\n readonly manual?: boolean;\n /** Re-run the command on the new version after installing (default true). */\n readonly reexec?: boolean;\n}\n\nexport interface SelfUpdateRuntime {\n readonly env: NodeJS.ProcessEnv;\n readonly argv: readonly string[];\n readonly execPath: string;\n readonly execArgv: readonly string[];\n readonly platform: NodeJS.Platform;\n readonly homeDirectory: string;\n readonly now: () => Date;\n readonly fetchImpl: typeof fetch;\n readonly spawnImpl: SpawnLike;\n readonly reexecImpl: ReexecImpl;\n readonly checkTimeoutMs: number;\n readonly installTimeoutMs: number;\n readonly realpath?: (path: string) => string;\n readonly isWritable?: (path: string) => boolean;\n readonly exists?: (path: string) => boolean;\n}\n\nexport type SelfUpdateOutcome =\n | { readonly kind: \"skipped\"; readonly reason: string }\n | { readonly kind: \"current\"; readonly latest: string }\n | { readonly kind: \"notified\"; readonly latest: string; readonly reason: string }\n | { readonly kind: \"updated\"; readonly from: string; readonly to: string }\n | { readonly kind: \"failed\"; readonly latest: string; readonly reason: string };\n\nexport interface SelfUpdateStatus {\n readonly packageName: string;\n readonly installed: string;\n readonly location: InstallLocation;\n readonly policy: PolicyDecision;\n readonly registryUrl: string;\n readonly statePath: string;\n readonly latest: string | undefined;\n readonly checkError: string | undefined;\n}\n\n/** After a failed registry call, stay quiet this long instead of paying the timeout on every command. */\nconst FAILURE_BACKOFF_MS = 15 * 60_000;\n/** A version we already announced is not announced again for a day. */\nconst NOTIFY_INTERVAL_MS = 24 * 60 * 60_000;\n/** A version whose install failed is not retried for a day; the notice carries the manual command instead. */\nconst INSTALL_RETRY_BACKOFF_MS = 24 * 60 * 60_000;\n\ninterface Context {\n readonly options: SelfUpdateOptions;\n readonly runtime: SelfUpdateRuntime;\n readonly binPath: string;\n readonly location: InstallLocation;\n readonly decision: PolicyDecision;\n readonly registryUrl: string;\n readonly statePath: string;\n readonly intervalMs: number;\n state: UpdateState;\n readonly notice: (line: string) => void;\n readonly debug: (line: string) => void;\n}\n\nfunction defaultRuntime(): SelfUpdateRuntime {\n return {\n env: process.env,\n argv: process.argv,\n execPath: process.execPath,\n execArgv: process.execArgv,\n platform: process.platform,\n homeDirectory: homedir(),\n now: (): Date => new Date(),\n fetchImpl: fetch,\n spawnImpl: spawn,\n reexecImpl: reexecProcess,\n checkTimeoutMs: DEFAULT_CHECK_TIMEOUT_MS,\n installTimeoutMs: DEFAULT_INSTALL_TIMEOUT_MS,\n };\n}\n\nfunction ageMs(isoTimestamp: string, nowMs: number): number {\n const then = Date.parse(isoTimestamp);\n // A timestamp in the future means the clock moved backwards; treat it as stale so the state self-heals.\n return Number.isNaN(then) || then > nowMs ? Number.POSITIVE_INFINITY : nowMs - then;\n}\n\nfunction detectLocation(options: SelfUpdateOptions, runtime: SelfUpdateRuntime, binPath: string): InstallLocation {\n return detectInstallLocation({\n binPath,\n packageName: options.packageName,\n platform: runtime.platform,\n env: runtime.env,\n ...(runtime.realpath === undefined ? {} : { realpath: runtime.realpath }),\n ...(runtime.isWritable === undefined ? {} : { isWritable: runtime.isWritable }),\n });\n}\n\nfunction createContext(options: SelfUpdateOptions, runtime: SelfUpdateRuntime): Context {\n const { env } = runtime;\n const binPath = runtime.argv[1] ?? \"\";\n const location = detectLocation(options, runtime, binPath);\n const decision = resolveUpdatePolicy({\n env,\n location,\n skipCommands: options.skipCommands ?? [],\n manual: options.manual === true,\n ...(options.envPrefix === undefined ? {} : { envPrefix: options.envPrefix }),\n ...(options.commandPath === undefined ? {} : { commandPath: options.commandPath }),\n });\n const statePath = updateStatePath(resolveSaptoolsRoot(options.saptoolsRoot, env), options.packageName);\n const notice =\n options.notice ??\n ((line: string): void => {\n process.stderr.write(`${options.binName}: ${line}\\n`);\n });\n const debug = isTruthyFlag(env[DEBUG_ENV])\n ? (line: string): void => {\n process.stderr.write(`${options.binName}: [self-update] ${line}\\n`);\n }\n : (): void => {\n // Debug output is off unless SAPTOOLS_UPDATE_DEBUG is set.\n };\n return {\n options,\n runtime,\n binPath,\n location,\n decision,\n registryUrl: resolveRegistryUrl(env, readUserNpmrc(runtime.homeDirectory)),\n statePath,\n intervalMs: resolveCheckIntervalMs(env),\n // Loaded lazily in resolveLatest: a disabled run must not touch ~/.saptools at all.\n state: EMPTY_UPDATE_STATE,\n notice,\n debug,\n };\n}\n\nfunction saveState(ctx: Context): void {\n try {\n writeUpdateState(ctx.statePath, ctx.state);\n } catch (error) {\n ctx.debug(`cannot write ${ctx.statePath}: ${errorMessage(error)}`);\n }\n}\n\n/** The newest published version: from the state file while it is fresh, otherwise from the registry. */\nasync function resolveLatest(ctx: Context): Promise<string | undefined> {\n ctx.state = readUpdateState(ctx.statePath);\n const { state } = ctx;\n const nowMs = ctx.runtime.now().getTime();\n if (ctx.options.manual !== true) {\n if (state.latest !== undefined && state.checkedAt !== undefined && ageMs(state.checkedAt, nowMs) < ctx.intervalMs) {\n ctx.debug(`using cached latest ${state.latest} (checked ${state.checkedAt})`);\n return state.latest;\n }\n if (state.lastFailureAt !== undefined && ageMs(state.lastFailureAt, nowMs) < FAILURE_BACKOFF_MS) {\n ctx.debug(`skipping the registry check after a recent failure: ${state.lastFailureReason ?? \"unknown\"}`);\n return state.latest;\n }\n }\n const result = await fetchLatestVersion(ctx.options.packageName, ctx.registryUrl, {\n fetchImpl: ctx.runtime.fetchImpl,\n timeoutMs: ctx.runtime.checkTimeoutMs,\n userAgent: `${ctx.options.binName}/${ctx.options.currentVersion} saptools-self-update`,\n });\n const at = ctx.runtime.now().toISOString();\n if (result.ok) {\n ctx.state = clearFailure({ ...ctx.state, checkedAt: at, latest: result.latest });\n saveState(ctx);\n return result.latest;\n }\n ctx.state = { ...ctx.state, lastFailureAt: at, lastFailureReason: result.reason };\n saveState(ctx);\n ctx.debug(`registry check failed: ${result.reason}`);\n return ctx.state.latest;\n}\n\nfunction notify(ctx: Context, latest: string, reason: string): SelfUpdateOutcome {\n const nowMs = ctx.runtime.now().getTime();\n const alreadyAnnounced =\n ctx.state.notifiedVersion === latest && ctx.state.notifiedAt !== undefined && ageMs(ctx.state.notifiedAt, nowMs) < NOTIFY_INTERVAL_MS;\n if (!alreadyAnnounced || ctx.options.manual === true) {\n const command = manualInstallCommand(ctx.location.kind, `${ctx.options.packageName}@${latest}`);\n ctx.notice(`${latest} is available (installed ${ctx.options.currentVersion}) but was not installed: ${reason}. Run: ${command}`);\n ctx.state = { ...ctx.state, notifiedVersion: latest, notifiedAt: ctx.runtime.now().toISOString() };\n saveState(ctx);\n }\n return { kind: \"notified\", latest, reason };\n}\n\nfunction recentInstallFailure(ctx: Context, latest: string): string | undefined {\n const attempt = ctx.state.lastInstall;\n if (ctx.options.manual === true || attempt === undefined || attempt.ok || attempt.version !== latest) {\n return;\n }\n if (ageMs(attempt.at, ctx.runtime.now().getTime()) >= INSTALL_RETRY_BACKOFF_MS) {\n return;\n }\n return `the previous attempt failed (${attempt.reason ?? \"unknown reason\"})`;\n}\n\nfunction recordInstall(ctx: Context, latest: string, ok: boolean, reason?: string): void {\n const at = ctx.runtime.now().toISOString();\n ctx.state = { ...ctx.state, lastInstall: reason === undefined ? { version: latest, at, ok } : { version: latest, at, ok, reason } };\n saveState(ctx);\n}\n\nasync function installLatest(ctx: Context, latest: string): Promise<SelfUpdateOutcome | undefined> {\n const command = buildInstallCommand({\n location: ctx.location,\n packageName: ctx.options.packageName,\n version: latest,\n registryUrl: ctx.registryUrl,\n execPath: ctx.runtime.execPath,\n platform: ctx.runtime.platform,\n ...(ctx.runtime.exists === undefined ? {} : { exists: ctx.runtime.exists }),\n ...(ctx.runtime.realpath === undefined ? {} : { realpath: ctx.runtime.realpath }),\n });\n if (command === undefined) {\n return notify(ctx, latest, \"no supported package manager was found for this install\");\n }\n const lock = acquireUpdateLock(updateLockPath(ctx.statePath), ctx.runtime.now());\n if (lock === undefined) {\n ctx.debug(\"another process holds the update lock\");\n return { kind: \"skipped\", reason: \"another process is installing the update\" };\n }\n try {\n ctx.notice(`updating ${ctx.options.currentVersion} -> ${latest} ...`);\n const result = await runInstall(command, { env: ctx.runtime.env, timeoutMs: ctx.runtime.installTimeoutMs, spawnImpl: ctx.runtime.spawnImpl });\n const installed = ctx.location.packageDirectory === undefined ? undefined : readPackageManifest(ctx.location.packageDirectory)?.version;\n const failure = result.ok ? (installed === latest ? undefined : `the installed version is ${installed ?? \"unreadable\"}, not ${latest}`) : result.reason;\n if (failure !== undefined) {\n recordInstall(ctx, latest, false, failure);\n ctx.notice(`update to ${latest} failed (${failure}); continuing with ${ctx.options.currentVersion}. Run: ${command.display}`);\n return { kind: \"failed\", latest, reason: failure };\n }\n recordInstall(ctx, latest, true);\n } finally {\n lock.release();\n }\n return;\n}\n\nasync function upgrade(ctx: Context, latest: string): Promise<SelfUpdateOutcome> {\n const failed = await installLatest(ctx, latest);\n if (failed !== undefined) {\n return failed;\n }\n const outcome: SelfUpdateOutcome = { kind: \"updated\", from: ctx.options.currentVersion, to: latest };\n if (ctx.options.reexec === false) {\n ctx.notice(`updated to ${latest}`);\n return outcome;\n }\n ctx.notice(`updated to ${latest}; re-running the command`);\n try {\n await ctx.runtime.reexecImpl({\n execPath: ctx.runtime.execPath,\n execArgv: ctx.runtime.execArgv,\n binPath: ctx.binPath,\n args: ctx.runtime.argv.slice(2),\n env: ctx.runtime.env,\n });\n } catch (error) {\n ctx.notice(`could not re-run on ${latest} (${errorMessage(error)}); continuing with the already loaded ${ctx.options.currentVersion}`);\n }\n return outcome;\n}\n\nasync function runSelfUpdateUnsafe(options: SelfUpdateOptions, runtime: SelfUpdateRuntime): Promise<SelfUpdateOutcome> {\n const ctx = createContext(options, runtime);\n if (ctx.decision.policy === \"off\") {\n ctx.debug(`off: ${ctx.decision.reason}`);\n return { kind: \"skipped\", reason: ctx.decision.reason };\n }\n const latest = await resolveLatest(ctx);\n if (latest === undefined) {\n return { kind: \"skipped\", reason: \"the latest version is unknown\" };\n }\n if (!isNewerRelease(latest, options.currentVersion)) {\n return { kind: \"current\", latest };\n }\n if (ctx.decision.policy === \"notify\") {\n return notify(ctx, latest, ctx.decision.reason);\n }\n const backoff = recentInstallFailure(ctx, latest);\n if (backoff !== undefined) {\n return notify(ctx, latest, backoff);\n }\n return await upgrade(ctx, latest);\n}\n\n/**\n * Check for, install, and re-run on a newer release. Never throws, never\n * writes to stdout, never prompts, never escalates privileges: whatever goes\n * wrong, the command the user asked for still runs on the installed version.\n */\nexport async function runSelfUpdate(options: SelfUpdateOptions, overrides: Partial<SelfUpdateRuntime> = {}): Promise<SelfUpdateOutcome> {\n const runtime: SelfUpdateRuntime = { ...defaultRuntime(), ...overrides };\n try {\n return await runSelfUpdateUnsafe(options, runtime);\n } catch (error) {\n const reason = errorMessage(error);\n if (isTruthyFlag(runtime.env[DEBUG_ENV])) {\n process.stderr.write(`${options.binName}: [self-update] ${reason}\\n`);\n }\n return { kind: \"skipped\", reason };\n }\n}\n\n/** Everything the `self-update` command reports; performs one fresh registry check. */\nexport async function inspectSelfUpdate(options: SelfUpdateOptions, overrides: Partial<SelfUpdateRuntime> = {}): Promise<SelfUpdateStatus> {\n const runtime: SelfUpdateRuntime = { ...defaultRuntime(), ...overrides };\n const ctx = createContext({ ...options, manual: true }, runtime);\n const result = await fetchLatestVersion(options.packageName, ctx.registryUrl, {\n fetchImpl: runtime.fetchImpl,\n timeoutMs: runtime.checkTimeoutMs,\n userAgent: `${options.binName}/${options.currentVersion} saptools-self-update`,\n });\n return {\n packageName: options.packageName,\n installed: options.currentVersion,\n location: ctx.location,\n policy: resolveUpdatePolicy({\n env: runtime.env,\n location: ctx.location,\n ...(options.envPrefix === undefined ? {} : { envPrefix: options.envPrefix }),\n }),\n registryUrl: ctx.registryUrl,\n statePath: ctx.statePath,\n latest: result.ok ? result.latest : undefined,\n checkError: result.ok ? undefined : result.reason,\n };\n}\n","import { accessSync, constants, realpathSync } from \"node:fs\";\nimport { basename, dirname, join, sep } from \"node:path\";\n\nimport { findPackageMetadata } from \"../package-metadata.js\";\nimport { errorMessage } from \"../records.js\";\n\nexport type InstallKind = \"npm-global\" | \"pnpm-global\" | \"yarn-global\" | \"bun-global\" | \"volta\" | \"npx\" | \"local\" | \"unknown\";\n\nexport interface InstallLocation {\n readonly kind: InstallKind;\n /** Directory holding the CLI's package.json, when it could be found. */\n readonly packageDirectory: string | undefined;\n /** npm global prefix (`npm prefix -g`), npm-global installs only. */\n readonly prefix: string | undefined;\n /** Whether this user can replace the installed files without escalating privileges. */\n readonly writable: boolean;\n readonly detail: string;\n}\n\nexport interface DetectInstallLocationOptions {\n readonly binPath: string;\n readonly packageName: string;\n readonly platform?: NodeJS.Platform;\n readonly env?: NodeJS.ProcessEnv;\n readonly realpath?: (path: string) => string;\n readonly isWritable?: (path: string) => boolean;\n}\n\nconst UPGRADABLE_KINDS: ReadonlySet<InstallKind> = new Set<InstallKind>([\"npm-global\", \"pnpm-global\", \"yarn-global\", \"bun-global\", \"volta\"]);\n\nexport function isUpgradableKind(kind: InstallKind): boolean {\n return UPGRADABLE_KINDS.has(kind);\n}\n\nfunction defaultIsWritable(path: string): boolean {\n try {\n accessSync(path, constants.W_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction toPosix(path: string): string {\n return path.split(sep).join(\"/\");\n}\n\nfunction isPnpmGlobal(posixDirectory: string, env: NodeJS.ProcessEnv): boolean {\n // ~/Library/pnpm/global/5/... (macOS), ~/.local/share/pnpm/global/5/... (Linux), or a custom PNPM_HOME.\n if (posixDirectory.includes(\"/pnpm/global/\")) {\n return true;\n }\n const home = env[\"PNPM_HOME\"];\n return home !== undefined && home.length > 0 && posixDirectory.startsWith(`${toPosix(home).replace(/\\/+$/, \"\")}/global/`);\n}\n\n/** `<node_modules>` that directly holds `<node_modules>/@scope/name` or `<node_modules>/name`. */\nfunction nodeModulesRootOf(packageDirectory: string): string | undefined {\n const parent = dirname(packageDirectory);\n if (basename(parent) === \"node_modules\") {\n return parent;\n }\n const grandparent = dirname(parent);\n return basename(grandparent) === \"node_modules\" ? grandparent : undefined;\n}\n\n/**\n * npm's global layout is `<prefix>/lib/node_modules` on POSIX and\n * `<prefix>/node_modules` on Windows, where the default prefix directory is\n * named `npm`. Anything else under a `node_modules` is a project-local install.\n */\nfunction npmPrefixFor(packageDirectory: string, platform: NodeJS.Platform): string | undefined {\n const nodeModules = nodeModulesRootOf(packageDirectory);\n if (nodeModules === undefined) {\n return;\n }\n const parent = dirname(nodeModules);\n if (platform === \"win32\") {\n return basename(parent).toLowerCase() === \"npm\" ? parent : undefined;\n }\n return basename(parent) === \"lib\" ? dirname(parent) : undefined;\n}\n\nfunction classifyKind(packageDirectory: string, platform: NodeJS.Platform, env: NodeJS.ProcessEnv): InstallKind {\n const posix = toPosix(packageDirectory);\n if (posix.includes(\"/_npx/\") || /\\/dlx-[^/]+\\//.test(posix) || posix.includes(\"/pnpm/dlx/\") || posix.includes(\"/.cache/pnpm/dlx\")) {\n return \"npx\";\n }\n if (posix.includes(\"/.volta/tools/image/packages/\")) {\n return \"volta\";\n }\n if (posix.includes(\"/.bun/install/global/\")) {\n return \"bun-global\";\n }\n if (posix.includes(\"/.config/yarn/global/\") || posix.includes(\"/yarn/global/node_modules/\")) {\n return \"yarn-global\";\n }\n if (isPnpmGlobal(posix, env)) {\n return \"pnpm-global\";\n }\n if (!posix.includes(\"/node_modules/\")) {\n return \"local\";\n }\n return npmPrefixFor(packageDirectory, platform) === undefined ? \"local\" : \"npm-global\";\n}\n\nfunction writableForUpgrade(\n packageDirectory: string,\n prefix: string | undefined,\n platform: NodeJS.Platform,\n isWritable: (path: string) => boolean,\n): boolean {\n // The package itself, its scope folder, the node_modules root (npm rewrites .package-lock.json) and the bin folder all get touched.\n const targets = [packageDirectory, dirname(packageDirectory)];\n const nodeModules = nodeModulesRootOf(packageDirectory);\n if (nodeModules !== undefined) {\n targets.push(nodeModules);\n }\n if (prefix !== undefined) {\n targets.push(platform === \"win32\" ? prefix : join(prefix, \"bin\"));\n }\n return targets.every((target) => isWritable(target));\n}\n\nfunction describe(kind: InstallKind, packageDirectory: string, prefix: string | undefined): string {\n if (kind === \"npm-global\" && prefix !== undefined) {\n return `npm global install under ${prefix}`;\n }\n return `${kind} install at ${packageDirectory}`;\n}\n\nfunction unknownLocation(detail: string): InstallLocation {\n return { kind: \"unknown\", packageDirectory: undefined, prefix: undefined, writable: false, detail };\n}\n\n/**\n * Where does the running CLI come from, and which package manager owns it?\n * Decided from the real path of the executing script, never from PATH or\n * `npm prefix -g`: the install we upgrade must be the one we are running.\n */\nexport function detectInstallLocation(options: DetectInstallLocationOptions): InstallLocation {\n const platform = options.platform ?? process.platform;\n const env = options.env ?? process.env;\n const realpath = options.realpath ?? ((path: string): string => realpathSync(path));\n const isWritable = options.isWritable ?? defaultIsWritable;\n\n let resolvedBin: string;\n try {\n resolvedBin = realpath(options.binPath);\n } catch (error) {\n return unknownLocation(`cannot resolve ${options.binPath}: ${errorMessage(error)}`);\n }\n const manifest = findPackageMetadata(dirname(resolvedBin), options.packageName);\n if (manifest === undefined) {\n return unknownLocation(`no package.json for ${options.packageName} above ${resolvedBin}`);\n }\n\n const packageDirectory = manifest.directory;\n const kind = classifyKind(packageDirectory, platform, env);\n const prefix = kind === \"npm-global\" ? npmPrefixFor(packageDirectory, platform) : undefined;\n const writable = isUpgradableKind(kind) && writableForUpgrade(packageDirectory, prefix, platform, isWritable);\n return { kind, packageDirectory, prefix, writable, detail: describe(kind, packageDirectory, prefix) };\n}\n","import { existsSync, realpathSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { errorMessage } from \"../records.js\";\n\nimport type { InstallKind, InstallLocation } from \"./install-location.js\";\nimport type { SpawnLike } from \"./process-types.js\";\n\nexport interface InstallCommand {\n readonly file: string;\n readonly args: readonly string[];\n /** The equivalent command a human would type; used in notices. */\n readonly display: string;\n}\n\nexport interface BuildInstallCommandOptions {\n readonly location: InstallLocation;\n readonly packageName: string;\n readonly version: string;\n readonly registryUrl: string;\n readonly execPath?: string;\n readonly platform?: NodeJS.Platform;\n readonly exists?: (path: string) => boolean;\n readonly realpath?: (path: string) => string;\n}\n\nexport type InstallResult = { readonly ok: true } | { readonly ok: false; readonly reason: string };\n\nexport interface RunInstallOptions {\n readonly env: NodeJS.ProcessEnv;\n readonly timeoutMs?: number;\n readonly spawnImpl: SpawnLike;\n}\n\n/** A global install of a ~200 KB CLI takes a few seconds; three minutes only matters on a stalled network. */\nexport const DEFAULT_INSTALL_TIMEOUT_MS = 180_000;\n\n/** What to tell a human to run; also the fallback when we cannot upgrade for them. */\nexport function manualInstallCommand(kind: InstallKind, spec: string): string {\n switch (kind) {\n case \"pnpm-global\":\n return `pnpm add -g ${spec}`;\n case \"yarn-global\":\n return `yarn global add ${spec}`;\n case \"bun-global\":\n return `bun add -g ${spec}`;\n case \"volta\":\n return `volta install ${spec}`;\n case \"npm-global\":\n case \"npx\":\n case \"local\":\n case \"unknown\":\n return `npm install -g ${spec}`;\n }\n}\n\ninterface NpmInvocation {\n readonly file: string;\n readonly leadingArgs: readonly string[];\n}\n\n/**\n * Prefer the npm that ships with the node running us (`<bin>/npm` beside\n * `process.execPath`), executed through that same node: PATH may hold a\n * different Node installation whose npm would upgrade a different prefix. On\n * Windows the `.cmd` shim cannot be spawned without a shell, so only the\n * bundled `npm-cli.js` is used there.\n */\nfunction resolveNpmInvocation(\n execPath: string,\n platform: NodeJS.Platform,\n exists: (path: string) => boolean,\n realpath: (path: string) => string,\n): NpmInvocation | undefined {\n const binDirectory = dirname(execPath);\n if (platform === \"win32\") {\n const cli = join(binDirectory, \"node_modules\", \"npm\", \"bin\", \"npm-cli.js\");\n return exists(cli) ? { file: execPath, leadingArgs: [cli] } : undefined;\n }\n const sibling = join(binDirectory, \"npm\");\n if (exists(sibling)) {\n try {\n const target = realpath(sibling);\n return target.endsWith(\".js\") ? { file: execPath, leadingArgs: [target] } : { file: target, leadingArgs: [] };\n } catch {\n // A dangling symlink: fall through to PATH.\n }\n }\n return { file: \"npm\", leadingArgs: [] };\n}\n\nfunction buildNpmCommand(options: BuildInstallCommandOptions, spec: string): InstallCommand | undefined {\n if (options.location.prefix === undefined) {\n return;\n }\n const npm = resolveNpmInvocation(\n options.execPath ?? process.execPath,\n options.platform ?? process.platform,\n options.exists ?? existsSync,\n options.realpath ?? ((path: string): string => realpathSync(path)),\n );\n if (npm === undefined) {\n return;\n }\n return {\n file: npm.file,\n args: [\n ...npm.leadingArgs,\n \"install\",\n \"--global\",\n \"--prefix\",\n options.location.prefix,\n spec,\n \"--registry\",\n options.registryUrl,\n \"--no-fund\",\n \"--no-audit\",\n \"--no-update-notifier\",\n \"--loglevel=error\",\n ],\n display: manualInstallCommand(\"npm-global\", spec),\n };\n}\n\n/** The exact command that upgrades this install in place; undefined when the location cannot be upgraded by us. */\nexport function buildInstallCommand(options: BuildInstallCommandOptions): InstallCommand | undefined {\n const spec = `${options.packageName}@${options.version}`;\n switch (options.location.kind) {\n case \"npm-global\":\n return buildNpmCommand(options, spec);\n case \"pnpm-global\":\n return { file: \"pnpm\", args: [\"add\", \"--global\", spec], display: manualInstallCommand(\"pnpm-global\", spec) };\n case \"yarn-global\":\n return { file: \"yarn\", args: [\"global\", \"add\", spec], display: manualInstallCommand(\"yarn-global\", spec) };\n case \"bun-global\":\n return { file: \"bun\", args: [\"add\", \"--global\", spec], display: manualInstallCommand(\"bun-global\", spec) };\n case \"volta\":\n return { file: \"volta\", args: [\"install\", spec], display: manualInstallCommand(\"volta\", spec) };\n case \"npx\":\n case \"local\":\n case \"unknown\":\n return;\n }\n}\n\nfunction lastLine(text: string): string {\n const lines = text\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0);\n return lines.at(-1) ?? \"\";\n}\n\n/**\n * Run the install with no shell, no stdin, and a hard timeout. Credentials for\n * SAP never reach the package manager, and the child inherits an explicit\n * `SAPTOOLS_AUTO_UPDATE=off` so nothing it runs can start a nested update.\n * `cwd` is the temp directory so a project's `.npmrc` cannot redirect the\n * install of a global tool.\n */\nexport function runInstall(command: InstallCommand, options: RunInstallOptions): Promise<InstallResult> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_INSTALL_TIMEOUT_MS;\n const env: NodeJS.ProcessEnv = { ...options.env, SAPTOOLS_AUTO_UPDATE: \"off\" };\n delete env[\"SAP_EMAIL\"];\n delete env[\"SAP_PASSWORD\"];\n\n return new Promise<InstallResult>((resolve) => {\n let child: ReturnType<SpawnLike>;\n try {\n child = options.spawnImpl(command.file, command.args, { cwd: tmpdir(), env, stdio: [\"ignore\", \"pipe\", \"pipe\"], windowsHide: true });\n } catch (error) {\n resolve({ ok: false, reason: errorMessage(error) });\n return;\n }\n let stderr = \"\";\n child.stderr?.on(\"data\", (chunk: Buffer | string) => {\n stderr = `${stderr}${chunk.toString()}`.slice(-4_000);\n });\n const timer = setTimeout(() => {\n child.kill(\"SIGKILL\");\n }, timeoutMs);\n child.once(\"error\", (error) => {\n clearTimeout(timer);\n resolve({ ok: false, reason: `${command.file}: ${error.message}` });\n });\n child.once(\"close\", (code, signal) => {\n clearTimeout(timer);\n if (code === 0) {\n resolve({ ok: true });\n return;\n }\n const detail = lastLine(stderr);\n const suffix = detail.length > 0 ? `: ${detail}` : \"\";\n resolve({\n ok: false,\n reason:\n signal === null\n ? `${command.display} exited with code ${String(code ?? -1)}${suffix}`\n : `${command.display} was killed by ${signal} after ${String(Math.round(timeoutMs / 1000))}s`,\n });\n });\n });\n}\n","import { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { errorMessage, isRecord, readString } from \"../records.js\";\n\nimport { parseSemver } from \"./semver.js\";\n\nexport const DEFAULT_NPM_REGISTRY = \"https://registry.npmjs.org\";\nexport const REGISTRY_ENV = \"SAPTOOLS_NPM_REGISTRY\";\n/**\n * The registry answers in ~0.5 s from Asia; two seconds separates \"slow\" from\n * \"offline or captive portal\" without holding up a 1.5 s command for long.\n */\nexport const DEFAULT_CHECK_TIMEOUT_MS = 2_000;\n\nexport type LatestVersionResult =\n | { readonly ok: true; readonly latest: string }\n | { readonly ok: false; readonly reason: string };\n\nexport interface FetchLatestOptions {\n readonly fetchImpl?: typeof fetch;\n readonly timeoutMs?: number;\n readonly userAgent?: string;\n}\n\nexport function normalizeRegistryUrl(value: string | undefined): string | undefined {\n if (value === undefined) {\n return;\n }\n const trimmed = value.trim().replace(/\\/+$/, \"\");\n if (!/^https?:\\/\\/\\S+$/i.test(trimmed)) {\n return;\n }\n return trimmed;\n}\n\nfunction registryFromNpmrc(text: string | undefined, key: string): string | undefined {\n if (text === undefined) {\n return;\n }\n for (const line of text.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (trimmed.length === 0 || trimmed.startsWith(\"#\") || trimmed.startsWith(\";\")) {\n continue;\n }\n const separator = trimmed.indexOf(\"=\");\n if (separator === -1 || trimmed.slice(0, separator).trim() !== key) {\n continue;\n }\n return trimmed\n .slice(separator + 1)\n .trim()\n .replace(/^\"(.*)\"$/, \"$1\");\n }\n return;\n}\n\n/** `~/.npmrc` as text, or undefined when absent; the project-level `.npmrc` is deliberately ignored (see resolveRegistryUrl). */\nexport function readUserNpmrc(homeDirectory: string): string | undefined {\n try {\n return readFileSync(join(homeDirectory, \".npmrc\"), \"utf8\");\n } catch {\n return;\n }\n}\n\n/**\n * Registry precedence: explicit saptools override, the registry npm itself was\n * configured with when it launched us, the user's `~/.npmrc` (scoped entry\n * first), then npmjs. The current directory's `.npmrc` is ignored on purpose:\n * a project's private registry has nothing to do with where the user's global\n * CLI came from.\n */\nexport function resolveRegistryUrl(env: NodeJS.ProcessEnv, userNpmrc: string | undefined): string {\n const candidates = [\n env[REGISTRY_ENV],\n env[\"npm_config_registry\"],\n registryFromNpmrc(userNpmrc, \"@saptools:registry\"),\n registryFromNpmrc(userNpmrc, \"registry\"),\n ];\n for (const candidate of candidates) {\n const normalized = normalizeRegistryUrl(candidate);\n if (normalized !== undefined) {\n return normalized;\n }\n }\n return DEFAULT_NPM_REGISTRY;\n}\n\ntype JsonResponse =\n | { readonly ok: true; readonly body: unknown }\n | { readonly ok: false; readonly status: number | undefined; readonly reason: string };\n\nasync function fetchJson(\n fetchImpl: typeof fetch,\n url: string,\n headers: Record<string, string>,\n timeoutMs: number,\n): Promise<JsonResponse> {\n try {\n const response = await fetchImpl(url, { headers, signal: AbortSignal.timeout(timeoutMs), redirect: \"follow\" });\n if (!response.ok) {\n return { ok: false, status: response.status, reason: `HTTP ${String(response.status)} from ${url}` };\n }\n const body: unknown = await response.json();\n return { ok: true, body };\n } catch (error) {\n return { ok: false, status: undefined, reason: `${errorMessage(error)} (${url})` };\n }\n}\n\nfunction readLatestTag(body: unknown, nestedUnderDistTags: boolean): string | undefined {\n if (!isRecord(body)) {\n return;\n }\n const tags = nestedUnderDistTags ? body[\"dist-tags\"] : body;\n if (!isRecord(tags)) {\n return;\n }\n const latest = readString(tags, \"latest\");\n return latest !== undefined && parseSemver(latest) !== undefined ? latest : undefined;\n}\n\n/**\n * Ask the registry for the `latest` dist-tag. The dedicated dist-tags endpoint\n * is 18 bytes; registries that do not implement it (some private mirrors) get\n * a second try through the abbreviated packument. A network failure on the\n * first request is not retried: the registry is unreachable, not old.\n */\nexport async function fetchLatestVersion(\n packageName: string,\n registryUrl: string,\n options: FetchLatestOptions = {},\n): Promise<LatestVersionResult> {\n const fetchImpl = options.fetchImpl ?? fetch;\n const timeoutMs = options.timeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;\n const encoded = encodeURIComponent(packageName);\n const baseHeaders: Record<string, string> = { \"user-agent\": options.userAgent ?? \"saptools-self-update\" };\n\n const distTags = await fetchJson(fetchImpl, `${registryUrl}/-/package/${encoded}/dist-tags`, { ...baseHeaders, accept: \"application/json\" }, timeoutMs);\n if (distTags.ok) {\n const latest = readLatestTag(distTags.body, false);\n return latest === undefined ? { ok: false, reason: \"dist-tags response carries no valid latest version\" } : { ok: true, latest };\n }\n if (distTags.status === undefined) {\n return { ok: false, reason: distTags.reason };\n }\n\n const packument = await fetchJson(\n fetchImpl,\n `${registryUrl}/${encoded}`,\n { ...baseHeaders, accept: \"application/vnd.npm.install-v1+json\" },\n timeoutMs,\n );\n if (!packument.ok) {\n return { ok: false, reason: packument.reason };\n }\n const latest = readLatestTag(packument.body, true);\n return latest === undefined ? { ok: false, reason: \"packument carries no valid latest dist-tag\" } : { ok: true, latest };\n}\n","export interface SemanticVersion {\n readonly major: number;\n readonly minor: number;\n readonly patch: number;\n readonly prerelease: readonly string[];\n}\n\nconst SEMVER_PATTERN =\n /^v?(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$/;\n\nexport function parseSemver(text: string): SemanticVersion | undefined {\n const match = SEMVER_PATTERN.exec(text.trim());\n if (match === null) {\n return;\n }\n const [, major, minor, patch, prerelease] = match;\n if (major === undefined || minor === undefined || patch === undefined) {\n return;\n }\n return {\n major: Number(major),\n minor: Number(minor),\n patch: Number(patch),\n prerelease: prerelease === undefined ? [] : prerelease.split(\".\"),\n };\n}\n\nfunction compareIdentifiers(left: string, right: string): number {\n const leftNumeric = /^\\d+$/.test(left);\n const rightNumeric = /^\\d+$/.test(right);\n if (leftNumeric && rightNumeric) {\n return Math.sign(Number(left) - Number(right));\n }\n // Numeric identifiers always sort before alphanumeric ones (semver 2.0.0 §11).\n if (leftNumeric) {\n return -1;\n }\n if (rightNumeric) {\n return 1;\n }\n if (left === right) {\n return 0;\n }\n return left < right ? -1 : 1;\n}\n\nfunction comparePrerelease(left: readonly string[], right: readonly string[]): number {\n if (left.length === 0 && right.length === 0) {\n return 0;\n }\n // A release outranks any prerelease of the same version.\n if (left.length === 0) {\n return 1;\n }\n if (right.length === 0) {\n return -1;\n }\n for (const [index, identifier] of left.entries()) {\n const other = right[index];\n if (other === undefined) {\n return 1;\n }\n const result = compareIdentifiers(identifier, other);\n if (result !== 0) {\n return result;\n }\n }\n return left.length < right.length ? -1 : 0;\n}\n\nexport function compareSemver(left: SemanticVersion, right: SemanticVersion): number {\n for (const key of [\"major\", \"minor\", \"patch\"] as const) {\n if (left[key] !== right[key]) {\n return left[key] < right[key] ? -1 : 1;\n }\n }\n return comparePrerelease(left.prerelease, right.prerelease);\n}\n\n/**\n * True when `candidate` is a release strictly newer than `current`. A\n * prerelease is never a target: someone who installed 1.2.0 must not be moved\n * onto 1.3.0-beta.1 by a background updater.\n */\nexport function isNewerRelease(candidate: string, current: string): boolean {\n const next = parseSemver(candidate);\n const installed = parseSemver(current);\n if (next === undefined || installed === undefined) {\n return false;\n }\n if (next.prerelease.length > 0) {\n return false;\n }\n return compareSemver(next, installed) > 0;\n}\n","import { closeSync, openSync, rmSync, statSync, utimesSync, writeSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\nimport { isRecord, readString } from \"../records.js\";\nimport { ensurePrivateDirectorySync, readJsonFileSync, writeFileAtomicSync } from \"../saptools-paths.js\";\n\nexport interface InstallAttempt {\n readonly version: string;\n readonly at: string;\n readonly ok: boolean;\n readonly reason?: string;\n}\n\nexport interface UpdateState {\n readonly version: 1;\n readonly checkedAt?: string;\n readonly latest?: string;\n readonly lastFailureAt?: string;\n readonly lastFailureReason?: string;\n readonly notifiedVersion?: string;\n readonly notifiedAt?: string;\n readonly lastInstall?: InstallAttempt;\n}\n\ntype UpdateStateDraft = { -readonly [K in keyof UpdateState]: UpdateState[K] };\n\nexport const EMPTY_UPDATE_STATE: UpdateState = { version: 1 };\nexport const UPDATES_DIRECTORY_NAME = \"updates\";\n/** A stuck installer holds the lock this long before another instance may take over. */\nexport const DEFAULT_LOCK_STALE_MS = 10 * 60_000;\n\nconst STRING_FIELDS = [\"checkedAt\", \"latest\", \"lastFailureAt\", \"lastFailureReason\", \"notifiedVersion\", \"notifiedAt\"] as const;\n\n/** `@saptools/cf-metrics` → `saptools__cf-metrics.json`: one file per package, no shared writes between CLIs. */\nexport function updateStateFileName(packageName: string): string {\n return `${packageName.replace(/^@/, \"\").replaceAll(\"/\", \"__\")}.json`;\n}\n\nexport function updateStatePath(saptoolsRoot: string, packageName: string): string {\n return join(saptoolsRoot, UPDATES_DIRECTORY_NAME, updateStateFileName(packageName));\n}\n\nexport function updateLockPath(statePath: string): string {\n return statePath.replace(/\\.json$/, \".lock\");\n}\n\nfunction readInstallAttempt(value: unknown): InstallAttempt | undefined {\n if (!isRecord(value)) {\n return;\n }\n const version = readString(value, \"version\");\n const at = readString(value, \"at\");\n const ok = value[\"ok\"];\n if (version === undefined || at === undefined || typeof ok !== \"boolean\") {\n return;\n }\n const reason = readString(value, \"reason\");\n return reason === undefined ? { version, at, ok } : { version, at, ok, reason };\n}\n\n/** Tolerant read: an unknown, malformed, or older-format file reads as empty state. */\nexport function readUpdateState(path: string): UpdateState {\n const parsed = readJsonFileSync(path);\n if (!isRecord(parsed) || parsed[\"version\"] !== 1) {\n return EMPTY_UPDATE_STATE;\n }\n const draft: UpdateStateDraft = { version: 1 };\n for (const key of STRING_FIELDS) {\n const value = readString(parsed, key);\n if (value !== undefined) {\n draft[key] = value;\n }\n }\n const lastInstall = readInstallAttempt(parsed[\"lastInstall\"]);\n if (lastInstall !== undefined) {\n draft.lastInstall = lastInstall;\n }\n return draft;\n}\n\n/** The same state with a successful check: the failure fields no longer apply. */\nexport function clearFailure(state: UpdateState): UpdateState {\n const next: UpdateStateDraft = { ...state };\n delete next.lastFailureAt;\n delete next.lastFailureReason;\n return next;\n}\n\nexport function writeUpdateState(path: string, state: UpdateState): void {\n ensurePrivateDirectorySync(dirname(path));\n writeFileAtomicSync(path, `${JSON.stringify(state, null, 2)}\\n`, 0o600);\n}\n\nexport interface UpdateLock {\n readonly release: () => void;\n}\n\nfunction tryCreateLock(lockPath: string, now: Date): UpdateLock | undefined {\n let descriptor: number;\n try {\n descriptor = openSync(lockPath, \"wx\", 0o600);\n } catch {\n return;\n }\n try {\n writeSync(descriptor, `${JSON.stringify({ pid: process.pid, at: now.toISOString() })}\\n`);\n } finally {\n closeSync(descriptor);\n }\n // Staleness is judged against the caller's clock, so stamp the file with it rather than the filesystem's.\n utimesSync(lockPath, now, now);\n return {\n release: (): void => {\n rmSync(lockPath, { force: true });\n },\n };\n}\n\nfunction isStaleLock(lockPath: string, now: Date, staleMs: number): boolean {\n try {\n return now.getTime() - statSync(lockPath).mtimeMs > staleMs;\n } catch {\n return false;\n }\n}\n\n/**\n * Exclusive-create lock so two commands started at once install only once;\n * the loser skips the update and runs on the installed version. A lock older\n * than `staleMs` belongs to a crashed installer and is taken over.\n */\nexport function acquireUpdateLock(lockPath: string, now: Date, staleMs = DEFAULT_LOCK_STALE_MS): UpdateLock | undefined {\n ensurePrivateDirectorySync(dirname(lockPath));\n const lock = tryCreateLock(lockPath, now);\n if (lock !== undefined) {\n return lock;\n }\n if (!isStaleLock(lockPath, now, staleMs)) {\n return;\n }\n rmSync(lockPath, { force: true });\n return tryCreateLock(lockPath, now);\n}\n","import type { Command } from \"commander\";\n\nimport { SELF_UPDATE_COMMAND } from \"./policy.js\";\nimport { inspectSelfUpdate, runSelfUpdate } from \"./run.js\";\nimport type { SelfUpdateOptions, SelfUpdateOutcome, SelfUpdateStatus } from \"./run.js\";\nimport { isNewerRelease } from \"./semver.js\";\n\nexport type AttachSelfUpdateOptions = Omit<SelfUpdateOptions, \"commandPath\" | \"manual\" | \"reexec\">;\n\nexport interface SelfUpdateCommandOptions extends AttachSelfUpdateOptions {\n /** Where the status lines go; defaults to stdout. */\n readonly print?: (line: string) => void;\n}\n\n/** `credential list` for a nested subcommand, `` for the root action. */\nexport function commandPathOf(command: Command): string {\n const names: string[] = [];\n let current: Command = command;\n while (current.parent !== null) {\n names.unshift(current.name());\n current = current.parent;\n }\n return names.join(\" \");\n}\n\n/**\n * Run the self-updater before every action of `program`. `--help` and\n * `--version` never reach an action, so they never trigger it; the\n * `self-update` command and `skipCommands` are excluded by the policy.\n */\nexport function attachSelfUpdate(program: Command, options: AttachSelfUpdateOptions): void {\n program.hook(\"preAction\", async (_thisCommand: Command, actionCommand: Command): Promise<void> => {\n await runSelfUpdate({ ...options, commandPath: commandPathOf(actionCommand) });\n });\n}\n\nexport function formatSelfUpdateStatus(status: SelfUpdateStatus): readonly string[] {\n const latest =\n status.latest ?? (status.checkError === undefined ? \"unknown\" : `unknown (${status.checkError})`);\n const install = status.location.packageDirectory === undefined ? status.location.detail : `${status.location.kind} ${status.location.packageDirectory}`;\n return [\n `package=${status.packageName}`,\n `installed=${status.installed}`,\n `latest=${latest}`,\n `policy=${status.policy.policy} (${status.policy.reason})`,\n `install=${install}`,\n `writable=${status.location.writable ? \"yes\" : \"no\"}`,\n `registry=${status.registryUrl}`,\n `state=${status.statePath}`,\n ];\n}\n\nexport function describeOutcome(outcome: SelfUpdateOutcome): string {\n switch (outcome.kind) {\n case \"current\":\n return `current (${outcome.latest} is the newest release)`;\n case \"updated\":\n return `updated ${outcome.from} -> ${outcome.to}`;\n case \"notified\":\n return `not installed (${outcome.reason})`;\n case \"failed\":\n return `failed (${outcome.reason})`;\n case \"skipped\":\n return `skipped (${outcome.reason})`;\n }\n}\n\nasync function runSelfUpdateCommand(options: SelfUpdateCommandOptions, checkOnly: boolean): Promise<void> {\n const print =\n options.print ??\n ((line: string): void => {\n process.stdout.write(`${line}\\n`);\n });\n const status = await inspectSelfUpdate(options);\n for (const line of formatSelfUpdateStatus(status)) {\n print(line);\n }\n if (checkOnly) {\n const verdict = status.latest === undefined ? \"unknown\" : isNewerRelease(status.latest, status.installed) ? \"update-available\" : \"current\";\n print(`result=${verdict}`);\n return;\n }\n const outcome = await runSelfUpdate({ ...options, manual: true, reexec: false });\n print(`result=${describeOutcome(outcome)}`);\n if (outcome.kind === \"failed\") {\n process.exitCode = 1;\n }\n}\n\n/** `<bin> self-update [--check]`: a forced check and install for humans and agents who do not want to wait for the hourly check. */\nexport function registerSelfUpdateCommand(program: Command, options: SelfUpdateCommandOptions): void {\n program\n .command(SELF_UPDATE_COMMAND)\n .description(\"check npm for a newer release and install it now; every other command does this automatically (at most once an hour)\")\n .option(\"--check\", \"report whether a newer release exists without installing it\")\n .action(async (flags: { readonly check?: boolean }): Promise<void> => {\n await runSelfUpdateCommand(options, flags.check === true);\n });\n}\n","import { CfDebuggerError } from \"./types.js\";\n\nexport function readRequiredOption(\n value: string | undefined,\n flag: string,\n): string {\n if (value === undefined || value.trim().length === 0) {\n throw new CfDebuggerError(\"UNSAFE_INPUT\", `Missing required option ${flag}.`);\n }\n return value;\n}\n\nexport function parseOptionalInteger(\n raw: string | undefined,\n label: string,\n minimum: number,\n maximum = Number.MAX_SAFE_INTEGER,\n): number | undefined {\n if (raw === undefined) {\n return undefined;\n }\n if (!/^\\d+$/.test(raw)) {\n throw new CfDebuggerError(\"UNSAFE_INPUT\", `${label} must be an integer.`);\n }\n const value = Number(raw);\n if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {\n throw new CfDebuggerError(\n \"UNSAFE_INPUT\",\n `${label} must be from ${minimum.toString()} to ${maximum.toString()}.`,\n );\n }\n return value;\n}\n\nexport function parseSeconds(\n raw: string | undefined,\n label: string,\n): number | undefined {\n const seconds = parseOptionalInteger(raw, label, 1);\n return seconds === undefined ? undefined : seconds * 1000;\n}\n","import { readFileSync } from \"node:fs\";\n\nimport { CfDebuggerError } from \"./types.js\";\n\nexport function readPackageVersion(): string {\n const parsed: unknown = JSON.parse(\n readFileSync(new URL(\"../package.json\", import.meta.url), \"utf8\"),\n );\n if (typeof parsed !== \"object\" || parsed === null) {\n throw new CfDebuggerError(\"PACKAGE_METADATA_INVALID\", \"Package metadata is not an object.\");\n }\n const version: unknown = Reflect.get(parsed, \"version\");\n if (typeof version !== \"string\" || version.length === 0) {\n throw new CfDebuggerError(\"PACKAGE_METADATA_INVALID\", \"Package metadata has no version.\");\n }\n return version;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,OAAO,iBAAiB;;;ACFxB,SAAS,oBAAoB;AAC7B,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;;;ACFvB,SAAS,SAAS,OAAkD;AACzE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEO,SAAS,aAAa,OAAwB;AACnD,SAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;AAGO,SAAS,WAAW,QAAiC,KAAiC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OAAO,MAAM;AAAA,EAA4B,MAAM,OAAO,KAAK,CAAC;AAAA,CAAI;AAAA,IAC9E;AACA,gBAAY,KAAK,iBAAiB,KAAK,CAAC;AAAA,EAC1C;AACA,MAAI,4BAA4B,KAAK,GAAG;AACtC,UAAMC,WAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,gBAAY,OAAO,MAAM,yBAAyBA,QAAO;AAAA,CAAI;AAC7D,gBAAY,KAAK,yBAAyB;AAAA,EAC5C;AACA,QAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,cAAY,OAAO,MAAM,UAAU,OAAO;AAAA,CAAI;AAC9C,cAAY,KAAK,iBAAiB,KAAK,CAAC;AAC1C;AAEA,IAAI;AACF,QAAM,KAAK,YAAY,IAAI;AAC7B,SAAS,OAAgB;AACvB,qBAAmB,KAAK;AAC1B;","names":["readFileSync","join","spawn","homedir","constants","dirname","join","constants","dirname","join","realpathSync","dirname","join","dirname","join","realpathSync","readFileSync","join","readFileSync","join","latest","rmSync","dirname","join","join","dirname","rmSync","defaultRuntime","homedir","spawn","notify","readFileSync","readFileSync","message"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../../core/src/package-metadata.ts","../../core/src/records.ts","../../core/src/saptools-paths.ts","../../core/src/self-update/reexec.ts","../../core/src/self-update/policy.ts","../../core/src/self-update/run.ts","../../core/src/self-update/install-location.ts","../../core/src/self-update/installer.ts","../../core/src/self-update/registry.ts","../../core/src/self-update/semver.ts","../../core/src/self-update/state.ts","../../core/src/self-update/commander.ts","../../core/src/cloud-logging/instance-discovery.ts","../../core/src/cloud-logging/credential-cache.ts","../../core/src/cloud-logging/result-store.ts","../src/cli-input.ts","../src/package-version.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport nodeProcess from \"node:process\";\n\nimport { attachSelfUpdate, registerSelfUpdateCommand } from \"@saptools/core\";\nimport { Command } from \"commander\";\n\nimport { readCurrentCfTarget, requireCurrentCfRegion } from \"./cf.js\";\nimport type { CurrentCfTargetReadOptions } from \"./cf.js\";\nimport {\n CLEANUP_FAILURE_EXIT_CODE,\n cliErrorExitCode,\n hasTunnelTerminationFailure,\n stopAllExitCode,\n} from \"./cli-errors.js\";\nimport {\n parseOptionalInteger,\n parseSeconds,\n readRequiredOption,\n} from \"./cli-input.js\";\nimport {\n DEFAULT_NODE_INSPECTOR_PORT,\n resolveNodeTarget,\n} from \"./cloud-foundry/node-process.js\";\nimport { runDoctor } from \"./debug-session/doctor.js\";\nimport { getDebuggerHandleTunnelError } from \"./debug-session/lifecycle.js\";\nimport { startDebuggerWithinDeadline } from \"./debug-session/start.js\";\nimport {\n createStartupDeadline,\n remainingStartupMs,\n resolveStartupTimeoutMs,\n startupTimeoutError,\n} from \"./debug-session/startup-deadline.js\";\nimport {\n getSession,\n listSessions,\n stopAllDebuggers,\n stopDebugger,\n} from \"./debugger.js\";\nimport { readPackageVersion } from \"./package-version.js\";\nimport { validateApiEndpointOverride } from \"./regions.js\";\nimport { parseRestartEnvironment } from \"./restart-policy.js\";\nimport type {\n DebuggerHandle,\n ResolvedSessionKey,\n SessionStatus,\n StartDebuggerOptions,\n} from \"./types.js\";\nimport { CfDebuggerError } from \"./types.js\";\n\ninterface TargetCommandOptions {\n readonly process?: string;\n readonly instance?: string;\n readonly nodePid?: string;\n readonly apiEndpoint?: string;\n}\n\ninterface StartCommandOptions extends TargetCommandOptions {\n readonly region?: string;\n readonly org?: string;\n readonly space?: string;\n readonly app?: string;\n readonly port?: string;\n readonly remotePort?: string;\n readonly timeout?: string;\n readonly startupTimeout?: string;\n readonly allowSshEnableRestart?: boolean;\n readonly sshEnableRestart?: boolean;\n readonly verbose?: boolean;\n}\n\ninterface StopCommandOptions extends TargetCommandOptions {\n readonly region?: string;\n readonly org?: string;\n readonly space?: string;\n readonly app?: string;\n readonly sessionId?: string;\n readonly all?: boolean;\n readonly force?: boolean;\n}\n\ntype StatusCommandOptions = Omit<StopCommandOptions, \"all\" | \"force\">;\nconst STOP_SCOPE_OPTION_NAMES = [\n \"apiEndpoint\",\n \"app\",\n \"instance\",\n \"nodePid\",\n \"org\",\n \"process\",\n \"region\",\n \"sessionId\",\n \"space\",\n] as const;\n\nfunction logStatus(verbose: boolean, status: SessionStatus, message?: string): void {\n if (!verbose) {\n return;\n }\n const suffix = message === undefined ? \"\" : `: ${message}`;\n nodeProcess.stdout.write(`[cf-debugger] ${status}${suffix}\\n`);\n}\n\nfunction mergeSelector<\n T extends { region?: string; org?: string; space?: string; app?: string },\n>(selector: string | undefined, options: T): T {\n if (selector === undefined) {\n return options;\n }\n const parts = selector.split(\"/\");\n if (parts.length === 1 && parts[0]?.length !== 0) {\n return { ...options, app: options.app ?? parts[0] };\n }\n if (parts.length === 4 && parts.every((part) => part.length > 0)) {\n return {\n ...options,\n region: options.region ?? parts[0],\n org: options.org ?? parts[1],\n space: options.space ?? parts[2],\n app: options.app ?? parts[3],\n };\n }\n throw new CfDebuggerError(\n \"UNSAFE_INPUT\",\n \"Invalid app selector. Expected <app> or non-empty <region>/<org>/<space>/<app> segments.\",\n );\n}\n\ninterface StartupAbort {\n readonly signal: AbortSignal;\n requestedExitCode(): number | undefined;\n dispose(): void;\n}\n\nfunction startupAbort(app: string): StartupAbort {\n const controller = new AbortController();\n let requestedExitCode: number | undefined;\n const handler = (exitCode: number) => (): void => {\n requestedExitCode ??= exitCode;\n controller.abort();\n nodeProcess.stderr.write(`\\nAborting startup for ${app}...\\n`);\n };\n const onSigint = handler(130);\n const onSigterm = handler(143);\n nodeProcess.on(\"SIGINT\", onSigint);\n nodeProcess.on(\"SIGTERM\", onSigterm);\n return {\n signal: controller.signal,\n requestedExitCode: (): number | undefined => requestedExitCode,\n dispose: (): void => {\n nodeProcess.off(\"SIGINT\", onSigint);\n nodeProcess.off(\"SIGTERM\", onSigterm);\n },\n };\n}\n\nfunction writeReady(\n app: string,\n key: ResolvedSessionKey,\n handle: DebuggerHandle,\n): void {\n nodeProcess.stdout.write(\n `Debugger ready for ${app} (${key.region}/${key.org}/${key.space}).\\n` +\n ` Process: ${key.process}\\n` +\n ` Instance: ${key.instance.toString()}\\n` +\n ` Local port: ${handle.session.localPort.toString()}\\n` +\n ` Remote port: ${handle.session.remotePort.toString()}\\n` +\n ` Session id: ${handle.session.sessionId}\\n` +\n ` Tunnel PID: ${handle.session.pid.toString()}\\n` +\n ` Node PID: ${handle.session.remoteNodePid?.toString() ?? \"unknown\"}\\n` +\n \"Press Ctrl+C to stop.\\n\",\n );\n}\n\nfunction writeCleanupError(error: unknown): void {\n const message = error instanceof Error ? error.message : String(error);\n nodeProcess.stderr.write(`Error during stop: ${message}\\n`);\n}\n\nasync function waitForHandle(\n app: string,\n handle: DebuggerHandle,\n): Promise<void> {\n let pendingDispose: Promise<void> | undefined;\n let requestedExitCode: number | undefined;\n const dispose = (): Promise<void> => {\n pendingDispose ??= (async (): Promise<void> => {\n nodeProcess.stdout.write(`\\nStopping debugger for ${app}...\\n`);\n await handle.dispose();\n })();\n return pendingDispose;\n };\n const stop = (exitCode: number) => (): void => {\n requestedExitCode = exitCode;\n void dispose()\n .catch((error: unknown) => {\n writeCleanupError(error);\n nodeProcess.exit(CLEANUP_FAILURE_EXIT_CODE);\n });\n };\n nodeProcess.on(\"SIGINT\", stop(130));\n nodeProcess.on(\"SIGTERM\", stop(143));\n const code = await handle.waitForExit();\n const tunnelError = getDebuggerHandleTunnelError(handle);\n if (tunnelError !== undefined) {\n nodeProcess.stderr.write(\n `Error [${tunnelError.code}]: ${tunnelError.message}\\n`,\n );\n if (tunnelError.stderr !== undefined && tunnelError.stderr.trim().length > 0) {\n nodeProcess.stderr.write(`[cf-debugger transport]\\n${tunnelError.stderr.trim()}\\n`);\n }\n }\n try {\n await dispose();\n } catch (error: unknown) {\n writeCleanupError(error);\n nodeProcess.exit(CLEANUP_FAILURE_EXIT_CODE);\n }\n nodeProcess.exit(requestedExitCode ?? code ?? 0);\n}\n\nfunction buildStartOptions(\n options: StartCommandOptions,\n key: ResolvedSessionKey,\n app: string,\n signal: AbortSignal,\n startupTimeoutMs: number,\n): StartDebuggerOptions {\n const preferredPort = parseOptionalInteger(options.port, \"port\", 1, 65_535);\n const remotePort = parseOptionalInteger(options.remotePort, \"remotePort\", 1, 65_535);\n const nodePid = parseOptionalInteger(options.nodePid, \"nodePid\", 1);\n const tunnelReadyTimeoutMs = parseSeconds(options.timeout, \"timeout\");\n const restartEnvironment = parseRestartEnvironment(\n nodeProcess.env[\"CF_DEBUGGER_ALLOW_RESTART\"],\n );\n const allowSshEnableRestart =\n options.sshEnableRestart !== false &&\n restartEnvironment !== \"forbid\" &&\n (options.allowSshEnableRestart === true || restartEnvironment === \"allow\");\n return {\n region: key.region,\n org: key.org,\n space: key.space,\n app,\n process: key.process,\n instance: key.instance,\n signal,\n allowSshEnableRestart,\n ...(options.apiEndpoint === undefined ? {} : { apiEndpoint: options.apiEndpoint }),\n ...(preferredPort === undefined ? {} : { preferredPort }),\n ...(remotePort === undefined ? {} : { remotePort }),\n ...(nodePid === undefined ? {} : { nodePid }),\n ...(tunnelReadyTimeoutMs === undefined ? {} : { tunnelReadyTimeoutMs }),\n startupTimeoutMs,\n };\n}\n\nfunction deadlineTimedOut(\n deadline: ReturnType<typeof createStartupDeadline>,\n): boolean {\n return remainingStartupMs(deadline.expiresAt) === 0 ||\n (\n deadline.signal.reason instanceof CfDebuggerError &&\n deadline.signal.reason.code === \"STARTUP_TIMEOUT\"\n );\n}\n\nfunction validateStartEndpoint(options: StartCommandOptions): StartCommandOptions {\n return options.apiEndpoint === undefined\n ? options\n : {\n ...options,\n apiEndpoint: validateApiEndpointOverride(options.apiEndpoint),\n };\n}\n\nasync function handleStart(\n selector: string | undefined,\n rawOptions: StartCommandOptions,\n): Promise<void> {\n const options = validateStartEndpoint(mergeSelector(selector, rawOptions));\n const app = readRequiredOption(options.app, \"--app or selector\");\n const verbose = options.verbose ?? false;\n const startupTimeoutMs = resolveStartupTimeoutMs(\n parseSeconds(options.startupTimeout, \"startupTimeout\"),\n );\n const abort = startupAbort(app);\n const deadline = createStartupDeadline(startupTimeoutMs, abort.signal);\n let handle;\n let phase = \"current CF target discovery\";\n let key: ResolvedSessionKey;\n try {\n key = await resolveSessionKey({ ...options, app }, deadline.signal);\n if (deadlineTimedOut(deadline)) {\n throw startupTimeoutError(startupTimeoutMs, phase);\n }\n phase = \"startup\";\n handle = await startDebuggerWithinDeadline({\n ...buildStartOptions(options, key, app, deadline.signal, startupTimeoutMs),\n verbose,\n onStatus: (status, message): void => {\n logStatus(verbose, status, message);\n },\n }, deadline);\n } catch (error: unknown) {\n const normalized = deadlineTimedOut(deadline) &&\n !(error instanceof CfDebuggerError && error.code === \"STARTUP_TIMEOUT\")\n ? startupTimeoutError(startupTimeoutMs, phase)\n : error;\n const exitCode = abort.requestedExitCode();\n if (exitCode !== undefined && typeof normalized === \"object\" && normalized !== null) {\n Reflect.set(normalized, \"cliExitCode\", exitCode);\n }\n throw normalized;\n } finally {\n deadline.dispose();\n abort.dispose();\n }\n writeReady(app, key, handle);\n await waitForHandle(app, handle);\n}\n\nfunction optionalText(value: string | undefined): string | undefined {\n const trimmed = value?.trim();\n return trimmed === undefined || trimmed.length === 0 ? undefined : trimmed;\n}\n\nfunction currentCfOptions(signal?: AbortSignal): CurrentCfTargetReadOptions | undefined {\n const command = nodeProcess.env[\"CF_DEBUGGER_CF_BIN\"];\n if (command === undefined && signal === undefined) {\n return undefined;\n }\n return {\n ...(command === undefined ? {} : { command }),\n ...(signal === undefined ? {} : { signal }),\n };\n}\n\ninterface ResolvedCfScope {\n readonly region: string;\n readonly org: string;\n readonly space: string;\n}\n\nfunction currentTargetReadError(error: unknown): CfDebuggerError {\n return new CfDebuggerError(\n \"CF_TARGET_FAILED\",\n \"No current CF target. Run `cf target -o <org> -s <space>` or pass --region/--org/--space.\",\n error instanceof Error ? error.message : String(error),\n );\n}\n\nfunction missingCurrentTargetError(): CfDebuggerError {\n return new CfDebuggerError(\n \"CF_TARGET_FAILED\",\n \"No current CF target. Run `cf target -o <org> -s <space>` or pass --region/--org/--space.\",\n );\n}\n\nasync function resolveCfScope(\n region: string | undefined,\n org: string | undefined,\n space: string | undefined,\n signal?: AbortSignal,\n): Promise<ResolvedCfScope> {\n if (region !== undefined && org !== undefined && space !== undefined) {\n return { region, org, space };\n }\n const current = await readCurrentCfTarget(currentCfOptions(signal)).catch((error: unknown) => {\n if (\n error instanceof CfDebuggerError &&\n (error.code === \"ABORTED\" || error.code === \"STARTUP_TIMEOUT\")\n ) {\n throw error;\n }\n throw currentTargetReadError(error);\n });\n if (current === undefined) {\n throw missingCurrentTargetError();\n }\n return {\n region: region ?? requireCurrentCfRegion(current),\n org: org ?? current.org,\n space: space ?? current.space,\n };\n}\n\nasync function resolveSessionKey(\n options: StopCommandOptions,\n signal?: AbortSignal,\n): Promise<ResolvedSessionKey> {\n const app = readRequiredOption(options.app, \"--app or selector\");\n const region = optionalText(options.region);\n const org = optionalText(options.org);\n const space = optionalText(options.space);\n const nodePid = parseOptionalInteger(options.nodePid, \"nodePid\", 1);\n const instance = parseOptionalInteger(options.instance, \"instance\", 0);\n const target = resolveNodeTarget({\n ...(options.process === undefined ? {} : { process: options.process }),\n ...(instance === undefined ? {} : { instance }),\n ...(nodePid === undefined ? {} : { nodePid }),\n });\n const scope = await resolveCfScope(region, org, space, signal);\n return {\n ...scope,\n app,\n process: target.process,\n instance: target.instance,\n ...(options.apiEndpoint === undefined ? {} : { apiEndpoint: options.apiEndpoint }),\n ...(target.nodePid === undefined ? {} : { nodePid: target.nodePid }),\n };\n}\n\nasync function resolveOptionalSessionKey(\n options: StopCommandOptions,\n): Promise<ResolvedSessionKey | undefined> {\n if (optionalText(options.app) === undefined) {\n if (\n optionalText(options.region) !== undefined ||\n optionalText(options.org) !== undefined ||\n optionalText(options.space) !== undefined\n ) {\n readRequiredOption(options.app, \"--app or selector\");\n }\n return undefined;\n }\n return await resolveSessionKey(options);\n}\n\nfunction writeStopResult(result: Awaited<ReturnType<typeof stopDebugger>>): void {\n if (result === undefined) {\n return;\n }\n if (result.warning !== undefined) {\n nodeProcess.stderr.write(`[cf-debugger] warning: ${result.warning}\\n`);\n }\n if (result.pending) {\n nodeProcess.stdout.write(\n `Stop requested for session ${result.sessionId} (${result.app}, phase ${result.status}).\\n`,\n );\n } else if (result.stale) {\n nodeProcess.stdout.write(\n `Removed ${result.forced ? \"forced \" : \"\"}stale session ${result.sessionId} ` +\n `(${result.app}, port ${result.localPort.toString()}).\\n`,\n );\n } else {\n nodeProcess.stdout.write(\n `Stopped session ${result.sessionId} (${result.app}, port ${result.localPort.toString()}).\\n`,\n );\n }\n}\n\nfunction rejectScopedStopAll(\n selector: string | undefined,\n options: StopCommandOptions,\n command: Command,\n): void {\n if (\n options.all === true &&\n (\n selector !== undefined ||\n STOP_SCOPE_OPTION_NAMES.some((name) => command.getOptionValueSource(name) === \"cli\")\n )\n ) {\n throw new CfDebuggerError(\n \"UNSAFE_INPUT\",\n \"--all cannot be combined with a selector, --session-id, or target selector options.\",\n );\n }\n}\n\nasync function handleStopAll(force: boolean): Promise<void> {\n const summary = await stopAllDebuggers(force);\n for (const outcome of summary.outcomes) {\n if (outcome.error === undefined) {\n writeStopResult(outcome.result);\n } else {\n nodeProcess.stderr.write(\n `Failed ${outcome.sessionId} (${outcome.app}): ${outcome.error.message}\\n`,\n );\n }\n }\n nodeProcess.stdout.write(\n `Stop summary: ${summary.stopped.toString()} stopped, ${summary.forced.toString()} forced, ` +\n `${summary.stale.toString()} stale, ` +\n `${summary.pending.toString()} pending, ${summary.failed.toString()} failed.\\n`,\n );\n const exitCode = stopAllExitCode(\n summary.outcomes.flatMap((outcome) =>\n outcome.error === undefined ? [] : [outcome.error]),\n );\n if (exitCode !== undefined) {\n nodeProcess.exitCode = exitCode;\n }\n}\n\nasync function handleStop(\n selector: string | undefined,\n rawOptions: StopCommandOptions,\n command: Command,\n): Promise<void> {\n rejectScopedStopAll(selector, rawOptions, command);\n const options = mergeSelector(selector, rawOptions);\n if (options.all === true) {\n await handleStopAll(options.force === true);\n return;\n }\n const key = await resolveOptionalSessionKey(options);\n const result = await stopDebugger({\n ...(options.sessionId === undefined ? {} : { sessionId: options.sessionId }),\n ...(key === undefined ? {} : { key }),\n force: options.force === true,\n });\n if (result === undefined) {\n throw new CfDebuggerError(\n \"SESSION_NOT_FOUND\",\n \"No matching session. Use `cf-debugger list` and pass --session-id or an exact key.\",\n );\n }\n writeStopResult(result);\n}\n\nasync function handleList(): Promise<void> {\n nodeProcess.stdout.write(`${JSON.stringify(await listSessions(), null, 2)}\\n`);\n}\n\nasync function handleStatus(\n selector: string | undefined,\n rawOptions: StatusCommandOptions,\n): Promise<void> {\n const options = mergeSelector(selector, rawOptions);\n const session = options.sessionId === undefined\n ? await getSession(await resolveSessionKey(options))\n : (await listSessions()).find((candidate) => candidate.sessionId === options.sessionId);\n nodeProcess.stdout.write(`${JSON.stringify(session ?? null, null, 2)}\\n`);\n}\n\nasync function handleDoctor(cleanup: boolean): Promise<void> {\n const report = await runDoctor({ cleanup });\n nodeProcess.stdout.write(`${JSON.stringify(report, null, 2)}\\n`);\n}\n\nfunction registerStartCommand(program: Command): void {\n program\n .command(\"start\")\n .description(\"Open a debug tunnel for one app\")\n .argument(\"[selector]\", \"Optional <app> or <region>/<org>/<space>/<app>\")\n .option(\"--region <key>\", \"CF region key (default: current cf target)\")\n .option(\"--api-endpoint <url>\", \"Absolute HTTPS CF API endpoint override\")\n .option(\"--org <name>\", \"CF org (default: current cf target)\")\n .option(\"--space <name>\", \"CF space (default: current cf target)\")\n .option(\"--app <name>\", \"CF app name\")\n .option(\"--process <name>\", \"CF process name\", \"web\")\n .option(\"-i, --instance <index>\", \"CF process instance\", \"0\")\n .option(\"--node-pid <pid>\", \"Explicit remote Node.js PID\")\n .option(\"--port <number>\", \"Preferred local port\")\n .option(\n \"--remote-port <number>\",\n \"Port where cf-debugger looks for an existing remote inspector\",\n DEFAULT_NODE_INSPECTOR_PORT.toString(),\n )\n .option(\"--timeout <seconds>\", \"Tunnel/inspector readiness timeout\", \"180\")\n .option(\"--startup-timeout <seconds>\", \"Overall startup deadline\", \"300\")\n .option(\n \"--allow-ssh-enable-restart\",\n \"Allow app-level SSH enablement and an app restart (opt-in)\",\n )\n .option(\n \"--no-ssh-enable-restart\",\n \"Forbid app-level SSH enablement and restart, overriding flag/environment\",\n )\n .option(\"--verbose\", \"Print status transitions and tunnel diagnostics\", false)\n .action(async (selector: string | undefined, options: StartCommandOptions): Promise<void> => {\n await handleStart(selector, options);\n });\n}\n\nfunction addKeyOptions(command: Command): Command {\n return command\n .option(\"--region <key>\")\n .option(\"--api-endpoint <url>\", \"Exact API endpoint selector\")\n .option(\"--org <name>\")\n .option(\"--space <name>\")\n .option(\"--app <name>\")\n .option(\"--process <name>\", \"CF process name\", \"web\")\n .option(\"-i, --instance <index>\", \"CF process instance\", \"0\")\n .option(\"--node-pid <pid>\", \"Exact remote Node PID selector\");\n}\n\nfunction registerStopCommand(program: Command): void {\n addKeyOptions(\n program\n .command(\"stop\")\n .description(\"Stop one session by exact key/id, or every session with --all\")\n .argument(\"[selector]\", \"Optional <app> or <region>/<org>/<space>/<app>\"),\n )\n .option(\"--session-id <id>\")\n .option(\n \"--all\",\n \"Attempt every active session; cannot be combined with session selectors\",\n false,\n )\n .option(\n \"--force\",\n \"Forget unverifiable state first; best-effort remove its exact owned CF home; \" +\n \"never signal an unverified process\",\n false,\n )\n .action(\n async (\n selector: string | undefined,\n options: StopCommandOptions,\n command: Command,\n ): Promise<void> => {\n await handleStop(selector, options, command);\n },\n );\n}\n\nfunction registerReadCommands(program: Command): void {\n program\n .command(\"list\")\n .description(\"Print every active debugger session as JSON\")\n .action(async (): Promise<void> => {\n await handleList();\n });\n addKeyOptions(\n program\n .command(\"status\")\n .description(\"Print one exact session as JSON; null only when no session matches\")\n .argument(\"[selector]\", \"Optional <app> or <region>/<org>/<space>/<app>\"),\n )\n .option(\"--session-id <id>\", \"Exact session ID selector\")\n .action(async (selector: string | undefined, options: StatusCommandOptions): Promise<void> => {\n await handleStatus(selector, options);\n });\n program\n .command(\"doctor\")\n .description(\"Report session health, orphan homes/ports, temp files, and legacy credentials\")\n .option(\"--cleanup\", \"Remove only safe orphan v2 homes and stale v2 temp/lock files\", false)\n .action(async (options: { readonly cleanup?: boolean }): Promise<void> => {\n await handleDoctor(options.cleanup === true);\n });\n}\n\nexport async function main(argv: readonly string[]): Promise<void> {\n const version = readPackageVersion();\n // Every command first checks npm (at most once an hour) and re-runs itself on a newer release; see `@saptools/core`.\n const selfUpdate = { packageName: \"@saptools/cf-debugger\", currentVersion: version, binName: \"cf-debugger\", envPrefix: \"CF_DEBUGGER\" };\n const program = new Command()\n .name(\"cf-debugger\")\n .description(\"Open an SSH debug tunnel to a SAP BTP Cloud Foundry Node.js inspector\")\n .version(version);\n attachSelfUpdate(program, selfUpdate);\n registerStartCommand(program);\n registerStopCommand(program);\n registerReadCommands(program);\n registerSelfUpdateCommand(program, selfUpdate);\n await program.parseAsync([...argv]);\n}\n\nfunction writeTopLevelError(error: unknown): void {\n if (error instanceof CfDebuggerError) {\n if (error.code === \"ABORTED\") {\n nodeProcess.stderr.write(`Aborted: ${error.message}\\n`);\n nodeProcess.exit(cliErrorExitCode(error));\n }\n nodeProcess.stderr.write(`Error [${error.code}]: ${error.message}\\n`);\n if (error.stderr !== undefined && error.stderr.trim().length > 0) {\n nodeProcess.stderr.write(`[cf-debugger transport]\\n${error.stderr.trim()}\\n`);\n }\n nodeProcess.exit(cliErrorExitCode(error));\n }\n if (hasTunnelTerminationFailure(error)) {\n const message = error instanceof Error ? error.message : String(error);\n nodeProcess.stderr.write(`Error during cleanup: ${message}\\n`);\n nodeProcess.exit(CLEANUP_FAILURE_EXIT_CODE);\n }\n const message = error instanceof Error ? error.message : String(error);\n nodeProcess.stderr.write(`Error: ${message}\\n`);\n nodeProcess.exit(cliErrorExitCode(error));\n}\n\ntry {\n await main(nodeProcess.argv);\n} catch (error: unknown) {\n writeTopLevelError(error);\n}\n","import { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { isRecord, readString } from \"./records.js\";\n\nexport interface PackageMetadata {\n readonly name: string;\n readonly version: string;\n /** Directory that holds the package.json. */\n readonly directory: string;\n}\n\n/**\n * A bundled CLI lives at `<package>/dist/cli.js`; a source file under test at\n * `<package>/src/...`; tsup chunks one level deeper. Six levels covers every\n * layout in this repo with room to spare while still failing fast on a stray\n * file outside any package.\n */\nconst MAX_WALK_UP = 6;\n\n/** Parse `<directory>/package.json`; undefined when missing, unreadable, or not a manifest with name and version. */\nexport function readPackageManifest(directory: string): PackageMetadata | undefined {\n let raw: string;\n try {\n raw = readFileSync(join(directory, \"package.json\"), \"utf8\");\n } catch {\n return;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return;\n }\n if (!isRecord(parsed)) {\n return;\n }\n const name = readString(parsed, \"name\");\n const version = readString(parsed, \"version\");\n if (name === undefined || version === undefined) {\n return;\n }\n return { name, version, directory };\n}\n\n/** Walk up from `startDirectory` to the nearest package.json whose `name` is `expectedName`. */\nexport function findPackageMetadata(startDirectory: string, expectedName: string): PackageMetadata | undefined {\n let current = startDirectory;\n for (let depth = 0; depth < MAX_WALK_UP; depth += 1) {\n const manifest = readPackageManifest(current);\n if (manifest?.name === expectedName) {\n return manifest;\n }\n const parent = dirname(current);\n if (parent === current) {\n return;\n }\n current = parent;\n }\n return;\n}\n\n/**\n * Version and name of the package that owns the calling module, read from its\n * package.json at runtime so `--version` and the self-updater can never drift\n * from the manifest the way a hand-maintained constant does. Throws when the\n * manifest cannot be found: a broken install should fail loudly, not report\n * \"0.0.0\".\n */\nexport function readPackageMetadata(importMetaUrl: string, expectedName: string): PackageMetadata {\n const startDirectory = dirname(fileURLToPath(importMetaUrl));\n const found = findPackageMetadata(startDirectory, expectedName);\n if (found === undefined) {\n throw new Error(`Cannot find the package.json of ${expectedName} above ${startDirectory}`);\n }\n return found;\n}\n","export function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** A non-empty string field of a parsed JSON object, or undefined when absent or of another type. */\nexport function readString(record: Record<string, unknown>, key: string): string | undefined {\n const value = record[key];\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n","import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport const SAPTOOLS_DIR_NAME = \".saptools\";\n/** Relocates every saptools state file at once; packages may still offer their own narrower override. */\nexport const SAPTOOLS_ROOT_ENV = \"SAPTOOLS_ROOT\";\n\nexport function resolveSaptoolsRoot(explicit?: string, env: NodeJS.ProcessEnv = process.env): string {\n if (explicit !== undefined && explicit.length > 0) {\n return explicit;\n }\n const fromEnv = env[SAPTOOLS_ROOT_ENV];\n if (fromEnv !== undefined && fromEnv.length > 0) {\n return fromEnv;\n }\n return join(homedir(), SAPTOOLS_DIR_NAME);\n}\n\n/**\n * Create `directory` (and missing parents) readable by the current user only.\n * Only the leaf has its mode enforced: parents such as `~/.saptools` itself\n * belong to every tool and keep whatever mode they already have.\n */\nexport function ensurePrivateDirectorySync(directory: string): void {\n mkdirSync(directory, { recursive: true, mode: 0o700 });\n try {\n chmodSync(directory, 0o700);\n } catch {\n // Filesystems without POSIX modes (some network mounts, Windows) reject chmod; the directory still exists.\n }\n}\n\n/**\n * Replace `path` atomically: write a sibling temp file with `mode`, then\n * rename it over the target, so a concurrent reader never sees a half-written\n * file and a crash never leaves a truncated one behind.\n */\nexport function writeFileAtomicSync(path: string, data: string, mode = 0o600): void {\n const temp = `${path}.${String(process.pid)}.${Math.random().toString(36).slice(2, 8)}.tmp`;\n try {\n writeFileSync(temp, data, { encoding: \"utf8\", mode });\n try {\n chmodSync(temp, mode);\n } catch {\n // Same as above: best effort where modes are unsupported.\n }\n renameSync(temp, path);\n } catch (error) {\n rmSync(temp, { force: true });\n throw error;\n }\n}\n\n/** Parse a JSON file; a missing or malformed file reads as undefined so corrupt state can never break a command. */\nexport function readJsonFileSync(path: string): unknown {\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch {\n return;\n }\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n return;\n }\n}\n","import { spawn } from \"node:child_process\";\nimport { constants } from \"node:os\";\n\nimport type { SpawnLike } from \"./process-types.js\";\n\n/** Set on the re-executed process so it can never start a second update. */\nexport const REEXEC_MARKER_ENV = \"SAPTOOLS_SELF_UPDATE_REEXEC\";\n\nexport interface ReexecRequest {\n readonly execPath: string;\n readonly execArgv: readonly string[];\n readonly binPath: string;\n readonly args: readonly string[];\n readonly env: NodeJS.ProcessEnv;\n}\n\n/** Resolves only when the re-executed command has finished and the replacement failed to end this process itself. */\nexport type ReexecImpl = (request: ReexecRequest) => Promise<void>;\n\ntype ExecveLike = (file: string, args: readonly string[], env: NodeJS.ProcessEnv) => never;\n\nexport interface ReexecRuntime {\n readonly platform: NodeJS.Platform;\n readonly execve: ExecveLike | undefined;\n readonly spawnImpl: SpawnLike;\n readonly onSignal: (signal: NodeJS.Signals, handler: (signal: NodeJS.Signals) => void) => void;\n readonly offSignal: (signal: NodeJS.Signals, handler: (signal: NodeJS.Signals) => void) => void;\n readonly kill: (pid: number, signal: NodeJS.Signals) => void;\n readonly exit: (code: number) => void;\n}\n\nconst FORWARDED_SIGNALS: readonly NodeJS.Signals[] = [\"SIGINT\", \"SIGTERM\", \"SIGHUP\"];\n\nfunction nativeExecve(): ExecveLike | undefined {\n return process.execve?.bind(process);\n}\n\nfunction defaultRuntime(): ReexecRuntime {\n return {\n platform: process.platform,\n execve: nativeExecve(),\n spawnImpl: spawn,\n onSignal: (signal, handler): void => {\n process.on(signal, handler);\n },\n offSignal: (signal, handler): void => {\n process.off(signal, handler);\n },\n kill: (pid, signal): void => {\n process.kill(pid, signal);\n },\n exit: (code): void => {\n process.exit(code);\n },\n };\n}\n\nexport function buildReexecArgv(request: ReexecRequest): string[] {\n return [...request.execArgv, request.binPath, ...request.args];\n}\n\nexport function reexecEnvironment(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n return { ...env, [REEXEC_MARKER_ENV]: \"1\" };\n}\n\nfunction signalExitCode(signal: NodeJS.Signals): number {\n const number = constants.signals[signal];\n return 128 + number;\n}\n\n/**\n * Run the same command again on the freshly installed version. On POSIX with\n * Node >= 22.15 the process image is replaced outright (`execve`), so stdin,\n * stdout, the exit code and signals all belong to the new version with no\n * wrapper left behind. Elsewhere a child inherits our stdio, terminal signals\n * are forwarded to it, and we mirror its exit code or signal.\n */\nexport async function reexecProcess(request: ReexecRequest, runtimeOverrides: Partial<ReexecRuntime> = {}): Promise<void> {\n const runtime: ReexecRuntime = { ...defaultRuntime(), ...runtimeOverrides };\n const argv = buildReexecArgv(request);\n const env = reexecEnvironment(request.env);\n\n if (runtime.platform !== \"win32\" && runtime.execve !== undefined) {\n try {\n runtime.execve(request.execPath, [request.execPath, ...argv], env);\n } catch {\n // execve refused (for example EACCES on an odd mount): the child-process route below still works.\n }\n }\n\n await new Promise<void>((resolve, reject) => {\n const child = runtime.spawnImpl(request.execPath, argv, { stdio: \"inherit\", env });\n const forward = (signal: NodeJS.Signals): void => {\n child.kill(signal);\n };\n for (const signal of FORWARDED_SIGNALS) {\n runtime.onSignal(signal, forward);\n }\n const detach = (): void => {\n for (const signal of FORWARDED_SIGNALS) {\n runtime.offSignal(signal, forward);\n }\n };\n child.once(\"error\", (error) => {\n detach();\n reject(error);\n });\n child.once(\"exit\", (code, signal) => {\n detach();\n if (signal === null) {\n runtime.exit(code ?? 1);\n } else {\n runtime.kill(process.pid, signal);\n runtime.exit(signalExitCode(signal));\n }\n resolve();\n });\n });\n}\n","import type { InstallLocation } from \"./install-location.js\";\nimport { REEXEC_MARKER_ENV } from \"./reexec.js\";\n\nexport type UpdatePolicy = \"on\" | \"notify\" | \"off\";\n\nexport const POLICY_ENV = \"SAPTOOLS_AUTO_UPDATE\";\nexport const INTERVAL_ENV = \"SAPTOOLS_UPDATE_INTERVAL_MINUTES\";\nexport const DEBUG_ENV = \"SAPTOOLS_UPDATE_DEBUG\";\nexport const DEFAULT_CHECK_INTERVAL_MINUTES = 60;\nexport const SELF_UPDATE_COMMAND = \"self-update\";\n\nexport interface PolicyDecision {\n readonly policy: UpdatePolicy;\n readonly reason: string;\n /** True when the user set the policy through the environment rather than relying on the default. */\n readonly explicit: boolean;\n}\n\nexport interface ResolvePolicyInput {\n readonly env: NodeJS.ProcessEnv;\n readonly envPrefix?: string;\n readonly location: InstallLocation;\n /** Space-joined command path being run, e.g. `credential list`; empty for the root action. */\n readonly commandPath?: string;\n readonly skipCommands?: readonly string[];\n /** The explicit `self-update` command: ignore the exclusions and CI/test gates, but never the install-location facts. */\n readonly manual?: boolean;\n}\n\nexport function parsePolicy(raw: string | undefined): UpdatePolicy | undefined {\n if (raw === undefined) {\n return;\n }\n const value = raw.trim().toLowerCase();\n if ([\"on\", \"1\", \"true\", \"yes\", \"auto\", \"always\"].includes(value)) {\n return \"on\";\n }\n if ([\"notify\", \"check\"].includes(value)) {\n return \"notify\";\n }\n if ([\"off\", \"0\", \"false\", \"no\", \"never\", \"disabled\"].includes(value)) {\n return \"off\";\n }\n return;\n}\n\n/** `CI=true`, `CI=1`, even `CI=yes` count; `CI=0`, `CI=false` and an empty value do not. */\nexport function isTruthyFlag(raw: string | undefined): boolean {\n return raw !== undefined && ![\"\", \"0\", \"false\", \"no\", \"off\"].includes(raw.trim().toLowerCase());\n}\n\nfunction readExplicitPolicy(env: NodeJS.ProcessEnv, envPrefix: string | undefined): UpdatePolicy | undefined {\n const perPackage = envPrefix === undefined ? undefined : parsePolicy(env[`${envPrefix}_AUTO_UPDATE`]);\n return perPackage ?? parsePolicy(env[POLICY_ENV]);\n}\n\nfunction off(reason: string, explicit: boolean): PolicyDecision {\n return { policy: \"off\", reason, explicit };\n}\n\nfunction notify(reason: string, explicit: boolean): PolicyDecision {\n return { policy: \"notify\", reason, explicit };\n}\n\nfunction locationDecision(location: InstallLocation, explicit: boolean): PolicyDecision | undefined {\n switch (location.kind) {\n case \"local\":\n return off(\"running from a source checkout or linked package, not a package-manager install\", explicit);\n case \"npx\":\n return off(\"running through npx or dlx, which resolves the version on its own\", explicit);\n case \"unknown\":\n return notify(`install location not recognized (${location.detail})`, explicit);\n case \"npm-global\":\n case \"pnpm-global\":\n case \"yarn-global\":\n case \"bun-global\":\n case \"volta\":\n return;\n }\n}\n\n/**\n * Decide what this invocation may do. Order matters: the re-exec marker and\n * the command exclusions are absolute, an explicit `off` wins next, then the\n * environment defaults (CI, test runs) that only an explicit setting\n * overrides, and only then the facts about the install: a checkout can never\n * be upgraded by npm, a read-only prefix can only be announced.\n */\nexport function resolveUpdatePolicy(input: ResolvePolicyInput): PolicyDecision {\n const { env, location } = input;\n const manual = input.manual === true;\n const explicit = readExplicitPolicy(env, input.envPrefix);\n\n if (!manual && isTruthyFlag(env[REEXEC_MARKER_ENV])) {\n return off(\"already re-executed after an update\", false);\n }\n const commandPath = input.commandPath ?? \"\";\n if (!manual && (commandPath === SELF_UPDATE_COMMAND || (input.skipCommands ?? []).includes(commandPath))) {\n return off(`the \"${commandPath}\" command is excluded from automatic updates`, false);\n }\n if (!manual && explicit === \"off\") {\n return off(`${POLICY_ENV} is off`, true);\n }\n if (!manual && explicit === undefined) {\n if (isTruthyFlag(env[\"NO_UPDATE_NOTIFIER\"])) {\n return off(\"NO_UPDATE_NOTIFIER is set\", false);\n }\n if (isTruthyFlag(env[\"CI\"])) {\n return off(\"running in CI\", false);\n }\n if (env[\"NODE_ENV\"] === \"test\") {\n return off(\"NODE_ENV is test\", false);\n }\n }\n const byLocation = locationDecision(location, explicit !== undefined);\n if (byLocation !== undefined) {\n return byLocation;\n }\n if (!location.writable) {\n return notify(\"the install directory is not writable by this user\", explicit !== undefined);\n }\n if (manual) {\n return { policy: \"on\", reason: \"requested explicitly\", explicit: true };\n }\n return explicit === undefined\n ? { policy: \"on\", reason: \"default\", explicit: false }\n : { policy: explicit, reason: `${POLICY_ENV} is ${explicit}`, explicit: true };\n}\n\n/** Minutes between registry checks; `0` checks on every run. Invalid values fall back to the default. */\nexport function resolveCheckIntervalMs(env: NodeJS.ProcessEnv): number {\n const raw = env[INTERVAL_ENV];\n if (raw === undefined) {\n return DEFAULT_CHECK_INTERVAL_MINUTES * 60_000;\n }\n const minutes = Number(raw.trim());\n if (!Number.isFinite(minutes) || minutes < 0) {\n return DEFAULT_CHECK_INTERVAL_MINUTES * 60_000;\n }\n return Math.round(minutes * 60_000);\n}\n","import { spawn } from \"node:child_process\";\nimport { homedir } from \"node:os\";\n\nimport { readPackageManifest } from \"../package-metadata.js\";\nimport { errorMessage } from \"../records.js\";\nimport { resolveSaptoolsRoot } from \"../saptools-paths.js\";\n\nimport { detectInstallLocation } from \"./install-location.js\";\nimport type { InstallLocation } from \"./install-location.js\";\nimport { buildInstallCommand, DEFAULT_INSTALL_TIMEOUT_MS, manualInstallCommand, runInstall } from \"./installer.js\";\nimport { DEBUG_ENV, isTruthyFlag, resolveCheckIntervalMs, resolveUpdatePolicy } from \"./policy.js\";\nimport type { PolicyDecision } from \"./policy.js\";\nimport type { SpawnLike } from \"./process-types.js\";\nimport { reexecProcess } from \"./reexec.js\";\nimport type { ReexecImpl } from \"./reexec.js\";\nimport { DEFAULT_CHECK_TIMEOUT_MS, fetchLatestVersion, readUserNpmrc, resolveRegistryUrl } from \"./registry.js\";\nimport { isNewerRelease } from \"./semver.js\";\nimport {\n acquireUpdateLock,\n clearFailure,\n EMPTY_UPDATE_STATE,\n readUpdateState,\n updateLockPath,\n updateStatePath,\n writeUpdateState,\n} from \"./state.js\";\nimport type { UpdateState } from \"./state.js\";\n\nexport interface SelfUpdateOptions {\n /** npm package name, e.g. `@saptools/cf-metrics`. */\n readonly packageName: string;\n /** The running version, read from package.json (see readPackageMetadata). */\n readonly currentVersion: string;\n /** Executable name used as the prefix of every notice, e.g. `cf-metrics`. */\n readonly binName: string;\n /** Per-package override namespace: `CF_METRICS` honours `CF_METRICS_AUTO_UPDATE`. */\n readonly envPrefix?: string;\n /** Space-joined command paths that must never trigger an update (internal workers, daemons). */\n readonly skipCommands?: readonly string[];\n /** The command being run, supplied by the commander hook. */\n readonly commandPath?: string;\n readonly saptoolsRoot?: string;\n /** Where notices go; defaults to `<binName>: <line>` on stderr. Never stdout. */\n readonly notice?: (line: string) => void;\n /** The explicit `self-update` command: ignore the check interval, backoffs and policy gates. */\n readonly manual?: boolean;\n /** Re-run the command on the new version after installing (default true). */\n readonly reexec?: boolean;\n}\n\nexport interface SelfUpdateRuntime {\n readonly env: NodeJS.ProcessEnv;\n readonly argv: readonly string[];\n readonly execPath: string;\n readonly execArgv: readonly string[];\n readonly platform: NodeJS.Platform;\n readonly homeDirectory: string;\n readonly now: () => Date;\n readonly fetchImpl: typeof fetch;\n readonly spawnImpl: SpawnLike;\n readonly reexecImpl: ReexecImpl;\n readonly checkTimeoutMs: number;\n readonly installTimeoutMs: number;\n readonly realpath?: (path: string) => string;\n readonly isWritable?: (path: string) => boolean;\n readonly exists?: (path: string) => boolean;\n}\n\nexport type SelfUpdateOutcome =\n | { readonly kind: \"skipped\"; readonly reason: string }\n | { readonly kind: \"current\"; readonly latest: string }\n | { readonly kind: \"notified\"; readonly latest: string; readonly reason: string }\n | { readonly kind: \"updated\"; readonly from: string; readonly to: string }\n | { readonly kind: \"failed\"; readonly latest: string; readonly reason: string };\n\nexport interface SelfUpdateStatus {\n readonly packageName: string;\n readonly installed: string;\n readonly location: InstallLocation;\n readonly policy: PolicyDecision;\n readonly registryUrl: string;\n readonly statePath: string;\n readonly latest: string | undefined;\n readonly checkError: string | undefined;\n}\n\n/** After a failed registry call, stay quiet this long instead of paying the timeout on every command. */\nconst FAILURE_BACKOFF_MS = 15 * 60_000;\n/** A version we already announced is not announced again for a day. */\nconst NOTIFY_INTERVAL_MS = 24 * 60 * 60_000;\n/** A version whose install failed is not retried for a day; the notice carries the manual command instead. */\nconst INSTALL_RETRY_BACKOFF_MS = 24 * 60 * 60_000;\n\ninterface Context {\n readonly options: SelfUpdateOptions;\n readonly runtime: SelfUpdateRuntime;\n readonly binPath: string;\n readonly location: InstallLocation;\n readonly decision: PolicyDecision;\n readonly registryUrl: string;\n readonly statePath: string;\n readonly intervalMs: number;\n state: UpdateState;\n readonly notice: (line: string) => void;\n readonly debug: (line: string) => void;\n}\n\nfunction defaultRuntime(): SelfUpdateRuntime {\n return {\n env: process.env,\n argv: process.argv,\n execPath: process.execPath,\n execArgv: process.execArgv,\n platform: process.platform,\n homeDirectory: homedir(),\n now: (): Date => new Date(),\n fetchImpl: fetch,\n spawnImpl: spawn,\n reexecImpl: reexecProcess,\n checkTimeoutMs: DEFAULT_CHECK_TIMEOUT_MS,\n installTimeoutMs: DEFAULT_INSTALL_TIMEOUT_MS,\n };\n}\n\nfunction ageMs(isoTimestamp: string, nowMs: number): number {\n const then = Date.parse(isoTimestamp);\n // A timestamp in the future means the clock moved backwards; treat it as stale so the state self-heals.\n return Number.isNaN(then) || then > nowMs ? Number.POSITIVE_INFINITY : nowMs - then;\n}\n\nfunction detectLocation(options: SelfUpdateOptions, runtime: SelfUpdateRuntime, binPath: string): InstallLocation {\n return detectInstallLocation({\n binPath,\n packageName: options.packageName,\n platform: runtime.platform,\n env: runtime.env,\n ...(runtime.realpath === undefined ? {} : { realpath: runtime.realpath }),\n ...(runtime.isWritable === undefined ? {} : { isWritable: runtime.isWritable }),\n });\n}\n\nfunction createContext(options: SelfUpdateOptions, runtime: SelfUpdateRuntime): Context {\n const { env } = runtime;\n const binPath = runtime.argv[1] ?? \"\";\n const location = detectLocation(options, runtime, binPath);\n const decision = resolveUpdatePolicy({\n env,\n location,\n skipCommands: options.skipCommands ?? [],\n manual: options.manual === true,\n ...(options.envPrefix === undefined ? {} : { envPrefix: options.envPrefix }),\n ...(options.commandPath === undefined ? {} : { commandPath: options.commandPath }),\n });\n const statePath = updateStatePath(resolveSaptoolsRoot(options.saptoolsRoot, env), options.packageName);\n const notice =\n options.notice ??\n ((line: string): void => {\n process.stderr.write(`${options.binName}: ${line}\\n`);\n });\n const debug = isTruthyFlag(env[DEBUG_ENV])\n ? (line: string): void => {\n process.stderr.write(`${options.binName}: [self-update] ${line}\\n`);\n }\n : (): void => {\n // Debug output is off unless SAPTOOLS_UPDATE_DEBUG is set.\n };\n return {\n options,\n runtime,\n binPath,\n location,\n decision,\n registryUrl: resolveRegistryUrl(env, readUserNpmrc(runtime.homeDirectory)),\n statePath,\n intervalMs: resolveCheckIntervalMs(env),\n // Loaded lazily in resolveLatest: a disabled run must not touch ~/.saptools at all.\n state: EMPTY_UPDATE_STATE,\n notice,\n debug,\n };\n}\n\nfunction saveState(ctx: Context): void {\n try {\n writeUpdateState(ctx.statePath, ctx.state);\n } catch (error) {\n ctx.debug(`cannot write ${ctx.statePath}: ${errorMessage(error)}`);\n }\n}\n\n/** The newest published version: from the state file while it is fresh, otherwise from the registry. */\nasync function resolveLatest(ctx: Context): Promise<string | undefined> {\n ctx.state = readUpdateState(ctx.statePath);\n const { state } = ctx;\n const nowMs = ctx.runtime.now().getTime();\n if (ctx.options.manual !== true) {\n if (state.latest !== undefined && state.checkedAt !== undefined && ageMs(state.checkedAt, nowMs) < ctx.intervalMs) {\n ctx.debug(`using cached latest ${state.latest} (checked ${state.checkedAt})`);\n return state.latest;\n }\n if (state.lastFailureAt !== undefined && ageMs(state.lastFailureAt, nowMs) < FAILURE_BACKOFF_MS) {\n ctx.debug(`skipping the registry check after a recent failure: ${state.lastFailureReason ?? \"unknown\"}`);\n return state.latest;\n }\n }\n const result = await fetchLatestVersion(ctx.options.packageName, ctx.registryUrl, {\n fetchImpl: ctx.runtime.fetchImpl,\n timeoutMs: ctx.runtime.checkTimeoutMs,\n userAgent: `${ctx.options.binName}/${ctx.options.currentVersion} saptools-self-update`,\n });\n const at = ctx.runtime.now().toISOString();\n if (result.ok) {\n ctx.state = clearFailure({ ...ctx.state, checkedAt: at, latest: result.latest });\n saveState(ctx);\n return result.latest;\n }\n ctx.state = { ...ctx.state, lastFailureAt: at, lastFailureReason: result.reason };\n saveState(ctx);\n ctx.debug(`registry check failed: ${result.reason}`);\n return ctx.state.latest;\n}\n\nfunction notify(ctx: Context, latest: string, reason: string): SelfUpdateOutcome {\n const nowMs = ctx.runtime.now().getTime();\n const alreadyAnnounced =\n ctx.state.notifiedVersion === latest && ctx.state.notifiedAt !== undefined && ageMs(ctx.state.notifiedAt, nowMs) < NOTIFY_INTERVAL_MS;\n if (!alreadyAnnounced || ctx.options.manual === true) {\n const command = manualInstallCommand(ctx.location.kind, `${ctx.options.packageName}@${latest}`);\n ctx.notice(`${latest} is available (installed ${ctx.options.currentVersion}) but was not installed: ${reason}. Run: ${command}`);\n ctx.state = { ...ctx.state, notifiedVersion: latest, notifiedAt: ctx.runtime.now().toISOString() };\n saveState(ctx);\n }\n return { kind: \"notified\", latest, reason };\n}\n\nfunction recentInstallFailure(ctx: Context, latest: string): string | undefined {\n const attempt = ctx.state.lastInstall;\n if (ctx.options.manual === true || attempt === undefined || attempt.ok || attempt.version !== latest) {\n return;\n }\n if (ageMs(attempt.at, ctx.runtime.now().getTime()) >= INSTALL_RETRY_BACKOFF_MS) {\n return;\n }\n return `the previous attempt failed (${attempt.reason ?? \"unknown reason\"})`;\n}\n\nfunction recordInstall(ctx: Context, latest: string, ok: boolean, reason?: string): void {\n const at = ctx.runtime.now().toISOString();\n ctx.state = { ...ctx.state, lastInstall: reason === undefined ? { version: latest, at, ok } : { version: latest, at, ok, reason } };\n saveState(ctx);\n}\n\nasync function installLatest(ctx: Context, latest: string): Promise<SelfUpdateOutcome | undefined> {\n const command = buildInstallCommand({\n location: ctx.location,\n packageName: ctx.options.packageName,\n version: latest,\n registryUrl: ctx.registryUrl,\n execPath: ctx.runtime.execPath,\n platform: ctx.runtime.platform,\n ...(ctx.runtime.exists === undefined ? {} : { exists: ctx.runtime.exists }),\n ...(ctx.runtime.realpath === undefined ? {} : { realpath: ctx.runtime.realpath }),\n });\n if (command === undefined) {\n return notify(ctx, latest, \"no supported package manager was found for this install\");\n }\n const lock = acquireUpdateLock(updateLockPath(ctx.statePath), ctx.runtime.now());\n if (lock === undefined) {\n ctx.debug(\"another process holds the update lock\");\n return { kind: \"skipped\", reason: \"another process is installing the update\" };\n }\n try {\n ctx.notice(`updating ${ctx.options.currentVersion} -> ${latest} ...`);\n const result = await runInstall(command, { env: ctx.runtime.env, timeoutMs: ctx.runtime.installTimeoutMs, spawnImpl: ctx.runtime.spawnImpl });\n const installed = ctx.location.packageDirectory === undefined ? undefined : readPackageManifest(ctx.location.packageDirectory)?.version;\n const failure = result.ok ? (installed === latest ? undefined : `the installed version is ${installed ?? \"unreadable\"}, not ${latest}`) : result.reason;\n if (failure !== undefined) {\n recordInstall(ctx, latest, false, failure);\n ctx.notice(`update to ${latest} failed (${failure}); continuing with ${ctx.options.currentVersion}. Run: ${command.display}`);\n return { kind: \"failed\", latest, reason: failure };\n }\n recordInstall(ctx, latest, true);\n } finally {\n lock.release();\n }\n return;\n}\n\nasync function upgrade(ctx: Context, latest: string): Promise<SelfUpdateOutcome> {\n const failed = await installLatest(ctx, latest);\n if (failed !== undefined) {\n return failed;\n }\n const outcome: SelfUpdateOutcome = { kind: \"updated\", from: ctx.options.currentVersion, to: latest };\n if (ctx.options.reexec === false) {\n ctx.notice(`updated to ${latest}`);\n return outcome;\n }\n ctx.notice(`updated to ${latest}; re-running the command`);\n try {\n await ctx.runtime.reexecImpl({\n execPath: ctx.runtime.execPath,\n execArgv: ctx.runtime.execArgv,\n binPath: ctx.binPath,\n args: ctx.runtime.argv.slice(2),\n env: ctx.runtime.env,\n });\n } catch (error) {\n ctx.notice(`could not re-run on ${latest} (${errorMessage(error)}); continuing with the already loaded ${ctx.options.currentVersion}`);\n }\n return outcome;\n}\n\nasync function runSelfUpdateUnsafe(options: SelfUpdateOptions, runtime: SelfUpdateRuntime): Promise<SelfUpdateOutcome> {\n const ctx = createContext(options, runtime);\n if (ctx.decision.policy === \"off\") {\n ctx.debug(`off: ${ctx.decision.reason}`);\n return { kind: \"skipped\", reason: ctx.decision.reason };\n }\n const latest = await resolveLatest(ctx);\n if (latest === undefined) {\n return { kind: \"skipped\", reason: \"the latest version is unknown\" };\n }\n if (!isNewerRelease(latest, options.currentVersion)) {\n return { kind: \"current\", latest };\n }\n if (ctx.decision.policy === \"notify\") {\n return notify(ctx, latest, ctx.decision.reason);\n }\n const backoff = recentInstallFailure(ctx, latest);\n if (backoff !== undefined) {\n return notify(ctx, latest, backoff);\n }\n return await upgrade(ctx, latest);\n}\n\n/**\n * Check for, install, and re-run on a newer release. Never throws, never\n * writes to stdout, never prompts, never escalates privileges: whatever goes\n * wrong, the command the user asked for still runs on the installed version.\n */\nexport async function runSelfUpdate(options: SelfUpdateOptions, overrides: Partial<SelfUpdateRuntime> = {}): Promise<SelfUpdateOutcome> {\n const runtime: SelfUpdateRuntime = { ...defaultRuntime(), ...overrides };\n try {\n return await runSelfUpdateUnsafe(options, runtime);\n } catch (error) {\n const reason = errorMessage(error);\n if (isTruthyFlag(runtime.env[DEBUG_ENV])) {\n process.stderr.write(`${options.binName}: [self-update] ${reason}\\n`);\n }\n return { kind: \"skipped\", reason };\n }\n}\n\n/** Everything the `self-update` command reports; performs one fresh registry check. */\nexport async function inspectSelfUpdate(options: SelfUpdateOptions, overrides: Partial<SelfUpdateRuntime> = {}): Promise<SelfUpdateStatus> {\n const runtime: SelfUpdateRuntime = { ...defaultRuntime(), ...overrides };\n const ctx = createContext({ ...options, manual: true }, runtime);\n const result = await fetchLatestVersion(options.packageName, ctx.registryUrl, {\n fetchImpl: runtime.fetchImpl,\n timeoutMs: runtime.checkTimeoutMs,\n userAgent: `${options.binName}/${options.currentVersion} saptools-self-update`,\n });\n return {\n packageName: options.packageName,\n installed: options.currentVersion,\n location: ctx.location,\n policy: resolveUpdatePolicy({\n env: runtime.env,\n location: ctx.location,\n ...(options.envPrefix === undefined ? {} : { envPrefix: options.envPrefix }),\n }),\n registryUrl: ctx.registryUrl,\n statePath: ctx.statePath,\n latest: result.ok ? result.latest : undefined,\n checkError: result.ok ? undefined : result.reason,\n };\n}\n","import { accessSync, constants, realpathSync } from \"node:fs\";\nimport { basename, dirname, join, sep } from \"node:path\";\n\nimport { findPackageMetadata } from \"../package-metadata.js\";\nimport { errorMessage } from \"../records.js\";\n\nexport type InstallKind = \"npm-global\" | \"pnpm-global\" | \"yarn-global\" | \"bun-global\" | \"volta\" | \"npx\" | \"local\" | \"unknown\";\n\nexport interface InstallLocation {\n readonly kind: InstallKind;\n /** Directory holding the CLI's package.json, when it could be found. */\n readonly packageDirectory: string | undefined;\n /** npm global prefix (`npm prefix -g`), npm-global installs only. */\n readonly prefix: string | undefined;\n /** Whether this user can replace the installed files without escalating privileges. */\n readonly writable: boolean;\n readonly detail: string;\n}\n\nexport interface DetectInstallLocationOptions {\n readonly binPath: string;\n readonly packageName: string;\n readonly platform?: NodeJS.Platform;\n readonly env?: NodeJS.ProcessEnv;\n readonly realpath?: (path: string) => string;\n readonly isWritable?: (path: string) => boolean;\n}\n\nconst UPGRADABLE_KINDS: ReadonlySet<InstallKind> = new Set<InstallKind>([\"npm-global\", \"pnpm-global\", \"yarn-global\", \"bun-global\", \"volta\"]);\n\nexport function isUpgradableKind(kind: InstallKind): boolean {\n return UPGRADABLE_KINDS.has(kind);\n}\n\nfunction defaultIsWritable(path: string): boolean {\n try {\n accessSync(path, constants.W_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction toPosix(path: string): string {\n return path.split(sep).join(\"/\");\n}\n\nfunction isPnpmGlobal(posixDirectory: string, env: NodeJS.ProcessEnv): boolean {\n // ~/Library/pnpm/global/5/... (macOS), ~/.local/share/pnpm/global/5/... (Linux), or a custom PNPM_HOME.\n if (posixDirectory.includes(\"/pnpm/global/\")) {\n return true;\n }\n const home = env[\"PNPM_HOME\"];\n return home !== undefined && home.length > 0 && posixDirectory.startsWith(`${toPosix(home).replace(/\\/+$/, \"\")}/global/`);\n}\n\n/** `<node_modules>` that directly holds `<node_modules>/@scope/name` or `<node_modules>/name`. */\nfunction nodeModulesRootOf(packageDirectory: string): string | undefined {\n const parent = dirname(packageDirectory);\n if (basename(parent) === \"node_modules\") {\n return parent;\n }\n const grandparent = dirname(parent);\n return basename(grandparent) === \"node_modules\" ? grandparent : undefined;\n}\n\n/**\n * npm's global layout is `<prefix>/lib/node_modules` on POSIX and\n * `<prefix>/node_modules` on Windows, where the default prefix directory is\n * named `npm`. Anything else under a `node_modules` is a project-local install.\n */\nfunction npmPrefixFor(packageDirectory: string, platform: NodeJS.Platform): string | undefined {\n const nodeModules = nodeModulesRootOf(packageDirectory);\n if (nodeModules === undefined) {\n return;\n }\n const parent = dirname(nodeModules);\n if (platform === \"win32\") {\n return basename(parent).toLowerCase() === \"npm\" ? parent : undefined;\n }\n return basename(parent) === \"lib\" ? dirname(parent) : undefined;\n}\n\nfunction classifyKind(packageDirectory: string, platform: NodeJS.Platform, env: NodeJS.ProcessEnv): InstallKind {\n const posix = toPosix(packageDirectory);\n if (posix.includes(\"/_npx/\") || /\\/dlx-[^/]+\\//.test(posix) || posix.includes(\"/pnpm/dlx/\") || posix.includes(\"/.cache/pnpm/dlx\")) {\n return \"npx\";\n }\n if (posix.includes(\"/.volta/tools/image/packages/\")) {\n return \"volta\";\n }\n if (posix.includes(\"/.bun/install/global/\")) {\n return \"bun-global\";\n }\n if (posix.includes(\"/.config/yarn/global/\") || posix.includes(\"/yarn/global/node_modules/\")) {\n return \"yarn-global\";\n }\n if (isPnpmGlobal(posix, env)) {\n return \"pnpm-global\";\n }\n if (!posix.includes(\"/node_modules/\")) {\n return \"local\";\n }\n return npmPrefixFor(packageDirectory, platform) === undefined ? \"local\" : \"npm-global\";\n}\n\nfunction writableForUpgrade(\n packageDirectory: string,\n prefix: string | undefined,\n platform: NodeJS.Platform,\n isWritable: (path: string) => boolean,\n): boolean {\n // The package itself, its scope folder, the node_modules root (npm rewrites .package-lock.json) and the bin folder all get touched.\n const targets = [packageDirectory, dirname(packageDirectory)];\n const nodeModules = nodeModulesRootOf(packageDirectory);\n if (nodeModules !== undefined) {\n targets.push(nodeModules);\n }\n if (prefix !== undefined) {\n targets.push(platform === \"win32\" ? prefix : join(prefix, \"bin\"));\n }\n return targets.every((target) => isWritable(target));\n}\n\nfunction describe(kind: InstallKind, packageDirectory: string, prefix: string | undefined): string {\n if (kind === \"npm-global\" && prefix !== undefined) {\n return `npm global install under ${prefix}`;\n }\n return `${kind} install at ${packageDirectory}`;\n}\n\nfunction unknownLocation(detail: string): InstallLocation {\n return { kind: \"unknown\", packageDirectory: undefined, prefix: undefined, writable: false, detail };\n}\n\n/**\n * Where does the running CLI come from, and which package manager owns it?\n * Decided from the real path of the executing script, never from PATH or\n * `npm prefix -g`: the install we upgrade must be the one we are running.\n */\nexport function detectInstallLocation(options: DetectInstallLocationOptions): InstallLocation {\n const platform = options.platform ?? process.platform;\n const env = options.env ?? process.env;\n const realpath = options.realpath ?? ((path: string): string => realpathSync(path));\n const isWritable = options.isWritable ?? defaultIsWritable;\n\n let resolvedBin: string;\n try {\n resolvedBin = realpath(options.binPath);\n } catch (error) {\n return unknownLocation(`cannot resolve ${options.binPath}: ${errorMessage(error)}`);\n }\n const manifest = findPackageMetadata(dirname(resolvedBin), options.packageName);\n if (manifest === undefined) {\n return unknownLocation(`no package.json for ${options.packageName} above ${resolvedBin}`);\n }\n\n const packageDirectory = manifest.directory;\n const kind = classifyKind(packageDirectory, platform, env);\n const prefix = kind === \"npm-global\" ? npmPrefixFor(packageDirectory, platform) : undefined;\n const writable = isUpgradableKind(kind) && writableForUpgrade(packageDirectory, prefix, platform, isWritable);\n return { kind, packageDirectory, prefix, writable, detail: describe(kind, packageDirectory, prefix) };\n}\n","import { existsSync, realpathSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { errorMessage } from \"../records.js\";\n\nimport type { InstallKind, InstallLocation } from \"./install-location.js\";\nimport type { SpawnLike } from \"./process-types.js\";\n\nexport interface InstallCommand {\n readonly file: string;\n readonly args: readonly string[];\n /** The equivalent command a human would type; used in notices. */\n readonly display: string;\n}\n\nexport interface BuildInstallCommandOptions {\n readonly location: InstallLocation;\n readonly packageName: string;\n readonly version: string;\n readonly registryUrl: string;\n readonly execPath?: string;\n readonly platform?: NodeJS.Platform;\n readonly exists?: (path: string) => boolean;\n readonly realpath?: (path: string) => string;\n}\n\nexport type InstallResult = { readonly ok: true } | { readonly ok: false; readonly reason: string };\n\nexport interface RunInstallOptions {\n readonly env: NodeJS.ProcessEnv;\n readonly timeoutMs?: number;\n readonly spawnImpl: SpawnLike;\n}\n\n/** A global install of a ~200 KB CLI takes a few seconds; three minutes only matters on a stalled network. */\nexport const DEFAULT_INSTALL_TIMEOUT_MS = 180_000;\n\n/** What to tell a human to run; also the fallback when we cannot upgrade for them. */\nexport function manualInstallCommand(kind: InstallKind, spec: string): string {\n switch (kind) {\n case \"pnpm-global\":\n return `pnpm add -g ${spec}`;\n case \"yarn-global\":\n return `yarn global add ${spec}`;\n case \"bun-global\":\n return `bun add -g ${spec}`;\n case \"volta\":\n return `volta install ${spec}`;\n case \"npm-global\":\n case \"npx\":\n case \"local\":\n case \"unknown\":\n return `npm install -g ${spec}`;\n }\n}\n\ninterface NpmInvocation {\n readonly file: string;\n readonly leadingArgs: readonly string[];\n}\n\n/**\n * Prefer the npm that ships with the node running us (`<bin>/npm` beside\n * `process.execPath`), executed through that same node: PATH may hold a\n * different Node installation whose npm would upgrade a different prefix. On\n * Windows the `.cmd` shim cannot be spawned without a shell, so only the\n * bundled `npm-cli.js` is used there.\n */\nfunction resolveNpmInvocation(\n execPath: string,\n platform: NodeJS.Platform,\n exists: (path: string) => boolean,\n realpath: (path: string) => string,\n): NpmInvocation | undefined {\n const binDirectory = dirname(execPath);\n if (platform === \"win32\") {\n const cli = join(binDirectory, \"node_modules\", \"npm\", \"bin\", \"npm-cli.js\");\n return exists(cli) ? { file: execPath, leadingArgs: [cli] } : undefined;\n }\n const sibling = join(binDirectory, \"npm\");\n if (exists(sibling)) {\n try {\n const target = realpath(sibling);\n return target.endsWith(\".js\") ? { file: execPath, leadingArgs: [target] } : { file: target, leadingArgs: [] };\n } catch {\n // A dangling symlink: fall through to PATH.\n }\n }\n return { file: \"npm\", leadingArgs: [] };\n}\n\nfunction buildNpmCommand(options: BuildInstallCommandOptions, spec: string): InstallCommand | undefined {\n if (options.location.prefix === undefined) {\n return;\n }\n const npm = resolveNpmInvocation(\n options.execPath ?? process.execPath,\n options.platform ?? process.platform,\n options.exists ?? existsSync,\n options.realpath ?? ((path: string): string => realpathSync(path)),\n );\n if (npm === undefined) {\n return;\n }\n return {\n file: npm.file,\n args: [\n ...npm.leadingArgs,\n \"install\",\n \"--global\",\n \"--prefix\",\n options.location.prefix,\n spec,\n \"--registry\",\n options.registryUrl,\n \"--no-fund\",\n \"--no-audit\",\n \"--no-update-notifier\",\n \"--loglevel=error\",\n ],\n display: manualInstallCommand(\"npm-global\", spec),\n };\n}\n\n/** The exact command that upgrades this install in place; undefined when the location cannot be upgraded by us. */\nexport function buildInstallCommand(options: BuildInstallCommandOptions): InstallCommand | undefined {\n const spec = `${options.packageName}@${options.version}`;\n switch (options.location.kind) {\n case \"npm-global\":\n return buildNpmCommand(options, spec);\n case \"pnpm-global\":\n return { file: \"pnpm\", args: [\"add\", \"--global\", spec], display: manualInstallCommand(\"pnpm-global\", spec) };\n case \"yarn-global\":\n return { file: \"yarn\", args: [\"global\", \"add\", spec], display: manualInstallCommand(\"yarn-global\", spec) };\n case \"bun-global\":\n return { file: \"bun\", args: [\"add\", \"--global\", spec], display: manualInstallCommand(\"bun-global\", spec) };\n case \"volta\":\n return { file: \"volta\", args: [\"install\", spec], display: manualInstallCommand(\"volta\", spec) };\n case \"npx\":\n case \"local\":\n case \"unknown\":\n return;\n }\n}\n\nfunction lastLine(text: string): string {\n const lines = text\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0);\n return lines.at(-1) ?? \"\";\n}\n\n/**\n * Run the install with no shell, no stdin, and a hard timeout. Credentials for\n * SAP never reach the package manager, and the child inherits an explicit\n * `SAPTOOLS_AUTO_UPDATE=off` so nothing it runs can start a nested update.\n * `cwd` is the temp directory so a project's `.npmrc` cannot redirect the\n * install of a global tool.\n */\nexport function runInstall(command: InstallCommand, options: RunInstallOptions): Promise<InstallResult> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_INSTALL_TIMEOUT_MS;\n const env: NodeJS.ProcessEnv = { ...options.env, SAPTOOLS_AUTO_UPDATE: \"off\" };\n delete env[\"SAP_EMAIL\"];\n delete env[\"SAP_PASSWORD\"];\n\n return new Promise<InstallResult>((resolve) => {\n let child: ReturnType<SpawnLike>;\n try {\n child = options.spawnImpl(command.file, command.args, { cwd: tmpdir(), env, stdio: [\"ignore\", \"pipe\", \"pipe\"], windowsHide: true });\n } catch (error) {\n resolve({ ok: false, reason: errorMessage(error) });\n return;\n }\n let stderr = \"\";\n child.stderr?.on(\"data\", (chunk: Buffer | string) => {\n stderr = `${stderr}${chunk.toString()}`.slice(-4_000);\n });\n const timer = setTimeout(() => {\n child.kill(\"SIGKILL\");\n }, timeoutMs);\n child.once(\"error\", (error) => {\n clearTimeout(timer);\n resolve({ ok: false, reason: `${command.file}: ${error.message}` });\n });\n child.once(\"close\", (code, signal) => {\n clearTimeout(timer);\n if (code === 0) {\n resolve({ ok: true });\n return;\n }\n const detail = lastLine(stderr);\n const suffix = detail.length > 0 ? `: ${detail}` : \"\";\n resolve({\n ok: false,\n reason:\n signal === null\n ? `${command.display} exited with code ${String(code ?? -1)}${suffix}`\n : `${command.display} was killed by ${signal} after ${String(Math.round(timeoutMs / 1000))}s`,\n });\n });\n });\n}\n","import { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { errorMessage, isRecord, readString } from \"../records.js\";\n\nimport { parseSemver } from \"./semver.js\";\n\nexport const DEFAULT_NPM_REGISTRY = \"https://registry.npmjs.org\";\nexport const REGISTRY_ENV = \"SAPTOOLS_NPM_REGISTRY\";\n/**\n * The registry answers in ~0.5 s from Asia; two seconds separates \"slow\" from\n * \"offline or captive portal\" without holding up a 1.5 s command for long.\n */\nexport const DEFAULT_CHECK_TIMEOUT_MS = 2_000;\n\nexport type LatestVersionResult =\n | { readonly ok: true; readonly latest: string }\n | { readonly ok: false; readonly reason: string };\n\nexport interface FetchLatestOptions {\n readonly fetchImpl?: typeof fetch;\n readonly timeoutMs?: number;\n readonly userAgent?: string;\n}\n\nexport function normalizeRegistryUrl(value: string | undefined): string | undefined {\n if (value === undefined) {\n return;\n }\n const trimmed = value.trim().replace(/\\/+$/, \"\");\n if (!/^https?:\\/\\/\\S+$/i.test(trimmed)) {\n return;\n }\n return trimmed;\n}\n\nfunction registryFromNpmrc(text: string | undefined, key: string): string | undefined {\n if (text === undefined) {\n return;\n }\n for (const line of text.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (trimmed.length === 0 || trimmed.startsWith(\"#\") || trimmed.startsWith(\";\")) {\n continue;\n }\n const separator = trimmed.indexOf(\"=\");\n if (separator === -1 || trimmed.slice(0, separator).trim() !== key) {\n continue;\n }\n return trimmed\n .slice(separator + 1)\n .trim()\n .replace(/^\"(.*)\"$/, \"$1\");\n }\n return;\n}\n\n/** `~/.npmrc` as text, or undefined when absent; the project-level `.npmrc` is deliberately ignored (see resolveRegistryUrl). */\nexport function readUserNpmrc(homeDirectory: string): string | undefined {\n try {\n return readFileSync(join(homeDirectory, \".npmrc\"), \"utf8\");\n } catch {\n return;\n }\n}\n\n/**\n * Registry precedence: explicit saptools override, the registry npm itself was\n * configured with when it launched us, the user's `~/.npmrc` (scoped entry\n * first), then npmjs. The current directory's `.npmrc` is ignored on purpose:\n * a project's private registry has nothing to do with where the user's global\n * CLI came from.\n */\nexport function resolveRegistryUrl(env: NodeJS.ProcessEnv, userNpmrc: string | undefined): string {\n const candidates = [\n env[REGISTRY_ENV],\n env[\"npm_config_registry\"],\n registryFromNpmrc(userNpmrc, \"@saptools:registry\"),\n registryFromNpmrc(userNpmrc, \"registry\"),\n ];\n for (const candidate of candidates) {\n const normalized = normalizeRegistryUrl(candidate);\n if (normalized !== undefined) {\n return normalized;\n }\n }\n return DEFAULT_NPM_REGISTRY;\n}\n\ntype JsonResponse =\n | { readonly ok: true; readonly body: unknown }\n | { readonly ok: false; readonly status: number | undefined; readonly reason: string };\n\nasync function fetchJson(\n fetchImpl: typeof fetch,\n url: string,\n headers: Record<string, string>,\n timeoutMs: number,\n): Promise<JsonResponse> {\n try {\n const response = await fetchImpl(url, { headers, signal: AbortSignal.timeout(timeoutMs), redirect: \"follow\" });\n if (!response.ok) {\n return { ok: false, status: response.status, reason: `HTTP ${String(response.status)} from ${url}` };\n }\n const body: unknown = await response.json();\n return { ok: true, body };\n } catch (error) {\n return { ok: false, status: undefined, reason: `${errorMessage(error)} (${url})` };\n }\n}\n\nfunction readLatestTag(body: unknown, nestedUnderDistTags: boolean): string | undefined {\n if (!isRecord(body)) {\n return;\n }\n const tags = nestedUnderDistTags ? body[\"dist-tags\"] : body;\n if (!isRecord(tags)) {\n return;\n }\n const latest = readString(tags, \"latest\");\n return latest !== undefined && parseSemver(latest) !== undefined ? latest : undefined;\n}\n\n/**\n * Ask the registry for the `latest` dist-tag. The dedicated dist-tags endpoint\n * is 18 bytes; registries that do not implement it (some private mirrors) get\n * a second try through the abbreviated packument. A network failure on the\n * first request is not retried: the registry is unreachable, not old.\n */\nexport async function fetchLatestVersion(\n packageName: string,\n registryUrl: string,\n options: FetchLatestOptions = {},\n): Promise<LatestVersionResult> {\n const fetchImpl = options.fetchImpl ?? fetch;\n const timeoutMs = options.timeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;\n const encoded = encodeURIComponent(packageName);\n const baseHeaders: Record<string, string> = { \"user-agent\": options.userAgent ?? \"saptools-self-update\" };\n\n const distTags = await fetchJson(fetchImpl, `${registryUrl}/-/package/${encoded}/dist-tags`, { ...baseHeaders, accept: \"application/json\" }, timeoutMs);\n if (distTags.ok) {\n const latest = readLatestTag(distTags.body, false);\n return latest === undefined ? { ok: false, reason: \"dist-tags response carries no valid latest version\" } : { ok: true, latest };\n }\n if (distTags.status === undefined) {\n return { ok: false, reason: distTags.reason };\n }\n\n const packument = await fetchJson(\n fetchImpl,\n `${registryUrl}/${encoded}`,\n { ...baseHeaders, accept: \"application/vnd.npm.install-v1+json\" },\n timeoutMs,\n );\n if (!packument.ok) {\n return { ok: false, reason: packument.reason };\n }\n const latest = readLatestTag(packument.body, true);\n return latest === undefined ? { ok: false, reason: \"packument carries no valid latest dist-tag\" } : { ok: true, latest };\n}\n","export interface SemanticVersion {\n readonly major: number;\n readonly minor: number;\n readonly patch: number;\n readonly prerelease: readonly string[];\n}\n\nconst SEMVER_PATTERN =\n /^v?(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$/;\n\nexport function parseSemver(text: string): SemanticVersion | undefined {\n const match = SEMVER_PATTERN.exec(text.trim());\n if (match === null) {\n return;\n }\n const [, major, minor, patch, prerelease] = match;\n if (major === undefined || minor === undefined || patch === undefined) {\n return;\n }\n return {\n major: Number(major),\n minor: Number(minor),\n patch: Number(patch),\n prerelease: prerelease === undefined ? [] : prerelease.split(\".\"),\n };\n}\n\nfunction compareIdentifiers(left: string, right: string): number {\n const leftNumeric = /^\\d+$/.test(left);\n const rightNumeric = /^\\d+$/.test(right);\n if (leftNumeric && rightNumeric) {\n return Math.sign(Number(left) - Number(right));\n }\n // Numeric identifiers always sort before alphanumeric ones (semver 2.0.0 §11).\n if (leftNumeric) {\n return -1;\n }\n if (rightNumeric) {\n return 1;\n }\n if (left === right) {\n return 0;\n }\n return left < right ? -1 : 1;\n}\n\nfunction comparePrerelease(left: readonly string[], right: readonly string[]): number {\n if (left.length === 0 && right.length === 0) {\n return 0;\n }\n // A release outranks any prerelease of the same version.\n if (left.length === 0) {\n return 1;\n }\n if (right.length === 0) {\n return -1;\n }\n for (const [index, identifier] of left.entries()) {\n const other = right[index];\n if (other === undefined) {\n return 1;\n }\n const result = compareIdentifiers(identifier, other);\n if (result !== 0) {\n return result;\n }\n }\n return left.length < right.length ? -1 : 0;\n}\n\nexport function compareSemver(left: SemanticVersion, right: SemanticVersion): number {\n for (const key of [\"major\", \"minor\", \"patch\"] as const) {\n if (left[key] !== right[key]) {\n return left[key] < right[key] ? -1 : 1;\n }\n }\n return comparePrerelease(left.prerelease, right.prerelease);\n}\n\n/**\n * True when `candidate` is a release strictly newer than `current`. A\n * prerelease is never a target: someone who installed 1.2.0 must not be moved\n * onto 1.3.0-beta.1 by a background updater.\n */\nexport function isNewerRelease(candidate: string, current: string): boolean {\n const next = parseSemver(candidate);\n const installed = parseSemver(current);\n if (next === undefined || installed === undefined) {\n return false;\n }\n if (next.prerelease.length > 0) {\n return false;\n }\n return compareSemver(next, installed) > 0;\n}\n","import { closeSync, openSync, rmSync, statSync, utimesSync, writeSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\nimport { isRecord, readString } from \"../records.js\";\nimport { ensurePrivateDirectorySync, readJsonFileSync, writeFileAtomicSync } from \"../saptools-paths.js\";\n\nexport interface InstallAttempt {\n readonly version: string;\n readonly at: string;\n readonly ok: boolean;\n readonly reason?: string;\n}\n\nexport interface UpdateState {\n readonly version: 1;\n readonly checkedAt?: string;\n readonly latest?: string;\n readonly lastFailureAt?: string;\n readonly lastFailureReason?: string;\n readonly notifiedVersion?: string;\n readonly notifiedAt?: string;\n readonly lastInstall?: InstallAttempt;\n}\n\ntype UpdateStateDraft = { -readonly [K in keyof UpdateState]: UpdateState[K] };\n\nexport const EMPTY_UPDATE_STATE: UpdateState = { version: 1 };\nexport const UPDATES_DIRECTORY_NAME = \"updates\";\n/** A stuck installer holds the lock this long before another instance may take over. */\nexport const DEFAULT_LOCK_STALE_MS = 10 * 60_000;\n\nconst STRING_FIELDS = [\"checkedAt\", \"latest\", \"lastFailureAt\", \"lastFailureReason\", \"notifiedVersion\", \"notifiedAt\"] as const;\n\n/** `@saptools/cf-metrics` → `saptools__cf-metrics.json`: one file per package, no shared writes between CLIs. */\nexport function updateStateFileName(packageName: string): string {\n return `${packageName.replace(/^@/, \"\").replaceAll(\"/\", \"__\")}.json`;\n}\n\nexport function updateStatePath(saptoolsRoot: string, packageName: string): string {\n return join(saptoolsRoot, UPDATES_DIRECTORY_NAME, updateStateFileName(packageName));\n}\n\nexport function updateLockPath(statePath: string): string {\n return statePath.replace(/\\.json$/, \".lock\");\n}\n\nfunction readInstallAttempt(value: unknown): InstallAttempt | undefined {\n if (!isRecord(value)) {\n return;\n }\n const version = readString(value, \"version\");\n const at = readString(value, \"at\");\n const ok = value[\"ok\"];\n if (version === undefined || at === undefined || typeof ok !== \"boolean\") {\n return;\n }\n const reason = readString(value, \"reason\");\n return reason === undefined ? { version, at, ok } : { version, at, ok, reason };\n}\n\n/** Tolerant read: an unknown, malformed, or older-format file reads as empty state. */\nexport function readUpdateState(path: string): UpdateState {\n const parsed = readJsonFileSync(path);\n if (!isRecord(parsed) || parsed[\"version\"] !== 1) {\n return EMPTY_UPDATE_STATE;\n }\n const draft: UpdateStateDraft = { version: 1 };\n for (const key of STRING_FIELDS) {\n const value = readString(parsed, key);\n if (value !== undefined) {\n draft[key] = value;\n }\n }\n const lastInstall = readInstallAttempt(parsed[\"lastInstall\"]);\n if (lastInstall !== undefined) {\n draft.lastInstall = lastInstall;\n }\n return draft;\n}\n\n/** The same state with a successful check: the failure fields no longer apply. */\nexport function clearFailure(state: UpdateState): UpdateState {\n const next: UpdateStateDraft = { ...state };\n delete next.lastFailureAt;\n delete next.lastFailureReason;\n return next;\n}\n\nexport function writeUpdateState(path: string, state: UpdateState): void {\n ensurePrivateDirectorySync(dirname(path));\n writeFileAtomicSync(path, `${JSON.stringify(state, null, 2)}\\n`, 0o600);\n}\n\nexport interface UpdateLock {\n readonly release: () => void;\n}\n\nfunction tryCreateLock(lockPath: string, now: Date): UpdateLock | undefined {\n let descriptor: number;\n try {\n descriptor = openSync(lockPath, \"wx\", 0o600);\n } catch {\n return;\n }\n try {\n writeSync(descriptor, `${JSON.stringify({ pid: process.pid, at: now.toISOString() })}\\n`);\n } finally {\n closeSync(descriptor);\n }\n // Staleness is judged against the caller's clock, so stamp the file with it rather than the filesystem's.\n utimesSync(lockPath, now, now);\n return {\n release: (): void => {\n rmSync(lockPath, { force: true });\n },\n };\n}\n\nfunction isStaleLock(lockPath: string, now: Date, staleMs: number): boolean {\n try {\n return now.getTime() - statSync(lockPath).mtimeMs > staleMs;\n } catch {\n return false;\n }\n}\n\n/**\n * Exclusive-create lock so two commands started at once install only once;\n * the loser skips the update and runs on the installed version. A lock older\n * than `staleMs` belongs to a crashed installer and is taken over.\n */\nexport function acquireUpdateLock(lockPath: string, now: Date, staleMs = DEFAULT_LOCK_STALE_MS): UpdateLock | undefined {\n ensurePrivateDirectorySync(dirname(lockPath));\n const lock = tryCreateLock(lockPath, now);\n if (lock !== undefined) {\n return lock;\n }\n if (!isStaleLock(lockPath, now, staleMs)) {\n return;\n }\n rmSync(lockPath, { force: true });\n return tryCreateLock(lockPath, now);\n}\n","import type { Command } from \"commander\";\n\nimport { SELF_UPDATE_COMMAND } from \"./policy.js\";\nimport { inspectSelfUpdate, runSelfUpdate } from \"./run.js\";\nimport type { SelfUpdateOptions, SelfUpdateOutcome, SelfUpdateStatus } from \"./run.js\";\nimport { isNewerRelease } from \"./semver.js\";\n\nexport type AttachSelfUpdateOptions = Omit<SelfUpdateOptions, \"commandPath\" | \"manual\" | \"reexec\">;\n\nexport interface SelfUpdateCommandOptions extends AttachSelfUpdateOptions {\n /** Where the status lines go; defaults to stdout. */\n readonly print?: (line: string) => void;\n}\n\n/** `credential list` for a nested subcommand, `` for the root action. */\nexport function commandPathOf(command: Command): string {\n const names: string[] = [];\n let current: Command = command;\n while (current.parent !== null) {\n names.unshift(current.name());\n current = current.parent;\n }\n return names.join(\" \");\n}\n\n/**\n * Run the self-updater before every action of `program`. `--help` and\n * `--version` never reach an action, so they never trigger it; the\n * `self-update` command and `skipCommands` are excluded by the policy.\n */\nexport function attachSelfUpdate(program: Command, options: AttachSelfUpdateOptions): void {\n program.hook(\"preAction\", async (_thisCommand: Command, actionCommand: Command): Promise<void> => {\n await runSelfUpdate({ ...options, commandPath: commandPathOf(actionCommand) });\n });\n}\n\nexport function formatSelfUpdateStatus(status: SelfUpdateStatus): readonly string[] {\n const latest =\n status.latest ?? (status.checkError === undefined ? \"unknown\" : `unknown (${status.checkError})`);\n const install = status.location.packageDirectory === undefined ? status.location.detail : `${status.location.kind} ${status.location.packageDirectory}`;\n return [\n `package=${status.packageName}`,\n `installed=${status.installed}`,\n `latest=${latest}`,\n `policy=${status.policy.policy} (${status.policy.reason})`,\n `install=${install}`,\n `writable=${status.location.writable ? \"yes\" : \"no\"}`,\n `registry=${status.registryUrl}`,\n `state=${status.statePath}`,\n ];\n}\n\nexport function describeOutcome(outcome: SelfUpdateOutcome): string {\n switch (outcome.kind) {\n case \"current\":\n return `current (${outcome.latest} is the newest release)`;\n case \"updated\":\n return `updated ${outcome.from} -> ${outcome.to}`;\n case \"notified\":\n return `not installed (${outcome.reason})`;\n case \"failed\":\n return `failed (${outcome.reason})`;\n case \"skipped\":\n return `skipped (${outcome.reason})`;\n }\n}\n\nasync function runSelfUpdateCommand(options: SelfUpdateCommandOptions, checkOnly: boolean): Promise<void> {\n const print =\n options.print ??\n ((line: string): void => {\n process.stdout.write(`${line}\\n`);\n });\n const status = await inspectSelfUpdate(options);\n for (const line of formatSelfUpdateStatus(status)) {\n print(line);\n }\n if (checkOnly) {\n const verdict = status.latest === undefined ? \"unknown\" : isNewerRelease(status.latest, status.installed) ? \"update-available\" : \"current\";\n print(`result=${verdict}`);\n return;\n }\n const outcome = await runSelfUpdate({ ...options, manual: true, reexec: false });\n print(`result=${describeOutcome(outcome)}`);\n if (outcome.kind === \"failed\") {\n process.exitCode = 1;\n }\n}\n\n/** `<bin> self-update [--check]`: a forced check and install for humans and agents who do not want to wait for the hourly check. */\nexport function registerSelfUpdateCommand(program: Command, options: SelfUpdateCommandOptions): void {\n program\n .command(SELF_UPDATE_COMMAND)\n .description(\"check npm for a newer release and install it now; every other command does this automatically (at most once an hour)\")\n .option(\"--check\", \"report whether a newer release exists without installing it\")\n .action(async (flags: { readonly check?: boolean }): Promise<void> => {\n await runSelfUpdateCommand(options, flags.check === true);\n });\n}\n","import type { CloudLoggingCfExecutor, CloudLoggingInstance } from \"./types.js\";\n\nconst CLOUD_LOGGING_OFFERING = \"cloud-logging\";\nconst INSTANCES_PAGE_SIZE = 200;\nconst MAX_INSTANCE_PAGES = 20;\nconst INSTANCE_LISTING_FIELDS =\n `&${encodeURIComponent(\"fields[service_plan]\")}=guid,name,relationships.service_offering` +\n `&${encodeURIComponent(\"fields[service_plan.service_offering]\")}=guid,name`;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction readString(record: Record<string, unknown>, key: string): string | undefined {\n const value = record[key];\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nfunction relationshipGuid(resource: Record<string, unknown>, relationship: string): string | undefined {\n const relationships = resource[\"relationships\"];\n const entry = isRecord(relationships) ? relationships[relationship] : undefined;\n const data = isRecord(entry) ? entry[\"data\"] : undefined;\n return isRecord(data) ? readString(data, \"guid\") : undefined;\n}\n\nfunction recordsOf(payload: Record<string, unknown>, ...path: readonly string[]): readonly Record<string, unknown>[] {\n let cursor: unknown = payload;\n for (const key of path) {\n cursor = isRecord(cursor) ? cursor[key] : undefined;\n }\n return Array.isArray(cursor) ? cursor.filter(isRecord) : [];\n}\n\nfunction offeringNamesByPlanGuid(payload: Record<string, unknown>): ReadonlyMap<string, string> {\n const offeringNames = new Map<string, string>();\n for (const offering of recordsOf(payload, \"included\", \"service_offerings\")) {\n const guid = readString(offering, \"guid\");\n const name = readString(offering, \"name\");\n if (guid !== undefined && name !== undefined) {\n offeringNames.set(guid, name);\n }\n }\n const byPlan = new Map<string, string>();\n for (const plan of recordsOf(payload, \"included\", \"service_plans\")) {\n const guid = readString(plan, \"guid\");\n const offeringGuid = relationshipGuid(plan, \"service_offering\");\n const offeringName = offeringGuid === undefined ? undefined : offeringNames.get(offeringGuid);\n if (guid !== undefined && offeringName !== undefined) {\n byPlan.set(guid, offeringName);\n }\n }\n return byPlan;\n}\n\ninterface ManagedInstance extends CloudLoggingInstance {\n readonly offering: string | undefined;\n}\n\nfunction parseInstancesPage(payload: Record<string, unknown>): readonly ManagedInstance[] {\n const offeringByPlan = offeringNamesByPlanGuid(payload);\n const instances: ManagedInstance[] = [];\n for (const resource of recordsOf(payload, \"resources\")) {\n const name = readString(resource, \"name\");\n const guid = readString(resource, \"guid\");\n if (name === undefined || guid === undefined) {\n continue;\n }\n const planGuid = relationshipGuid(resource, \"service_plan\");\n instances.push({ name, guid, offering: planGuid === undefined ? undefined : offeringByPlan.get(planGuid) });\n }\n return instances;\n}\n\nfunction parseListing(raw: string): Record<string, unknown> {\n const parsed: unknown = JSON.parse(raw);\n if (!isRecord(parsed)) {\n throw new Error(\"cf curl /v3/service_instances returned an unexpected shape.\");\n }\n return parsed;\n}\n\n/** Every Cloud Logging service instance in the target's space, via the v3 API. */\nexport async function listCloudLoggingInstances(\n target: { readonly space: string },\n executor: CloudLoggingCfExecutor,\n): Promise<readonly CloudLoggingInstance[]> {\n const spaceGuid = await executor.cfSpaceGuid(target.space, executor.ambientContext);\n const instances: ManagedInstance[] = [];\n let page = 1;\n let hasMore = true;\n while (hasMore && page <= MAX_INSTANCE_PAGES) {\n const raw = await executor.cfCurl(\n `/v3/service_instances?space_guids=${encodeURIComponent(spaceGuid)}&type=managed&per_page=${String(INSTANCES_PAGE_SIZE)}&page=${String(page)}${INSTANCE_LISTING_FIELDS}`,\n executor.ambientContext,\n );\n const payload = parseListing(raw);\n instances.push(...parseInstancesPage(payload));\n const pagination = payload[\"pagination\"];\n const reported = isRecord(pagination) ? pagination[\"total_pages\"] : undefined;\n hasMore = page < (typeof reported === \"number\" && reported > 0 ? reported : 1);\n page += 1;\n }\n return instances.filter((instance) => instance.offering?.toLowerCase() === CLOUD_LOGGING_OFFERING).map(({ name, guid }) => ({ name, guid }));\n}\n\n/** Auto-discover the single Cloud Logging instance in the space, failing closed on 0 or many. */\nexport async function discoverServiceInstance(\n target: { readonly space: string },\n executor: CloudLoggingCfExecutor,\n): Promise<CloudLoggingInstance> {\n const instances = await listCloudLoggingInstances(target, executor);\n if (instances.length > 1) {\n const names = instances.map((instance) => instance.name).join(\", \");\n throw new Error(`Multiple \"${CLOUD_LOGGING_OFFERING}\" service instances found in this space (${names}); pass --service-instance to pick one.`);\n }\n const [only] = instances;\n if (only === undefined) {\n throw new Error(`No \"${CLOUD_LOGGING_OFFERING}\" service instance found in this space. Pass --service-instance to name one explicitly.`);\n }\n return only;\n}\n","import { readdir, rm } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\n\nimport { ensurePrivateDirectorySync, readJsonFileSync, resolveSaptoolsRoot, writeFileAtomicSync } from \"../saptools-paths.js\";\n\nimport type { DashboardsCredential, ResolvedTarget } from \"./types.js\";\n\nconst CACHE_FILE_NAME = \"credentials.json\";\nconst DEFAULT_TTL_MINUTES = 10_080;\nconst AUTO_INSTANCE_SELECTOR = \"auto\";\n\ninterface StoredCredentialEntry {\n readonly region: string;\n readonly apiEndpoint: string;\n readonly org: string;\n readonly space: string;\n readonly instanceSelector: string;\n readonly instance: string;\n readonly source: string;\n readonly dashboardsEndpoint: string;\n readonly username: string;\n readonly password: string;\n readonly cachedAt: string;\n readonly expiresAt: string;\n}\n\ninterface StoredCredentialCache {\n readonly version: 1;\n readonly entries: readonly StoredCredentialEntry[];\n}\n\nexport interface CredentialCacheKey {\n readonly target: ResolvedTarget;\n readonly instanceSelector?: string;\n}\n\nexport interface CredentialCacheOptions {\n /** Which consumer's cache file to use — `~/.saptools/<cliName>/credentials.json`. Required: keeps cf-otel's, cf-metrics's, and cf-log-search's caches from ever colliding. */\n readonly cliName: string;\n readonly saptoolsRoot?: string;\n readonly now?: () => Date;\n readonly ttlMinutes?: number;\n}\n\nexport interface CachedCredentialSummary {\n readonly region: string;\n readonly org: string;\n readonly space: string;\n readonly instance: string;\n readonly source: string;\n readonly dashboardsEndpoint: string;\n readonly cachedAt: string;\n readonly expiresAt: string;\n}\n\nconst EMPTY_CACHE: StoredCredentialCache = { version: 1, entries: [] };\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction cachePath(options: CredentialCacheOptions): string {\n return join(resolveSaptoolsRoot(options.saptoolsRoot), options.cliName, CACHE_FILE_NAME);\n}\n\nfunction isStoredEntry(value: unknown): value is StoredCredentialEntry {\n if (!isRecord(value)) {\n return false;\n }\n const stringKeys: readonly (keyof StoredCredentialEntry)[] = [\n \"region\", \"apiEndpoint\", \"org\", \"space\", \"instanceSelector\", \"instance\", \"source\", \"dashboardsEndpoint\", \"username\", \"password\", \"cachedAt\", \"expiresAt\",\n ];\n return stringKeys.every((key) => {\n return typeof value[key] === \"string\";\n });\n}\n\nfunction readStore(path: string): StoredCredentialCache {\n const parsed = readJsonFileSync(path);\n if (!isRecord(parsed) || parsed[\"version\"] !== 1 || !Array.isArray(parsed[\"entries\"])) {\n return EMPTY_CACHE;\n }\n return { version: 1, entries: parsed[\"entries\"].filter(isStoredEntry) };\n}\n\nfunction writeStore(path: string, store: StoredCredentialCache): void {\n ensurePrivateDirectorySync(dirname(path));\n writeFileAtomicSync(path, `${JSON.stringify(store, null, 2)}\\n`, 0o600);\n}\n\nfunction normalizeEndpoint(apiEndpoint: string): string {\n return apiEndpoint.trim().toLowerCase().replace(/\\/+$/, \"\");\n}\n\nfunction matchesKey(entry: StoredCredentialEntry, key: CredentialCacheKey): boolean {\n if (normalizeEndpoint(entry.apiEndpoint) !== normalizeEndpoint(key.target.apiEndpoint) || entry.org !== key.target.org || entry.space !== key.target.space) {\n return false;\n }\n if (key.instanceSelector === undefined) {\n return entry.instanceSelector === AUTO_INSTANCE_SELECTOR;\n }\n return entry.instance === key.instanceSelector;\n}\n\nfunction isLive(entry: StoredCredentialEntry, nowMs: number): boolean {\n const expires = Date.parse(entry.expiresAt);\n return Number.isFinite(expires) && expires > nowMs;\n}\n\nfunction liveEntries(store: StoredCredentialCache, nowMs: number): readonly StoredCredentialEntry[] {\n return store.entries.filter((entry) => isLive(entry, nowMs));\n}\n\n// eslint-disable-next-line @typescript-eslint/require-await -- async is deliberate: it converts a synchronous throw from readStore into a rejected Promise, matching this function's Promise<...> contract\nexport async function readCachedCredential(key: CredentialCacheKey, options: CredentialCacheOptions): Promise<DashboardsCredential | undefined> {\n const store = readStore(cachePath(options));\n const nowMs = (options.now?.() ?? new Date()).getTime();\n const entry = liveEntries(store, nowMs).find((candidate) => matchesKey(candidate, key));\n if (entry === undefined) {\n return undefined;\n }\n return { dashboardsEndpoint: entry.dashboardsEndpoint, username: entry.username, password: entry.password, source: entry.source, instance: entry.instance };\n}\n\n// eslint-disable-next-line @typescript-eslint/require-await -- async is deliberate: it converts a synchronous throw from writeStore into a rejected Promise, matching this function's Promise<...> contract\nexport async function writeCachedCredential(key: CredentialCacheKey, credential: DashboardsCredential, options: CredentialCacheOptions): Promise<void> {\n const path = cachePath(options);\n const store = readStore(path);\n const now = options.now?.() ?? new Date();\n const ttlMinutes = options.ttlMinutes ?? DEFAULT_TTL_MINUTES;\n const entry: StoredCredentialEntry = {\n region: key.target.region,\n apiEndpoint: key.target.apiEndpoint,\n org: key.target.org,\n space: key.target.space,\n instanceSelector: key.instanceSelector ?? AUTO_INSTANCE_SELECTOR,\n instance: credential.instance,\n source: credential.source,\n dashboardsEndpoint: credential.dashboardsEndpoint,\n username: credential.username,\n password: credential.password,\n cachedAt: now.toISOString(),\n expiresAt: new Date(now.getTime() + ttlMinutes * 60_000).toISOString(),\n };\n const kept = liveEntries(store, now.getTime()).filter((candidate) => !matchesKey(candidate, key));\n writeStore(path, { version: 1, entries: [...kept, entry] });\n}\n\n// eslint-disable-next-line @typescript-eslint/require-await -- async is deliberate: it converts a synchronous throw from writeStore into a rejected Promise, matching this function's Promise<...> contract\nexport async function deleteCachedCredential(key: CredentialCacheKey, options: CredentialCacheOptions): Promise<boolean> {\n const path = cachePath(options);\n const store = readStore(path);\n const kept = store.entries.filter((candidate) => !matchesKey(candidate, key));\n if (kept.length === store.entries.length) {\n return false;\n }\n writeStore(path, { version: 1, entries: kept });\n return true;\n}\n\n// eslint-disable-next-line @typescript-eslint/require-await -- async is deliberate: it converts a synchronous throw from readStore into a rejected Promise, matching this function's Promise<...> contract\nexport async function listCachedCredentials(options: CredentialCacheOptions): Promise<readonly CachedCredentialSummary[]> {\n const store = readStore(cachePath(options));\n const nowMs = (options.now?.() ?? new Date()).getTime();\n return liveEntries(store, nowMs)\n .map((entry) => {\n return { region: entry.region, org: entry.org, space: entry.space, instance: entry.instance, source: entry.source, dashboardsEndpoint: entry.dashboardsEndpoint, cachedAt: entry.cachedAt, expiresAt: entry.expiresAt };\n })\n .sort((left, right) => {\n return `${left.region}/${left.org}/${left.space}/${left.instance}`.localeCompare(`${right.region}/${right.org}/${right.space}/${right.instance}`);\n });\n}\n\nexport async function clearCredentialCache(options: CredentialCacheOptions): Promise<number> {\n const path = cachePath(options);\n const store = readStore(path);\n const nowMs = (options.now?.() ?? new Date()).getTime();\n const count = liveEntries(store, nowMs).length;\n await rm(path, { force: true });\n const directory = dirname(path);\n const prefix = `${CACHE_FILE_NAME}.`;\n let names: readonly string[];\n try {\n names = await readdir(directory);\n } catch {\n return count;\n }\n await Promise.all(\n names\n .filter((name) => name.startsWith(prefix) && name.endsWith(\".tmp\"))\n .map(async (name) => {\n await rm(join(directory, name), { force: true });\n }),\n );\n return count;\n}\n","import { randomBytes } from \"node:crypto\";\nimport { mkdir, readdir, readFile, rename, rm, stat, unlink, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { resolveSaptoolsRoot } from \"../saptools-paths.js\";\n\nconst RESULT_REF_PATTERN = /^[0-9a-f]{8}$/;\nconst TEMP_REF_PATTERN = /^([0-9a-f]{8})\\.tmp-(\\d+)$/;\nconst MANIFEST_FILE_NAME = \"manifest.json\";\nconst MAX_DATE_MILLIS = 8_640_000_000_000_000;\nconst DEFAULT_TTL_MINUTES = 10_080;\nconst DEFAULT_MAX_BYTES = 256 * 1024 * 1024;\n\ninterface StoredResultSession<TRow> {\n readonly version: 1;\n readonly ref: string;\n readonly createdAt: string;\n readonly expiresAt: string;\n readonly ttlMinutes: number;\n readonly command: string;\n readonly rows: readonly TRow[];\n}\n\nexport interface CreateResultSessionInput<TRow> {\n readonly cliName: string;\n readonly command: string;\n readonly rows: readonly TRow[];\n readonly ttlMinutes?: number;\n}\n\nexport interface ResultStoreOptions {\n readonly cliName: string;\n readonly saptoolsRoot?: string;\n readonly now?: () => Date;\n readonly ref?: string;\n readonly maxBytes?: number;\n}\n\nexport type ResultSession<TRow> = StoredResultSession<TRow>;\n\nexport interface ResultSessionSummary {\n readonly ref: string;\n readonly createdAt: string;\n readonly expiresAt: string;\n readonly command: string;\n readonly rowCount: number;\n}\n\nexport interface PruneOutcome {\n readonly removed: number;\n readonly failed: number;\n readonly retainedRefs: readonly string[];\n readonly strandedRemoved: number;\n}\n\nfunction resultsRoot(options: Pick<ResultStoreOptions, \"cliName\" | \"saptoolsRoot\">): string {\n return join(resolveSaptoolsRoot(options.saptoolsRoot), options.cliName, \"results\");\n}\n\nfunction sessionDirectory(ref: string, options: Pick<ResultStoreOptions, \"cliName\" | \"saptoolsRoot\">): string {\n return join(resultsRoot(options), ref);\n}\n\nfunction manifestPath(ref: string, options: Pick<ResultStoreOptions, \"cliName\" | \"saptoolsRoot\">): string {\n return join(sessionDirectory(ref, options), MANIFEST_FILE_NAME);\n}\n\nfunction resolveRef(value: string | undefined): string {\n const ref = value ?? randomBytes(4).toString(\"hex\");\n if (!RESULT_REF_PATTERN.test(ref)) {\n throw new Error(\"Invalid saved result ref\");\n }\n return ref;\n}\n\nfunction resolveTtl(value: number | undefined): number {\n const ttl = value ?? DEFAULT_TTL_MINUTES;\n if (!Number.isSafeInteger(ttl) || ttl <= 0) {\n throw new Error(\"Result TTL must be a positive safe integer\");\n }\n return ttl;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isStoredSession<TRow>(value: unknown): value is StoredResultSession<TRow> {\n return (\n isRecord(value) &&\n value[\"version\"] === 1 &&\n typeof value[\"ref\"] === \"string\" &&\n typeof value[\"createdAt\"] === \"string\" &&\n typeof value[\"expiresAt\"] === \"string\" &&\n typeof value[\"ttlMinutes\"] === \"number\" &&\n typeof value[\"command\"] === \"string\" &&\n Array.isArray(value[\"rows\"])\n );\n}\n\ntype SessionReadFailure = \"absent\" | \"unreadable\" | \"unrecognized\";\ntype SessionRead<TRow> = { readonly ok: true; readonly session: StoredResultSession<TRow> } | { readonly ok: false; readonly failure: SessionReadFailure };\n\nfunction isMissingPathError(error: unknown): boolean {\n const code = (error as NodeJS.ErrnoException | null)?.code;\n return code === \"ENOENT\" || code === \"ENOTDIR\";\n}\n\nasync function readStoredSession<TRow>(path: string): Promise<SessionRead<TRow>> {\n let text: string;\n try {\n text = await readFile(path, \"utf8\");\n } catch (error) {\n return { ok: false, failure: isMissingPathError(error) ? \"absent\" : \"unreadable\" };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return { ok: false, failure: \"unrecognized\" };\n }\n if (isStoredSession<TRow>(parsed)) {\n return { ok: true, session: parsed };\n }\n return { ok: false, failure: \"unrecognized\" };\n}\n\nfunction resolveExpiryMillis(session: StoredResultSession<unknown>): number | undefined {\n const explicit = Date.parse(session.expiresAt);\n if (Number.isFinite(explicit)) {\n return explicit;\n }\n const created = Date.parse(session.createdAt);\n if (!Number.isFinite(created) || !Number.isSafeInteger(session.ttlMinutes) || session.ttlMinutes <= 0) {\n return undefined;\n }\n const derived = created + session.ttlMinutes * 60_000;\n if (Math.abs(derived) > MAX_DATE_MILLIS) {\n return undefined;\n }\n return derived;\n}\n\nasync function listSessionRefs(options: ResultStoreOptions): Promise<readonly string[]> {\n try {\n const entries = await readdir(resultsRoot(options), { withFileTypes: true });\n return entries.filter((entry) => entry.isDirectory() && RESULT_REF_PATTERN.test(entry.name)).map((entry) => entry.name);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return [];\n }\n throw error;\n }\n}\n\nfunction isOwnerAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n return code !== \"ESRCH\";\n }\n}\n\nconst STRANDED_AGE_MS = 24 * 60 * 60 * 1000;\n\n/**\n * Remove `<ref>.tmp-<pid>` directories left behind by an interrupted save.\n * Liveness (`process.kill(pid, 0)`) is the primary gate — real-world\n * measurement (see `.plans` design doc / project memory) found pid reuse\n * rare enough that 100/100 real saves survived a sweep with only the\n * liveness check. The 24h mtime age gate is a fallback for a pid namespace\n * where a live pid in a *different* container reads as dead (`ESRCH`).\n */\nasync function removeStrandedTempDirectories(options: ResultStoreOptions): Promise<number> {\n const root = resultsRoot(options);\n let names: readonly string[];\n try {\n names = await readdir(root);\n } catch {\n return 0;\n }\n let removed = 0;\n for (const name of names) {\n const match = TEMP_REF_PATTERN.exec(name);\n if (match === null) {\n continue;\n }\n const pid = Number(match[2]);\n const path = join(root, name);\n let ageMs: number;\n try {\n ageMs = Date.now() - (await stat(path)).mtimeMs;\n } catch {\n continue;\n }\n if (isOwnerAlive(pid) && ageMs < STRANDED_AGE_MS) {\n continue;\n }\n try {\n await rm(path, { recursive: true, force: true });\n removed += 1;\n } catch {\n // best effort\n }\n }\n return removed;\n}\n\nexport async function createResultSession<TRow>(input: CreateResultSessionInput<TRow>, options: Omit<ResultStoreOptions, \"cliName\"> = {}): Promise<ResultSession<TRow>> {\n const fullOptions: ResultStoreOptions = { ...options, cliName: input.cliName };\n await pruneBestEffort(fullOptions);\n const ref = resolveRef(fullOptions.ref);\n const now = fullOptions.now?.() ?? new Date();\n const ttlMinutes = resolveTtl(input.ttlMinutes);\n const stored: StoredResultSession<TRow> = {\n version: 1,\n ref,\n createdAt: now.toISOString(),\n expiresAt: new Date(now.getTime() + ttlMinutes * 60_000).toISOString(),\n ttlMinutes,\n command: input.command,\n rows: input.rows,\n };\n const serialized = `${JSON.stringify(stored)}\\n`;\n if (Buffer.byteLength(serialized) > (fullOptions.maxBytes ?? DEFAULT_MAX_BYTES)) {\n throw new Error(\"Saved result exceeds the storage limit\");\n }\n const root = resultsRoot(fullOptions);\n const finalDirectory = sessionDirectory(ref, fullOptions);\n const tempDirectory = `${finalDirectory}.tmp-${process.pid.toString()}`;\n await mkdir(root, { recursive: true, mode: 0o700 });\n await rm(tempDirectory, { recursive: true, force: true });\n await mkdir(tempDirectory, { mode: 0o700 });\n try {\n await writeFile(join(tempDirectory, MANIFEST_FILE_NAME), serialized, { encoding: \"utf8\", mode: 0o600 });\n await rename(tempDirectory, finalDirectory);\n } catch (error) {\n await rm(tempDirectory, { recursive: true, force: true });\n throw error;\n }\n return stored;\n}\n\n/** Verify a saved result could be written, without writing one — call before expensive credential discovery so a broken store fails fast. */\nexport async function assertResultStoreWritable(options: ResultStoreOptions): Promise<void> {\n const root = resultsRoot(options);\n const probe = join(root, `.writable-${process.pid.toString()}-${randomBytes(4).toString(\"hex\")}`);\n try {\n await mkdir(root, { recursive: true, mode: 0o700 });\n await writeFile(probe, \"\", { encoding: \"utf8\", mode: 0o600 });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`--save cannot write to the saved-result store at ${root}: ${message}`, { cause: error });\n }\n try {\n await unlink(probe);\n } catch {\n // already proved what it was for\n }\n}\n\nfunction readFailureError(ref: string, failure: SessionReadFailure, options: ResultStoreOptions): Error {\n const path = manifestPath(ref, options);\n switch (failure) {\n case \"absent\": {\n return new Error(\"Saved result not found or expired\");\n }\n case \"unreadable\": {\n return new Error(`Saved result \"${ref}\" exists but could not be read; check permissions on ${path}`);\n }\n case \"unrecognized\": {\n return new Error(`Saved result \"${ref}\" is not in a format this version understands. It has been left in place at ${path}.`);\n }\n }\n}\n\nexport async function readResultSession<TRow>(ref: string, options: ResultStoreOptions): Promise<ResultSession<TRow>> {\n const resolvedRef = resolveRef(ref);\n await pruneBestEffort(options);\n const read = await readStoredSession<TRow>(manifestPath(resolvedRef, options));\n if (!read.ok) {\n throw readFailureError(resolvedRef, read.failure, options);\n }\n const now = (options.now?.() ?? new Date()).getTime();\n const expiry = resolveExpiryMillis(read.session);\n if (expiry === undefined) {\n throw readFailureError(resolvedRef, \"unrecognized\", options);\n }\n if (expiry <= now) {\n throw new Error(\"Saved result not found or expired\");\n }\n return read.session;\n}\n\nexport async function listResultSessions(options: ResultStoreOptions): Promise<readonly ResultSessionSummary[]> {\n await pruneBestEffort(options);\n const refs = await listSessionRefs(options);\n const now = (options.now?.() ?? new Date()).getTime();\n const reads = await Promise.all(refs.map(async (ref) => ({ ref, read: await readStoredSession(manifestPath(ref, options)) })));\n return reads\n .flatMap(({ ref, read }) => {\n if (!read.ok) {\n return [];\n }\n const expiry = resolveExpiryMillis(read.session);\n if (expiry === undefined || expiry <= now) {\n return [];\n }\n return [{ ref, createdAt: read.session.createdAt, expiresAt: read.session.expiresAt, command: read.session.command, rowCount: read.session.rows.length }];\n })\n .sort((left, right) => left.ref.localeCompare(right.ref));\n}\n\nasync function isEmptyDirectory(path: string): Promise<boolean> {\n try {\n return (await readdir(path)).length === 0;\n } catch {\n return false;\n }\n}\n\nexport async function pruneResultSessions(options: ResultStoreOptions): Promise<PruneOutcome> {\n const refs = await listSessionRefs(options);\n const now = (options.now?.() ?? new Date()).getTime();\n let removed = 0;\n let failed = 0;\n const retainedRefs: string[] = [];\n for (const ref of refs) {\n const directory = sessionDirectory(ref, options);\n const read = await readStoredSession(manifestPath(ref, options));\n if (!read.ok && read.failure !== \"absent\") {\n retainedRefs.push(ref);\n continue;\n }\n if (read.ok) {\n const expiry = resolveExpiryMillis(read.session);\n if (expiry === undefined) {\n retainedRefs.push(ref);\n continue;\n }\n if (expiry > now) {\n continue;\n }\n }\n if (!read.ok && !(await isEmptyDirectory(directory))) {\n retainedRefs.push(ref);\n continue;\n }\n try {\n await rm(directory, { recursive: true, force: true });\n removed += 1;\n } catch {\n failed += 1;\n }\n }\n const strandedRemoved = await removeStrandedTempDirectories(options);\n return { removed, failed, retainedRefs, strandedRemoved };\n}\n\nasync function pruneBestEffort(options: ResultStoreOptions): Promise<void> {\n try {\n await pruneResultSessions(options);\n } catch {\n // Intentionally ignored: a broken store must not block save/read/list of an intact session.\n }\n}\n\nexport async function clearResultSessions(options: ResultStoreOptions): Promise<number> {\n const refs = await listSessionRefs(options);\n await Promise.all(refs.map(async (ref) => { await rm(sessionDirectory(ref, options), { recursive: true, force: true }); }));\n return refs.length;\n}\n","import { CfDebuggerError } from \"./types.js\";\n\nexport function readRequiredOption(\n value: string | undefined,\n flag: string,\n): string {\n if (value === undefined || value.trim().length === 0) {\n throw new CfDebuggerError(\"UNSAFE_INPUT\", `Missing required option ${flag}.`);\n }\n return value;\n}\n\nexport function parseOptionalInteger(\n raw: string | undefined,\n label: string,\n minimum: number,\n maximum = Number.MAX_SAFE_INTEGER,\n): number | undefined {\n if (raw === undefined) {\n return undefined;\n }\n if (!/^\\d+$/.test(raw)) {\n throw new CfDebuggerError(\"UNSAFE_INPUT\", `${label} must be an integer.`);\n }\n const value = Number(raw);\n if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {\n throw new CfDebuggerError(\n \"UNSAFE_INPUT\",\n `${label} must be from ${minimum.toString()} to ${maximum.toString()}.`,\n );\n }\n return value;\n}\n\nexport function parseSeconds(\n raw: string | undefined,\n label: string,\n): number | undefined {\n const seconds = parseOptionalInteger(raw, label, 1);\n return seconds === undefined ? undefined : seconds * 1000;\n}\n","import { readFileSync } from \"node:fs\";\n\nimport { CfDebuggerError } from \"./types.js\";\n\nexport function readPackageVersion(): string {\n const parsed: unknown = JSON.parse(\n readFileSync(new URL(\"../package.json\", import.meta.url), \"utf8\"),\n );\n if (typeof parsed !== \"object\" || parsed === null) {\n throw new CfDebuggerError(\"PACKAGE_METADATA_INVALID\", \"Package metadata is not an object.\");\n }\n const version: unknown = Reflect.get(parsed, \"version\");\n if (typeof version !== \"string\" || version.length === 0) {\n throw new CfDebuggerError(\"PACKAGE_METADATA_INVALID\", \"Package metadata has no version.\");\n }\n return version;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,OAAO,iBAAiB;;;ACFxB,SAAS,oBAAoB;AAC7B,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;;;ACFvB,SAAS,SAAS,OAAkD;AACzE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEO,SAAS,aAAa,OAAwB;AACnD,SAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;AAGO,SAAS,WAAW,QAAiC,KAAiC;AAC3F,QAAM,QAAQ,OAAO,GAAG;AACxB,SAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ;AACjE;;;ADOA,IAAM,cAAc;AAGb,SAAS,oBAAoB,WAAgD;AAClF,MAAI;AACJ,MAAI;AACF,UAAM,aAAa,KAAK,WAAW,cAAc,GAAG,MAAM;AAAA,EAC5D,QAAQ;AACN;AAAA,EACF;AACA,MAAI;AACJ,MAAI;AACF,aAAS,KAAK,MAAM,GAAG;AAAA,EACzB,QAAQ;AACN;AAAA,EACF;AACA,MAAI,CAAC,SAAS,MAAM,GAAG;AACrB;AAAA,EACF;AACA,QAAM,OAAO,WAAW,QAAQ,MAAM;AACtC,QAAM,UAAU,WAAW,QAAQ,SAAS;AAC5C,MAAI,SAAS,UAAa,Y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MAAI,4BAA4B,KAAK,GAAG;AACtC,UAAMC,WAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,gBAAY,OAAO,MAAM,yBAAyBA,QAAO;AAAA,CAAI;AAC7D,gBAAY,KAAK,yBAAyB;AAAA,EAC5C;AACA,QAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,cAAY,OAAO,MAAM,UAAU,OAAO;AAAA,CAAI;AAC9C,cAAY,KAAK,iBAAiB,KAAK,CAAC;AAC1C;AAEA,IAAI;AACF,QAAM,KAAK,YAAY,IAAI;AAC7B,SAAS,OAAgB;AACvB,qBAAmB,KAAK;AAC1B;","names":["readFileSync","join","spawn","homedir","constants","dirname","join","constants","dirname","join","realpathSync","dirname","join","dirname","join","realpathSync","readFileSync","join","readFileSync","join","latest","rmSync","dirname","join","join","dirname","rmSync","defaultRuntime","homedir","spawn","notify","dirname","join","readdir","rm","join","readFileSync","readFileSync","message"]}
|