@oseo/host 0.0.0-stage → 0.1.0-canary.0

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 CHANGED
@@ -1,3 +1,93 @@
1
- # Temporary Holding Version
1
+ @oseo/host
2
+ ==========
2
3
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
4
+ This package adapts filesystem, temporary-directory, and subprocess operations
5
+ for Node.js and Deno. Compiler-core code consumes only the host-neutral
6
+ interface. Both hosts canonicalize file module identities and share a relative
7
+ `file:` resolver, content hashing, and owned loader diagnostics.
8
+
9
+ The file loader identifies dependencies with a *.json* pathname as JSON
10
+ modules and other files as JavaScript modules. It retains their original
11
+ bytes and digest. The compiler validates static `type: "json"` requests
12
+ against that module kind before canonical identity deduplication; the host
13
+ does not parse JSON or execute dynamic import options.
14
+
15
+ Node.js and Deno adapters also normalize their runtime operating-system and
16
+ architecture spellings into an execution-host description. Unknown values stay
17
+ explicitly unknown so the composition root can reject unsupported native
18
+ execution without inheriting an ambient toolchain target.
19
+
20
+ The host also owns optional persistent compiler-cache storage. Linux uses
21
+ `XDG_CACHE_HOME`, falling back to *~/.cache*, and macOS uses
22
+ *~/Library/Caches*. Cache clients receive an existing namespaced directory,
23
+ nonempty regular-file checks, per-artifact exclusive leases, and atomic
24
+ publication.
25
+
26
+ The selected root is resolved to an absolute normalized path, so clients and
27
+ toolchain subprocesses observe the same archive from different working
28
+ directories. Namespace names must be portable leaf names other than `.` and
29
+ `..`, so clients cannot escape the Oseo-owned directory.
30
+
31
+ A lease serializes the lookup-through-publication interval for concurrent cold
32
+ callers. Owner tokens make release ownership-safe, and an expiration time lets
33
+ a later caller reclaim a lease abandoned by an interrupted process. An active
34
+ owner renews that time.
35
+
36
+ Release and reclamation atomically rename the exact observed state file, then
37
+ move the complete lock directory to a unique disposal path before deletion. An
38
+ exclusive state file also protects the interval before initial owner
39
+ publication, so an earlier owner or concurrent reclaimer cannot target a
40
+ replacement lease. Renewal overwrites only the already-claimed state file and
41
+ cannot recreate it in a replacement directory.
42
+
43
+ The host selects the location and lifetime. An injected host may omit cache
44
+ support or reject an unavailable operation and keep the caller on its uncached
45
+ path.
46
+
47
+ Content-addressed archives remain until the operating system or user removes
48
+ the Oseo cache namespace. There is no automatic age or count pruning. Removing
49
+ that namespace is safe; the next native workflow rebuilds its archive.
50
+
51
+ Toolchains declare the host variables they permit their subprocesses to
52
+ inherit. A capable host captures those variables once, and every process request
53
+ in that workflow receives the same immutable snapshot. Unlisted ambient
54
+ compiler settings cannot leak across the toolchain boundary. A Deno host
55
+ without `--allow-env` reports snapshot capture as unavailable; the caller
56
+ disables cache reuse and process requests retain ordinary child inheritance.
57
+
58
+ Node hosts may opt into `createNodeHost({ delegateSpawns: true })`. One lazy,
59
+ reusable Node process then spawns commands and collects their output. The
60
+ helper imports no compiler implementation, so repeated forks do not copy the
61
+ compiler's address space. The product CLI keeps direct spawning by default.
62
+ `await host.close()` drains accepted requests and closes the helper. Idle
63
+ helpers do not keep the parent alive, and process exit disconnects their IPC.
64
+
65
+ Delegated requests capture the caller's current environment and absolute working
66
+ directory. Commands inherit the umask the helper started with; reading the
67
+ umask in Node briefly sets it to zero for the whole process, which would race
68
+ with other threads. Output is decoded once after each pipe closes, just as in
69
+ the direct host. Signal termination retains the host's existing status mapping
70
+ (`null` becomes `1`). Spawn errors retain Node's error codes and command
71
+ metadata. Transport failure rejects outstanding and future requests; commands
72
+ are never replayed after an uncertain failure.
73
+
74
+ The helper and its commands retain the caller's process group. Existing fixture
75
+ supervisors must continue to signal that group for timeout and descendant
76
+ cleanup. The host API adds no timeout or cancellation protocol. Disconnect
77
+ cleanup kills direct commands; arbitrary helper loss alone does not guarantee
78
+ termination of descendants that outlive their direct parent.
79
+
80
+ `createExecutablePublisher()` supplies retained-executable publication outside
81
+ `CompilerHost`. Its Node.js-compatible filesystem operations run under both
82
+ Node.js and Deno. Call `inspect(destination, protectedPaths)` before native
83
+ compilation, retaining the returned destination identity, then call
84
+ `publish(linkedPath, destination)` after a successful link. Protected paths
85
+ include the source and every module in its closed graph.
86
+
87
+ Inspection refuses missing parents, non-executables, symlinks, and graph-source
88
+ aliases. Publication preserves linker bytes and mode bits, rechecks replacement
89
+ identity, and stages in the destination directory so readers never see partial
90
+ bytes. [ADR 0037] specifies hard-link fallback, concurrent replacement windows,
91
+ and cleanup errors. This API adds no crash-durability guarantee.
92
+
93
+ [ADR 0037]: ../../docs/adr/0037-retained-native-executables.md
@@ -0,0 +1,35 @@
1
+ //#region src/cache-files.d.ts
2
+ interface DenoExistingTextFileWriter {
3
+ writeTextFile(path: string, contents: string, options: {
4
+ readonly create: false;
5
+ }): Promise<void>;
6
+ }
7
+ interface CacheLockDirectoryRenameOptions {
8
+ readonly deadlineMilliseconds: number;
9
+ readonly retryPermissionErrors: boolean;
10
+ }
11
+ /**
12
+ * Rename a claimed cache-lock directory across host sharing semantics.
13
+ *
14
+ * Windows can reject a directory rename while another waiter briefly
15
+ * enumerates it. The claimed state file remains the ownership fence while
16
+ * retrying, so no other caller can publish through the same lease.
17
+ */
18
+ declare function renameClaimedCacheLockDirectory(rename: (fromPath: string, toPath: string) => Promise<void>, fromPath: string, toPath: string, options: CacheLockDirectoryRenameOptions): Promise<void>;
19
+ /**
20
+ * Overwrite an existing Node.js cache state file without recreating it.
21
+ *
22
+ * A missing path means that another process replaced the cache lock directory,
23
+ * so recreating the state file would let a stale owner join the replacement.
24
+ */
25
+ declare function overwriteExistingNodeTextFile(path: string, contents: string): Promise<void>;
26
+ /**
27
+ * Overwrite an existing Deno cache state file without recreating it.
28
+ *
29
+ * This mirrors the Node.js claim rule while keeping Deno filesystem behavior
30
+ * behind the host adapter's narrow runtime interface.
31
+ */
32
+ declare function overwriteExistingDenoTextFile(runtime: DenoExistingTextFileWriter, path: string, contents: string): Promise<void>;
33
+ //#endregion
34
+ export { overwriteExistingDenoTextFile, overwriteExistingNodeTextFile, renameClaimedCacheLockDirectory };
35
+ //# sourceMappingURL=cache-files.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache-files.d.ts","names":[],"sources":["../src/cache-files.ts"],"mappings":";UAAU;EACR,cACE,cACA,kBACA;aAAoB;MACnB;;UAmBK;WACC;WACA;;;;;;;;;iBAUW,gCACpB,SAAS,kBAAkB,mBAAmB,eAC9C,kBACA,gBACA,SAAS,kCACR;;;;;;;iBA8BmB,8BACpB,cACA,mBACC;;;;;;;iBAiBmB,8BACpB,SAAS,4BACT,cACA,mBACC"}
@@ -0,0 +1,50 @@
1
+ //#region src/cache-files.ts
2
+ const cacheLockRenameRetryMilliseconds = 5;
3
+ function isTransientDirectoryRenameError(cause, retryPermissionErrors) {
4
+ return cause instanceof Error && "code" in cause && (retryPermissionErrors && (cause.code === "EACCES" || cause.code === "EPERM") || cause.code === "EBUSY" || cause.code === "ENOTEMPTY");
5
+ }
6
+ /**
7
+ * Rename a claimed cache-lock directory across host sharing semantics.
8
+ *
9
+ * Windows can reject a directory rename while another waiter briefly
10
+ * enumerates it. The claimed state file remains the ownership fence while
11
+ * retrying, so no other caller can publish through the same lease.
12
+ */
13
+ async function renameClaimedCacheLockDirectory(rename, fromPath, toPath, options) {
14
+ while (true) try {
15
+ await rename(fromPath, toPath);
16
+ return;
17
+ } catch (error) {
18
+ if (!isTransientDirectoryRenameError(error, options.retryPermissionErrors) || Date.now() >= options.deadlineMilliseconds) throw error;
19
+ await new Promise((resolve) => setTimeout(resolve, cacheLockRenameRetryMilliseconds));
20
+ }
21
+ }
22
+ /**
23
+ * Overwrite an existing Node.js cache state file without recreating it.
24
+ *
25
+ * A missing path means that another process replaced the cache lock directory,
26
+ * so recreating the state file would let a stale owner join the replacement.
27
+ */
28
+ async function overwriteExistingNodeTextFile(path, contents) {
29
+ const { open } = await import("node:fs/promises");
30
+ const file = await open(path, "r+");
31
+ try {
32
+ await file.truncate(0);
33
+ await file.writeFile(contents);
34
+ } finally {
35
+ await file.close();
36
+ }
37
+ }
38
+ /**
39
+ * Overwrite an existing Deno cache state file without recreating it.
40
+ *
41
+ * This mirrors the Node.js claim rule while keeping Deno filesystem behavior
42
+ * behind the host adapter's narrow runtime interface.
43
+ */
44
+ async function overwriteExistingDenoTextFile(runtime, path, contents) {
45
+ await runtime.writeTextFile(path, contents, { create: false });
46
+ }
47
+
48
+ //#endregion
49
+ export { overwriteExistingDenoTextFile, overwriteExistingNodeTextFile, renameClaimedCacheLockDirectory };
50
+ //# sourceMappingURL=cache-files.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache-files.js","names":[],"sources":["../src/cache-files.ts"],"sourcesContent":["interface DenoExistingTextFileWriter {\n writeTextFile(\n path: string,\n contents: string,\n options: { readonly create: false },\n ): Promise<void>;\n}\n\nconst cacheLockRenameRetryMilliseconds = 5;\n\nfunction isTransientDirectoryRenameError(\n cause: unknown,\n retryPermissionErrors: boolean,\n): boolean {\n return (\n cause instanceof Error &&\n \"code\" in cause &&\n ((retryPermissionErrors &&\n (cause.code === \"EACCES\" || cause.code === \"EPERM\")) ||\n cause.code === \"EBUSY\" ||\n cause.code === \"ENOTEMPTY\")\n );\n}\n\ninterface CacheLockDirectoryRenameOptions {\n readonly deadlineMilliseconds: number;\n readonly retryPermissionErrors: boolean;\n}\n\n/**\n * Rename a claimed cache-lock directory across host sharing semantics.\n *\n * Windows can reject a directory rename while another waiter briefly\n * enumerates it. The claimed state file remains the ownership fence while\n * retrying, so no other caller can publish through the same lease.\n */\nexport async function renameClaimedCacheLockDirectory(\n rename: (fromPath: string, toPath: string) => Promise<void>,\n fromPath: string,\n toPath: string,\n options: CacheLockDirectoryRenameOptions,\n): Promise<void> {\n /* eslint-disable no-await-in-loop -- Rename attempts retain one claim. */\n while (true) {\n try {\n await rename(fromPath, toPath);\n return;\n } catch (error) {\n if (\n !isTransientDirectoryRenameError(\n error,\n options.retryPermissionErrors,\n ) ||\n Date.now() >= options.deadlineMilliseconds\n ) {\n throw error;\n }\n await new Promise((resolve) =>\n setTimeout(resolve, cacheLockRenameRetryMilliseconds),\n );\n }\n }\n /* eslint-enable no-await-in-loop */\n}\n\n/**\n * Overwrite an existing Node.js cache state file without recreating it.\n *\n * A missing path means that another process replaced the cache lock directory,\n * so recreating the state file would let a stale owner join the replacement.\n */\nexport async function overwriteExistingNodeTextFile(\n path: string,\n contents: string,\n): Promise<void> {\n const { open } = await import(\"node:fs/promises\");\n const file = await open(path, \"r+\");\n try {\n await file.truncate(0);\n await file.writeFile(contents);\n } finally {\n await file.close();\n }\n}\n\n/**\n * Overwrite an existing Deno cache state file without recreating it.\n *\n * This mirrors the Node.js claim rule while keeping Deno filesystem behavior\n * behind the host adapter's narrow runtime interface.\n */\nexport async function overwriteExistingDenoTextFile(\n runtime: DenoExistingTextFileWriter,\n path: string,\n contents: string,\n): Promise<void> {\n await runtime.writeTextFile(path, contents, { create: false });\n}\n"],"mappings":";AAQA,MAAM,mCAAmC;AAEzC,SAAS,gCACP,OACA,uBACS;CACT,OACE,iBAAiB,SACjB,UAAU,UACR,0BACC,MAAM,SAAS,YAAY,MAAM,SAAS,YAC3C,MAAM,SAAS,WACf,MAAM,SAAS;AAErB;;;;;;;;AAcA,eAAsB,gCACpB,QACA,UACA,QACA,SACe;CAEf,OAAO,MACL,IAAI;EACF,MAAM,OAAO,UAAU,MAAM;EAC7B;CACF,SAAS,OAAO;EACd,IACE,CAAC,gCACC,OACA,QAAQ,qBACV,KACA,KAAK,IAAI,KAAK,QAAQ,sBAEtB,MAAM;EAER,MAAM,IAAI,SAAS,YACjB,WAAW,SAAS,gCAAgC,CACtD;CACF;AAGJ;;;;;;;AAQA,eAAsB,8BACpB,MACA,UACe;CACf,MAAM,EAAE,SAAS,MAAM,OAAO;CAC9B,MAAM,OAAO,MAAM,KAAK,MAAM,IAAI;CAClC,IAAI;EACF,MAAM,KAAK,SAAS,CAAC;EACrB,MAAM,KAAK,UAAU,QAAQ;CAC/B,UAAU;EACR,MAAM,KAAK,MAAM;CACnB;AACF;;;;;;;AAQA,eAAsB,8BACpB,SACA,MACA,UACe;CACf,MAAM,QAAQ,cAAc,MAAM,UAAU,EAAE,QAAQ,MAAM,CAAC;AAC/D"}
@@ -0,0 +1,35 @@
1
+ import { chmod, copyFile, link, rename, unlink } from "node:fs/promises";
2
+ //#region src/executable-publication.d.ts
3
+ /** Identity retained between destination inspection and publication. */
4
+ interface ExecutableDestination {
5
+ readonly path: string;
6
+ readonly protectedPaths: readonly string[];
7
+ readonly existing?: {
8
+ readonly device: bigint;
9
+ readonly inode: bigint;
10
+ };
11
+ }
12
+ /** Filesystem publication boundary shared by both compiler hosts. */
13
+ interface ExecutablePublisher {
14
+ /** Validate the parent, replacement kind, and source graph before linking. */
15
+ inspect(destination: string, protectedPaths: readonly string[]): Promise<ExecutableDestination>;
16
+ /** Publish unchanged linker bytes under ADR 0037's replacement rules. */
17
+ publish(linkedPath: string, destination: ExecutableDestination): Promise<void>;
18
+ }
19
+ /**
20
+ * Create ADR 0037 publication operations using Node.js-compatible filesystem
21
+ * APIs, supported unchanged by Node.js and Deno. CompilerHost stays narrow.
22
+ */
23
+ declare function createExecutablePublisher(): ExecutablePublisher;
24
+ interface PublicationFiles {
25
+ readonly chmod: typeof chmod;
26
+ readonly copyFile: typeof copyFile;
27
+ readonly link: typeof link;
28
+ readonly rename: typeof rename;
29
+ readonly unlink: typeof unlink;
30
+ }
31
+ /** Internal fault-injection boundary for publication failure tests. */
32
+ declare function createPublicationWithFiles(overrides?: Partial<PublicationFiles>): ExecutablePublisher;
33
+ //#endregion
34
+ export { ExecutableDestination, ExecutablePublisher, createExecutablePublisher, createPublicationWithFiles };
35
+ //# sourceMappingURL=executable-publication.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"executable-publication.d.ts","names":[],"sources":["../src/executable-publication.ts"],"mappings":";;;UAgBiB;WACN;WACA;WACA;aACE;aACA;;;;UAKI;;EAEf,QACE,qBACA,oCACC,QAAQ;;EAEX,QACE,oBACA,aAAa,wBACZ;;;;;;iBA4GW,6BAA6B;UAInC;WACC,cAAc;WACd,iBAAiB;WACjB,aAAa;WACb,eAAe;WACf,eAAe;;;iBAIV,2BACd,YAAW,QAAQ,oBAClB"}
@@ -0,0 +1,133 @@
1
+ import { chmod, copyFile, link, lstat, open, realpath, rename, stat, unlink } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ import { basename, dirname, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ //#region src/executable-publication.ts
7
+ function errorCode(error) {
8
+ if (!("code" in error)) return void 0;
9
+ const code = error.code;
10
+ return code === "ENOENT" || code === "EPERM" || code === "ENOTSUP" ? code : void 0;
11
+ }
12
+ function filesystemPath(path) {
13
+ return /^file:/iu.test(path) ? fileURLToPath(path) : path;
14
+ }
15
+ function refusal(path, reason) {
16
+ return /* @__PURE__ */ new Error(`Cannot publish '${path}': ${reason}; choose --output.`);
17
+ }
18
+ async function inspectDestination(destination, protectedPaths) {
19
+ const path = resolve(destination);
20
+ if (!(await stat(dirname(path))).isDirectory()) throw refusal(path, "the parent is not a directory");
21
+ let existing;
22
+ try {
23
+ existing = await lstat(path, { bigint: true });
24
+ } catch (error) {
25
+ if (!(error instanceof Error) || errorCode(error) !== "ENOENT") throw error;
26
+ }
27
+ if (existing == null) return {
28
+ path,
29
+ protectedPaths
30
+ };
31
+ if (!existing.isFile()) throw refusal(path, "the destination is not a regular file");
32
+ const canonicalPath = await realpath(path);
33
+ for (const protectedPath of protectedPaths) {
34
+ let canonicalProtectedPath;
35
+ try {
36
+ canonicalProtectedPath = await realpath(filesystemPath(protectedPath));
37
+ } catch (error) {
38
+ if (!(error instanceof Error) || errorCode(error) !== "ENOENT") throw error;
39
+ canonicalProtectedPath = resolve(filesystemPath(protectedPath));
40
+ }
41
+ if (canonicalPath === canonicalProtectedPath) throw refusal(path, "the destination is a source in the build graph");
42
+ }
43
+ const file = await open(path, "r");
44
+ const bytes = /* @__PURE__ */ new Uint8Array(4);
45
+ try {
46
+ await file.read(bytes, 0, 4, 0);
47
+ } finally {
48
+ await file.close();
49
+ }
50
+ const magic = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
51
+ if (![
52
+ "7f454c46",
53
+ "feedface",
54
+ "cefaedfe",
55
+ "feedfacf",
56
+ "cffaedfe",
57
+ "cafebabe",
58
+ "bebafeca",
59
+ "cafebabf",
60
+ "bfbafeca"
61
+ ].includes(magic)) throw refusal(path, "the destination is not an ELF or Mach-O file");
62
+ return {
63
+ existing: {
64
+ device: existing.dev,
65
+ inode: existing.ino
66
+ },
67
+ path,
68
+ protectedPaths
69
+ };
70
+ }
71
+ async function requireUnchangedDestination(destination) {
72
+ const current = await inspectDestination(destination.path, destination.protectedPaths);
73
+ if (current.existing?.device !== destination.existing?.device || current.existing?.inode !== destination.existing?.inode) throw refusal(destination.path, "the destination changed during the build");
74
+ }
75
+ /**
76
+ * Create ADR 0037 publication operations using Node.js-compatible filesystem
77
+ * APIs, supported unchanged by Node.js and Deno. CompilerHost stays narrow.
78
+ */
79
+ function createExecutablePublisher() {
80
+ return createPublicationWithFiles();
81
+ }
82
+ /** Internal fault-injection boundary for publication failure tests. */
83
+ function createPublicationWithFiles(overrides = {}) {
84
+ const files = {
85
+ chmod,
86
+ copyFile,
87
+ link,
88
+ rename,
89
+ unlink,
90
+ ...overrides
91
+ };
92
+ return {
93
+ inspect: inspectDestination,
94
+ async publish(linkedPath, destination) {
95
+ const temporaryPath = resolve(dirname(destination.path), `.${basename(destination.path)}.oseo-${randomUUID()}.tmp`);
96
+ let copied = false;
97
+ let failure;
98
+ try {
99
+ const reserved = await open(temporaryPath, "wx");
100
+ copied = true;
101
+ await reserved.close();
102
+ await files.copyFile(linkedPath, temporaryPath);
103
+ await files.chmod(temporaryPath, (await stat(linkedPath)).mode & 4095);
104
+ await requireUnchangedDestination(destination);
105
+ if (destination.existing != null) {
106
+ await files.rename(temporaryPath, destination.path);
107
+ copied = false;
108
+ } else try {
109
+ await files.link(temporaryPath, destination.path);
110
+ } catch (error) {
111
+ const code = error instanceof Error ? errorCode(error) : void 0;
112
+ if (code !== "EPERM" && code !== "ENOTSUP") throw error;
113
+ await requireUnchangedDestination(destination);
114
+ await files.rename(temporaryPath, destination.path);
115
+ copied = false;
116
+ }
117
+ } catch (error) {
118
+ failure = error;
119
+ }
120
+ if (copied) try {
121
+ await files.unlink(temporaryPath);
122
+ } catch (error) {
123
+ if (failure != null) throw new AggregateError([failure, error], `${String(failure)}; temporary file cleanup failed: ${error}`, { cause: error });
124
+ throw error;
125
+ }
126
+ if (failure != null) throw failure;
127
+ }
128
+ };
129
+ }
130
+
131
+ //#endregion
132
+ export { createExecutablePublisher, createPublicationWithFiles };
133
+ //# sourceMappingURL=executable-publication.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"executable-publication.js","names":[],"sources":["../src/executable-publication.ts"],"sourcesContent":["import {\n chmod,\n copyFile,\n link,\n lstat,\n open,\n realpath,\n rename,\n stat,\n unlink,\n} from \"node:fs/promises\";\nimport { randomUUID } from \"node:crypto\";\nimport { basename, dirname, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/** Identity retained between destination inspection and publication. */\nexport interface ExecutableDestination {\n readonly path: string;\n readonly protectedPaths: readonly string[];\n readonly existing?: {\n readonly device: bigint;\n readonly inode: bigint;\n };\n}\n\n/** Filesystem publication boundary shared by both compiler hosts. */\nexport interface ExecutablePublisher {\n /** Validate the parent, replacement kind, and source graph before linking. */\n inspect(\n destination: string,\n protectedPaths: readonly string[],\n ): Promise<ExecutableDestination>;\n /** Publish unchanged linker bytes under ADR 0037's replacement rules. */\n publish(\n linkedPath: string,\n destination: ExecutableDestination,\n ): Promise<void>;\n}\n\ntype PublicationErrorCode = \"ENOENT\" | \"EPERM\" | \"ENOTSUP\";\n\nfunction errorCode(error: Error): PublicationErrorCode | undefined {\n if (!(\"code\" in error)) return undefined;\n const code = error.code;\n return code === \"ENOENT\" || code === \"EPERM\" || code === \"ENOTSUP\"\n ? code\n : undefined;\n}\n\nfunction filesystemPath(path: string): string {\n return /^file:/iu.test(path) ? fileURLToPath(path) : path;\n}\n\nfunction refusal(path: string, reason: string): Error {\n return new Error(`Cannot publish '${path}': ${reason}; choose --output.`);\n}\n\nasync function inspectDestination(\n destination: string,\n protectedPaths: readonly string[],\n): Promise<ExecutableDestination> {\n const path = resolve(destination);\n if (!(await stat(dirname(path))).isDirectory()) {\n throw refusal(path, \"the parent is not a directory\");\n }\n let existing;\n try {\n existing = await lstat(path, { bigint: true });\n } catch (error) {\n if (!(error instanceof Error) || errorCode(error) !== \"ENOENT\") {\n throw error;\n }\n }\n if (existing == null) return { path, protectedPaths };\n if (!existing.isFile()) {\n throw refusal(path, \"the destination is not a regular file\");\n }\n const canonicalPath = await realpath(path);\n for (const protectedPath of protectedPaths) {\n let canonicalProtectedPath: string;\n try {\n // eslint-disable-next-line no-await-in-loop -- Ordered graph validation.\n canonicalProtectedPath = await realpath(filesystemPath(protectedPath));\n } catch (error) {\n if (!(error instanceof Error) || errorCode(error) !== \"ENOENT\") {\n throw error;\n }\n canonicalProtectedPath = resolve(filesystemPath(protectedPath));\n }\n if (canonicalPath === canonicalProtectedPath) {\n throw refusal(path, \"the destination is a source in the build graph\");\n }\n }\n const file = await open(path, \"r\");\n const bytes = new Uint8Array(4);\n try {\n await file.read(bytes, 0, 4, 0);\n } finally {\n await file.close();\n }\n const magic = Array.from(bytes, (byte) =>\n byte.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n if (\n ![\n \"7f454c46\", // ELF\n \"feedface\",\n \"cefaedfe\",\n \"feedfacf\",\n \"cffaedfe\", // Mach-O\n \"cafebabe\",\n \"bebafeca\",\n \"cafebabf\",\n \"bfbafeca\", // Universal Mach-O\n ].includes(magic)\n ) {\n throw refusal(path, \"the destination is not an ELF or Mach-O file\");\n }\n return {\n existing: { device: existing.dev, inode: existing.ino },\n path,\n protectedPaths,\n };\n}\n\nasync function requireUnchangedDestination(\n destination: ExecutableDestination,\n): Promise<void> {\n const current = await inspectDestination(\n destination.path,\n destination.protectedPaths,\n );\n if (\n current.existing?.device !== destination.existing?.device ||\n current.existing?.inode !== destination.existing?.inode\n ) {\n throw refusal(destination.path, \"the destination changed during the build\");\n }\n}\n\n/**\n * Create ADR 0037 publication operations using Node.js-compatible filesystem\n * APIs, supported unchanged by Node.js and Deno. CompilerHost stays narrow.\n */\nexport function createExecutablePublisher(): ExecutablePublisher {\n return createPublicationWithFiles();\n}\n\ninterface PublicationFiles {\n readonly chmod: typeof chmod;\n readonly copyFile: typeof copyFile;\n readonly link: typeof link;\n readonly rename: typeof rename;\n readonly unlink: typeof unlink;\n}\n\n/** Internal fault-injection boundary for publication failure tests. */\nexport function createPublicationWithFiles(\n overrides: Partial<PublicationFiles> = {},\n): ExecutablePublisher {\n const files = { chmod, copyFile, link, rename, unlink, ...overrides };\n return {\n inspect: inspectDestination,\n async publish(linkedPath, destination) {\n const temporaryPath = resolve(\n dirname(destination.path),\n `.${basename(destination.path)}.oseo-${randomUUID()}.tmp`,\n );\n let copied = false;\n let failure: unknown;\n try {\n const reserved = await open(temporaryPath, \"wx\");\n copied = true;\n await reserved.close();\n await files.copyFile(linkedPath, temporaryPath);\n await files.chmod(\n temporaryPath,\n (await stat(linkedPath)).mode & 0o7777,\n );\n await requireUnchangedDestination(destination);\n if (destination.existing != null) {\n await files.rename(temporaryPath, destination.path);\n copied = false;\n } else {\n try {\n await files.link(temporaryPath, destination.path);\n } catch (error) {\n const code = error instanceof Error ? errorCode(error) : undefined;\n if (code !== \"EPERM\" && code !== \"ENOTSUP\") throw error;\n await requireUnchangedDestination(destination);\n await files.rename(temporaryPath, destination.path);\n copied = false;\n }\n }\n } catch (error) {\n failure = error;\n }\n if (copied) {\n try {\n await files.unlink(temporaryPath);\n } catch (error) {\n if (failure != null) {\n throw new AggregateError(\n [failure, error],\n `${String(failure)}; temporary file cleanup failed: ${error}`,\n { cause: error },\n );\n }\n throw error;\n }\n }\n if (failure != null) throw failure;\n },\n };\n}\n"],"mappings":";;;;;;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AClD,SAAS;IACX,OACE,IAAI;KACF,MAAM,MAAM,KAAK,eAAe,YAAY,IAAI;IAClD,SAAS,OAAO;KACd,MAAM,OAAO,iBAAiB,QAAQ,UAAU,KAAK,IAAI;KACzD,IAAI,SAAS,WAAW,SAAS,WAAW,MAAM;KAClD,MAAM,4BAA4B,WAAW;KAC7C,MAAM,MAAM,OAAO,eAAe,YAAY,IAAI;KAClD,SAAS;IACX;GAEJ,SAAS,OAAO;IACd,UAAU;GACZ;GACA,IAAI,QACF,IAAI;IACF,MAAM,MAAM,OAAO,aAAa;GAClC,SAAS,OAAO;IACd,IAAI,WAAW,MACb,MAAM,IAAI,eACR,CAAC,SAAS,KAAK,GACf,GAAG,OAAO,OAAO,EAAE,mCAAmC,SACtD,EAAE,OAAO,MAAM,CACjB;IAEF,MAAM;GACR;GAEF,IAAI,WAAW,MAAM,MAAM;EAC7B;CACF;AACF"}
@@ -0,0 +1,30 @@
1
+ import { ExecutableDestination, ExecutablePublisher, createExecutablePublisher } from "./executable-publication.js";
2
+ import { CompilerHost, ExecutionHostDescription, ModuleLoader, ModuleResolver } from "@oseo/compiler";
3
+ //#region src/index.d.ts
4
+ /** Normalize Node.js or Deno platform facts at the concrete host boundary. */
5
+ declare function normalizeExecutionHost(reportedOperatingSystem: string, reportedArchitecture: string): ExecutionHostDescription;
6
+ /** Normalize one file URL to the canonical module identity spelling. */
7
+ declare function canonicalizeFileModuleUrl(url: URL): string;
8
+ /** Produce the stable content identity recorded in a module graph. */
9
+ declare function hashModuleSource(source: string): string;
10
+ /** Load canonical file URLs through one explicit compiler host. */
11
+ declare function createFileModuleLoader(host: CompilerHost, runtimeAbiVersion?: string): ModuleLoader;
12
+ /** Resolve the relative file specifiers frozen by the M4 profile. */
13
+ declare const fileModuleResolver: ModuleResolver;
14
+ /** Optional execution services for long-running Node.js compiler hosts. */
15
+ interface NodeHostOptions {
16
+ /** Spawn through a small reusable process instead of the compiler heap. */
17
+ readonly delegateSpawns?: boolean;
18
+ }
19
+ /** A Node host can explicitly drain and close its optional spawn service. */
20
+ interface NodeHost extends CompilerHost {
21
+ /** Stop accepting delegated work, drain pending requests, and close IPC. */
22
+ close(): Promise<void>;
23
+ }
24
+ /** Create the Node.js implementation of compiler host operations. */
25
+ declare function createNodeHost(options?: NodeHostOptions): NodeHost;
26
+ /** Create the Deno implementation of compiler host operations. */
27
+ declare function createDenoHost(): CompilerHost;
28
+ //#endregion
29
+ export { type ExecutableDestination, type ExecutablePublisher, NodeHost, NodeHostOptions, canonicalizeFileModuleUrl, createDenoHost, createExecutablePublisher, createFileModuleLoader, createNodeHost, fileModuleResolver, hashModuleSource, normalizeExecutionHost };
30
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";;;;iBAuCgB,uBACd,iCACA,+BACC;;iBAy2Ba,0BAA0B,KAAK;;iBAY/B,iBAAiB;;iBAUjB,uBACd,MAAM,cACN,6BACC;;cAoFU,oBAAoB;;UAsDhB;;WAEN;;;UAIM,iBAAiB;;EAEhC,SAAS;;;iBAIK,eAAe,UAAS,kBAAuB;;iBAkI/C,kBAAkB"}