@oseo/host 0.0.0-stage → 0.1.0-canary.370
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/LICENSE +674 -0
- package/README.md +76 -2
- package/dist/cache-files.d.ts +35 -0
- package/dist/cache-files.d.ts.map +1 -0
- package/dist/cache-files.js +50 -0
- package/dist/cache-files.js.map +1 -0
- package/dist/executable-publication.d.ts +35 -0
- package/dist/executable-publication.d.ts.map +1 -0
- package/dist/executable-publication.js +133 -0
- package/dist/executable-publication.js.map +1 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +850 -0
- package/dist/index.js.map +1 -0
- package/dist/spawn-delegate.d.ts +35 -0
- package/dist/spawn-delegate.d.ts.map +1 -0
- package/dist/spawn-delegate.js +165 -0
- package/dist/spawn-delegate.js.map +1 -0
- package/dist/spawn-helper.d.ts +1 -0
- package/dist/spawn-helper.js +80 -0
- package/dist/spawn-helper.js.map +1 -0
- package/dist/spawn-protocol.d.ts +47 -0
- package/dist/spawn-protocol.d.ts.map +1 -0
- package/dist/spawn-protocol.js +57 -0
- package/dist/spawn-protocol.js.map +1 -0
- package/package.json +35 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/*\n * Oseo, an ahead-of-time compiler for JavaScript and TypeScript.\n * Copyright (C) 2026 Hong Minhee <https://hongminhee.org/>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <https://www.gnu.org/licenses/>.\n */\n\nimport { builtinModuleExports, isBuiltinModuleSpecifier } from \"@oseo/compiler\";\n\nimport type {\n CompilerCache,\n CompilerCacheLock,\n CompilerHost,\n Diagnostic,\n ExecutionHostDescription,\n FileFingerprint,\n ModuleLoader,\n ModuleResolver,\n ProcessObservation,\n ProcessRequest,\n SyntaxModuleSpecifier,\n} from \"@oseo/compiler\";\n\nimport {\n overwriteExistingDenoTextFile,\n overwriteExistingNodeTextFile,\n renameClaimedCacheLockDirectory,\n} from \"./cache-files.ts\";\n\nimport {\n isClosedInputError,\n validateProcessStreams,\n} from \"./spawn-protocol.ts\";\n\nfunction includePropertiesWhen<const Properties extends object>(\n properties: () => Properties | undefined,\n): Properties | { [Key in keyof Properties]?: never } {\n return properties() ?? {};\n}\n\n/** Text requests encode once; byte requests retain their original bytes. */\nfunction isTextProcessInput(value: string | Uint8Array): value is string {\n return typeof value === \"string\";\n}\n\n/** Normalize Node.js or Deno platform facts at the concrete host boundary. */\nexport function normalizeExecutionHost(\n reportedOperatingSystem: string,\n reportedArchitecture: string,\n): ExecutionHostDescription {\n return {\n architecture:\n reportedArchitecture === \"arm64\" || reportedArchitecture === \"aarch64\"\n ? \"aarch64\"\n : reportedArchitecture === \"amd64\" ||\n reportedArchitecture === \"x64\" ||\n reportedArchitecture === \"x86_64\"\n ? \"x86_64\"\n : \"unknown\",\n operatingSystem:\n reportedOperatingSystem === \"darwin\"\n ? \"macos\"\n : reportedOperatingSystem === \"linux\"\n ? \"linux\"\n : \"unknown\",\n };\n}\n\ninterface DenoCommandOutput {\n readonly code: number;\n readonly stderr: Uint8Array;\n readonly stdout: Uint8Array;\n}\n\ninterface DenoCommandChild {\n readonly output: () => Promise<DenoCommandOutput>;\n readonly stdin: WritableStream<Uint8Array>;\n}\n\ninterface DenoCommandInstance {\n output(): Promise<DenoCommandOutput>;\n spawn(): DenoCommandChild;\n}\n\ninterface DenoCommandOptions {\n readonly args: readonly string[];\n readonly clearEnv?: boolean;\n readonly cwd: string;\n readonly env?: Readonly<Record<string, string>>;\n readonly stderr: \"piped\" | \"inherit\";\n readonly stdin?: \"piped\" | \"inherit\" | \"null\";\n readonly stdout: \"piped\" | \"inherit\";\n}\n\ninterface DenoCommandConstructor {\n new (command: string, options: DenoCommandOptions): DenoCommandInstance;\n}\n\ninterface DenoRuntime {\n readonly Command: DenoCommandConstructor;\n readonly build?: {\n readonly arch: string;\n readonly os: string;\n };\n cwd(): string;\n readonly env: {\n get(name: string): string | undefined;\n };\n copyFile(fromPath: string, toPath: string): Promise<void>;\n makeTempFile(options: {\n readonly dir: string;\n readonly prefix: string;\n }): Promise<string>;\n makeTempDir(options: { readonly prefix: string }): Promise<string>;\n mkdir(path: string, options: { readonly recursive: boolean }): Promise<void>;\n readDir(path: string): AsyncIterable<{\n readonly isFile: boolean;\n readonly name: string;\n }>;\n readTextFile(path: string | URL): Promise<string>;\n remove(\n path: string,\n options?: { readonly recursive: boolean },\n ): Promise<void>;\n rename(oldPath: string, newPath: string): Promise<void>;\n realPath(path: string): Promise<string>;\n stat(path: string): Promise<{\n readonly ctime?: Date | null;\n readonly dev?: number | null;\n readonly ino?: number | null;\n readonly isFile: boolean;\n readonly mtime?: Date | null;\n readonly size: number;\n }>;\n writeTextFile(\n path: string,\n contents: string,\n options?: {\n readonly create?: boolean;\n readonly createNew?: boolean;\n },\n ): Promise<void>;\n}\n\nfunction isDenoRuntime<T>(value: T): value is T & DenoRuntime {\n return (\n value instanceof Object &&\n \"Command\" in value &&\n typeof value.Command === \"function\" &&\n \"cwd\" in value &&\n typeof value.cwd === \"function\" &&\n \"readTextFile\" in value &&\n typeof value.readTextFile === \"function\" &&\n \"stat\" in value &&\n typeof value.stat === \"function\"\n );\n}\n\nfunction denoRuntime(): DenoRuntime {\n const runtime = Object.getOwnPropertyDescriptor(globalThis, \"Deno\")?.value;\n if (!isDenoRuntime(runtime)) throw new Error(\"Deno host is unavailable.\");\n return runtime;\n}\n\nfunction remoteUrl(path: string | URL): URL | undefined {\n let url: URL;\n try {\n url = path instanceof URL ? path : new URL(path);\n } catch {\n return undefined;\n }\n return url.protocol === \"http:\" || url.protocol === \"https:\"\n ? url\n : undefined;\n}\n\nfunction requireCacheName(name: string): void {\n if (name === \".\" || name === \"..\" || !/^[A-Za-z0-9._-]+$/u.test(name)) {\n throw new Error(`Invalid compiler cache name '${name}'.`);\n }\n}\n\nfunction isNotFound(cause: unknown): boolean {\n return (\n cause instanceof Error &&\n (cause.name === \"NotFound\" || (\"code\" in cause && cause.code === \"ENOENT\"))\n );\n}\n\nfunction isAlreadyExists(cause: unknown): boolean {\n return (\n cause instanceof Error &&\n (cause.name === \"AlreadyExists\" ||\n (\"code\" in cause && cause.code === \"EEXIST\"))\n );\n}\n\nfunction isEnvironmentPermissionDenied(cause: unknown): boolean {\n return (\n cause instanceof Error &&\n (cause.name === \"NotCapable\" || cause.name === \"PermissionDenied\")\n );\n}\n\nfunction wait(milliseconds: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, milliseconds));\n}\n\n/**\n * Select the exact inherited environment declared by a process request.\n * Keeping this operation in the host adapter avoids exposing runtime-specific\n * environment APIs to toolchain packages.\n */\nfunction selectEnvironment(\n names: readonly string[],\n read: (name: string) => string | undefined,\n) {\n const selected: Record<string, string> = {};\n for (const name of names) {\n const value = read(name);\n if (value != null) selected[name] = value;\n }\n return selected;\n}\n\ninterface CacheLockOwner {\n readonly expiresAtMilliseconds: number;\n readonly token: string;\n}\n\ninterface CacheLockObservation {\n readonly owner?: CacheLockOwner | undefined;\n readonly ownerPath?: string | undefined;\n}\n\nfunction isCacheLockOwner(\n value: Partial<CacheLockOwner>,\n): value is CacheLockOwner {\n return (\n typeof value.token === \"string\" &&\n /^[A-Za-z0-9-]+$/u.test(value.token) &&\n typeof value.expiresAtMilliseconds === \"number\" &&\n Number.isFinite(value.expiresAtMilliseconds)\n );\n}\n\nfunction parseCacheLockOwner(contents: string): CacheLockOwner | undefined {\n try {\n // SAFETY: The optional fields are validated before this value is returned.\n const value = JSON.parse(contents) as Partial<CacheLockOwner>;\n return isCacheLockOwner(value)\n ? {\n expiresAtMilliseconds: value.expiresAtMilliseconds,\n token: value.token,\n }\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function readCacheLockOwner(\n readOwner: () => Promise<string>,\n): Promise<CacheLockOwner | undefined> {\n try {\n return parseCacheLockOwner(await readOwner());\n } catch (error) {\n if (isNotFound(error)) return undefined;\n throw error;\n }\n}\n\nconst cacheLockPollMilliseconds = 25;\nconst cacheLockLifetimeMilliseconds = 30_000;\nconst cacheLockRenewMilliseconds = 1_000;\nconst cacheLockRenameSafetyMilliseconds = 1_000;\n\nfunction cacheLockOwnerName(token: string): string {\n return `owner-${token}.json`;\n}\n\nfunction cacheLockOperationPath(\n lockPath: string,\n operation: \"reclaim\" | \"release\" | \"renew\",\n token: string,\n expiresAt = Date.now() + cacheLockLifetimeMilliseconds,\n): string {\n return (\n `${lockPath}/${operation}-${expiresAt}-${token}-` +\n `${crypto.randomUUID()}.json`\n );\n}\n\nfunction cacheLockOperationExpiration(name: string): number | undefined {\n const match = /^(?:reclaim|release|renew)-(\\d+)-/u.exec(name);\n if (match == null) return undefined;\n const expiresAt = Number(match[1]);\n return Number.isFinite(expiresAt) ? expiresAt : undefined;\n}\n\nfunction isCacheLockStateName(name: string): boolean {\n return (\n (name.startsWith(\"owner-\") ||\n name.startsWith(\"reclaim-\") ||\n name.startsWith(\"release-\") ||\n name.startsWith(\"renew-\")) &&\n name.endsWith(\".json\")\n );\n}\n\nfunction createRenewingCacheLock(\n renew: () => Promise<boolean>,\n release: () => Promise<void>,\n): CompilerCacheLock {\n let released = false;\n let renewal = Promise.resolve();\n let timer: ReturnType<typeof setTimeout> | undefined;\n function schedule(): void {\n timer = setTimeout(() => {\n renewal = renew()\n .then((owned) => {\n if (owned && !released) schedule();\n })\n .catch(() => {\n if (!released) schedule();\n });\n }, cacheLockRenewMilliseconds);\n // SAFETY: Runtime timers may expose unref; its presence is checked below.\n const unref = (\n timer as ReturnType<typeof setTimeout> & {\n readonly unref?: () => void;\n }\n ).unref;\n unref?.call(timer);\n }\n schedule();\n return {\n async release() {\n if (released) return;\n released = true;\n if (timer != null) clearTimeout(timer);\n await renewal.catch(() => undefined);\n await release();\n },\n };\n}\n\nfunction createNodeCache(): CompilerCache {\n return {\n async acquireFileLock(path): Promise<CompilerCacheLock> {\n const { mkdir, readFile, readdir, rename, rm, writeFile } =\n await import(\"node:fs/promises\");\n const lockPath = `${path}.lock`;\n const invalidOwnerExpiresAt = Date.now() + cacheLockLifetimeMilliseconds;\n async function observeOwner(): Promise<CacheLockObservation> {\n let names: readonly string[];\n try {\n names = await readdir(lockPath);\n } catch (error) {\n if (isNotFound(error)) return {};\n throw error;\n }\n const ownerName = names.find(isCacheLockStateName);\n if (ownerName == null) return {};\n const ownerPath = `${lockPath}/${ownerName}`;\n const owner = await readCacheLockOwner(\n async () => await readFile(ownerPath, \"utf8\"),\n );\n const operationExpiration = cacheLockOperationExpiration(ownerName);\n return {\n owner:\n operationExpiration == null\n ? owner\n : {\n expiresAtMilliseconds: Math.max(\n owner?.expiresAtMilliseconds ?? 0,\n operationExpiration,\n ),\n token: owner?.token ?? \"operation\",\n },\n ownerPath,\n };\n }\n async function disposeLockDirectory(statePath: string): Promise<void> {\n const disposalExpiresAt = Date.now() + cacheLockLifetimeMilliseconds;\n const disposalStatePath = cacheLockOperationPath(\n lockPath,\n \"reclaim\",\n \"disposal\",\n disposalExpiresAt,\n );\n try {\n await rename(statePath, disposalStatePath);\n } catch (error) {\n if (isNotFound(error)) return;\n throw error;\n }\n const disposalPath = `${lockPath}.dispose-${crypto.randomUUID()}`;\n try {\n await renameClaimedCacheLockDirectory(\n rename,\n lockPath,\n disposalPath,\n {\n deadlineMilliseconds:\n disposalExpiresAt - cacheLockRenameSafetyMilliseconds,\n retryPermissionErrors: process.platform === \"win32\",\n },\n );\n } catch (error) {\n if (isNotFound(error)) return;\n throw error;\n }\n await rm(disposalPath, { force: true, recursive: true });\n }\n async function claimEmptyLock(): Promise<void> {\n const token = crypto.randomUUID();\n const ownerName = \"owner-empty-reclaimer.json\";\n const ownerPath = `${lockPath}/${ownerName}`;\n try {\n await writeFile(\n ownerPath,\n JSON.stringify({\n expiresAtMilliseconds: Date.now() + cacheLockLifetimeMilliseconds,\n token,\n }),\n { flag: \"wx\" },\n );\n } catch (error) {\n if (isAlreadyExists(error) || isNotFound(error)) return;\n throw error;\n }\n const names = await readdir(lockPath);\n if (names.some((name) => name !== ownerName)) {\n await rm(ownerPath, { force: true });\n return;\n }\n await disposeLockDirectory(ownerPath);\n }\n /* eslint-disable no-await-in-loop -- Lease steps are ordered. */\n while (true) {\n try {\n await mkdir(lockPath);\n const owner = {\n expiresAtMilliseconds: Date.now() + cacheLockLifetimeMilliseconds,\n token: crypto.randomUUID(),\n };\n const ownerPath = `${lockPath}/${cacheLockOwnerName(owner.token)}`;\n try {\n await writeFile(ownerPath, JSON.stringify(owner));\n } catch (error) {\n await rm(ownerPath, { force: true });\n if (isNotFound(error)) continue;\n throw error;\n }\n const names = await readdir(lockPath);\n if (\n names.some(\n (name) =>\n isCacheLockStateName(name) &&\n name !== cacheLockOwnerName(owner.token),\n )\n ) {\n await rm(ownerPath, { force: true });\n continue;\n }\n return createRenewingCacheLock(\n async () => {\n const renewalPath = cacheLockOperationPath(\n lockPath,\n \"renew\",\n owner.token,\n );\n try {\n await rename(ownerPath, renewalPath);\n } catch (error) {\n if (isNotFound(error)) return false;\n throw error;\n }\n try {\n await overwriteExistingNodeTextFile(\n renewalPath,\n JSON.stringify({\n expiresAtMilliseconds:\n Date.now() + cacheLockLifetimeMilliseconds,\n token: owner.token,\n }),\n );\n await rename(renewalPath, ownerPath);\n return true;\n } catch (error) {\n try {\n await rename(renewalPath, ownerPath);\n } catch {\n // The state was claimed by a concurrent reclaimer.\n }\n throw error;\n }\n },\n async () => {\n const releasePath = cacheLockOperationPath(\n lockPath,\n \"release\",\n owner.token,\n );\n try {\n await rename(ownerPath, releasePath);\n } catch (error) {\n if (isNotFound(error)) return;\n throw error;\n }\n await disposeLockDirectory(releasePath);\n },\n );\n } catch (error) {\n if (!isAlreadyExists(error)) throw error;\n const observed = await observeOwner();\n const expiresAt =\n observed.owner?.expiresAtMilliseconds ?? invalidOwnerExpiresAt;\n if (Date.now() >= expiresAt) {\n if (observed.ownerPath == null) {\n await claimEmptyLock();\n continue;\n }\n const claimPath = cacheLockOperationPath(\n lockPath,\n \"reclaim\",\n \"stale\",\n );\n try {\n await rename(observed.ownerPath, claimPath);\n } catch (claimError) {\n if (isNotFound(claimError)) continue;\n throw claimError;\n }\n const claimedOwner = await readCacheLockOwner(\n async () => await readFile(claimPath, \"utf8\"),\n );\n if (\n claimedOwner != null &&\n Date.now() < claimedOwner.expiresAtMilliseconds\n ) {\n try {\n await rename(\n claimPath,\n `${lockPath}/${cacheLockOwnerName(claimedOwner.token)}`,\n );\n } catch (restoreError) {\n if (!isNotFound(restoreError)) throw restoreError;\n }\n continue;\n }\n await disposeLockDirectory(claimPath);\n continue;\n }\n await wait(cacheLockPollMilliseconds);\n }\n }\n /* eslint-enable no-await-in-loop */\n },\n async getDirectory(name) {\n requireCacheName(name);\n const [{ mkdir }, { homedir }, { join, resolve }] = await Promise.all([\n import(\"node:fs/promises\"),\n import(\"node:os\"),\n import(\"node:path\"),\n ]);\n const configured = process.env.XDG_CACHE_HOME;\n const root =\n process.platform === \"darwin\"\n ? join(homedir(), \"Library\", \"Caches\")\n : configured == null || configured === \"\"\n ? join(homedir(), \".cache\")\n : configured;\n const directory = resolve(root, \"oseo\", name);\n await mkdir(directory, { recursive: true });\n return directory;\n },\n async hasFile(path) {\n const { stat } = await import(\"node:fs/promises\");\n try {\n const entry = await stat(path);\n return entry.isFile() && entry.size > 0;\n } catch (error) {\n if (isNotFound(error)) return false;\n throw error;\n }\n },\n async publishFile(sourcePath, destinationPath) {\n const [{ copyFile, rename, rm }, { randomUUID }] = await Promise.all([\n import(\"node:fs/promises\"),\n import(\"node:crypto\"),\n ]);\n const temporaryPath = `${destinationPath}.${randomUUID()}.tmp`;\n try {\n await copyFile(sourcePath, temporaryPath);\n await rename(temporaryPath, destinationPath);\n } finally {\n await rm(temporaryPath, { force: true });\n }\n },\n };\n}\n\nfunction createDenoCache(runtime: DenoRuntime): CompilerCache {\n async function removeTemporary(path: string): Promise<void> {\n try {\n await runtime.remove(path);\n } catch (error) {\n if (!isNotFound(error)) throw error;\n }\n }\n\n return {\n async acquireFileLock(path): Promise<CompilerCacheLock> {\n const lockPath = `${path}.lock`;\n const invalidOwnerExpiresAt = Date.now() + cacheLockLifetimeMilliseconds;\n async function observeOwner(): Promise<CacheLockObservation> {\n let ownerName: string | undefined;\n try {\n for await (const entry of runtime.readDir(lockPath)) {\n if (entry.isFile && isCacheLockStateName(entry.name)) {\n ownerName = entry.name;\n break;\n }\n }\n } catch (error) {\n if (isNotFound(error)) return {};\n throw error;\n }\n if (ownerName == null) return {};\n const ownerPath = `${lockPath}/${ownerName}`;\n const owner = await readCacheLockOwner(\n async () => await runtime.readTextFile(ownerPath),\n );\n const operationExpiration = cacheLockOperationExpiration(ownerName);\n return {\n owner:\n operationExpiration == null\n ? owner\n : {\n expiresAtMilliseconds: Math.max(\n owner?.expiresAtMilliseconds ?? 0,\n operationExpiration,\n ),\n token: owner?.token ?? \"operation\",\n },\n ownerPath,\n };\n }\n async function disposeLockDirectory(statePath: string): Promise<void> {\n const disposalExpiresAt = Date.now() + cacheLockLifetimeMilliseconds;\n const disposalStatePath = cacheLockOperationPath(\n lockPath,\n \"reclaim\",\n \"disposal\",\n disposalExpiresAt,\n );\n try {\n await runtime.rename(statePath, disposalStatePath);\n } catch (error) {\n if (isNotFound(error)) return;\n throw error;\n }\n const disposalPath = `${lockPath}.dispose-${crypto.randomUUID()}`;\n try {\n await renameClaimedCacheLockDirectory(\n async (fromPath, toPath) => await runtime.rename(fromPath, toPath),\n lockPath,\n disposalPath,\n {\n deadlineMilliseconds:\n disposalExpiresAt - cacheLockRenameSafetyMilliseconds,\n retryPermissionErrors: runtime.build?.os === \"windows\",\n },\n );\n } catch (error) {\n if (isNotFound(error)) return;\n throw error;\n }\n await runtime.remove(disposalPath, { recursive: true });\n }\n async function claimEmptyLock(): Promise<void> {\n const token = crypto.randomUUID();\n const ownerName = \"owner-empty-reclaimer.json\";\n const ownerPath = `${lockPath}/${ownerName}`;\n try {\n await runtime.writeTextFile(\n ownerPath,\n JSON.stringify({\n expiresAtMilliseconds: Date.now() + cacheLockLifetimeMilliseconds,\n token,\n }),\n { createNew: true },\n );\n } catch (error) {\n if (isAlreadyExists(error) || isNotFound(error)) return;\n throw error;\n }\n let competingState = false;\n for await (const entry of runtime.readDir(lockPath)) {\n if (entry.isFile && entry.name !== ownerName) {\n competingState = true;\n break;\n }\n }\n if (competingState) {\n await removeTemporary(ownerPath);\n return;\n }\n await disposeLockDirectory(ownerPath);\n }\n /* eslint-disable no-await-in-loop -- Lease steps are ordered. */\n while (true) {\n try {\n await runtime.mkdir(lockPath, { recursive: false });\n const owner = {\n expiresAtMilliseconds: Date.now() + cacheLockLifetimeMilliseconds,\n token: crypto.randomUUID(),\n };\n const ownerPath = `${lockPath}/${cacheLockOwnerName(owner.token)}`;\n try {\n await runtime.writeTextFile(ownerPath, JSON.stringify(owner));\n } catch (error) {\n await removeTemporary(ownerPath);\n if (isNotFound(error)) continue;\n throw error;\n }\n let competingState = false;\n for await (const entry of runtime.readDir(lockPath)) {\n if (\n entry.isFile &&\n isCacheLockStateName(entry.name) &&\n entry.name !== cacheLockOwnerName(owner.token)\n ) {\n competingState = true;\n break;\n }\n }\n if (competingState) {\n await removeTemporary(ownerPath);\n continue;\n }\n return createRenewingCacheLock(\n async () => {\n const renewalPath = cacheLockOperationPath(\n lockPath,\n \"renew\",\n owner.token,\n );\n try {\n await runtime.rename(ownerPath, renewalPath);\n } catch (error) {\n if (isNotFound(error)) return false;\n throw error;\n }\n try {\n await overwriteExistingDenoTextFile(\n runtime,\n renewalPath,\n JSON.stringify({\n expiresAtMilliseconds:\n Date.now() + cacheLockLifetimeMilliseconds,\n token: owner.token,\n }),\n );\n await runtime.rename(renewalPath, ownerPath);\n return true;\n } catch (error) {\n try {\n await runtime.rename(renewalPath, ownerPath);\n } catch {\n // The state was claimed by a concurrent reclaimer.\n }\n throw error;\n }\n },\n async () => {\n const releasePath = cacheLockOperationPath(\n lockPath,\n \"release\",\n owner.token,\n );\n try {\n await runtime.rename(ownerPath, releasePath);\n } catch (error) {\n if (isNotFound(error)) return;\n throw error;\n }\n await disposeLockDirectory(releasePath);\n },\n );\n } catch (error) {\n if (!isAlreadyExists(error)) throw error;\n const observed = await observeOwner();\n const expiresAt =\n observed.owner?.expiresAtMilliseconds ?? invalidOwnerExpiresAt;\n if (Date.now() >= expiresAt) {\n if (observed.ownerPath == null) {\n await claimEmptyLock();\n continue;\n }\n const claimPath = cacheLockOperationPath(\n lockPath,\n \"reclaim\",\n \"stale\",\n );\n try {\n await runtime.rename(observed.ownerPath, claimPath);\n } catch (claimError) {\n if (isNotFound(claimError)) continue;\n throw claimError;\n }\n const claimedOwner = await readCacheLockOwner(\n async () => await runtime.readTextFile(claimPath),\n );\n if (\n claimedOwner != null &&\n Date.now() < claimedOwner.expiresAtMilliseconds\n ) {\n try {\n await runtime.rename(\n claimPath,\n `${lockPath}/${cacheLockOwnerName(claimedOwner.token)}`,\n );\n } catch (restoreError) {\n if (!isNotFound(restoreError)) throw restoreError;\n }\n continue;\n }\n await disposeLockDirectory(claimPath);\n continue;\n }\n await wait(cacheLockPollMilliseconds);\n }\n }\n /* eslint-enable no-await-in-loop */\n },\n async getDirectory(name) {\n requireCacheName(name);\n const configured = runtime.env.get(\"XDG_CACHE_HOME\");\n const home = runtime.env.get(\"HOME\");\n const root =\n runtime.build?.os === \"darwin\"\n ? home == null\n ? undefined\n : `${home}/Library/Caches`\n : configured == null || configured === \"\"\n ? home == null\n ? undefined\n : `${home}/.cache`\n : configured;\n if (root == null) {\n throw new Error(\"The compiler cache directory is unavailable.\");\n }\n const { resolve } = await import(\"node:path\");\n const directory = resolve(root, \"oseo\", name);\n await runtime.mkdir(directory, { recursive: true });\n return directory;\n },\n async hasFile(path) {\n try {\n const entry = await runtime.stat(path);\n return entry.isFile && entry.size > 0;\n } catch (error) {\n if (isNotFound(error)) return false;\n throw error;\n }\n },\n async publishFile(sourcePath, destinationPath) {\n const separator = destinationPath.lastIndexOf(\"/\");\n const directory = destinationPath.slice(0, separator);\n const temporaryPath = await runtime.makeTempFile({\n dir: directory,\n prefix: \".oseo-publish-\",\n });\n try {\n await runtime.copyFile(sourcePath, temporaryPath);\n await runtime.rename(temporaryPath, destinationPath);\n } catch (error) {\n try {\n await removeTemporary(temporaryPath);\n } catch {\n // The publication failure remains the authoritative observation.\n }\n throw error;\n }\n await removeTemporary(temporaryPath);\n },\n };\n}\n\nfunction moduleDiagnostic(\n sourceId: string,\n specifier: SyntaxModuleSpecifier | undefined,\n message: string,\n): Diagnostic {\n return {\n byteRange: specifier?.byteRange ?? { end: 0, start: 0 },\n code: \"OSEO3001\",\n message,\n range: specifier?.range ?? {\n end: { column: 1, line: 1 },\n start: { column: 1, line: 1 },\n },\n sourceId,\n };\n}\n\nfunction isUnreservedPathByte(value: number): boolean {\n return (\n (value >= 0x41 && value <= 0x5a) ||\n (value >= 0x61 && value <= 0x7a) ||\n (value >= 0x30 && value <= 0x39) ||\n value === 0x2d ||\n value === 0x2e ||\n value === 0x5f ||\n value === 0x7e\n );\n}\n\n/** Normalize one file URL to the canonical module identity spelling. */\nexport function canonicalizeFileModuleUrl(url: URL): string {\n const canonical = new URL(url.href);\n canonical.pathname = canonical.pathname.replace(/%[0-9a-f]{2}/giu, (part) => {\n const value = Number.parseInt(part.slice(1), 16);\n return isUnreservedPathByte(value)\n ? String.fromCharCode(value)\n : part.toUpperCase();\n });\n return canonical.href;\n}\n\n/** Produce the stable content identity recorded in a module graph. */\nexport function hashModuleSource(source: string): string {\n let hash = 0xcbf2_9ce4_8422_2325n;\n for (const byte of new TextEncoder().encode(source)) {\n hash ^= BigInt(byte);\n hash = BigInt.asUintN(64, hash * 0x0000_0100_0000_01b3n);\n }\n return `fnv1a64:${hash.toString(16).padStart(16, \"0\")}`;\n}\n\n/** Load canonical file URLs through one explicit compiler host. */\nexport function createFileModuleLoader(\n host: CompilerHost,\n runtimeAbiVersion = \"m5-160\",\n): ModuleLoader {\n return {\n async load(canonicalId, referrer) {\n if (isBuiltinModuleSpecifier(canonicalId)) {\n return {\n diagnostics: [],\n builtin: {\n kind: \"builtin\",\n specifier: canonicalId,\n sourceHash: hashModuleSource(\n JSON.stringify({\n exports: builtinModuleExports[canonicalId],\n runtimeAbiVersion,\n }),\n ),\n },\n };\n }\n const diagnosticSourceId = referrer?.importerId ?? canonicalId;\n const diagnosticSpecifier = referrer?.specifier;\n if (canonicalId.startsWith(\"node:\")) {\n return {\n diagnostics: [\n moduleDiagnostic(\n diagnosticSourceId,\n diagnosticSpecifier,\n \"Only node:process and node:fs builtin modules are supported.\",\n ),\n ],\n };\n }\n let url: URL;\n try {\n url = new URL(canonicalId);\n } catch {\n return {\n diagnostics: [\n moduleDiagnostic(\n diagnosticSourceId,\n diagnosticSpecifier,\n \"Invalid module URL.\",\n ),\n ],\n };\n }\n if (url.protocol !== \"file:\") {\n return {\n diagnostics: [\n moduleDiagnostic(\n diagnosticSourceId,\n diagnosticSpecifier,\n \"Only file module URLs are supported in M4.\",\n ),\n ],\n };\n }\n try {\n const source = await host.readTextFile(url);\n const kind = url.pathname.endsWith(\".json\") ? \"json\" : \"javascript\";\n return {\n diagnostics: [],\n source: {\n kind,\n source: kind === \"json\" ? source.replace(/^\\uFEFF+/u, \"\") : source,\n sourceHash: hashModuleSource(source),\n sourceId: url.href,\n },\n };\n } catch {\n return {\n diagnostics: [\n moduleDiagnostic(\n diagnosticSourceId,\n diagnosticSpecifier,\n \"The module source could not be read.\",\n ),\n ],\n };\n }\n },\n };\n}\n\n/** Resolve the relative file specifiers frozen by the M4 profile. */\nexport const fileModuleResolver: ModuleResolver = {\n resolve(importerId, specifier) {\n if (isBuiltinModuleSpecifier(specifier.value)) {\n return { canonicalId: specifier.value, diagnostics: [] };\n }\n if (specifier.value.startsWith(\"node:\")) {\n return {\n diagnostics: [\n moduleDiagnostic(\n importerId,\n specifier,\n \"Only node:process and node:fs builtin modules are supported.\",\n ),\n ],\n };\n }\n if (\n !specifier.value.startsWith(\"./\") &&\n !specifier.value.startsWith(\"../\")\n ) {\n return {\n diagnostics: [\n moduleDiagnostic(\n importerId,\n specifier,\n `Unsupported module specifier '${specifier.value}'.`,\n ),\n ],\n };\n }\n try {\n const importer = new URL(importerId);\n if (importer.protocol !== \"file:\") throw new Error(\"not a file URL\");\n const resolved = new URL(specifier.value, importer);\n if (resolved.protocol !== \"file:\") throw new Error(\"not a file URL\");\n return {\n canonicalId: canonicalizeFileModuleUrl(resolved),\n diagnostics: [],\n };\n } catch {\n return {\n diagnostics: [\n moduleDiagnostic(\n importerId,\n specifier,\n `Cannot resolve module specifier '${specifier.value}'.`,\n ),\n ],\n };\n }\n },\n};\n\n/** Optional execution services for long-running Node.js compiler hosts. */\nexport interface NodeHostOptions {\n /** Spawn through a small reusable process instead of the compiler heap. */\n readonly delegateSpawns?: boolean;\n}\n\n/** A Node host can explicitly drain and close its optional spawn service. */\nexport interface NodeHost extends CompilerHost {\n /** Stop accepting delegated work, drain pending requests, and close IPC. */\n close(): Promise<void>;\n}\n\n/** Create the Node.js implementation of compiler host operations. */\nexport function createNodeHost(options: NodeHostOptions = {}): NodeHost {\n const delegate =\n options.delegateSpawns === true\n ? import(\"./spawn-delegate.ts\").then(({ createSpawnDelegate }) =>\n createSpawnDelegate(),\n )\n : undefined;\n return {\n async close() {\n await (await delegate)?.close();\n },\n cache: createNodeCache(),\n captureEnvironment(policy) {\n return Promise.resolve({\n variables: selectEnvironment(\n policy.inherit,\n (name) => process.env[name],\n ),\n });\n },\n executionHost: normalizeExecutionHost(process.platform, process.arch),\n async canonicalizeFile(path: string): Promise<string> {\n try {\n const url = new URL(path);\n if (url.protocol === \"file:\") {\n return canonicalizeFileModuleUrl(url);\n }\n } catch {\n // A filesystem path is canonicalized below.\n }\n const [{ resolve }, { pathToFileURL }] = await Promise.all([\n import(\"node:path\"),\n import(\"node:url\"),\n ]);\n return canonicalizeFileModuleUrl(pathToFileURL(resolve(path)));\n },\n async describeFile(path: string): Promise<FileFingerprint | undefined> {\n const { realpath, stat } = await import(\"node:fs/promises\");\n try {\n // stat resolves symbolic links, so a relinked path reports the new\n // target's identity and a replaced file reports new size and time.\n const [resolved, status] = await Promise.all([\n realpath(path),\n stat(path),\n ]);\n const fingerprint: FileFingerprint = {\n device: Number(status.dev),\n inode: Number(status.ino),\n modifiedAtMilliseconds: status.mtimeMs,\n realPath: resolved,\n size: Number(status.size),\n };\n if (status.ctimeMs == null) return fingerprint;\n return { ...fingerprint, changedAtMilliseconds: status.ctimeMs };\n } catch {\n return undefined;\n }\n },\n async makeTemporaryDirectory(prefix: string): Promise<string> {\n const [{ mkdtemp }, { tmpdir }, { join }] = await Promise.all([\n import(\"node:fs/promises\"),\n import(\"node:os\"),\n import(\"node:path\"),\n ]);\n return await mkdtemp(join(tmpdir(), prefix));\n },\n async readTextFile(path: string | URL): Promise<string> {\n const { readFile } = await import(\"node:fs/promises\");\n return await readFile(path, \"utf8\");\n },\n async remove(path: string): Promise<void> {\n const { rm } = await import(\"node:fs/promises\");\n await rm(path, { force: true, recursive: true });\n },\n async run(request: ProcessRequest): Promise<ProcessObservation> {\n validateProcessStreams(request);\n if (delegate != null) return await (await delegate).run(request);\n const { spawn } = await import(\"node:child_process\");\n return await new Promise((resolve, reject) => {\n const environment = request.environment;\n const child = spawn(request.command, [...request.args], {\n cwd: request.cwd,\n env: environment?.variables ?? process.env,\n stdio: [\n request.input == null && request.inheritStdin ? \"inherit\" : \"pipe\",\n request.inheritOutput ? \"inherit\" : \"pipe\",\n request.inheritOutput ? \"inherit\" : \"pipe\",\n ],\n });\n if (\n !request.inheritOutput &&\n (child.stdout == null || child.stderr == null)\n ) {\n throw new Error(\"Process output pipes are unavailable.\");\n }\n const stdout: Uint8Array[] = [];\n const stderr: Uint8Array[] = [];\n child.stdout?.on(\"data\", (chunk: Uint8Array) => stdout.push(chunk));\n child.stderr?.on(\"data\", (chunk: Uint8Array) => stderr.push(chunk));\n // A program may exit before consuming all input. Its status and\n // output remain authoritative when the input pipe closes early.\n child.stdin?.on(\"error\", (error: NodeJS.ErrnoException) => {\n if (!isClosedInputError(error)) reject(error);\n });\n child.stdin?.end(request.input);\n child.on(\"error\", reject);\n child.on(\"close\", (code) => {\n resolve({\n exitStatus: code ?? 1,\n stderr: Buffer.concat(stderr).toString(\"utf8\"),\n stdout: Buffer.concat(stdout).toString(\"utf8\"),\n ...includePropertiesWhen(() => {\n if (!request.captureBytes) return undefined;\n return {\n stdoutBytes: new Uint8Array(Buffer.concat(stdout)),\n stderrBytes: new Uint8Array(Buffer.concat(stderr)),\n };\n }),\n });\n });\n });\n },\n async writeTextFile(path: string, contents: string): Promise<void> {\n const { writeFile } = await import(\"node:fs/promises\");\n await writeFile(path, contents);\n },\n };\n}\n\n/** Create the Deno implementation of compiler host operations. */\nexport function createDenoHost(): CompilerHost {\n const runtime = denoRuntime();\n const decoder = new TextDecoder(\"utf-8\", { ignoreBOM: true });\n return {\n cache: createDenoCache(runtime),\n captureEnvironment(policy) {\n try {\n return Promise.resolve({\n variables: selectEnvironment(policy.inherit, (name) =>\n runtime.env.get(name),\n ),\n });\n } catch (error) {\n if (isEnvironmentPermissionDenied(error)) {\n return Promise.resolve(undefined);\n }\n return Promise.reject(error);\n }\n },\n executionHost: normalizeExecutionHost(\n runtime.build?.os ?? \"unknown\",\n runtime.build?.arch ?? \"unknown\",\n ),\n canonicalizeFile(path: string): Promise<string> {\n try {\n const url = new URL(path);\n if (url.protocol === \"file:\") {\n return Promise.resolve(canonicalizeFileModuleUrl(url));\n }\n } catch {\n // A filesystem path is canonicalized below.\n }\n const basePath = path.startsWith(\"/\")\n ? path\n : `${runtime.cwd().replace(/\\/$/u, \"\")}/${path}`;\n const url = new URL(\"file:///\");\n url.pathname = basePath.replaceAll(\"%\", \"%25\");\n return Promise.resolve(canonicalizeFileModuleUrl(url));\n },\n async describeFile(path: string): Promise<FileFingerprint | undefined> {\n try {\n const [resolved, status] = await Promise.all([\n runtime.realPath(path),\n runtime.stat(path),\n ]);\n const fingerprint: FileFingerprint = {\n device: status.dev ?? 0,\n inode: status.ino ?? 0,\n modifiedAtMilliseconds: status.mtime?.getTime() ?? 0,\n realPath: resolved,\n size: status.size,\n };\n const changedAt = status.ctime?.getTime();\n if (changedAt == null) return fingerprint;\n return { ...fingerprint, changedAtMilliseconds: changedAt };\n } catch {\n return undefined;\n }\n },\n async makeTemporaryDirectory(prefix: string): Promise<string> {\n return await runtime.makeTempDir({ prefix });\n },\n async readTextFile(path: string | URL): Promise<string> {\n const url = remoteUrl(path);\n if (url != null) {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch ${url.href}: ` +\n `${response.status} ${response.statusText}`,\n );\n }\n return await response.text();\n }\n return await runtime.readTextFile(path);\n },\n async remove(path: string): Promise<void> {\n await runtime.remove(path, { recursive: true });\n },\n async run(request: ProcessRequest): Promise<ProcessObservation> {\n validateProcessStreams(request);\n const environment = request.environment;\n const command = new runtime.Command(request.command, {\n args: request.args,\n ...includePropertiesWhen(() => {\n if (environment == null) return undefined;\n return {\n clearEnv: true,\n env: environment.variables,\n };\n }),\n cwd: request.cwd,\n ...includePropertiesWhen(() => {\n if (request.input != null) return { stdin: \"piped\" as const };\n if (request.inheritStdin) return { stdin: \"inherit\" as const };\n return { stdin: \"null\" as const };\n }),\n stderr: request.inheritOutput ? \"inherit\" : \"piped\",\n stdout: request.inheritOutput ? \"inherit\" : \"piped\",\n });\n let output: DenoCommandOutput;\n if (request.input == null) {\n output = await command.output();\n } else {\n const child = command.spawn();\n const capture = child.output();\n const writer = child.stdin.getWriter();\n try {\n await writer.write(\n isTextProcessInput(request.input)\n ? new TextEncoder().encode(request.input)\n : request.input,\n );\n await writer.close();\n } catch (error) {\n // Deno uses BrokenPipe when the program exits without reading.\n if (!(error instanceof Error) || error.name !== \"BrokenPipe\") {\n await capture;\n throw error;\n }\n } finally {\n writer.releaseLock();\n }\n output = await capture;\n }\n return {\n exitStatus: output.code,\n stderr: request.inheritOutput ? \"\" : decoder.decode(output.stderr),\n stdout: request.inheritOutput ? \"\" : decoder.decode(output.stdout),\n ...includePropertiesWhen(() => {\n if (!request.captureBytes) return undefined;\n return {\n stdoutBytes: output.stdout,\n stderrBytes: output.stderr,\n };\n }),\n };\n },\n async writeTextFile(path: string, contents: string): Promise<void> {\n await runtime.writeTextFile(path, contents);\n },\n };\n}\n\nexport { createExecutablePublisher } from \"./executable-publication.ts\";\nexport type {\n ExecutableDestination,\n ExecutablePublisher,\n} from \"./executable-publication.ts\";\n"],"mappings":";;;;;;AA6CA,SAAS,sBACP,YACoD;CACpD,OAAO,WAAW,KAAK,CAAC;AAC1B;;AAGA,SAAS,mBAAmB,OAA6C;CACvE,OAAO,OAAO,UAAU;AAC1B;;AAGA,SAAgB,uBACd,yBACA,sBAC0B;CAC1B,OAAO;EACL,cACE,yBAAyB,WAAW,yBAAyB,YACzD,YACA,yBAAyB,WACvB,yBAAyB,SACzB,yBAAyB,WACzB,WACA;EACR,iBACE,4BAA4B,WACxB,UACA,4BAA4B,UAC1B,UACA;CACV;AACF;AA8EA,SAAS,cAAiB,OAAoC;CAC5D,OACE,iBAAiB,UACjB,aAAa,SACb,OAAO,MAAM,YAAY,cACzB,SAAS,SACT,OAAO,MAAM,QAAQ,cACrB,kBAAkB,SAClB,OAAO,MAAM,iBAAiB,cAC9B,UAAU,SACV,OAAO,MAAM,SAAS;AAE1B;AAEA,SAAS,cAA2B;CAClC,MAAM,UAAU,OAAO,yBAAyB,YAAY,MAAM,CAAC,EAAE;CACrE,IAAI,CAAC,cAAc,OAAO,GAAG,MAAM,IAAI,MAAM,2BAA2B;CACxE,OAAO;AACT;AAEA,SAAS,UAAU,MAAqC;CACtD,IAAI;CACJ,IAAI;EACF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
|
|
2
|
+
import { ProcessObservation, ProcessRequest } from "@oseo/compiler";
|
|
3
|
+
import { ChildProcess } from "node:child_process";
|
|
4
|
+
import { EventEmitter } from "node:events";
|
|
5
|
+
//#region src/spawn-delegate.d.ts
|
|
6
|
+
/** The IPC surface used by the delegate, also implemented by test helpers. */
|
|
7
|
+
interface SpawnHelper extends EventEmitter {
|
|
8
|
+
readonly connected: boolean;
|
|
9
|
+
/** Absent after a failed process creation, which emits no `exit`. */
|
|
10
|
+
readonly pid?: number | undefined;
|
|
11
|
+
readonly channel?: {
|
|
12
|
+
ref(): void;
|
|
13
|
+
unref(): void;
|
|
14
|
+
} | null | undefined;
|
|
15
|
+
ref(): void;
|
|
16
|
+
unref(): void;
|
|
17
|
+
disconnect(): void;
|
|
18
|
+
send(request: SpawnRequest, callback: (error: Error | null) => void): boolean;
|
|
19
|
+
}
|
|
20
|
+
/** Host-local spawn service; closing drains requests and releases its IPC. */
|
|
21
|
+
interface SpawnDelegate {
|
|
22
|
+
run(request: ProcessRequest): Promise<ProcessObservation>;
|
|
23
|
+
close(): Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
/** Start a small Node process without the runner's preload or CLI arguments. */
|
|
26
|
+
declare function startSpawnHelper(): ChildProcess;
|
|
27
|
+
/**
|
|
28
|
+
* Multiplex requests without retrying a command after an uncertain failure.
|
|
29
|
+
* Idle IPC is unreferenced so an unused host cannot keep the runner alive.
|
|
30
|
+
* The factory is injectable to exercise helper failures without module mocks.
|
|
31
|
+
*/
|
|
32
|
+
declare function createSpawnDelegate(start?: () => SpawnHelper): SpawnDelegate;
|
|
33
|
+
//#endregion
|
|
34
|
+
export { SpawnDelegate, SpawnHelper, createSpawnDelegate, startSpawnHelper };
|
|
35
|
+
//# sourceMappingURL=spawn-delegate.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"spawn-delegate.d.ts","names":[],"sources":["../src/spawn-delegate.ts"],"mappings":";;;;;;UA2BiB,oBAAoB;WAC1B;;WAEA;WACA;IAEH;IACA;;EAIN;EACA;EACA;EACA,KAAK,SAAS,cAAc,WAAW,OAAO;;;UAkC/B;EACf,IAAI,SAAS,iBAAiB,QAAQ;EACtC,SAAS;;;iBAIK,oBAAoB;;;;;;iBAepB,oBACd,cAAa,cACZ"}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { isSpawnResponse, restoreSpawnError } from "./spawn-protocol.js";
|
|
2
|
+
import { isAbsolute, sep } from "node:path";
|
|
3
|
+
import { fork } from "node:child_process";
|
|
4
|
+
|
|
5
|
+
//#region src/spawn-delegate.ts
|
|
6
|
+
/** Match spawn's enumerable environment selection, including inherited keys. */
|
|
7
|
+
function snapshotEnvironment(environment) {
|
|
8
|
+
const snapshot = Object.create(null);
|
|
9
|
+
for (const name in environment) {
|
|
10
|
+
const value = environment[name];
|
|
11
|
+
if (value != null) snapshot[name] = value;
|
|
12
|
+
}
|
|
13
|
+
return snapshot;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Anchor a relative cwd to the caller's directory without normalizing it.
|
|
17
|
+
* The operating system must resolve `..` after symlinks, exactly as a
|
|
18
|
+
* direct spawn from the caller would; `path.resolve` would collapse
|
|
19
|
+
* `link/..` lexically and select a different directory.
|
|
20
|
+
*/
|
|
21
|
+
function anchorCwd(cwd) {
|
|
22
|
+
if (cwd === "") return process.cwd();
|
|
23
|
+
return isAbsolute(cwd) ? cwd : `${process.cwd()}${sep}${cwd}`;
|
|
24
|
+
}
|
|
25
|
+
/** Start a small Node process without the runner's preload or CLI arguments. */
|
|
26
|
+
function startSpawnHelper() {
|
|
27
|
+
const extension = import.meta.url.endsWith(".ts") ? "ts" : "js";
|
|
28
|
+
return fork(new URL(`./spawn-helper.${extension}`, import.meta.url), [], {
|
|
29
|
+
env: {
|
|
30
|
+
...process.env,
|
|
31
|
+
NODE_OPTIONS: void 0
|
|
32
|
+
},
|
|
33
|
+
execArgv: [],
|
|
34
|
+
serialization: "advanced",
|
|
35
|
+
stdio: [
|
|
36
|
+
"inherit",
|
|
37
|
+
"inherit",
|
|
38
|
+
"inherit",
|
|
39
|
+
"ipc"
|
|
40
|
+
]
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Multiplex requests without retrying a command after an uncertain failure.
|
|
45
|
+
* Idle IPC is unreferenced so an unused host cannot keep the runner alive.
|
|
46
|
+
* The factory is injectable to exercise helper failures without module mocks.
|
|
47
|
+
*/
|
|
48
|
+
function createSpawnDelegate(start = startSpawnHelper) {
|
|
49
|
+
const pending = /* @__PURE__ */ new Map();
|
|
50
|
+
let child;
|
|
51
|
+
let failure;
|
|
52
|
+
let closing = false;
|
|
53
|
+
let nextId = 0;
|
|
54
|
+
let closed;
|
|
55
|
+
let markClosed;
|
|
56
|
+
function releaseWhenIdle() {
|
|
57
|
+
if (child == null || pending.size > 0) return;
|
|
58
|
+
if (closing && child.connected) child.disconnect();
|
|
59
|
+
if (!closing) {
|
|
60
|
+
child.unref();
|
|
61
|
+
child.channel?.unref();
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
function fail(error) {
|
|
65
|
+
failure ??= error;
|
|
66
|
+
for (const request of pending.values()) request.reject(failure);
|
|
67
|
+
pending.clear();
|
|
68
|
+
if (child?.connected) child.disconnect();
|
|
69
|
+
releaseWhenIdle();
|
|
70
|
+
}
|
|
71
|
+
function helper() {
|
|
72
|
+
if (child != null) return child;
|
|
73
|
+
try {
|
|
74
|
+
child = start();
|
|
75
|
+
} catch (error) {
|
|
76
|
+
if (!(error instanceof Error)) throw error;
|
|
77
|
+
fail(error);
|
|
78
|
+
throw error;
|
|
79
|
+
}
|
|
80
|
+
const service = child;
|
|
81
|
+
let exited = false;
|
|
82
|
+
closed = new Promise((resolve) => {
|
|
83
|
+
markClosed = resolve;
|
|
84
|
+
});
|
|
85
|
+
function settleWhenGone() {
|
|
86
|
+
if (exited && !service.connected) markClosed?.();
|
|
87
|
+
}
|
|
88
|
+
service.on("error", (error) => {
|
|
89
|
+
if (service.pid == null) exited = true;
|
|
90
|
+
fail(error);
|
|
91
|
+
settleWhenGone();
|
|
92
|
+
});
|
|
93
|
+
service.on("disconnect", () => {
|
|
94
|
+
if (!closing || pending.size > 0) fail(/* @__PURE__ */ new Error("Spawn helper disconnected."));
|
|
95
|
+
settleWhenGone();
|
|
96
|
+
});
|
|
97
|
+
service.on("message", (response) => {
|
|
98
|
+
if (!isSpawnResponse(response)) {
|
|
99
|
+
fail(/* @__PURE__ */ new Error("Spawn helper returned a malformed response."));
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
const completion = pending.get(response.id);
|
|
103
|
+
if (completion == null) {
|
|
104
|
+
fail(/* @__PURE__ */ new Error("Spawn helper returned an unknown request."));
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
pending.delete(response.id);
|
|
108
|
+
if ("error" in response) completion.reject(restoreSpawnError(response.error));
|
|
109
|
+
else completion.resolve(response.observation);
|
|
110
|
+
releaseWhenIdle();
|
|
111
|
+
});
|
|
112
|
+
service.on("exit", () => {
|
|
113
|
+
exited = true;
|
|
114
|
+
settleWhenGone();
|
|
115
|
+
});
|
|
116
|
+
service.on("close", (code, signal) => {
|
|
117
|
+
exited = true;
|
|
118
|
+
if (!closing || pending.size > 0) fail(/* @__PURE__ */ new Error(`Spawn helper closed (status ${code}, signal ${signal}).`));
|
|
119
|
+
settleWhenGone();
|
|
120
|
+
});
|
|
121
|
+
return child;
|
|
122
|
+
}
|
|
123
|
+
return {
|
|
124
|
+
async run(request) {
|
|
125
|
+
if (failure != null) throw failure;
|
|
126
|
+
if (closing) throw new Error("Spawn delegate is closed.");
|
|
127
|
+
const service = helper();
|
|
128
|
+
service.ref();
|
|
129
|
+
service.channel?.ref();
|
|
130
|
+
const id = nextId++;
|
|
131
|
+
return await new Promise((resolve, reject) => {
|
|
132
|
+
pending.set(id, {
|
|
133
|
+
resolve,
|
|
134
|
+
reject
|
|
135
|
+
});
|
|
136
|
+
try {
|
|
137
|
+
service.send({
|
|
138
|
+
id,
|
|
139
|
+
request: {
|
|
140
|
+
...request,
|
|
141
|
+
cwd: anchorCwd(request.cwd),
|
|
142
|
+
environment: { variables: snapshotEnvironment(request.environment?.variables ?? process.env) }
|
|
143
|
+
}
|
|
144
|
+
}, (error) => {
|
|
145
|
+
if (error != null) fail(error);
|
|
146
|
+
});
|
|
147
|
+
} catch (error) {
|
|
148
|
+
if (!(error instanceof Error)) throw error;
|
|
149
|
+
fail(error);
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
},
|
|
153
|
+
async close() {
|
|
154
|
+
closing = true;
|
|
155
|
+
child?.ref();
|
|
156
|
+
child?.channel?.ref();
|
|
157
|
+
releaseWhenIdle();
|
|
158
|
+
await closed;
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
//#endregion
|
|
164
|
+
export { createSpawnDelegate, startSpawnHelper };
|
|
165
|
+
//# sourceMappingURL=spawn-delegate.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"spawn-delegate.js","names":[],"sources":["../src/spawn-delegate.ts"],"sourcesContent":["/*\n * Oseo, an ahead-of-time compiler for JavaScript and TypeScript.\n * Copyright (C) 2026 Hong Minhee <https://hongminhee.org/>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <https://www.gnu.org/licenses/>.\n */\n\nimport { fork } from \"node:child_process\";\nimport type { ChildProcess } from \"node:child_process\";\nimport type { EventEmitter } from \"node:events\";\nimport { isAbsolute, sep } from \"node:path\";\nimport type { ProcessObservation, ProcessRequest } from \"@oseo/compiler\";\nimport { isSpawnResponse, restoreSpawnError } from \"./spawn-protocol.ts\";\nimport type { SpawnRequest } from \"./spawn-protocol.ts\";\n\n/** The IPC surface used by the delegate, also implemented by test helpers. */\nexport interface SpawnHelper extends EventEmitter {\n readonly connected: boolean;\n /** Absent after a failed process creation, which emits no `exit`. */\n readonly pid?: number | undefined;\n readonly channel?:\n | {\n ref(): void;\n unref(): void;\n }\n | null\n | undefined;\n ref(): void;\n unref(): void;\n disconnect(): void;\n send(request: SpawnRequest, callback: (error: Error | null) => void): boolean;\n}\n\n/** One completion retained until the helper closes the command's pipes. */\ninterface PendingSpawn {\n readonly resolve: (observation: ProcessObservation) => void;\n readonly reject: (error: Error) => void;\n}\n\n/** Match spawn's enumerable environment selection, including inherited keys. */\nfunction snapshotEnvironment(\n environment: Readonly<Record<string, string | undefined>>,\n): Readonly<Record<string, string>> {\n // SAFETY: A null prototype also retains an own '__proto__' environment key.\n const snapshot = Object.create(null) as Record<string, string>;\n for (const name in environment) {\n const value = environment[name];\n if (value != null) snapshot[name] = value;\n }\n return snapshot;\n}\n\n/**\n * Anchor a relative cwd to the caller's directory without normalizing it.\n * The operating system must resolve `..` after symlinks, exactly as a\n * direct spawn from the caller would; `path.resolve` would collapse\n * `link/..` lexically and select a different directory.\n */\nfunction anchorCwd(cwd: string): string {\n if (cwd === \"\") return process.cwd();\n return isAbsolute(cwd) ? cwd : `${process.cwd()}${sep}${cwd}`;\n}\n\n/** Host-local spawn service; closing drains requests and releases its IPC. */\nexport interface SpawnDelegate {\n run(request: ProcessRequest): Promise<ProcessObservation>;\n close(): Promise<void>;\n}\n\n/** Start a small Node process without the runner's preload or CLI arguments. */\nexport function startSpawnHelper(): ChildProcess {\n const extension = import.meta.url.endsWith(\".ts\") ? \"ts\" : \"js\";\n return fork(new URL(`./spawn-helper.${extension}`, import.meta.url), [], {\n env: { ...process.env, NODE_OPTIONS: undefined },\n execArgv: [],\n serialization: \"advanced\",\n stdio: [\"inherit\", \"inherit\", \"inherit\", \"ipc\"],\n });\n}\n\n/**\n * Multiplex requests without retrying a command after an uncertain failure.\n * Idle IPC is unreferenced so an unused host cannot keep the runner alive.\n * The factory is injectable to exercise helper failures without module mocks.\n */\nexport function createSpawnDelegate(\n start: () => SpawnHelper = startSpawnHelper,\n): SpawnDelegate {\n const pending = new Map<number, PendingSpawn>();\n let child: SpawnHelper | undefined;\n let failure: Error | undefined;\n let closing = false;\n let nextId = 0;\n let closed: Promise<void> | undefined;\n let markClosed: (() => void) | undefined;\n\n function releaseWhenIdle(): void {\n if (child == null || pending.size > 0) return;\n if (closing && child.connected) child.disconnect();\n if (!closing) {\n child.unref();\n child.channel?.unref();\n }\n }\n\n function fail(error: Error): void {\n failure ??= error;\n for (const request of pending.values()) request.reject(failure);\n pending.clear();\n // A broken service must not leave a live IPC channel holding the parent.\n if (child?.connected) child.disconnect();\n releaseWhenIdle();\n }\n\n function helper(): SpawnHelper {\n if (child != null) return child;\n try {\n child = start();\n } catch (error) {\n if (!(error instanceof Error)) throw error;\n fail(error);\n throw error;\n }\n const service = child;\n let exited = false;\n closed = new Promise((resolve) => {\n markClosed = resolve;\n });\n // Node emits `close` only when the channel reaches EOF in the parent.\n // After the parent calls `disconnect()` itself, the helper's exit\n // never produces `close`, so completion is `exit` plus a closed channel.\n function settleWhenGone(): void {\n if (exited && !service.connected) markClosed?.();\n }\n service.on(\"error\", (error: Error) => {\n if (service.pid == null) exited = true;\n fail(error);\n settleWhenGone();\n });\n service.on(\"disconnect\", () => {\n // Channel EOF follows every message the helper wrote, so pending\n // requests here have no response and must not be replayed.\n if (!closing || pending.size > 0) {\n fail(new Error(\"Spawn helper disconnected.\"));\n }\n settleWhenGone();\n });\n service.on(\"message\", (response) => {\n if (!isSpawnResponse(response)) {\n fail(new Error(\"Spawn helper returned a malformed response.\"));\n return;\n }\n const completion = pending.get(response.id);\n if (completion == null) {\n fail(new Error(\"Spawn helper returned an unknown request.\"));\n return;\n }\n pending.delete(response.id);\n if (\"error\" in response) {\n completion.reject(restoreSpawnError(response.error));\n } else {\n completion.resolve(response.observation);\n }\n releaseWhenIdle();\n });\n service.on(\"exit\", () => {\n // Failure waits for `disconnect`: buffered responses precede EOF.\n exited = true;\n settleWhenGone();\n });\n service.on(\"close\", (code, signal) => {\n exited = true;\n if (!closing || pending.size > 0) {\n fail(\n new Error(`Spawn helper closed (status ${code}, signal ${signal}).`),\n );\n }\n settleWhenGone();\n });\n return child;\n }\n\n return {\n async run(request) {\n if (failure != null) throw failure;\n if (closing) throw new Error(\"Spawn delegate is closed.\");\n const service = helper();\n service.ref();\n service.channel?.ref();\n const id = nextId++;\n return await new Promise((resolve, reject) => {\n pending.set(id, { resolve, reject });\n try {\n service.send(\n {\n id,\n request: {\n ...request,\n cwd: anchorCwd(request.cwd),\n environment: {\n variables: snapshotEnvironment(\n request.environment?.variables ?? process.env,\n ),\n },\n },\n },\n (error: Error | null) => {\n if (error != null) fail(error);\n },\n );\n } catch (error) {\n if (!(error instanceof Error)) throw error;\n fail(error);\n }\n });\n },\n async close() {\n closing = true;\n child?.ref();\n child?.channel?.ref();\n releaseWhenIdle();\n await closed;\n },\n };\n}\n"],"mappings":";;;;;;AAmDA,SAAS,oBACP,aACkC;CAElC,MAAM,WAAW,OAAO,OAAO,IAAI;CACnC,KAAK,MAAM,QAAQ,aAAa;EAC9B,MAAM,QAAQ,YAAY;EAC1B,IAAI,SAAS,MAAM,SAAS,QAAQ;CACtC;CACA,OAAO;AACT;;;;;;;AAQA,SAAS,UAAU,KAAqB;CACtC,IAAI,QAAQ,IAAI,OAAO,QAAQ,IAAI;CACnC,OAAO,WAAW,GAAG,IAAI,MAAM,GAAG,QAAQ,IAAI,IAAI,MAAM;AAC1D;;AASA,SAAgB,mBAAiC;CAC/C,MAAM,YAAY,OAAO,KAAK,IAAI,SAAS,KAAK,IAAI,OAAO;CAC3D,OAAO,KAAK,IAAI,IAAI,kBAAkB,aAAa,OAAO,KAAK,GAAG,GAAG,CAAC,GAAG;EACvE,K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H;EACA,MAAM,QAAQ;GACZ,UAAU;GACV,OAAO,IAAI;GACX,OAAO,SAAS,IAAI;GACpB,gBAAgB;GAChB,MAAM;EACR;CACF;AACF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { };
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { describeSpawnError, isClosedInputError, validateProcessStreams } from "./spawn-protocol.js";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
|
|
4
|
+
//#region src/spawn-helper.ts
|
|
5
|
+
const children = /* @__PURE__ */ new Set();
|
|
6
|
+
function disconnect() {
|
|
7
|
+
for (const child of children) child.kill("SIGKILL");
|
|
8
|
+
if (process.connected) process.disconnect();
|
|
9
|
+
}
|
|
10
|
+
function respond(response) {
|
|
11
|
+
if (!process.connected) return;
|
|
12
|
+
process.send?.(response, (error) => {
|
|
13
|
+
if (error != null) disconnect();
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
process.on("disconnect", disconnect);
|
|
17
|
+
process.on("message", ({ id, request }) => {
|
|
18
|
+
try {
|
|
19
|
+
validateProcessStreams(request);
|
|
20
|
+
const child = spawn(request.command, [...request.args], {
|
|
21
|
+
cwd: request.cwd,
|
|
22
|
+
env: request.environment?.variables,
|
|
23
|
+
stdio: [
|
|
24
|
+
request.input == null && request.inheritStdin ? "inherit" : "pipe",
|
|
25
|
+
request.inheritOutput ? "inherit" : "pipe",
|
|
26
|
+
request.inheritOutput ? "inherit" : "pipe"
|
|
27
|
+
]
|
|
28
|
+
});
|
|
29
|
+
children.add(child);
|
|
30
|
+
if (!request.inheritOutput && (child.stdout == null || child.stderr == null)) throw new Error("Process output pipes are unavailable.");
|
|
31
|
+
const stdout = [];
|
|
32
|
+
const stderr = [];
|
|
33
|
+
let failed = false;
|
|
34
|
+
child.stdout?.on("data", (chunk) => stdout.push(chunk));
|
|
35
|
+
child.stderr?.on("data", (chunk) => stderr.push(chunk));
|
|
36
|
+
child.stdin?.on("error", (error) => {
|
|
37
|
+
if (isClosedInputError(error)) return;
|
|
38
|
+
failed = true;
|
|
39
|
+
respond({
|
|
40
|
+
id,
|
|
41
|
+
error: describeSpawnError(error)
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
child.stdin?.end(request.input);
|
|
45
|
+
child.on("error", (error) => {
|
|
46
|
+
failed = true;
|
|
47
|
+
respond({
|
|
48
|
+
id,
|
|
49
|
+
error: describeSpawnError(error)
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
child.on("close", (code) => {
|
|
53
|
+
children.delete(child);
|
|
54
|
+
if (failed) return;
|
|
55
|
+
const observation = {
|
|
56
|
+
exitStatus: code ?? 1,
|
|
57
|
+
stderr: Buffer.concat(stderr).toString("utf8"),
|
|
58
|
+
stdout: Buffer.concat(stdout).toString("utf8")
|
|
59
|
+
};
|
|
60
|
+
respond({
|
|
61
|
+
id,
|
|
62
|
+
observation: request.captureBytes ? {
|
|
63
|
+
...observation,
|
|
64
|
+
stdoutBytes: new Uint8Array(Buffer.concat(stdout)),
|
|
65
|
+
stderrBytes: new Uint8Array(Buffer.concat(stderr))
|
|
66
|
+
} : observation
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
} catch (error) {
|
|
70
|
+
if (!(error instanceof Error)) throw error;
|
|
71
|
+
respond({
|
|
72
|
+
id,
|
|
73
|
+
error: describeSpawnError(error)
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
//#endregion
|
|
79
|
+
export { };
|
|
80
|
+
//# sourceMappingURL=spawn-helper.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"spawn-helper.js","names":[],"sources":["../src/spawn-helper.ts"],"sourcesContent":["/*\n * Oseo, an ahead-of-time compiler for JavaScript and TypeScript.\n * Copyright (C) 2026 Hong Minhee <https://hongminhee.org/>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <https://www.gnu.org/licenses/>.\n */\n\nimport { spawn } from \"node:child_process\";\nimport type { ChildProcess } from \"node:child_process\";\nimport {\n describeSpawnError,\n isClosedInputError,\n validateProcessStreams,\n} from \"./spawn-protocol.ts\";\nimport type { SpawnRequest, SpawnResponse } from \"./spawn-protocol.ts\";\n\n// This process deliberately imports no compiler implementation. Its small\n// address space, rather than a thread in the compiler, owns fork/exec work.\nconst children = new Set<ChildProcess>();\n\nfunction disconnect(): void {\n for (const child of children) child.kill(\"SIGKILL\");\n if (process.connected) process.disconnect();\n}\n\nfunction respond(response: SpawnResponse): void {\n if (!process.connected) return;\n process.send?.(response, (error: Error | null) => {\n if (error != null) disconnect();\n });\n}\n\nprocess.on(\"disconnect\", disconnect);\nprocess.on(\"message\", ({ id, request }: SpawnRequest) => {\n try {\n validateProcessStreams(request);\n // Keep the caller's process group: existing fixture timeout/interrupt\n // supervisors must still kill the helper, command, and descendants.\n const child = spawn(request.command, [...request.args], {\n cwd: request.cwd,\n env: request.environment?.variables,\n stdio: [\n request.input == null && request.inheritStdin ? \"inherit\" : \"pipe\",\n request.inheritOutput ? \"inherit\" : \"pipe\",\n request.inheritOutput ? \"inherit\" : \"pipe\",\n ],\n });\n children.add(child);\n if (\n !request.inheritOutput &&\n (child.stdout == null || child.stderr == null)\n ) {\n throw new Error(\"Process output pipes are unavailable.\");\n }\n const stdout: Uint8Array[] = [];\n const stderr: Uint8Array[] = [];\n let failed = false;\n child.stdout?.on(\"data\", (chunk: Uint8Array) => stdout.push(chunk));\n child.stderr?.on(\"data\", (chunk: Uint8Array) => stderr.push(chunk));\n child.stdin?.on(\"error\", (error: NodeJS.ErrnoException) => {\n if (isClosedInputError(error)) return;\n failed = true;\n respond({ id, error: describeSpawnError(error) });\n });\n child.stdin?.end(request.input);\n child.on(\"error\", (error) => {\n failed = true;\n respond({ id, error: describeSpawnError(error) });\n });\n child.on(\"close\", (code) => {\n children.delete(child);\n if (failed) return;\n const observation = {\n exitStatus: code ?? 1,\n stderr: Buffer.concat(stderr).toString(\"utf8\"),\n stdout: Buffer.concat(stdout).toString(\"utf8\"),\n };\n respond({\n id,\n observation: request.captureBytes\n ? {\n ...observation,\n stdoutBytes: new Uint8Array(Buffer.concat(stdout)),\n stderrBytes: new Uint8Array(Buffer.concat(stderr)),\n }\n : observation,\n });\n });\n } catch (error) {\n if (!(error instanceof Error)) throw error;\n respond({ id, error: describeSpawnError(error) });\n }\n});\n"],"mappings":";;;;AA6BA,MAAM,2BAAW,IAAI,IAAkB;AAEvC,SAAS,aAAmB;CAC1B,KAAK,MAAM,SAAS,UAAU,MAAM,KAAK,SAAS;CAClD,IAAI,QAAQ,WAAW,QAAQ,WAAW;AAC5C;AAEA,SAAS,QAAQ,UAA+B;CAC9C,IAAI,CAAC,QAAQ,WAAW;CACxB,QAAQ,OAAO,WAAW,UAAwB;EAChD,IAAI,SAAS,MAAM,WAAW;CAChC,CAAC;AACH;AAEA,QAAQ,GAAG,cAAc,UAAU;AACnC,QAAQ,GAAG,YAAY,EAAE,IAAI,cAA4B;CACvD,IAAI;EACF,uBAAuB,OAAO;EAG9B,MAAM,QAAQ,MAAM,QAAQ,SAAS,CAAC,GAAG,QAAQ,IAAI,GAAG;GACtD,KAAK,QAAQ;GACb,KAAK,QAAQ,aAAa;GAC1B,OAAO;IACL,QAAQ,SAAS,QAAQ,QAAQ,eAAe,YAAY;IAC5D,QAAQ,gBAAgB,YAAY;IACpC,QAAQ,gBAAgB,YAAY;GACtC;EACF,CAAC;EACD,SAAS,IAAI,KAAK;EAClB,IACE,CAAC,QAAQ,kBACR,MAAM,UAAU,QAAQ,MAAM,UAAU,OAEzC,MAAM,IAAI,MAAM,uCAAuC;EAEzD,MAAM,SAAuB,CAAC;EAC9B,MAAM,SAAuB,CAAC;EAC9B,IAAI,SAAS;EACb,MAAM,QAAQ,GAAG,SAAS,UAAsB,OAAO,KAAK,KAAK,CAAC;EAClE,MAAM,QAAQ,GAAG,SAAS,UAAsB,OAAO,KAAK,KAAK,CAAC;EAClE,MAAM,OAAO,GAAG,UAAU,UAAiC;GACzD,IAAI,mBAAmB,KAAK,GAAG;GAC/B,SAAS;GACT,QAAQ;IAAE;IAAI,OAAO,mBAAmB,KAAK;GAAE,CAAC;EAClD,CAAC;EACD,MAAM,OAAO,IAAI,QAAQ,KAAK;EAC9B,MAAM,GAAG,UAAU,UAAU;GAC3B,SAAS;GACT,QAAQ;IAAE;IAAI,OAAO,mBAAmB,KAAK;GAAE,CAAC;EAClD,CAAC;EACD,MAAM,GAAG,UAAU,SAAS;GAC1B,SAAS,OAAO,KAAK;GACrB,IAAI,QAAQ;GACZ,MAAM,cAAc;IAClB,YAAY,QAAQ;IACpB,QAAQ,OAAO,OAAO,MAAM,CAAC,CAAC,SAAS,MAAM;IAC7C,QAAQ,OAAO,OAAO,MAAM,CAAC,CAAC,SAAS,MAAM;GAC/C;GACA,QAAQ;IACN;IACA,aAAa,QAAQ,eACjB;KACE,GAAG;KACH,aAAa,IAAI,WAAW,OAAO,OAAO,MAAM,CAAC;KACjD,aAAa,IAAI,WAAW,OAAO,OAAO,MAAM,CAAC;IACnD,IACA;GACN,CAAC;EACH,CAAC;CACH,SAAS,OAAO;EACd,IAAI,EAAE,iBAAiB,QAAQ,MAAM;EACrC,QAAQ;GAAE;GAAI,OAAO,mBAAmB,KAAK;EAAE,CAAC;CAClD;AACF,CAAC"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { ProcessObservation, ProcessRequest } from "@oseo/compiler";
|
|
2
|
+
//#region src/spawn-protocol.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* A request owns its environment snapshot, even when the parent changes it.
|
|
5
|
+
* It carries no umask: commands inherit the umask the helper started with,
|
|
6
|
+
* because reading it in Node briefly sets the process-wide umask to zero.
|
|
7
|
+
*/
|
|
8
|
+
interface SpawnRequest {
|
|
9
|
+
readonly id: number;
|
|
10
|
+
readonly request: ProcessRequest;
|
|
11
|
+
}
|
|
12
|
+
/** Preserve the observable fields of Node's spawn and argument errors. */
|
|
13
|
+
interface SpawnError {
|
|
14
|
+
readonly name: string;
|
|
15
|
+
readonly message: string;
|
|
16
|
+
readonly stack?: string | undefined;
|
|
17
|
+
readonly code?: string | undefined;
|
|
18
|
+
readonly errno?: number | undefined;
|
|
19
|
+
readonly syscall?: string | undefined;
|
|
20
|
+
readonly path?: string | undefined;
|
|
21
|
+
readonly spawnargs?: readonly string[] | undefined;
|
|
22
|
+
}
|
|
23
|
+
/** Respond after child exit and closure of any captured output pipes. */
|
|
24
|
+
type SpawnResponse = {
|
|
25
|
+
readonly id: number;
|
|
26
|
+
readonly observation: ProcessObservation;
|
|
27
|
+
} | {
|
|
28
|
+
readonly id: number;
|
|
29
|
+
readonly error: SpawnError;
|
|
30
|
+
};
|
|
31
|
+
/** Reject malformed IPC before accessing a completion or resolving callers. */
|
|
32
|
+
declare function isSpawnResponse<T>(value: T): value is T & SpawnResponse;
|
|
33
|
+
/** Copy error metadata across IPC without losing Node's error codes. */
|
|
34
|
+
declare function describeSpawnError(error: Error): SpawnError;
|
|
35
|
+
/** Rebuild the rejection that direct spawn would expose to the caller. */
|
|
36
|
+
declare function restoreSpawnError(details: SpawnError): Error;
|
|
37
|
+
/**
|
|
38
|
+
* Recognize the input pipe error of a command that exited before reading
|
|
39
|
+
* all of its input. POSIX reports the closed pipe as EPIPE. Node.js on
|
|
40
|
+
* Windows reports the same write as EOF.
|
|
41
|
+
*/
|
|
42
|
+
declare function isClosedInputError(error: NodeJS.ErrnoException): boolean;
|
|
43
|
+
/** Reject contradictory stream ownership before starting a command. */
|
|
44
|
+
declare function validateProcessStreams(request: ProcessRequest): void;
|
|
45
|
+
//#endregion
|
|
46
|
+
export { SpawnError, SpawnRequest, SpawnResponse, describeSpawnError, isClosedInputError, isSpawnResponse, restoreSpawnError, validateProcessStreams };
|
|
47
|
+
//# sourceMappingURL=spawn-protocol.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"spawn-protocol.d.ts","names":[],"sources":["../src/spawn-protocol.ts"],"mappings":";;;;;;;UAyBiB;WACN;WACA,SAAS;;;UAIH;WACN;WACA;WACA;WACA;WACA;WACA;WACA;WACA;;;KAIC;WACG;WAAqB,aAAa;;WAClC;WAAqB,OAAO;;;iBAG3B,gBAAgB,GAAG,OAAO,IAAI,SAAS,IAAI;;iBAsC3C,mBAAmB,OAAO,QAAQ;;iBAoBlC,kBAAkB,SAAS,aAAa;;;;;;iBAyBxC,mBAAmB,OAAO,OAAO;;iBAQjC,uBAAuB,SAAS"}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
//#region src/spawn-protocol.ts
|
|
2
|
+
/** Reject malformed IPC before accessing a completion or resolving callers. */
|
|
3
|
+
function isSpawnResponse(value) {
|
|
4
|
+
if (value == null || typeof value !== "object" || !("id" in value) || !Number.isSafeInteger(value.id)) return false;
|
|
5
|
+
if ("error" in value) {
|
|
6
|
+
const error = value.error;
|
|
7
|
+
return error != null && typeof error === "object" && "name" in error && typeof error.name === "string" && "message" in error && typeof error.message === "string";
|
|
8
|
+
}
|
|
9
|
+
if (!("observation" in value)) return false;
|
|
10
|
+
const observation = value.observation;
|
|
11
|
+
return observation != null && typeof observation === "object" && "exitStatus" in observation && Number.isInteger(observation.exitStatus) && "stdout" in observation && typeof observation.stdout === "string" && "stderr" in observation && typeof observation.stderr === "string" && (!("stdoutBytes" in observation) || observation.stdoutBytes instanceof Uint8Array) && (!("stderrBytes" in observation) || observation.stderrBytes instanceof Uint8Array);
|
|
12
|
+
}
|
|
13
|
+
/** Copy error metadata across IPC without losing Node's error codes. */
|
|
14
|
+
function describeSpawnError(error) {
|
|
15
|
+
const details = error;
|
|
16
|
+
return {
|
|
17
|
+
name: error.name,
|
|
18
|
+
message: error.message,
|
|
19
|
+
stack: error.stack,
|
|
20
|
+
code: details.code,
|
|
21
|
+
errno: details.errno,
|
|
22
|
+
syscall: details.syscall,
|
|
23
|
+
path: details.path,
|
|
24
|
+
spawnargs: details.spawnargs
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/** Rebuild the rejection that direct spawn would expose to the caller. */
|
|
28
|
+
function restoreSpawnError(details) {
|
|
29
|
+
const error = details.name === "TypeError" ? new TypeError(details.message) : details.name === "RangeError" ? new RangeError(details.message) : new Error(details.message);
|
|
30
|
+
for (const [key, value] of Object.entries(details)) {
|
|
31
|
+
if (key === "name" && value === error.name) continue;
|
|
32
|
+
if (value !== void 0) Object.defineProperty(error, key, {
|
|
33
|
+
configurable: true,
|
|
34
|
+
enumerable: key !== "message" && key !== "stack",
|
|
35
|
+
value,
|
|
36
|
+
writable: true
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
return error;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Recognize the input pipe error of a command that exited before reading
|
|
43
|
+
* all of its input. POSIX reports the closed pipe as EPIPE. Node.js on
|
|
44
|
+
* Windows reports the same write as EOF.
|
|
45
|
+
*/
|
|
46
|
+
function isClosedInputError(error) {
|
|
47
|
+
return error.code === "EPIPE" || error.code === "EOF" && error.syscall === "write";
|
|
48
|
+
}
|
|
49
|
+
/** Reject contradictory stream ownership before starting a command. */
|
|
50
|
+
function validateProcessStreams(request) {
|
|
51
|
+
if (request.inheritStdin && request.input != null) throw new TypeError("Process input cannot also inherit stdin.");
|
|
52
|
+
if (request.inheritOutput && request.captureBytes) throw new TypeError("Inherited process output cannot also capture bytes.");
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
//#endregion
|
|
56
|
+
export { describeSpawnError, isClosedInputError, isSpawnResponse, restoreSpawnError, validateProcessStreams };
|
|
57
|
+
//# sourceMappingURL=spawn-protocol.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"spawn-protocol.js","names":[],"sources":["../src/spawn-protocol.ts"],"sourcesContent":["/*\n * Oseo, an ahead-of-time compiler for JavaScript and TypeScript.\n * Copyright (C) 2026 Hong Minhee <https://hongminhee.org/>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <https://www.gnu.org/licenses/>.\n */\n\nimport type { ProcessObservation, ProcessRequest } from \"@oseo/compiler\";\n\n/**\n * A request owns its environment snapshot, even when the parent changes it.\n * It carries no umask: commands inherit the umask the helper started with,\n * because reading it in Node briefly sets the process-wide umask to zero.\n */\nexport interface SpawnRequest {\n readonly id: number;\n readonly request: ProcessRequest;\n}\n\n/** Preserve the observable fields of Node's spawn and argument errors. */\nexport interface SpawnError {\n readonly name: string;\n readonly message: string;\n readonly stack?: string | undefined;\n readonly code?: string | undefined;\n readonly errno?: number | undefined;\n readonly syscall?: string | undefined;\n readonly path?: string | undefined;\n readonly spawnargs?: readonly string[] | undefined;\n}\n\n/** Respond after child exit and closure of any captured output pipes. */\nexport type SpawnResponse =\n | { readonly id: number; readonly observation: ProcessObservation }\n | { readonly id: number; readonly error: SpawnError };\n\n/** Reject malformed IPC before accessing a completion or resolving callers. */\nexport function isSpawnResponse<T>(value: T): value is T & SpawnResponse {\n if (\n value == null ||\n typeof value !== \"object\" ||\n !(\"id\" in value) ||\n !Number.isSafeInteger(value.id)\n )\n return false;\n if (\"error\" in value) {\n const error = value.error;\n return (\n error != null &&\n typeof error === \"object\" &&\n \"name\" in error &&\n typeof error.name === \"string\" &&\n \"message\" in error &&\n typeof error.message === \"string\"\n );\n }\n if (!(\"observation\" in value)) return false;\n const observation = value.observation;\n return (\n observation != null &&\n typeof observation === \"object\" &&\n \"exitStatus\" in observation &&\n Number.isInteger(observation.exitStatus) &&\n \"stdout\" in observation &&\n typeof observation.stdout === \"string\" &&\n \"stderr\" in observation &&\n typeof observation.stderr === \"string\" &&\n (!(\"stdoutBytes\" in observation) ||\n observation.stdoutBytes instanceof Uint8Array) &&\n (!(\"stderrBytes\" in observation) ||\n observation.stderrBytes instanceof Uint8Array)\n );\n}\n\n/** Copy error metadata across IPC without losing Node's error codes. */\nexport function describeSpawnError(error: Error): SpawnError {\n // SAFETY: Node adds optional spawn metadata to ordinary Error instances.\n const details = error as Error &\n NodeJS.ErrnoException & {\n readonly spawnargs?: readonly string[];\n readonly path?: string;\n };\n return {\n name: error.name,\n message: error.message,\n stack: error.stack,\n code: details.code,\n errno: details.errno,\n syscall: details.syscall,\n path: details.path,\n spawnargs: details.spawnargs,\n };\n}\n\n/** Rebuild the rejection that direct spawn would expose to the caller. */\nexport function restoreSpawnError(details: SpawnError): Error {\n const error =\n details.name === \"TypeError\"\n ? new TypeError(details.message)\n : details.name === \"RangeError\"\n ? new RangeError(details.message)\n : new Error(details.message);\n for (const [key, value] of Object.entries(details)) {\n if (key === \"name\" && value === error.name) continue;\n if (value !== undefined)\n Object.defineProperty(error, key, {\n configurable: true,\n enumerable: key !== \"message\" && key !== \"stack\",\n value,\n writable: true,\n });\n }\n return error;\n}\n\n/**\n * Recognize the input pipe error of a command that exited before reading\n * all of its input. POSIX reports the closed pipe as EPIPE. Node.js on\n * Windows reports the same write as EOF.\n */\nexport function isClosedInputError(error: NodeJS.ErrnoException): boolean {\n return (\n error.code === \"EPIPE\" ||\n (error.code === \"EOF\" && error.syscall === \"write\")\n );\n}\n\n/** Reject contradictory stream ownership before starting a command. */\nexport function validateProcessStreams(request: ProcessRequest): void {\n if (request.inheritStdin && request.input != null) {\n throw new TypeError(\"Process input cannot also inherit stdin.\");\n }\n if (request.inheritOutput && request.captureBytes) {\n throw new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