@dev-anywhere/proxy 0.9.1 → 0.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -3
- package/dist/autostart-C3RNQ65S.js +292 -0
- package/dist/autostart-C3RNQ65S.js.map +1 -0
- package/dist/chunk-2YUDGRJ6.js +379 -0
- package/dist/chunk-2YUDGRJ6.js.map +1 -0
- package/dist/chunk-74HWO753.js +285 -0
- package/dist/chunk-74HWO753.js.map +1 -0
- package/dist/chunk-77QVUYU7.js +42 -0
- package/dist/chunk-77QVUYU7.js.map +1 -0
- package/dist/chunk-DAFUSBKJ.js +299 -0
- package/dist/chunk-DAFUSBKJ.js.map +1 -0
- package/dist/{chunk-HLN3NOD2.js → chunk-GFDOVLGL.js} +70 -1
- package/dist/chunk-GFDOVLGL.js.map +1 -0
- package/dist/{chunk-SEMZ7GW7.js → chunk-GYL5JKWQ.js} +3 -3
- package/dist/{chunk-57LA2LWY.js → chunk-HYDXGNKA.js} +2 -2
- package/dist/chunk-ICSO3ZIS.js +658 -0
- package/dist/chunk-ICSO3ZIS.js.map +1 -0
- package/dist/chunk-JZ7MWN24.js +22 -0
- package/dist/chunk-JZ7MWN24.js.map +1 -0
- package/dist/chunk-KINQESTO.js +145 -0
- package/dist/chunk-KINQESTO.js.map +1 -0
- package/dist/{chunk-ZNMJH7BK.js → chunk-KWODOJBK.js} +3 -3
- package/dist/chunk-MLE2OKCM.js +116 -0
- package/dist/chunk-MLE2OKCM.js.map +1 -0
- package/dist/{chunk-UJEZAG57.js → chunk-PCF2R2TG.js} +3 -1
- package/dist/{chunk-UJEZAG57.js.map → chunk-PCF2R2TG.js.map} +1 -1
- package/dist/{chunk-NTL4CXBA.js → chunk-V4HDLUAQ.js} +27 -42
- package/dist/chunk-V4HDLUAQ.js.map +1 -0
- package/dist/{chunk-DZ4GXMP5.js → chunk-VHMAUU72.js} +56 -68
- package/dist/chunk-VHMAUU72.js.map +1 -0
- package/dist/{chunk-OFD4UVPB.js → chunk-XADKKDUV.js} +29 -153
- package/dist/chunk-XADKKDUV.js.map +1 -0
- package/dist/{chunk-WRU3BXW6.js → chunk-YK2XKOP4.js} +26 -10
- package/dist/chunk-YK2XKOP4.js.map +1 -0
- package/dist/index.js +130 -343
- package/dist/index.js.map +1 -1
- package/dist/logger-24TGGN76.js +10 -0
- package/dist/logger-24TGGN76.js.map +1 -0
- package/dist/logger-B7B64O4P.js +14 -0
- package/dist/logger-B7B64O4P.js.map +1 -0
- package/dist/{quick-tunnel-RI62V2RH.js → quick-tunnel-ZIFTYUUD.js} +3 -3
- package/dist/{relay-token-ZP3PAZD2.js → relay-token-N3BSBURG.js} +5 -5
- package/dist/serve.js +1158 -380
- package/dist/serve.js.map +1 -1
- package/dist/session-worker.js +91 -76
- package/dist/session-worker.js.map +1 -1
- package/dist/{terminal-BEXDQ5WK.js → terminal-7JY6J3XN.js} +88 -36
- package/dist/terminal-7JY6J3XN.js.map +1 -0
- package/dist/terminal-worker.js +93 -44
- package/dist/terminal-worker.js.map +1 -1
- package/dist/update-runner.js +86 -61
- package/dist/update-runner.js.map +1 -1
- package/package.json +9 -6
- package/scripts/postinstall.cjs +22 -0
- package/dist/chunk-7SYT65DN.js +0 -155
- package/dist/chunk-7SYT65DN.js.map +0 -1
- package/dist/chunk-DZ4GXMP5.js.map +0 -1
- package/dist/chunk-HLN3NOD2.js.map +0 -1
- package/dist/chunk-KGTYU4WO.js +0 -36
- package/dist/chunk-KGTYU4WO.js.map +0 -1
- package/dist/chunk-NTL4CXBA.js.map +0 -1
- package/dist/chunk-OFD4UVPB.js.map +0 -1
- package/dist/chunk-WC3KEY7N.js +0 -158
- package/dist/chunk-WC3KEY7N.js.map +0 -1
- package/dist/chunk-WRU3BXW6.js.map +0 -1
- package/dist/terminal-BEXDQ5WK.js.map +0 -1
- /package/dist/{chunk-SEMZ7GW7.js.map → chunk-GYL5JKWQ.js.map} +0 -0
- /package/dist/{chunk-57LA2LWY.js.map → chunk-HYDXGNKA.js.map} +0 -0
- /package/dist/{chunk-ZNMJH7BK.js.map → chunk-KWODOJBK.js.map} +0 -0
- /package/dist/{quick-tunnel-RI62V2RH.js.map → quick-tunnel-ZIFTYUUD.js.map} +0 -0
- /package/dist/{relay-token-ZP3PAZD2.js.map → relay-token-N3BSBURG.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../packages/shared/src/logger.ts"],"sourcesContent":["import {\n lstatSync,\n linkSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n renameSync,\n statSync,\n symlinkSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { randomUUID } from \"node:crypto\";\nimport { homedir } from \"node:os\";\nimport { basename, join } from \"node:path\";\nimport pino from \"pino\";\n\nexport type { Logger } from \"pino\";\n\nexport interface CreateLoggerOptions {\n name: string;\n level?: string;\n logDir?: string;\n retention?: number;\n // A live process must never be able to grow one log file without bound. The limit is applied\n // to serialized UTF-8 bytes and rotation keeps at most maxFilesPerRun files for this process.\n maxFileBytes?: number;\n maxFilesPerRun?: number;\n maxRecordBytes?: number;\n retentionBytes?: number;\n stdout?: boolean;\n silent?: boolean;\n // 同步落盘:sonic-boom 默认异步 open + 异步 write,测试里需要在断言前看到文件,\n // 或在 afterEach 删目录前确保后台 worker 已经退出,必须开同步。生产保留异步以避免热路径阻塞。\n sync?: boolean;\n}\n\nconst DEFAULT_LOG_DIR = `${homedir()}/.dev-anywhere/logs`;\nconst DEFAULT_LOG_RETENTION = 50;\nconst DEFAULT_LOG_RETENTION_BYTES = 256 * 1024 * 1024;\nconst DEFAULT_MAX_FILE_BYTES = 16 * 1024 * 1024;\nconst DEFAULT_MAX_FILES_PER_RUN = 2;\nconst DEFAULT_MAX_RECORD_BYTES = 256 * 1024;\nconst DEFAULT_MAX_STDOUT_BUFFER_BYTES = 1024 * 1024;\nconst LOG_IO_OPERATION_TIMEOUT_MS = 5_000;\nconst LOG_RUN_LEASE_SUFFIX = \".active\";\nconst LOG_RUN_LEASE_CANDIDATE_MARKER = `${LOG_RUN_LEASE_SUFFIX}.candidate-`;\n\nconst PROCESS_LOG_RUN_ID = sanitizeRunId(\n `${new Date().toISOString().replace(/[:.]/g, \"-\")}-${process.pid}`,\n);\n\nfunction sanitizeRunId(runId: string): string {\n return runId.replace(/[^a-zA-Z0-9._-]/g, \"_\");\n}\n\nfunction linkLatestLog(logDir: string, name: string, filePath: string, runId: string): void {\n const latestPath = join(logDir, `${name}.log`);\n\n try {\n const stat = lstatSync(latestPath);\n if (stat.isSymbolicLink()) {\n unlinkSync(latestPath);\n } else {\n renameSync(latestPath, join(logDir, `${name}-legacy-${runId}.log`));\n }\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== \"ENOENT\") return;\n }\n\n try {\n symlinkSync(basename(filePath), latestPath);\n } catch {\n // 日志本体仍然写入 run-specific 文件;latest 链接失败不应阻塞服务启动。\n }\n}\n\nfunction resolveRetention(retention: number | undefined): number {\n if (retention === undefined) return DEFAULT_LOG_RETENTION;\n return Number.isFinite(retention) && retention >= 0\n ? Math.floor(retention)\n : DEFAULT_LOG_RETENTION;\n}\n\nfunction resolvePositiveInteger(value: number | undefined, fallback: number): number {\n return value !== undefined && Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;\n}\n\ninterface LogRunLease {\n version: 1;\n pid: number;\n runId: string;\n fileName: string;\n}\n\nfunction leasePathForLog(filePath: string): string {\n return `${filePath}${LOG_RUN_LEASE_SUFFIX}`;\n}\n\nfunction createLogRunLease(filePath: string, runId: string): void {\n const lease: LogRunLease = {\n version: 1,\n pid: process.pid,\n runId,\n fileName: basename(filePath),\n };\n const leasePath = leasePathForLog(filePath);\n const candidatePath = `${leasePath}.candidate-${process.pid}-${randomUUID()}`;\n let candidateCreated = false;\n try {\n // Publish through a hard link only after the same-directory candidate has been completely\n // written and closed. Unlike writing directly to the final path, readers can therefore never\n // observe an empty or partially serialized lease, and link(2) retains O_EXCL semantics.\n writeFileSync(candidatePath, `${JSON.stringify(lease)}\\n`, { flag: \"wx\" });\n candidateCreated = true;\n linkSync(candidatePath, leasePath);\n } finally {\n if (candidateCreated) {\n try {\n unlinkSync(candidatePath);\n } catch {\n // A crash or unlink failure can leave a valid candidate. A future logger run reclaims it\n // once its owner is known to be dead.\n }\n }\n }\n}\n\nfunction isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code !== \"ESRCH\";\n }\n}\n\ntype LogRunLeaseReadResult =\n | { state: \"missing\" }\n | { state: \"invalid\" }\n | { state: \"valid\"; lease: LogRunLease };\n\nfunction readLogRunLease(leasePath: string, expectedFileName: string): LogRunLeaseReadResult {\n let raw: string;\n try {\n raw = readFileSync(leasePath, \"utf-8\");\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === \"ENOENT\"\n ? { state: \"missing\" }\n : { state: \"invalid\" };\n }\n\n try {\n const parsed = JSON.parse(raw) as Partial<LogRunLease>;\n const pid = parsed.pid;\n if (\n parsed.version !== 1 ||\n !Number.isSafeInteger(pid) ||\n typeof pid !== \"number\" ||\n pid <= 0 ||\n typeof parsed.runId !== \"string\" ||\n parsed.runId.length === 0 ||\n parsed.fileName !== expectedFileName\n ) {\n throw new Error(\"Invalid log run lease\");\n }\n return { state: \"valid\", lease: parsed as LogRunLease };\n } catch {\n // A malformed lease might be a concurrently published or externally damaged ownership\n // record. Fail closed: neither the lease nor its corresponding log may be deleted.\n return { state: \"invalid\" };\n }\n}\n\nfunction hasLiveLogRunLease(filePath: string): boolean {\n const leasePath = leasePathForLog(filePath);\n const result = readLogRunLease(leasePath, basename(filePath));\n if (result.state === \"missing\") return false;\n if (result.state === \"invalid\") return true;\n\n if (isProcessAlive(result.lease.pid)) return true;\n try {\n unlinkSync(leasePath);\n } catch {\n // The owning process is gone, so the log is stale even if its lease cannot be removed.\n }\n return false;\n}\n\nfunction removeOwnedLogRunLease(filePath: string, runId: string): void {\n const leasePath = leasePathForLog(filePath);\n const result = readLogRunLease(leasePath, basename(filePath));\n if (\n result.state !== \"valid\" ||\n result.lease.pid !== process.pid ||\n result.lease.runId !== runId\n ) {\n return;\n }\n try {\n unlinkSync(leasePath);\n } catch {\n // Cleanup is best effort. A valid lease left behind is reclaimable after this process exits.\n }\n}\n\nfunction parseLeaseEntry(\n entry: string,\n name: string,\n): { fileName: string; candidate: boolean } | null {\n const prefix = `${name}-`;\n if (!entry.startsWith(prefix)) return null;\n if (entry.endsWith(LOG_RUN_LEASE_SUFFIX)) {\n const fileName = entry.slice(0, -LOG_RUN_LEASE_SUFFIX.length);\n return fileName.endsWith(\".log\") ? { fileName, candidate: false } : null;\n }\n\n const markerIndex = entry.lastIndexOf(LOG_RUN_LEASE_CANDIDATE_MARKER);\n if (markerIndex < 0 || markerIndex + LOG_RUN_LEASE_CANDIDATE_MARKER.length >= entry.length) {\n return null;\n }\n const fileName = entry.slice(0, markerIndex);\n return fileName.endsWith(\".log\") ? { fileName, candidate: true } : null;\n}\n\nfunction pruneOrphanedLogRunLeases(logDir: string, name: string): void {\n for (const entry of readdirSync(logDir)) {\n const parsedEntry = parseLeaseEntry(entry, name);\n if (!parsedEntry) continue;\n\n const leasePath = join(logDir, entry);\n const result = readLogRunLease(leasePath, parsedEntry.fileName);\n if (result.state !== \"valid\" || isProcessAlive(result.lease.pid)) continue;\n\n let correspondingLogExists = false;\n try {\n statSync(join(logDir, parsedEntry.fileName));\n correspondingLogExists = true;\n } catch {\n // A missing log makes a valid dead-owner lease an orphan.\n }\n if (!parsedEntry.candidate && correspondingLogExists) continue;\n\n try {\n unlinkSync(leasePath);\n } catch {\n // A concurrent cleanup or filesystem error must not prevent logger startup.\n }\n }\n}\n\nfunction removeLogAndLease(filePath: string): void {\n unlinkSync(filePath);\n try {\n unlinkSync(leasePathForLog(filePath));\n } catch {\n // Missing or concurrently removed stale leases need no further cleanup.\n }\n}\n\nfunction pruneOldLogs(\n logDir: string,\n name: string,\n currentFilePath: string,\n retention: number | undefined,\n retentionBytes: number | undefined,\n): void {\n const keep = resolveRetention(retention);\n const byteBudget = resolvePositiveInteger(retentionBytes, DEFAULT_LOG_RETENTION_BYTES);\n pruneOrphanedLogRunLeases(logDir, name);\n if (keep === 0) return;\n\n const currentFileName = basename(currentFilePath);\n const prefix = `${name}-`;\n const candidates = readdirSync(logDir)\n .filter(\n (entry) => entry.startsWith(prefix) && entry.endsWith(\".log\") && entry !== currentFileName,\n )\n .map((entry) => {\n const path = join(logDir, entry);\n try {\n const stat = statSync(path);\n return { path, mtimeMs: stat.mtimeMs, size: stat.size };\n } catch {\n return null;\n }\n })\n .filter((entry): entry is { path: string; mtimeMs: number; size: number } => entry !== null)\n .sort((a, b) => b.mtimeMs - a.mtimeMs);\n\n const retained: typeof candidates = [];\n let retainedBytes = 0;\n for (const candidate of candidates) {\n if (hasLiveLogRunLease(candidate.path)) {\n retained.push(candidate);\n retainedBytes += candidate.size;\n continue;\n }\n const withinCount = keep === 0 || retained.length < Math.max(0, keep - 1);\n const withinBytes = retainedBytes + candidate.size <= byteBudget;\n if (withinCount && withinBytes) {\n retained.push(candidate);\n retainedBytes += candidate.size;\n continue;\n }\n try {\n removeLogAndLease(candidate.path);\n } catch {\n // 日志清理失败不能影响主进程启动。\n }\n }\n}\n\n// SonicBoom 实例的最小结构契约(pino.destination 返回它,但 pino 类型只暴露 DestinationStream\n// 接口,没有 fd / flushSync / once,所以这里手写一个结构类型用于 flushLogger)。\ninterface SonicLikeDestination {\n fd?: number;\n _writing?: boolean;\n sync?: boolean;\n write?: (data: string) => boolean | void;\n reopen?: (filePath?: string) => void;\n flushSync?: () => void;\n on?: (event: string, cb: (...args: unknown[]) => void) => void;\n off?: (event: string, cb: (...args: unknown[]) => void) => void;\n once?: (event: string, cb: (...args: unknown[]) => void) => void;\n listenerCount?: (event: string) => number;\n}\n\nfunction waitForDestinationEvent(\n destination: SonicLikeDestination,\n event: string,\n deadline?: number,\n): Promise<boolean> {\n if (!destination.on || !destination.off) return Promise.resolve(false);\n const addListener = destination.on.bind(destination);\n const removeListener = destination.off.bind(destination);\n const remaining = deadline === undefined ? undefined : deadline - Date.now();\n if (remaining !== undefined && remaining <= 0) return Promise.resolve(false);\n\n return new Promise<boolean>((resolve) => {\n let settled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const cleanup = () => {\n if (timer) clearTimeout(timer);\n removeListener(event, onEvent);\n removeListener(\"error\", onError);\n };\n const settle = (result: boolean) => {\n if (settled) return;\n settled = true;\n cleanup();\n resolve(result);\n };\n const onEvent = () => settle(true);\n const onError = () => settle(false);\n\n addListener(event, onEvent);\n addListener(\"error\", onError);\n if (remaining !== undefined) {\n timer = setTimeout(() => settle(false), remaining);\n timer.unref?.();\n }\n });\n}\n\ninterface WritableLikeDestination {\n writableLength?: number;\n write(data: string): boolean | void;\n}\n\nclass BoundedWritableDestination implements pino.DestinationStream {\n private droppedRecords = 0;\n private saturated = false;\n\n constructor(\n private readonly destination: WritableLikeDestination,\n private readonly maxPendingBytes: number,\n ) {}\n\n write(serialized: string): void {\n if (this.saturated) return;\n const bytes = Buffer.byteLength(serialized);\n const pendingBytes = this.destination.writableLength;\n if (\n bytes > this.maxPendingBytes ||\n typeof pendingBytes !== \"number\" ||\n !Number.isFinite(pendingBytes)\n ) {\n this.droppedRecords += 1;\n return;\n }\n\n const droppedDiagnostic =\n this.droppedRecords > 0\n ? `${JSON.stringify({\n level: 40,\n time: Date.now(),\n msg: \"Log records were dropped while stdout was backpressured\",\n dropped: this.droppedRecords,\n })}\\n`\n : null;\n const diagnosticBytes = droppedDiagnostic ? Buffer.byteLength(droppedDiagnostic) : 0;\n if (pendingBytes + diagnosticBytes + bytes > this.maxPendingBytes) {\n this.droppedRecords += 1;\n return;\n }\n\n try {\n if (droppedDiagnostic) this.destination.write(droppedDiagnostic);\n this.destination.write(serialized);\n this.droppedRecords = 0;\n } catch {\n this.saturated = true;\n }\n }\n}\n\nclass BoundedLogDestination implements pino.DestinationStream, SonicLikeDestination {\n private currentBytes = 0;\n private rotating = false;\n private saturated = false;\n private droppedDuringRotation = 0;\n private pendingRecord: string | null = null;\n private rotationPromise: Promise<void> | null = null;\n private readonly rotationWaiters = new Set<() => void>();\n\n constructor(\n private readonly destination: SonicLikeDestination,\n private readonly filePath: string,\n private readonly runId: string,\n private readonly logDir: string,\n private readonly name: string,\n private readonly retention: number | undefined,\n private readonly retentionBytes: number | undefined,\n private readonly maxFileBytes: number,\n private readonly maxFilesPerRun: number,\n private readonly maxRecordBytes: number,\n initialBytes: number,\n ) {\n this.currentBytes = initialBytes;\n // A filesystem failure in SonicBoom must not turn diagnostics into an uncaught process\n // exception. Stop accepting further records; the application can keep serving and the\n // already-enforced byte bound still holds.\n this.destination.on?.(\"error\", () => {\n this.rotating = false;\n this.saturated = true;\n if (this.destination.fd == null || this.destination.fd < 0) {\n removeOwnedLogRunLease(this.filePath, this.runId);\n }\n });\n }\n\n get fd(): number | undefined {\n return this.destination.fd;\n }\n\n get _writing(): boolean | undefined {\n return this.destination._writing;\n }\n\n once(event: string, cb: (...args: unknown[]) => void): void {\n this.destination.once?.(event, cb);\n }\n\n on(event: string, cb: (...args: unknown[]) => void): void {\n this.destination.on?.(event, cb);\n }\n\n off(event: string, cb: (...args: unknown[]) => void): void {\n this.destination.off?.(event, cb);\n }\n\n listenerCount(event: string): number {\n return this.destination.listenerCount?.(event) ?? 0;\n }\n\n write(serialized: string): void {\n if (this.saturated) return;\n const record = this.boundRecord(serialized);\n if (!record) return;\n const bytes = Buffer.byteLength(record);\n\n if (this.rotating) {\n this.droppedDuringRotation += 1;\n return;\n }\n if (this.currentBytes + bytes > this.maxFileBytes) {\n this.startRotation(record);\n return;\n }\n\n this.writeActiveRecord(record);\n }\n\n flushSync(): void {\n this.destination.flushSync?.();\n }\n\n async waitForRotation(deadline: number): Promise<boolean> {\n while (this.rotationPromise) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) return false;\n const settled = await new Promise<boolean>((resolve) => {\n let finished = false;\n const waiter = () => finish(true);\n const timer = setTimeout(() => finish(false), remaining);\n timer.unref?.();\n const finish = (result: boolean) => {\n if (finished) return;\n finished = true;\n clearTimeout(timer);\n this.rotationWaiters.delete(waiter);\n resolve(result);\n };\n\n this.rotationWaiters.add(waiter);\n if (!this.rotationPromise) finish(true);\n });\n if (!settled) return false;\n }\n return true;\n }\n\n private boundRecord(serialized: string): string | null {\n const bytes = Buffer.byteLength(serialized);\n if (bytes <= this.maxRecordBytes && bytes <= this.maxFileBytes) return serialized;\n return this.boundDiagnostic({\n level: 40,\n time: Date.now(),\n msg: \"Log entry omitted because it exceeded the configured byte limit\",\n originalBytes: bytes,\n });\n }\n\n private boundDiagnostic(value: Record<string, unknown>): string | null {\n const serialized = `${JSON.stringify(value)}\\n`;\n const bytes = Buffer.byteLength(serialized);\n return bytes <= this.maxRecordBytes && bytes <= this.maxFileBytes ? serialized : null;\n }\n\n private segmentPath(index: number): string {\n return this.filePath.replace(/\\.log$/, `.${index}.log`);\n }\n\n private writeActiveRecord(record: string): boolean {\n const bytes = Buffer.byteLength(record);\n if (!this.destination.write || this.currentBytes + bytes > this.maxFileBytes) return false;\n this.currentBytes += bytes;\n try {\n this.destination.write(record);\n return !this.saturated;\n } catch {\n this.saturated = true;\n return false;\n }\n }\n\n private startRotation(pendingRecord: string): void {\n if (this.rotating || this.saturated) return;\n this.rotating = true;\n this.pendingRecord = pendingRecord;\n\n const tracked = Promise.resolve()\n .then(() => this.performRotation())\n .catch(() => {\n this.saturated = true;\n this.rotating = false;\n this.pendingRecord = null;\n this.droppedDuringRotation = 0;\n })\n .finally(() => {\n if (this.rotationPromise === tracked) this.rotationPromise = null;\n for (const waiter of this.rotationWaiters) waiter();\n this.rotationWaiters.clear();\n });\n this.rotationPromise = tracked;\n }\n\n private async performRotation(): Promise<void> {\n if (!this.destination.reopen) throw new Error(\"Log destination cannot be reopened\");\n const deadline = Date.now() + LOG_IO_OPERATION_TIMEOUT_MS;\n\n if (this.destination.fd == null || this.destination.fd < 0) {\n if (!(await waitForDestinationEvent(this.destination, \"ready\", deadline))) {\n throw new Error(\"Log destination did not become ready\");\n }\n }\n if (this.destination._writing) {\n if (!(await waitForDestinationEvent(this.destination, \"drain\", deadline))) {\n throw new Error(\"Log destination did not drain\");\n }\n }\n\n this.rotateFiles();\n this.destination.reopen(this.filePath);\n if (!(await waitForDestinationEvent(this.destination, \"ready\", deadline))) {\n throw new Error(\"Rotated log destination did not become ready\");\n }\n pruneOldLogs(this.logDir, this.name, this.filePath, this.retention, this.retentionBytes);\n\n this.currentBytes = 0;\n const pendingRecord = this.pendingRecord;\n this.pendingRecord = null;\n const dropped = this.droppedDuringRotation;\n this.droppedDuringRotation = 0;\n this.rotating = false;\n\n if (pendingRecord && !this.writeActiveRecord(pendingRecord)) return;\n if (dropped === 0 || this.saturated) return;\n const diagnostic = this.boundDiagnostic({\n level: 40,\n time: Date.now(),\n msg: \"Log records were dropped while rotating the active file\",\n dropped,\n });\n if (diagnostic && this.currentBytes + Buffer.byteLength(diagnostic) <= this.maxFileBytes) {\n this.writeActiveRecord(diagnostic);\n }\n }\n\n private rotateFiles(): void {\n if (this.maxFilesPerRun > 1) {\n try {\n unlinkSync(this.segmentPath(this.maxFilesPerRun - 1));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n }\n for (let index = this.maxFilesPerRun - 2; index >= 1; index -= 1) {\n try {\n renameSync(this.segmentPath(index), this.segmentPath(index + 1));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n }\n }\n renameSync(this.filePath, this.segmentPath(1));\n } else {\n unlinkSync(this.filePath);\n }\n }\n}\n\ninterface FlushOperation {\n promise: Promise<void>;\n settled: boolean;\n waiters: Set<() => void>;\n}\n\ninterface LoggerMeta {\n materialized: boolean;\n destination: BoundedLogDestination | null;\n flushOperation: FlushOperation | null;\n}\n\nconst loggerMetaMap = new WeakMap<pino.Logger, LoggerMeta>();\n\nasync function flushDestination(\n destination: BoundedLogDestination,\n deadline: number,\n): Promise<void> {\n while (true) {\n if (!(await destination.waitForRotation(deadline))) return;\n\n if (destination.fd == null || destination.fd < 0) {\n if (!(await waitForDestinationEvent(destination, \"ready\", deadline))) return;\n continue;\n }\n if (destination._writing) {\n if (!(await waitForDestinationEvent(destination, \"drain\", deadline))) return;\n continue;\n }\n\n try {\n destination.flushSync();\n } catch {\n // 文件描述符已关闭、磁盘满等极端情况下吞掉异常,避免把退出路径变成崩溃路径。\n }\n return;\n }\n}\n\nfunction resolveFlushTimeout(timeoutMs: number): number {\n return Number.isFinite(timeoutMs) && timeoutMs >= 0 ? Math.floor(timeoutMs) : 200;\n}\n\nfunction startFlushOperation(meta: LoggerMeta, destination: BoundedLogDestination): FlushOperation {\n const operation: FlushOperation = {\n promise: flushDestination(destination, Date.now() + LOG_IO_OPERATION_TIMEOUT_MS),\n settled: false,\n waiters: new Set(),\n };\n meta.flushOperation = operation;\n\n const finish = () => {\n if (operation.settled) return;\n operation.settled = true;\n if (meta.flushOperation === operation) meta.flushOperation = null;\n for (const waiter of operation.waiters) waiter();\n operation.waiters.clear();\n };\n void operation.promise.then(finish, finish);\n return operation;\n}\n\nfunction waitForFlushOperation(operation: FlushOperation, timeoutMs: number): Promise<void> {\n if (operation.settled || timeoutMs <= 0) return Promise.resolve();\n\n return new Promise<void>((resolve) => {\n let settled = false;\n const finish = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n operation.waiters.delete(finish);\n resolve();\n };\n const timer = setTimeout(finish, timeoutMs);\n\n operation.waiters.add(finish);\n if (operation.settled) {\n finish();\n return;\n }\n });\n}\n\nfunction buildPinoLogger(options: CreateLoggerOptions): {\n logger: pino.Logger;\n destination: BoundedLogDestination | null;\n} {\n const {\n name,\n level = \"info\",\n logDir = DEFAULT_LOG_DIR,\n retention,\n retentionBytes,\n maxFileBytes: requestedMaxFileBytes,\n maxFilesPerRun: requestedMaxFilesPerRun,\n maxRecordBytes: requestedMaxRecordBytes,\n stdout = false,\n silent = false,\n sync = false,\n } = options;\n\n if (silent) {\n return { logger: pino({ level: \"silent\" }), destination: null };\n }\n\n mkdirSync(logDir, { recursive: true });\n\n const runId = `${PROCESS_LOG_RUN_ID}-${randomUUID()}`;\n const filePath = join(logDir, `${name}-${runId}.log`);\n createLogRunLease(filePath, runId);\n try {\n linkLatestLog(logDir, name, filePath, runId);\n pruneOldLogs(logDir, name, filePath, retention, retentionBytes);\n const maxFileBytes = resolvePositiveInteger(requestedMaxFileBytes, DEFAULT_MAX_FILE_BYTES);\n const maxFilesPerRun = resolvePositiveInteger(\n requestedMaxFilesPerRun,\n DEFAULT_MAX_FILES_PER_RUN,\n );\n const maxRecordBytes = Math.min(\n maxFileBytes,\n resolvePositiveInteger(requestedMaxRecordBytes, DEFAULT_MAX_RECORD_BYTES),\n );\n const sonicDestination = pino.destination({\n dest: filePath,\n sync,\n // Bound data queued while the filesystem is stalled. Dropping diagnostics is preferable to\n // allowing a logging failure to consume the application's heap.\n maxLength: Math.min(maxFileBytes, 1024 * 1024),\n }) as unknown as SonicLikeDestination;\n let initialBytes = 0;\n try {\n initialBytes = statSync(filePath).size;\n } catch {\n // A new run normally reaches this branch because SonicBoom creates the file asynchronously.\n }\n const destination = new BoundedLogDestination(\n sonicDestination,\n filePath,\n runId,\n logDir,\n name,\n retention,\n retentionBytes,\n maxFileBytes,\n maxFilesPerRun,\n maxRecordBytes,\n initialBytes,\n );\n const streams: pino.StreamEntry[] = [{ stream: destination }];\n\n if (stdout) {\n streams.unshift({\n stream: new BoundedWritableDestination(process.stdout, DEFAULT_MAX_STDOUT_BUFFER_BYTES),\n });\n }\n\n return { logger: pino({ level }, pino.multistream(streams)), destination };\n } catch (error) {\n removeOwnedLogRunLease(filePath, runId);\n throw error;\n }\n}\n\n// 返回一个 lazy proxy:调用 createLogger 本身不触发 mkdirSync / pino.destination\n// 等任何文件 IO,只有第一次实际访问 logger 的方法/属性时才构造底层 pino Logger。\n// 这样 `dev-anywhere -v` / `dev-anywhere init` 等不需要写日志的命令路径不会\n// 落地空 log 文件,也避免异步 SonicBoom 在 process.exit 时未 ready 的 race。\nexport function createLogger(options: CreateLoggerOptions): pino.Logger {\n let real: pino.Logger | null = null;\n const meta: LoggerMeta = { materialized: false, destination: null, flushOperation: null };\n const ensure = (): pino.Logger => {\n if (!real) {\n const built = buildPinoLogger(options);\n real = built.logger;\n meta.materialized = true;\n meta.destination = built.destination;\n }\n return real;\n };\n\n const proxy = new Proxy(Object.create(null) as pino.Logger, {\n get(_target, prop) {\n const target = ensure();\n const value = Reflect.get(target, prop, target);\n return typeof value === \"function\" ? value.bind(target) : value;\n },\n set(_target, prop, value) {\n return Reflect.set(ensure(), prop, value);\n },\n has(_target, prop) {\n return Reflect.has(ensure(), prop);\n },\n ownKeys() {\n return Reflect.ownKeys(ensure());\n },\n getOwnPropertyDescriptor(_target, prop) {\n return Reflect.getOwnPropertyDescriptor(ensure(), prop);\n },\n });\n\n loggerMetaMap.set(proxy, meta);\n return proxy;\n}\n\n// 进程退出前等 sonic-boom 真正落盘。`pino.flush(cb)` 在 destination 还没 ready\n// (fs.open 异步未完成)时会立刻回调 err=undefined 撒谎成功,但文件还是空的,所以\n// 这里直接走 sonic-boom 的 ready 事件 + flushSync 路径。\n// - 未实例化(lazy proxy 没被访问过) → no-op,不会触发文件 IO 副作用。\n// - silent / stdout-only(destination 为 null) → no-op。\n// - timeoutMs 是兜底,确保异常情况下不会卡住进程退出。\nexport async function flushLogger(logger: pino.Logger, timeoutMs = 200): Promise<void> {\n const meta = loggerMetaMap.get(logger);\n if (!meta || !meta.materialized) return;\n const dest = meta.destination;\n if (!dest) return;\n const operation = meta.flushOperation ?? startFlushOperation(meta, dest);\n await waitForFlushOperation(operation, resolveFlushTimeout(timeoutMs));\n}\n"],"mappings":";;;AAAA,SACE,WACA,UACA,WACA,cACA,aACA,YACA,UACA,aACA,YACA,qBACK;AACP,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AACxB,SAAS,UAAU,YAAY;AAC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AAI,IAAI;IACxD;GACD;AAED,gBAAc,IAAI,OAAO,IAAI;AAC7B,SAAO;AACT;AAQA,eAAsB,YAAY,QAAqB,YAAY,KAAG;AACpE,QAAM,OAAO,cAAc,IAAI,MAAM;AACrC,MAAI,CAAC,QAAQ,CAAC,KAAK;AAAc;AACjC,QAAM,OAAO,KAAK;AAClB,MAAI,CAAC;AAAM;AACX,QAAM,YAAY,KAAK,kBAAkB,oBAAoB,MAAM,IAAI;AACvE,QAAM,sBAAsB,WAAW,oBAAoB,SAAS,CAAC;AACvE;","names":["fileName"]}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/common/process-termination.ts
|
|
4
|
+
import { spawnSync } from "child_process";
|
|
5
|
+
function terminateOwnedProcessTree(child, signal = "SIGTERM") {
|
|
6
|
+
if (process.platform !== "win32") return child.kill(signal);
|
|
7
|
+
const pid = child.pid;
|
|
8
|
+
if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0 || child.exitCode !== null || child.signalCode !== null) {
|
|
9
|
+
return false;
|
|
10
|
+
}
|
|
11
|
+
const result = spawnSync("taskkill.exe", ["/PID", String(pid), "/T", "/F"], {
|
|
12
|
+
windowsHide: true,
|
|
13
|
+
timeout: 5e3,
|
|
14
|
+
stdio: "ignore"
|
|
15
|
+
});
|
|
16
|
+
return !result.error && result.status === 0;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export {
|
|
20
|
+
terminateOwnedProcessTree
|
|
21
|
+
};
|
|
22
|
+
//# sourceMappingURL=chunk-JZ7MWN24.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/common/process-termination.ts"],"sourcesContent":["import { spawnSync, type ChildProcess } from \"node:child_process\";\n\n/** Only for a directly owned command, never a daemon with independently retained sessions. */\nexport function terminateOwnedProcessTree(\n child: ChildProcess,\n signal: NodeJS.Signals = \"SIGTERM\",\n): boolean {\n if (process.platform !== \"win32\") return child.kill(signal);\n const pid = child.pid;\n if (\n typeof pid !== \"number\" ||\n !Number.isSafeInteger(pid) ||\n pid <= 0 ||\n child.exitCode !== null ||\n child.signalCode !== null\n ) {\n return false;\n }\n // Node's Windows SIGTERM/SIGKILL only terminate the root. Keep npm/Agent wrappers\n // and their descendants together without selecting unrelated processes by name.\n const result = spawnSync(\"taskkill.exe\", [\"/PID\", String(pid), \"/T\", \"/F\"], {\n windowsHide: true,\n timeout: 5_000,\n stdio: \"ignore\",\n });\n return !result.error && result.status === 0;\n}\n"],"mappings":";;;AAAA,SAAS,iBAAoC;AAGtC,SAAS,0BACd,OACA,SAAyB,WAChB;AACT,MAAI,QAAQ,aAAa,QAAS,QAAO,MAAM,KAAK,MAAM;AAC1D,QAAM,MAAM,MAAM;AAClB,MACE,OAAO,QAAQ,YACf,CAAC,OAAO,cAAc,GAAG,KACzB,OAAO,KACP,MAAM,aAAa,QACnB,MAAM,eAAe,MACrB;AACA,WAAO;AAAA,EACT;AAGA,QAAM,SAAS,UAAU,gBAAgB,CAAC,QAAQ,OAAO,GAAG,GAAG,MAAM,IAAI,GAAG;AAAA,IAC1E,aAAa;AAAA,IACb,SAAS;AAAA,IACT,OAAO;AAAA,EACT,CAAC;AACD,SAAO,CAAC,OAAO,SAAS,OAAO,WAAW;AAC5C;","names":[]}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/common/executable.ts
|
|
4
|
+
import { accessSync, constants, statSync } from "fs";
|
|
5
|
+
import { posix, win32 } from "path";
|
|
6
|
+
function environmentValue(env, name, platform = process.platform) {
|
|
7
|
+
if (platform !== "win32") return env[name];
|
|
8
|
+
const key = Object.keys(env).sort().find((key2) => key2.toLowerCase() === name.toLowerCase());
|
|
9
|
+
return key === void 0 ? void 0 : env[key];
|
|
10
|
+
}
|
|
11
|
+
function normalizeProcessEnvironment(env, platform = process.platform) {
|
|
12
|
+
if (platform !== "win32") return env;
|
|
13
|
+
const normalized = {};
|
|
14
|
+
const seen = /* @__PURE__ */ new Set();
|
|
15
|
+
for (const key of Object.keys(env).sort()) {
|
|
16
|
+
const lower = key.toLowerCase();
|
|
17
|
+
if (seen.has(lower)) continue;
|
|
18
|
+
seen.add(lower);
|
|
19
|
+
if (env[key] !== void 0) normalized[key] = env[key];
|
|
20
|
+
}
|
|
21
|
+
return normalized;
|
|
22
|
+
}
|
|
23
|
+
function isExecutableFile(path, platform = process.platform) {
|
|
24
|
+
try {
|
|
25
|
+
if (!statSync(path).isFile()) return false;
|
|
26
|
+
accessSync(path, platform === "win32" ? constants.F_OK : constants.X_OK);
|
|
27
|
+
return true;
|
|
28
|
+
} catch {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function findExecutableCandidates(name, env, options = {}) {
|
|
33
|
+
const platform = options.platform ?? process.platform;
|
|
34
|
+
const windows = platform === "win32";
|
|
35
|
+
const path = windows ? win32 : posix;
|
|
36
|
+
const probe = options.isExecutableFile ?? ((file) => isExecutableFile(file, platform));
|
|
37
|
+
const hasPath = windows ? /[\\/:]/.test(name) : name.includes("/");
|
|
38
|
+
const extensions = windows && !win32.extname(name) ? (environmentValue(env, "PATHEXT", platform) || ".COM;.EXE;.BAT;.CMD").split(";").map((ext) => ext.trim()).filter((ext) => /^\.[a-z0-9]+$/i.test(ext)) : [""];
|
|
39
|
+
const directories = hasPath ? [""] : (environmentValue(env, "PATH", platform) ?? "").split(windows ? ";" : ":").map((entry) => windows ? entry.replace(/^"(.*)"$/, "$1") : entry).filter(Boolean);
|
|
40
|
+
const seen = /* @__PURE__ */ new Set();
|
|
41
|
+
const candidates = [];
|
|
42
|
+
for (const directory of directories) {
|
|
43
|
+
const base = directory ? path.join(directory, name) : name;
|
|
44
|
+
for (const extension of extensions) {
|
|
45
|
+
const file = path.resolve(options.cwd ?? process.cwd(), `${base}${extension}`);
|
|
46
|
+
const key = windows ? file.toLowerCase() : file;
|
|
47
|
+
if (seen.has(key)) continue;
|
|
48
|
+
seen.add(key);
|
|
49
|
+
if (probe(file)) candidates.push(file);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return candidates;
|
|
53
|
+
}
|
|
54
|
+
function defaultShell(env = process.env, platform = process.platform) {
|
|
55
|
+
if (platform !== "win32") return env.SHELL || "/bin/sh";
|
|
56
|
+
return environmentValue(env, "ComSpec", platform) || win32.join(
|
|
57
|
+
environmentValue(env, "SystemRoot", platform) || "C:\\Windows",
|
|
58
|
+
"System32",
|
|
59
|
+
"cmd.exe"
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// src/common/command-launch.ts
|
|
64
|
+
import { spawn } from "child_process";
|
|
65
|
+
import { win32 as win322 } from "path";
|
|
66
|
+
import { fileURLToPath } from "url";
|
|
67
|
+
import escape from "cross-spawn/lib/util/escape.js";
|
|
68
|
+
function quoteWindowsArgument(value) {
|
|
69
|
+
if (value.includes("\0")) throw new TypeError("Command arguments cannot contain NUL");
|
|
70
|
+
let result = '"';
|
|
71
|
+
let backslashes = 0;
|
|
72
|
+
for (const char of value) {
|
|
73
|
+
if (char === "\\") {
|
|
74
|
+
backslashes += 1;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (char === '"') result += "\\".repeat(backslashes * 2 + 1);
|
|
78
|
+
else result += "\\".repeat(backslashes);
|
|
79
|
+
result += char;
|
|
80
|
+
backslashes = 0;
|
|
81
|
+
}
|
|
82
|
+
return `${result}${"\\".repeat(backslashes * 2)}"`;
|
|
83
|
+
}
|
|
84
|
+
function prepareCommandLaunch(command, args, env = process.env, platform = process.platform, cwd = process.cwd()) {
|
|
85
|
+
const environment = normalizeProcessEnvironment(env, platform);
|
|
86
|
+
if (platform !== "win32") return { command, args: [...args], env: environment };
|
|
87
|
+
const resolved = findExecutableCandidates(command, environment, { platform, cwd })[0] ?? command;
|
|
88
|
+
const batch = /\.(?:cmd|bat)$/i.test(resolved);
|
|
89
|
+
const cmd = /^cmd(?:\.exe)?$/i.test(win322.basename(resolved));
|
|
90
|
+
const directory = win322.resolve(cwd);
|
|
91
|
+
if ((batch || cmd) && /^\\\\(?![?.]\\)[^\\]+\\[^\\]+/.test(directory)) {
|
|
92
|
+
throw new Error(
|
|
93
|
+
"Windows CMD \u4E0D\u652F\u6301\u5C06\u7F51\u7EDC\u5171\u4EAB\u76EE\u5F55\u4F5C\u4E3A\u5DE5\u4F5C\u76EE\u5F55\uFF0C\u8BF7\u9009\u62E9\u672C\u5730\u76EE\u5F55\u6216\u5DF2\u6620\u5C04\u7684\u76D8\u7B26\u8DEF\u5F84\u3002"
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
if (!batch) {
|
|
97
|
+
return { command: resolved, args: [...args], env: environment };
|
|
98
|
+
}
|
|
99
|
+
if ([resolved, ...args].some((value) => /[\r\n\0]/.test(value))) {
|
|
100
|
+
throw new TypeError(
|
|
101
|
+
"Windows batch commands cannot accept line breaks or NUL in arguments; use a native executable"
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
const doubleEscape = /node_modules[\\/]\.bin[\\/][^\\/]+\.cmd$/i.test(resolved);
|
|
105
|
+
const line = [
|
|
106
|
+
escape.command(win322.normalize(resolved)),
|
|
107
|
+
...args.map((arg) => escape.argument(arg, doubleEscape))
|
|
108
|
+
].join(" ");
|
|
109
|
+
const shellArgs = ["/d", "/s", "/v:off", "/c", `"${line}"`];
|
|
110
|
+
return {
|
|
111
|
+
command: defaultShell(environment, platform),
|
|
112
|
+
args: shellArgs,
|
|
113
|
+
env: environment,
|
|
114
|
+
windowsVerbatimArguments: true,
|
|
115
|
+
ptyArgs: shellArgs.join(" ")
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
function spawnCommand(command, args, options = {}) {
|
|
119
|
+
if (options.shell) throw new TypeError("spawnCommand does not accept shell mode");
|
|
120
|
+
const cwd = typeof options.cwd === "object" ? fileURLToPath(options.cwd) : options.cwd;
|
|
121
|
+
const launch = prepareCommandLaunch(
|
|
122
|
+
command,
|
|
123
|
+
args,
|
|
124
|
+
options.env ?? process.env,
|
|
125
|
+
process.platform,
|
|
126
|
+
cwd
|
|
127
|
+
);
|
|
128
|
+
return spawn(launch.command, launch.args, {
|
|
129
|
+
...options,
|
|
130
|
+
env: launch.env,
|
|
131
|
+
...process.platform === "win32" ? { windowsHide: true } : {},
|
|
132
|
+
...launch.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export {
|
|
137
|
+
environmentValue,
|
|
138
|
+
normalizeProcessEnvironment,
|
|
139
|
+
findExecutableCandidates,
|
|
140
|
+
defaultShell,
|
|
141
|
+
quoteWindowsArgument,
|
|
142
|
+
prepareCommandLaunch,
|
|
143
|
+
spawnCommand
|
|
144
|
+
};
|
|
145
|
+
//# sourceMappingURL=chunk-KINQESTO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/common/executable.ts","../src/common/command-launch.ts"],"sourcesContent":["import { accessSync, constants, statSync } from \"node:fs\";\nimport { posix, win32 } from \"node:path\";\n\nexport interface ExecutableLookupOptions {\n platform?: NodeJS.Platform;\n cwd?: string;\n isExecutableFile?: (path: string) => boolean;\n}\n\n/** Matches Node's case-insensitive Windows environment lookup without duplicate PATH keys. */\nexport function environmentValue(\n env: NodeJS.ProcessEnv,\n name: string,\n platform: NodeJS.Platform = process.platform,\n): string | undefined {\n if (platform !== \"win32\") return env[name];\n const key = Object.keys(env)\n .sort()\n .find((key) => key.toLowerCase() === name.toLowerCase());\n return key === undefined ? undefined : env[key];\n}\n\nexport function normalizeProcessEnvironment(\n env: NodeJS.ProcessEnv,\n platform: NodeJS.Platform = process.platform,\n): NodeJS.ProcessEnv {\n if (platform !== \"win32\") return env;\n const normalized: NodeJS.ProcessEnv = {};\n const seen = new Set<string>();\n for (const key of Object.keys(env).sort()) {\n const lower = key.toLowerCase();\n if (seen.has(lower)) continue;\n seen.add(lower);\n if (env[key] !== undefined) normalized[key] = env[key];\n }\n return normalized;\n}\n\nexport function isExecutableFile(\n path: string,\n platform: NodeJS.Platform = process.platform,\n): boolean {\n try {\n if (!statSync(path).isFile()) return false;\n accessSync(path, platform === \"win32\" ? constants.F_OK : constants.X_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function findExecutableCandidates(\n name: string,\n env: NodeJS.ProcessEnv,\n options: ExecutableLookupOptions = {},\n): string[] {\n const platform = options.platform ?? process.platform;\n const windows = platform === \"win32\";\n const path = windows ? win32 : posix;\n const probe = options.isExecutableFile ?? ((file) => isExecutableFile(file, platform));\n const hasPath = windows ? /[\\\\/:]/.test(name) : name.includes(\"/\");\n const extensions =\n windows && !win32.extname(name)\n ? (environmentValue(env, \"PATHEXT\", platform) || \".COM;.EXE;.BAT;.CMD\")\n .split(\";\")\n .map((ext) => ext.trim())\n .filter((ext) => /^\\.[a-z0-9]+$/i.test(ext))\n : [\"\"];\n const directories = hasPath\n ? [\"\"]\n : (environmentValue(env, \"PATH\", platform) ?? \"\")\n .split(windows ? \";\" : \":\")\n .map((entry) => (windows ? entry.replace(/^\"(.*)\"$/, \"$1\") : entry))\n .filter(Boolean);\n const seen = new Set<string>();\n const candidates: string[] = [];\n for (const directory of directories) {\n const base = directory ? path.join(directory, name) : name;\n for (const extension of extensions) {\n const file = path.resolve(options.cwd ?? process.cwd(), `${base}${extension}`);\n const key = windows ? file.toLowerCase() : file;\n if (seen.has(key)) continue;\n seen.add(key);\n if (probe(file)) candidates.push(file);\n }\n }\n return candidates;\n}\n\nexport function defaultShell(\n env: NodeJS.ProcessEnv = process.env,\n platform: NodeJS.Platform = process.platform,\n): string {\n if (platform !== \"win32\") return env.SHELL || \"/bin/sh\";\n return (\n environmentValue(env, \"ComSpec\", platform) ||\n win32.join(\n environmentValue(env, \"SystemRoot\", platform) || \"C:\\\\Windows\",\n \"System32\",\n \"cmd.exe\",\n )\n );\n}\n","import { spawn, type ChildProcess, type SpawnOptions } from \"node:child_process\";\nimport { win32 } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport escape from \"cross-spawn/lib/util/escape.js\";\nimport {\n defaultShell,\n findExecutableCandidates,\n normalizeProcessEnvironment,\n} from \"./executable.js\";\n\nexport interface CommandLaunch {\n command: string;\n args: string[];\n env: NodeJS.ProcessEnv;\n windowsVerbatimArguments?: true;\n /** node-pty accepts an already escaped Windows command line as a string. */\n ptyArgs?: string;\n}\n\n/** Win32 argv quoting, not shell escaping. Use only with CreateProcess-style native execution. */\nexport function quoteWindowsArgument(value: string): string {\n if (value.includes(\"\\0\")) throw new TypeError(\"Command arguments cannot contain NUL\");\n let result = '\"';\n let backslashes = 0;\n for (const char of value) {\n if (char === \"\\\\\") {\n backslashes += 1;\n continue;\n }\n if (char === '\"') result += \"\\\\\".repeat(backslashes * 2 + 1);\n else result += \"\\\\\".repeat(backslashes);\n result += char;\n backslashes = 0;\n }\n return `${result}${\"\\\\\".repeat(backslashes * 2)}\"`;\n}\n\nexport function prepareCommandLaunch(\n command: string,\n args: readonly string[],\n env: NodeJS.ProcessEnv = process.env,\n platform: NodeJS.Platform = process.platform,\n cwd: string = process.cwd(),\n): CommandLaunch {\n const environment = normalizeProcessEnvironment(env, platform);\n if (platform !== \"win32\") return { command, args: [...args], env: environment };\n const resolved = findExecutableCandidates(command, environment, { platform, cwd })[0] ?? command;\n const batch = /\\.(?:cmd|bat)$/i.test(resolved);\n const cmd = /^cmd(?:\\.exe)?$/i.test(win32.basename(resolved));\n const directory = win32.resolve(cwd);\n if ((batch || cmd) && /^\\\\\\\\(?![?.]\\\\)[^\\\\]+\\\\[^\\\\]+/.test(directory)) {\n throw new Error(\n \"Windows CMD 不支持将网络共享目录作为工作目录,请选择本地目录或已映射的盘符路径。\",\n );\n }\n if (!batch) {\n return { command: resolved, args: [...args], env: environment };\n }\n if ([resolved, ...args].some((value) => /[\\r\\n\\0]/.test(value))) {\n throw new TypeError(\n \"Windows batch commands cannot accept line breaks or NUL in arguments; use a native executable\",\n );\n }\n\n // Share cross-spawn's CMD escaping between pipe-based processes and ConPTY. Pinning the\n // dependency keeps this internal utility's contract explicit; never enable spawn's shell mode.\n const doubleEscape = /node_modules[\\\\/]\\.bin[\\\\/][^\\\\/]+\\.cmd$/i.test(resolved);\n const line = [\n escape.command(win32.normalize(resolved)),\n ...args.map((arg) => escape.argument(arg, doubleEscape)),\n ].join(\" \");\n const shellArgs = [\"/d\", \"/s\", \"/v:off\", \"/c\", `\"${line}\"`];\n return {\n command: defaultShell(environment, platform),\n args: shellArgs,\n env: environment,\n windowsVerbatimArguments: true,\n ptyArgs: shellArgs.join(\" \"),\n };\n}\n\nexport function spawnCommand(\n command: string,\n args: readonly string[],\n options: SpawnOptions = {},\n): ChildProcess {\n if (options.shell) throw new TypeError(\"spawnCommand does not accept shell mode\");\n const cwd = typeof options.cwd === \"object\" ? fileURLToPath(options.cwd) : options.cwd;\n const launch = prepareCommandLaunch(\n command,\n args,\n options.env ?? process.env,\n process.platform,\n cwd,\n );\n return spawn(launch.command, launch.args, {\n ...options,\n env: launch.env,\n ...(process.platform === \"win32\" ? { windowsHide: true } : {}),\n ...(launch.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),\n });\n}\n"],"mappings":";;;AAAA,SAAS,YAAY,WAAW,gBAAgB;AAChD,SAAS,OAAO,aAAa;AAStB,SAAS,iBACd,KACA,MACA,WAA4B,QAAQ,UAChB;AACpB,MAAI,aAAa,QAAS,QAAO,IAAI,IAAI;AACzC,QAAM,MAAM,OAAO,KAAK,GAAG,EACxB,KAAK,EACL,KAAK,CAACA,SAAQA,KAAI,YAAY,MAAM,KAAK,YAAY,CAAC;AACzD,SAAO,QAAQ,SAAY,SAAY,IAAI,GAAG;AAChD;AAEO,SAAS,4BACd,KACA,WAA4B,QAAQ,UACjB;AACnB,MAAI,aAAa,QAAS,QAAO;AACjC,QAAM,aAAgC,CAAC;AACvC,QAAM,OAAO,oBAAI,IAAY;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c,QAAQ,GAAG,IAAI,QAAQ;AACnF,QAAM,SAAS;AAAA,IACb;AAAA,IACA;AAAA,IACA,QAAQ,OAAO,QAAQ;AAAA,IACvB,QAAQ;AAAA,IACR;AAAA,EACF;AACA,SAAO,MAAM,OAAO,SAAS,OAAO,MAAM;AAAA,IACxC,GAAG;AAAA,IACH,KAAK,OAAO;AAAA,IACZ,GAAI,QAAQ,aAAa,UAAU,EAAE,aAAa,KAAK,IAAI,CAAC;AAAA,IAC5D,GAAI,OAAO,2BAA2B,EAAE,0BAA0B,KAAK,IAAI,CAAC;AAAA,EAC9E,CAAC;AACH;","names":["key","win32","win32"]}
|
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
import {
|
|
3
3
|
CONFIG_PATH,
|
|
4
4
|
LOG_DIR
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-YK2XKOP4.js";
|
|
6
6
|
import {
|
|
7
7
|
createLogger
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-ICSO3ZIS.js";
|
|
9
9
|
|
|
10
10
|
// src/common/logger.ts
|
|
11
11
|
import { existsSync, readFileSync } from "fs";
|
|
@@ -91,4 +91,4 @@ export {
|
|
|
91
91
|
terminalLogger,
|
|
92
92
|
autoUpdateLogger
|
|
93
93
|
};
|
|
94
|
-
//# sourceMappingURL=chunk-
|
|
94
|
+
//# sourceMappingURL=chunk-KWODOJBK.js.map
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
atomicWriteFileSync
|
|
4
|
+
} from "./chunk-NQDJ6QAM.js";
|
|
5
|
+
import {
|
|
6
|
+
providerValues
|
|
7
|
+
} from "./chunk-V4HDLUAQ.js";
|
|
8
|
+
|
|
9
|
+
// src/cli-args.ts
|
|
10
|
+
function normalizeCliArgs(args) {
|
|
11
|
+
const normalized = [...args];
|
|
12
|
+
while (normalized[0] === "--") {
|
|
13
|
+
normalized.shift();
|
|
14
|
+
}
|
|
15
|
+
return normalized;
|
|
16
|
+
}
|
|
17
|
+
function stripProxyProfileArgs(args) {
|
|
18
|
+
const result = [];
|
|
19
|
+
for (let i = 0; i < args.length; i++) {
|
|
20
|
+
const arg = args[i];
|
|
21
|
+
if (arg === "claude" || arg === "codex" || arg === "kimi") {
|
|
22
|
+
result.push(...args.slice(i));
|
|
23
|
+
break;
|
|
24
|
+
}
|
|
25
|
+
if (arg === "--profile") {
|
|
26
|
+
i++;
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
if (arg.startsWith("--profile=")) {
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
result.push(arg);
|
|
33
|
+
}
|
|
34
|
+
return result;
|
|
35
|
+
}
|
|
36
|
+
function extractAgentInvocation(args) {
|
|
37
|
+
const [agent, ...providerArgs] = args;
|
|
38
|
+
if (agent !== "claude" && agent !== "codex" && agent !== "kimi") {
|
|
39
|
+
throw new Error(
|
|
40
|
+
'Missing Agent CLI. Use "dev-anywhere claude ...", "dev-anywhere codex ...", or "dev-anywhere kimi ...".'
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
return { provider: agent, args: providerArgs };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// src/common/session-runtime-ipc-version.ts
|
|
47
|
+
import { readFileSync } from "fs";
|
|
48
|
+
function isProtocolVersion(value) {
|
|
49
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
50
|
+
}
|
|
51
|
+
function readSessionRuntimeIpcVersions(path) {
|
|
52
|
+
try {
|
|
53
|
+
const value = JSON.parse(readFileSync(path, "utf-8"));
|
|
54
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return null;
|
|
55
|
+
const record = value;
|
|
56
|
+
if (Object.keys(record).some((key) => key !== "terminal" && key !== "worker")) return null;
|
|
57
|
+
if (!isProtocolVersion(record.terminal) || !isProtocolVersion(record.worker)) return null;
|
|
58
|
+
return { terminal: record.terminal, worker: record.worker };
|
|
59
|
+
} catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function sessionRuntimeIpcVersionMatches(actual, expected, kind) {
|
|
64
|
+
return actual?.[kind] === expected[kind];
|
|
65
|
+
}
|
|
66
|
+
function writeSessionRuntimeIpcVersions(path, versions) {
|
|
67
|
+
atomicWriteFileSync(path, `${JSON.stringify(versions)}
|
|
68
|
+
`, { ensureDir: true });
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// src/common/persisted-session.ts
|
|
72
|
+
import { z } from "zod";
|
|
73
|
+
var persistedSessionFields = {
|
|
74
|
+
id: z.string().min(1),
|
|
75
|
+
createdAt: z.number().finite().nonnegative(),
|
|
76
|
+
updatedAt: z.number().finite().nonnegative(),
|
|
77
|
+
name: z.string().optional(),
|
|
78
|
+
nameLocked: z.boolean().optional(),
|
|
79
|
+
cwd: z.string().min(1),
|
|
80
|
+
claudeSessionId: z.string().optional(),
|
|
81
|
+
historySessionId: z.string().optional(),
|
|
82
|
+
pid: z.number().int().positive().max(Number.MAX_SAFE_INTEGER)
|
|
83
|
+
};
|
|
84
|
+
var PersistedSessionRecordSchema = z.union([
|
|
85
|
+
z.object({
|
|
86
|
+
...persistedSessionFields,
|
|
87
|
+
kind: z.literal("agent"),
|
|
88
|
+
mode: z.literal("pty"),
|
|
89
|
+
provider: z.enum(providerValues),
|
|
90
|
+
ptyOwner: z.enum(["local-terminal", "proxy-hosted"])
|
|
91
|
+
}).strict(),
|
|
92
|
+
z.object({
|
|
93
|
+
...persistedSessionFields,
|
|
94
|
+
kind: z.literal("agent"),
|
|
95
|
+
mode: z.literal("json"),
|
|
96
|
+
provider: z.enum(providerValues)
|
|
97
|
+
}).strict(),
|
|
98
|
+
z.object({
|
|
99
|
+
...persistedSessionFields,
|
|
100
|
+
kind: z.literal("terminal"),
|
|
101
|
+
mode: z.literal("pty"),
|
|
102
|
+
provider: z.literal("claude"),
|
|
103
|
+
ptyOwner: z.literal("local-terminal")
|
|
104
|
+
}).strict()
|
|
105
|
+
]);
|
|
106
|
+
|
|
107
|
+
export {
|
|
108
|
+
normalizeCliArgs,
|
|
109
|
+
stripProxyProfileArgs,
|
|
110
|
+
extractAgentInvocation,
|
|
111
|
+
PersistedSessionRecordSchema,
|
|
112
|
+
readSessionRuntimeIpcVersions,
|
|
113
|
+
sessionRuntimeIpcVersionMatches,
|
|
114
|
+
writeSessionRuntimeIpcVersions
|
|
115
|
+
};
|
|
116
|
+
//# sourceMappingURL=chunk-MLE2OKCM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli-args.ts","../src/common/session-runtime-ipc-version.ts","../src/common/persisted-session.ts"],"sourcesContent":["import type { ProviderId } from \"./providers/index.js\";\n\nexport function normalizeCliArgs(args: string[]): string[] {\n const normalized = [...args];\n while (normalized[0] === \"--\") {\n normalized.shift();\n }\n return normalized;\n}\n\nexport function stripProxyProfileArgs(args: string[]): string[] {\n const result: string[] = [];\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg === \"claude\" || arg === \"codex\" || arg === \"kimi\") {\n result.push(...args.slice(i));\n break;\n }\n if (arg === \"--profile\") {\n i++;\n continue;\n }\n if (arg.startsWith(\"--profile=\")) {\n continue;\n }\n result.push(arg);\n }\n return result;\n}\n\nexport function extractAgentInvocation(args: string[]): { provider: ProviderId; args: string[] } {\n const [agent, ...providerArgs] = args;\n if (agent !== \"claude\" && agent !== \"codex\" && agent !== \"kimi\") {\n throw new Error(\n 'Missing Agent CLI. Use \"dev-anywhere claude ...\", \"dev-anywhere codex ...\", or \"dev-anywhere kimi ...\".',\n );\n }\n return { provider: agent, args: providerArgs };\n}\n","import { readFileSync } from \"node:fs\";\nimport { atomicWriteFileSync } from \"./atomic-write.js\";\n\nexport interface SessionRuntimeIpcVersions {\n terminal: number;\n worker: number;\n}\n\nfunction isProtocolVersion(value: unknown): value is number {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\n\nexport function readSessionRuntimeIpcVersions(path: string): SessionRuntimeIpcVersions | null {\n try {\n const value: unknown = JSON.parse(readFileSync(path, \"utf-8\"));\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return null;\n const record = value as {\n terminal?: unknown;\n worker?: unknown;\n };\n if (Object.keys(record).some((key) => key !== \"terminal\" && key !== \"worker\")) return null;\n if (!isProtocolVersion(record.terminal) || !isProtocolVersion(record.worker)) return null;\n return { terminal: record.terminal, worker: record.worker };\n } catch {\n return null;\n }\n}\n\nexport function sessionRuntimeIpcVersionMatches(\n actual: SessionRuntimeIpcVersions | null,\n expected: SessionRuntimeIpcVersions,\n kind: keyof SessionRuntimeIpcVersions,\n): boolean {\n return actual?.[kind] === expected[kind];\n}\n\nexport function writeSessionRuntimeIpcVersions(\n path: string,\n versions: SessionRuntimeIpcVersions,\n): void {\n atomicWriteFileSync(path, `${JSON.stringify(versions)}\\n`, { ensureDir: true });\n}\n","import { providerValues } from \"@dev-anywhere/shared\";\nimport { z } from \"zod\";\n\nconst persistedSessionFields = {\n id: z.string().min(1),\n createdAt: z.number().finite().nonnegative(),\n updatedAt: z.number().finite().nonnegative(),\n name: z.string().optional(),\n nameLocked: z.boolean().optional(),\n cwd: z.string().min(1),\n claudeSessionId: z.string().optional(),\n historySessionId: z.string().optional(),\n pid: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),\n};\n\nexport const PersistedSessionRecordSchema = z.union([\n z\n .object({\n ...persistedSessionFields,\n kind: z.literal(\"agent\"),\n mode: z.literal(\"pty\"),\n provider: z.enum(providerValues),\n ptyOwner: z.enum([\"local-terminal\", \"proxy-hosted\"]),\n })\n .strict(),\n z\n .object({\n ...persistedSessionFields,\n kind: z.literal(\"agent\"),\n mode: z.literal(\"json\"),\n provider: z.enum(providerValues),\n })\n .strict(),\n z\n .object({\n ...persistedSessionFields,\n kind: z.literal(\"terminal\"),\n mode: z.literal(\"pty\"),\n provider: z.literal(\"claude\"),\n ptyOwner: z.literal(\"local-terminal\"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N,GAAG;AAAA,IACH,MAAM,EAAE,QAAQ,OAAO;AAAA,IACvB,MAAM,EAAE,QAAQ,MAAM;AAAA,IACtB,UAAU,EAAE,KAAK,cAAc;AAAA,EACjC,CAAC,EACA,OAAO;AAAA,EACV,EACG,OAAO;AAAA,IACN,GAAG;AAAA,IACH,MAAM,EAAE,QAAQ,UAAU;AAAA,IAC1B,MAAM,EAAE,QAAQ,KAAK;AAAA,IACrB,UAAU,EAAE,QAAQ,QAAQ;AAAA,IAC5B,UAAU,EAAE,QAAQ,gBAAgB;AAAA,EACtC,CAAC,EACA,OAAO;AACZ,CAAC;","names":[]}
|
|
@@ -17,6 +17,7 @@ function spawnScript(script, args = [], options = {}) {
|
|
|
17
17
|
const runtimeArgs = IS_DEV ? ["--import", "tsx", scriptPath, ...args] : [scriptPath, ...args];
|
|
18
18
|
const child = spawn(process.execPath, runtimeArgs, {
|
|
19
19
|
detached: true,
|
|
20
|
+
...process.platform === "win32" ? { windowsHide: true } : {},
|
|
20
21
|
...rest,
|
|
21
22
|
stdio
|
|
22
23
|
});
|
|
@@ -56,6 +57,7 @@ function spawnScript(script, args = [], options = {}) {
|
|
|
56
57
|
|
|
57
58
|
export {
|
|
58
59
|
IS_DEV,
|
|
60
|
+
resolveTopLevelScript,
|
|
59
61
|
spawnScript
|
|
60
62
|
};
|
|
61
|
-
//# sourceMappingURL=chunk-
|
|
63
|
+
//# sourceMappingURL=chunk-PCF2R2TG.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/common/env.ts"],"sourcesContent":["import { spawn, type ChildProcess, type SpawnOptions } from \"node:child_process\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Logger } from \"pino\";\n\n// 运行环境判断。tsup 打包时通过 define 把 process.env.NODE_ENV 替换为 \"production\",\n// IS_DEV 随之静态折叠为 false,dev 分支被 dead-code elimination 删除。\n// node --import tsx 跑源码时 NODE_ENV 通常未设置,默认 \"development\",IS_DEV 为 true。\nexport const IS_DEV = (process.env.NODE_ENV ?? \"development\") !== \"production\";\n\ninterface SpawnScriptOptions extends Omit<SpawnOptions, \"detached\"> {\n // 默认 true。设为 false 时父进程退出会把子进程一并带走。\n unref?: boolean;\n // 传入后启用\"现场记录\":子进程 stderr 按行 pipe 进 logger.warn(stderr 原文语义模糊,\n // 可能只是 deprecation warning),非零退出和 spawn 失败进 logger.error(确定性失败)。\n // 需要自己精确控制 stderr 的调用方(例如 startDaemon 要按超时展示)不要在这里传 logger,\n // 改为显式 `stdio: [\"ignore\", \"ignore\", \"pipe\"]` 自行挂 handler。\n logger?: Logger;\n}\n\n/**\n * 顶层 entry(serve / session-worker)在 dev 下 `src/<name>.ts`、prod 下 `dist/<name>.js`。\n * env.ts 自身:dev 在 `src/common/env.ts`,prod 被 tsup 内联进 `dist/<chunk>.js`。\n * 因此从 env.ts 看,dev 走 `../<name>`、prod 走 `./<name>` 即可命中正确目录。\n *\n * 早期 API 让调用方在自己源文件里 `new URL(\"./serve\", import.meta.url)`,对顶层\n * caller(src/index.ts)巧合可用,但 src/terminal/、src/serve/ 这类嵌套 caller 在 src 下\n * 写 `../serve` 才对、tsup 把所有 chunk 拍平到 dist/ 根目录后又指错位置。把解析集中到\n * env.ts 这一处,调用方只传 entry 名,避免两层布局的相对路径陷阱。\n */\nexport function resolveTopLevelScript(name: string): URL {\n const baseDir = IS_DEV\n ? new URL(\"../\", import.meta.url) // src/common/env.ts → src/\n : new URL(\"./\", import.meta.url); // dist/<chunk>.js → dist/\n return new URL(name, baseDir);\n}\n\n/**\n * spawn 一个 Node 脚本作为后台 detached 子进程。\n *\n * 第一个参数支持两种形式:\n * - 顶层 entry 名(\"serve\" / \"session-worker\"):内部按 dev/prod 布局解析为\n * `src/<name>.ts` 或 `dist/<name>.js`。生产代码用这种形式。\n * - URL:fixture / 测试用,调用方自己用 `new URL(\"./xxx\", import.meta.url)` 构造。\n *\n * helper 根据 IS_DEV 自动补扩展名并选运行时:\n * dev: 执行 `node --import tsx <path>.ts`\n * prod: 执行 `node <path>.js`\n *\n * @example\n * spawnScript(\"serve\", [], { logger: terminalLogger });\n * spawnScript(\"session-worker\", [sessionId, sockPath], { logger });\n */\nexport function spawnScript(\n script: string | URL,\n args: readonly string[] = [],\n options: SpawnScriptOptions = {},\n): ChildProcess {\n const { unref = true, logger, ...rest } = options;\n // logger 传入时默认打开 stderr pipe;调用方显式传了 stdio 则尊重调用方。\n const stdio = rest.stdio ?? (logger ? [\"ignore\", \"ignore\", \"pipe\"] : \"ignore\");\n\n const scriptBaseUrl = typeof script === \"string\" ? resolveTopLevelScript(script) : script;\n const basePath = fileURLToPath(scriptBaseUrl);\n const scriptPath = `${basePath}${IS_DEV ? \".ts\" : \".js\"}`;\n const runtimeArgs = IS_DEV ? [\"--import\", \"tsx\", scriptPath, ...args] : [scriptPath, ...args];\n const child = spawn(process.execPath, runtimeArgs, {\n detached: true,\n ...rest,\n stdio,\n });\n\n if (logger) {\n if (child.stderr) {\n child.stderr.setEncoding(\"utf-8\");\n let buf = \"\";\n const emit = (line: string) => {\n const trimmed = line.trim();\n if (trimmed) logger.warn({ pid: child.pid, src: \"child-stderr\" }, trimmed);\n };\n child.stderr.on(\"data\", (chunk: string) => {\n buf += chunk;\n const lines = buf.split(\"\\n\");\n buf = lines.pop() ?? \"\";\n for (const line of lines) emit(line);\n });\n // 子进程结束时 buf 里可能还有不带 \\n 的残段(比如 stderr 最后一行无换行就退出),\n // 这里 flush 一次保证捕获 100% 行内容,不被\"没等到下一个 \\n\"吞掉。\n child.stderr.on(\"end\", () => {\n if (buf) {\n emit(buf);\n buf = \"\";\n }\n });\n }\n child.once(\"error\", (err) => {\n logger.error({ pid: child.pid, err: String(err) }, \"spawn failed\");\n });\n child.once(\"exit\", (code, signal) => {\n if (code !== 0 && code !== null) {\n logger.error({ pid: child.pid, code, signal }, \"child exited abnormally\");\n }\n });\n }\n\n if (unref) child.unref();\n return child;\n}\n"],"mappings":";;;AAAA,SAAS,aAAmD;AAC5D,SAAS,qBAAqB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ACR;AAAA,MACF,CAAC;AAAA,IACH;AACA,UAAM,KAAK,SAAS,CAAC,QAAQ;AAC3B,aAAO,MAAM,EAAE,KAAK,MAAM,KAAK,KAAK,OAAO,GAAG,EAAE,GAAG,cAAc;AAAA,IACnE,CAAC;AACD,UAAM,KAAK,QAAQ,CAAC,MAAM,WAAW;AACnC,UAAI,SAAS,KAAK,SAAS,MAAM;AAC/B,eAAO,MAAM,EAAE,KAAK,MAAM,KAAK,MAAM,OAAO,GAAG,yBAAyB;AAAA,MAC1E;AAAA,IACF,CAAC;AAAA,EACH;AAEA,MAAI,MAAO,OAAM,MAAM;AACvB,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/common/env.ts"],"sourcesContent":["import { spawn, type ChildProcess, type SpawnOptions } from \"node:child_process\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Logger } from \"pino\";\n\n// 运行环境判断。tsup 打包时通过 define 把 process.env.NODE_ENV 替换为 \"production\",\n// IS_DEV 随之静态折叠为 false,dev 分支被 dead-code elimination 删除。\n// node --import tsx 跑源码时 NODE_ENV 通常未设置,默认 \"development\",IS_DEV 为 true。\nexport const IS_DEV = (process.env.NODE_ENV ?? \"development\") !== \"production\";\n\ninterface SpawnScriptOptions extends Omit<SpawnOptions, \"detached\"> {\n // 默认 true。设为 false 时父进程退出会把子进程一并带走。\n unref?: boolean;\n // 传入后启用\"现场记录\":子进程 stderr 按行 pipe 进 logger.warn(stderr 原文语义模糊,\n // 可能只是 deprecation warning),非零退出和 spawn 失败进 logger.error(确定性失败)。\n // 需要自己精确控制 stderr 的调用方(例如 startDaemon 要按超时展示)不要在这里传 logger,\n // 改为显式 `stdio: [\"ignore\", \"ignore\", \"pipe\"]` 自行挂 handler。\n logger?: Logger;\n}\n\n/**\n * 顶层 entry(serve / session-worker)在 dev 下 `src/<name>.ts`、prod 下 `dist/<name>.js`。\n * env.ts 自身:dev 在 `src/common/env.ts`,prod 被 tsup 内联进 `dist/<chunk>.js`。\n * 因此从 env.ts 看,dev 走 `../<name>`、prod 走 `./<name>` 即可命中正确目录。\n *\n * 早期 API 让调用方在自己源文件里 `new URL(\"./serve\", import.meta.url)`,对顶层\n * caller(src/index.ts)巧合可用,但 src/terminal/、src/serve/ 这类嵌套 caller 在 src 下\n * 写 `../serve` 才对、tsup 把所有 chunk 拍平到 dist/ 根目录后又指错位置。把解析集中到\n * env.ts 这一处,调用方只传 entry 名,避免两层布局的相对路径陷阱。\n */\nexport function resolveTopLevelScript(name: string): URL {\n const baseDir = IS_DEV\n ? new URL(\"../\", import.meta.url) // src/common/env.ts → src/\n : new URL(\"./\", import.meta.url); // dist/<chunk>.js → dist/\n return new URL(name, baseDir);\n}\n\n/**\n * spawn 一个 Node 脚本作为后台 detached 子进程。\n *\n * 第一个参数支持两种形式:\n * - 顶层 entry 名(\"serve\" / \"session-worker\"):内部按 dev/prod 布局解析为\n * `src/<name>.ts` 或 `dist/<name>.js`。生产代码用这种形式。\n * - URL:fixture / 测试用,调用方自己用 `new URL(\"./xxx\", import.meta.url)` 构造。\n *\n * helper 根据 IS_DEV 自动补扩展名并选运行时:\n * dev: 执行 `node --import tsx <path>.ts`\n * prod: 执行 `node <path>.js`\n *\n * @example\n * spawnScript(\"serve\", [], { logger: terminalLogger });\n * spawnScript(\"session-worker\", [sessionId, sockPath], { logger });\n */\nexport function spawnScript(\n script: string | URL,\n args: readonly string[] = [],\n options: SpawnScriptOptions = {},\n): ChildProcess {\n const { unref = true, logger, ...rest } = options;\n // logger 传入时默认打开 stderr pipe;调用方显式传了 stdio 则尊重调用方。\n const stdio = rest.stdio ?? (logger ? [\"ignore\", \"ignore\", \"pipe\"] : \"ignore\");\n\n const scriptBaseUrl = typeof script === \"string\" ? resolveTopLevelScript(script) : script;\n const basePath = fileURLToPath(scriptBaseUrl);\n const scriptPath = `${basePath}${IS_DEV ? \".ts\" : \".js\"}`;\n const runtimeArgs = IS_DEV ? [\"--import\", \"tsx\", scriptPath, ...args] : [scriptPath, ...args];\n const child = spawn(process.execPath, runtimeArgs, {\n detached: true,\n ...(process.platform === \"win32\" ? { windowsHide: true } : {}),\n ...rest,\n stdio,\n });\n\n if (logger) {\n if (child.stderr) {\n child.stderr.setEncoding(\"utf-8\");\n let buf = \"\";\n const emit = (line: string) => {\n const trimmed = line.trim();\n if (trimmed) logger.warn({ pid: child.pid, src: \"child-stderr\" }, trimmed);\n };\n child.stderr.on(\"data\", (chunk: string) => {\n buf += chunk;\n const lines = buf.split(\"\\n\");\n buf = lines.pop() ?? \"\";\n for (const line of lines) emit(line);\n });\n // 子进程结束时 buf 里可能还有不带 \\n 的残段(比如 stderr 最后一行无换行就退出),\n // 这里 flush 一次保证捕获 100% 行内容,不被\"没等到下一个 \\n\"吞掉。\n child.stderr.on(\"end\", () => {\n if (buf) {\n emit(buf);\n buf = \"\";\n }\n });\n }\n child.once(\"error\", (err) => {\n logger.error({ pid: child.pid, err: String(err) }, \"spawn failed\");\n });\n child.once(\"exit\", (code, signal) => {\n if (code !== 0 && code !== null) {\n logger.error({ pid: child.pid, code, signal }, \"child exited abnormally\");\n }\n });\n }\n\n if (unref) child.unref();\n return child;\n}\n"],"mappings":";;;AAAA,SAAS,aAAmD;AAC5D,SAAS,qBAAqB;AAMvB,IAAM,SAAU;AAsBhB,SAAS,sBAAsB,MAAmB;AACvD,QAAM,UAAU,SACZ,IAAI,IAAI,OAAO,YAAY,GAAG,IAC9B,IAAI,IAAI,MAAM,YAAY,GAAG;AACjC,SAAO,IAAI,IAAI,MAAM,OAAO;AAC9B;AAkBO,SAAS,YACd,QACA,OAA0B,CAAC,GAC3B,UAA8B,CAAC,GACjB;AACd,QAAM,EAAE,QAAQ,MAAM,QAAQ,GAAG,KAAK,IAAI;AAE1C,QAAM,QAAQ,KAAK,UAAU,SAAS,CAAC,UAAU,UAAU,MAAM,IAAI;AAErE,QAAM,gBAAgB,OAAO,WAAW,WAAW,sBAAsB,MAAM,IAAI;AACnF,QAAM,WAAW,cAAc,aAAa;AAC5C,QAAM,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]}
|
|
@@ -431,7 +431,7 @@ var ProxyUpgradeBootstrapResponseSchema = z9.object({
|
|
|
431
431
|
bootstrapVersion: z9.literal(PROXY_UPGRADE_BOOTSTRAP_VERSION),
|
|
432
432
|
relayVersion: StableVersionSchema,
|
|
433
433
|
controlProtocolVersion: z9.number().int().positive()
|
|
434
|
-
})
|
|
434
|
+
});
|
|
435
435
|
|
|
436
436
|
// ../../packages/shared/dist/schemas/web-preview.js
|
|
437
437
|
import { z as z10 } from "zod";
|
|
@@ -2133,6 +2133,27 @@ var RelayCloseCode = {
|
|
|
2133
2133
|
DEVICE_STREAM_BINDING_REJECTED: 4404,
|
|
2134
2134
|
PROXY_PROTOCOL_REJECTED: 4405
|
|
2135
2135
|
};
|
|
2136
|
+
var ProxyProtocolAdmissionDirection = {
|
|
2137
|
+
COMPATIBLE: "compatible",
|
|
2138
|
+
PROXY_OUTDATED: "proxy_outdated",
|
|
2139
|
+
RELAY_OUTDATED: "relay_outdated",
|
|
2140
|
+
PROTOCOL_MISMATCH: "protocol_mismatch"
|
|
2141
|
+
};
|
|
2142
|
+
function isPositiveSafeProtocolVersion(value) {
|
|
2143
|
+
return Number.isSafeInteger(value) && value > 0;
|
|
2144
|
+
}
|
|
2145
|
+
function compareProxyRelayProtocolVersions(proxyProtocolVersion, relayProtocolVersion) {
|
|
2146
|
+
if (!isPositiveSafeProtocolVersion(proxyProtocolVersion) || !isPositiveSafeProtocolVersion(relayProtocolVersion)) {
|
|
2147
|
+
return ProxyProtocolAdmissionDirection.PROTOCOL_MISMATCH;
|
|
2148
|
+
}
|
|
2149
|
+
if (proxyProtocolVersion === relayProtocolVersion) {
|
|
2150
|
+
return ProxyProtocolAdmissionDirection.COMPATIBLE;
|
|
2151
|
+
}
|
|
2152
|
+
return proxyProtocolVersion < relayProtocolVersion ? ProxyProtocolAdmissionDirection.PROXY_OUTDATED : ProxyProtocolAdmissionDirection.RELAY_OUTDATED;
|
|
2153
|
+
}
|
|
2154
|
+
function isProxyProtocolRejectDirection(value) {
|
|
2155
|
+
return value === ProxyProtocolAdmissionDirection.PROXY_OUTDATED || value === ProxyProtocolAdmissionDirection.RELAY_OUTDATED || value === ProxyProtocolAdmissionDirection.PROTOCOL_MISMATCH;
|
|
2156
|
+
}
|
|
2136
2157
|
|
|
2137
2158
|
// ../../packages/shared/dist/constants/wire-limits.js
|
|
2138
2159
|
var RELAY_JSON_MESSAGE_MAX_BYTES = 8 * 1024 * 1024;
|
|
@@ -2343,7 +2364,7 @@ var LineBuffer = class extends Transform {
|
|
|
2343
2364
|
// src/ipc/ipc-protocol.ts
|
|
2344
2365
|
var IPC_BINARY_MARKER = 0;
|
|
2345
2366
|
var WORKER_IPC_PROTOCOL_VERSION = 1;
|
|
2346
|
-
var TERMINAL_IPC_PROTOCOL_VERSION =
|
|
2367
|
+
var TERMINAL_IPC_PROTOCOL_VERSION = 2;
|
|
2347
2368
|
function encodeBinaryIpcFrame(sessionId, data, outputSeq) {
|
|
2348
2369
|
const inner = encodeBinaryFrame(sessionId, outputSeq, data);
|
|
2349
2370
|
const frame = Buffer.alloc(1 + 4 + inner.length);
|
|
@@ -2352,7 +2373,6 @@ function encodeBinaryIpcFrame(sessionId, data, outputSeq) {
|
|
|
2352
2373
|
frame.set(inner, 5);
|
|
2353
2374
|
return frame;
|
|
2354
2375
|
}
|
|
2355
|
-
var sessionStateValues2 = Object.values(SessionState);
|
|
2356
2376
|
var ProviderHookContextSchema = z14.object({
|
|
2357
2377
|
provider: z14.enum(["claude", "codex"]),
|
|
2358
2378
|
sessionId: z14.string(),
|
|
@@ -2437,44 +2457,6 @@ var IpcMessageSchema = z14.discriminatedUnion("type", [
|
|
|
2437
2457
|
message: z14.string(),
|
|
2438
2458
|
code: z14.string().optional()
|
|
2439
2459
|
}),
|
|
2440
|
-
// 客户端请求服务状态(含 relay 连接信息和 worker 状态)
|
|
2441
|
-
z14.object({
|
|
2442
|
-
type: z14.literal("service_status_request"),
|
|
2443
|
-
protocolVersion: z14.literal(TERMINAL_IPC_PROTOCOL_VERSION)
|
|
2444
|
-
}).strict(),
|
|
2445
|
-
// 服务端响应增强版服务状态
|
|
2446
|
-
z14.object({
|
|
2447
|
-
type: z14.literal("service_status_response"),
|
|
2448
|
-
protocolVersion: z14.literal(TERMINAL_IPC_PROTOCOL_VERSION),
|
|
2449
|
-
config: z14.object({
|
|
2450
|
-
profile: z14.string().optional(),
|
|
2451
|
-
version: z14.string(),
|
|
2452
|
-
autoUpdate: z14.boolean(),
|
|
2453
|
-
relayName: z14.string(),
|
|
2454
|
-
relayNameSource: z14.enum(["cli", "profile", "env"]),
|
|
2455
|
-
relayUrl: z14.string().optional(),
|
|
2456
|
-
relayUrlSource: z14.enum(["env", "file", "none"]),
|
|
2457
|
-
relayTokenSource: z14.enum(["env", "file", "none"]),
|
|
2458
|
-
hookPort: z14.number(),
|
|
2459
|
-
hookPortSource: z14.enum(["env", "file", "default"])
|
|
2460
|
-
}),
|
|
2461
|
-
relay: z14.object({
|
|
2462
|
-
connected: z14.boolean(),
|
|
2463
|
-
proxyId: z14.string(),
|
|
2464
|
-
reconnectAttempt: z14.number(),
|
|
2465
|
-
queueDepth: z14.number()
|
|
2466
|
-
}).nullable(),
|
|
2467
|
-
sessions: z14.array(
|
|
2468
|
-
z14.object({
|
|
2469
|
-
id: z14.string(),
|
|
2470
|
-
mode: z14.enum(["pty", "json"]),
|
|
2471
|
-
state: z14.enum(sessionStateValues2),
|
|
2472
|
-
createdAt: z14.string(),
|
|
2473
|
-
name: z14.string().optional(),
|
|
2474
|
-
hasWorker: z14.boolean()
|
|
2475
|
-
})
|
|
2476
|
-
)
|
|
2477
|
-
}).strict(),
|
|
2478
2460
|
// terminal → serve:终端标题变化,由 xterm onTitleChange 触发
|
|
2479
2461
|
z14.object({
|
|
2480
2462
|
type: z14.literal("pty_title_change"),
|
|
@@ -2735,6 +2717,9 @@ export {
|
|
|
2735
2717
|
SessionState,
|
|
2736
2718
|
SESSION_CREATE_SERVER_DEADLINE_MS,
|
|
2737
2719
|
RelayCloseCode,
|
|
2720
|
+
ProxyProtocolAdmissionDirection,
|
|
2721
|
+
compareProxyRelayProtocolVersions,
|
|
2722
|
+
isProxyProtocolRejectDirection,
|
|
2738
2723
|
RELAY_JSON_MESSAGE_MAX_BYTES,
|
|
2739
2724
|
encodeBinaryFrame,
|
|
2740
2725
|
encodeFileStreamFrame,
|
|
@@ -2753,4 +2738,4 @@ export {
|
|
|
2753
2738
|
serializeIpc,
|
|
2754
2739
|
createIpcReader
|
|
2755
2740
|
};
|
|
2756
|
-
//# sourceMappingURL=chunk-
|
|
2741
|
+
//# sourceMappingURL=chunk-V4HDLUAQ.js.map
|