@intellectual-frontiers/system 0.0.0-stage → 0.1.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/dist/watch.js ADDED
@@ -0,0 +1,342 @@
1
+ // Spec: 0001-system FR-016
2
+ /**
3
+ * Files and folders watched (commons 0005-typescript-runtime FR-051), on `node:fs`'s `watch` alone, so the same code runs on Bun and
4
+ * Node, on Linux, macOS and Windows. `watchFs` gives an async iterable of events (`create`, `modify`, `remove`,
5
+ * `rename` with both paths), stopped by `close`, an `AbortSignal`, `using` or leaving the loop.
6
+ *
7
+ * What the platforms report differs (which of `rename` and `change`, how many, a name or none), so the raw reports only say where to look:
8
+ * they are joined over `debounceMs`, and then each path they name is compared with what the watcher last knew of it (kind, inode, size and
9
+ * times). One save is therefore one event, whether an editor writes the file in place or writes a new one and renames it over it (`modify`),
10
+ * a file created and removed within the window is no event, and a file moved within the watched tree is one `rename` where the platform
11
+ * gives inodes. A change that leaves the size and every time as they were (possible only on a file system with coarse times) is not seen.
12
+ *
13
+ * A folder is watched recursively with `recursive`, by the platform's own recursive watch where it has one, and otherwise by one watch for
14
+ * each folder, kept as folders come and go (FR-018); a folder made inside it is read at once, so files made in it before its watch began are
15
+ * reported too. A file is watched through its folder, so a save that replaces it keeps being seen.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * import { watchFs } from "./watch.ts";
20
+ * using watcher = watchFs("works", { recursive: true, debounceMs: 300 });
21
+ * for await (const e of watcher) console.log(e.kind, e.paths);
22
+ * ```
23
+ *
24
+ * @module
25
+ */
26
+ import * as nfs from "node:fs";
27
+ import { dirname, isAbsolute, join, resolve, sep } from "node:path";
28
+ import { fileURLToPath } from "node:url";
29
+ import { hostCallSync, mapError } from "./errors.js";
30
+ const under = (path, root) => path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
31
+ function snapOf(path) {
32
+ try {
33
+ const s = nfs.lstatSync(path);
34
+ return { dir: s.isDirectory(), dev: s.dev, ino: s.ino, size: s.size, mtimeMs: s.mtimeMs, ctimeMs: s.ctimeMs };
35
+ }
36
+ catch {
37
+ return undefined;
38
+ }
39
+ }
40
+ function namesIn(dir) {
41
+ try {
42
+ return nfs.readdirSync(dir);
43
+ }
44
+ catch {
45
+ return [];
46
+ }
47
+ }
48
+ const changed = (a, b) => a.dir !== b.dir || a.ino !== b.ino || a.size !== b.size || a.mtimeMs !== b.mtimeMs || a.ctimeMs !== b.ctimeMs;
49
+ const byPath = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
50
+ /**
51
+ * A running watch: an async iterable of {@link FsEvent}s, ended by `close`, the signal, `using`, `await using` or leaving a `for await`
52
+ * loop. A watch that fails (other than by its folder being removed) throws from the loop as an error of `./errors.ts`. Made by {@link watchFs}.
53
+ */
54
+ export class FsWatcher {
55
+ #targets;
56
+ #debounceMs;
57
+ #signal;
58
+ #known = new Map();
59
+ #pending = new Set();
60
+ #dirty = new Set();
61
+ #handles = new Map();
62
+ #perFolder = new Set();
63
+ #queue = [];
64
+ #waiting = [];
65
+ #error;
66
+ #closed = false;
67
+ #timer;
68
+ #firstAt = 0;
69
+ #onAbort = () => this.close();
70
+ /** A watch of the paths; use {@link watchFs}. */
71
+ constructor(paths, options) {
72
+ this.#debounceMs = Math.max(0, options.debounceMs ?? 100);
73
+ this.#signal = options.signal;
74
+ this.#targets = paths.map((path) => {
75
+ const s = hostCallSync(path, () => nfs.statSync(path));
76
+ return { path, real: hostCallSync(path, () => nfs.realpathSync(path)), dir: s.isDirectory(), recursive: options.recursive === true };
77
+ });
78
+ for (const t of this.#targets)
79
+ this.#scan(t.path, t.dir ? (t.recursive ? "all" : "children") : "self");
80
+ try {
81
+ for (const t of this.#targets)
82
+ this.#start(t);
83
+ }
84
+ catch (e) {
85
+ this.close();
86
+ throw mapError(e);
87
+ }
88
+ if (this.#signal?.aborted === true)
89
+ this.close();
90
+ else
91
+ this.#signal?.addEventListener("abort", this.#onAbort, { once: true });
92
+ }
93
+ #start(t) {
94
+ if (!t.dir)
95
+ return this.#listen(dirname(t.path), false);
96
+ if (!t.recursive)
97
+ return this.#listen(t.path, false);
98
+ try {
99
+ this.#listen(t.path, true);
100
+ }
101
+ catch {
102
+ // No recursive watch on this platform and runtime (FR-018): one watch for each folder, kept up to date in #flush.
103
+ this.#perFolder.add(t.path);
104
+ for (const [path, s] of this.#known)
105
+ if (s.dir && (path === t.path || under(path, t.path)))
106
+ this.#listen(path, false);
107
+ }
108
+ }
109
+ #listen(dir, recursive) {
110
+ if (this.#handles.has(dir))
111
+ return;
112
+ const w = nfs.watch(dir, { recursive, persistent: true }, (_type, name) => this.#raw(dir, name));
113
+ w.on("error", (e) => this.#failed(dir, e));
114
+ this.#handles.set(dir, w);
115
+ }
116
+ #unlisten(dir) {
117
+ this.#handles.get(dir)?.close();
118
+ this.#handles.delete(dir);
119
+ }
120
+ #failed(dir, e) {
121
+ this.#unlisten(dir);
122
+ if (snapOf(dir) === undefined) {
123
+ // The folder was removed (Windows reports it as an error): what was in it is removed, and the watch of it is over.
124
+ this.#dirty.add(dir);
125
+ this.#schedule();
126
+ return;
127
+ }
128
+ this.#error = mapError(e, dir);
129
+ for (const w of this.#waiting.splice(0))
130
+ w.reject(this.#error);
131
+ this.close();
132
+ }
133
+ /** A raw report: a name in a watched folder, or none (the folder is then read again). */
134
+ #raw(dir, name) {
135
+ if (this.#closed)
136
+ return;
137
+ if (name === null || name === "")
138
+ this.#dirty.add(dir);
139
+ else if (isAbsolute(name))
140
+ this.#pending.add(this.#unreal(name));
141
+ else
142
+ this.#pending.add(join(dir, name));
143
+ this.#schedule();
144
+ }
145
+ /** A path a platform gave absolute, by its real path (`/private/var` for `/var` on macOS), put back under the target's path. */
146
+ #unreal(path) {
147
+ for (const t of this.#targets) {
148
+ if (path === t.real)
149
+ return t.path;
150
+ if (under(path, t.real))
151
+ return join(t.path, path.slice(t.real.length));
152
+ }
153
+ return path;
154
+ }
155
+ #schedule() {
156
+ const now = Date.now();
157
+ if (this.#timer === undefined)
158
+ this.#firstAt = now;
159
+ else
160
+ clearTimeout(this.#timer);
161
+ // Reports that never stop are still flushed, at least once in ten windows (and once a second).
162
+ const late = now - this.#firstAt >= Math.max(1000, 10 * this.#debounceMs);
163
+ this.#timer = setTimeout(() => this.#flush(), late ? 0 : this.#debounceMs);
164
+ }
165
+ #inScope(path) {
166
+ return this.#targets.some((t) => !t.dir ? path === t.path : path === t.path || (t.recursive ? under(path, t.path) : dirname(path) === t.path));
167
+ }
168
+ #deep(path) {
169
+ return this.#targets.some((t) => t.dir && t.recursive && (path === t.path || under(path, t.path)));
170
+ }
171
+ /** What is at `path` now, recorded as known: the path itself, its children, or everything under it. */
172
+ #scan(path, how) {
173
+ const s = snapOf(path);
174
+ if (s === undefined)
175
+ return;
176
+ this.#known.set(path, s);
177
+ if (!s.dir || how === "self")
178
+ return;
179
+ for (const name of namesIn(path)) {
180
+ const child = join(path, name);
181
+ if (how === "all")
182
+ this.#scan(child, "all");
183
+ else {
184
+ const c = snapOf(child);
185
+ if (c !== undefined)
186
+ this.#known.set(child, c);
187
+ }
188
+ }
189
+ }
190
+ /** Every path under `dir` as it is now. */
191
+ #present(dir, into) {
192
+ for (const name of namesIn(dir)) {
193
+ const child = join(dir, name);
194
+ into.add(child);
195
+ if (snapOf(child)?.dir === true)
196
+ this.#present(child, into);
197
+ }
198
+ }
199
+ #flush() {
200
+ this.#timer = undefined;
201
+ if (this.#closed)
202
+ return;
203
+ const look = new Set(this.#pending);
204
+ this.#pending.clear();
205
+ for (const dir of this.#dirty) {
206
+ look.add(dir);
207
+ for (const k of this.#known.keys())
208
+ if (dirname(k) === dir)
209
+ look.add(k);
210
+ for (const name of namesIn(dir))
211
+ look.add(join(dir, name));
212
+ }
213
+ this.#dirty.clear();
214
+ // A folder removed takes what was in it; a folder made (or moved in) brings what is in it now.
215
+ for (const path of [...look]) {
216
+ const before = this.#known.get(path);
217
+ const now = snapOf(path);
218
+ if (before?.dir === true && now?.dir !== true)
219
+ for (const k of this.#known.keys())
220
+ if (under(k, path))
221
+ look.add(k);
222
+ if (now?.dir === true && before?.dir !== true && this.#deep(path))
223
+ this.#present(path, look);
224
+ }
225
+ const created = [];
226
+ const removed = [];
227
+ const events = [];
228
+ for (const path of [...look].filter((x) => this.#inScope(x)).sort(byPath)) {
229
+ const before = this.#known.get(path);
230
+ const now = snapOf(path);
231
+ if (before === undefined && now === undefined)
232
+ continue;
233
+ if (now === undefined) {
234
+ if (before !== undefined)
235
+ removed.push({ path, snap: before });
236
+ this.#known.delete(path);
237
+ }
238
+ else {
239
+ this.#known.set(path, now);
240
+ if (before === undefined)
241
+ created.push(path);
242
+ else if (changed(before, now) && !(before.dir && now.dir))
243
+ events.push({ kind: "modify", paths: [path] });
244
+ }
245
+ }
246
+ // A path removed and one made with the same inode, in the same window, is a move; what was under a moved folder moved with it.
247
+ const moved = new Set();
248
+ for (const r of removed) {
249
+ if (r.snap.ino === 0 || [...moved].some((m) => under(r.path, m)))
250
+ continue;
251
+ const to = created.find((c) => !moved.has(c) && this.#known.get(c)?.ino === r.snap.ino && this.#known.get(c)?.dev === r.snap.dev);
252
+ if (to === undefined)
253
+ continue;
254
+ moved.add(r.path).add(to);
255
+ events.push({ kind: "rename", paths: [r.path, to] });
256
+ }
257
+ const inMoved = (path) => [...moved].some((m) => path === m || under(path, m));
258
+ for (const r of removed)
259
+ if (!inMoved(r.path))
260
+ events.push({ kind: "remove", paths: [r.path] });
261
+ for (const c of created)
262
+ if (!inMoved(c))
263
+ events.push({ kind: "create", paths: [c] });
264
+ // Per-folder watches follow the folders.
265
+ if (this.#perFolder.size > 0) {
266
+ for (const r of removed)
267
+ if (this.#handles.has(r.path))
268
+ this.#unlisten(r.path);
269
+ for (const c of created) {
270
+ if (this.#known.get(c)?.dir === true && [...this.#perFolder].some((root) => under(c, root))) {
271
+ try {
272
+ this.#listen(c, false);
273
+ }
274
+ catch {
275
+ // The folder went again before its watch began; the next report of its parent says so.
276
+ }
277
+ }
278
+ }
279
+ }
280
+ const first = (e) => (e.kind === "rename" ? e.paths[1] : e.paths[0]);
281
+ events.sort((a, b) => byPath(first(a), first(b)));
282
+ for (const e of events) {
283
+ const w = this.#waiting.shift();
284
+ if (w === undefined)
285
+ this.#queue.push(e);
286
+ else
287
+ w.resolve({ value: e, done: false });
288
+ }
289
+ }
290
+ /** The next event, waiting for one; done once the watch is closed. */
291
+ next() {
292
+ const e = this.#queue.shift();
293
+ if (e !== undefined)
294
+ return Promise.resolve({ value: e, done: false });
295
+ if (this.#error !== undefined)
296
+ return Promise.reject(this.#error);
297
+ if (this.#closed)
298
+ return Promise.resolve({ value: undefined, done: true });
299
+ return new Promise((resolve, reject) => this.#waiting.push({ resolve, reject }));
300
+ }
301
+ /** The watch closed, as leaving a `for await` loop does. */
302
+ return() {
303
+ this.close();
304
+ return Promise.resolve({ value: undefined, done: true });
305
+ }
306
+ /** The watch itself, to iterate. */
307
+ [Symbol.asyncIterator]() {
308
+ return this;
309
+ }
310
+ /** The watch stopped: no more events; a loop over it ends. Closing it again does nothing. */
311
+ close() {
312
+ if (this.#closed)
313
+ return;
314
+ this.#closed = true;
315
+ if (this.#timer !== undefined)
316
+ clearTimeout(this.#timer);
317
+ this.#timer = undefined;
318
+ this.#signal?.removeEventListener("abort", this.#onAbort);
319
+ for (const dir of [...this.#handles.keys()])
320
+ this.#unlisten(dir);
321
+ this.#queue.length = 0;
322
+ for (const w of this.#waiting.splice(0))
323
+ w.resolve({ value: undefined, done: true });
324
+ }
325
+ /** Closed at the end of a `using` block. */
326
+ [Symbol.dispose]() {
327
+ this.close();
328
+ }
329
+ /** Closed at the end of an `await using` block. */
330
+ [Symbol.asyncDispose]() {
331
+ this.close();
332
+ return Promise.resolve();
333
+ }
334
+ }
335
+ /**
336
+ * Files and folders watched, (see the module's documentation): each path a file, or a folder whose entries
337
+ * (with `recursive`, everything under it) are watched. `NotFound` where a path is not there.
338
+ */
339
+ export function watchFs(paths, options = {}) {
340
+ const list = typeof paths === "string" || paths instanceof URL ? [paths] : paths;
341
+ return new FsWatcher(list.map((x) => resolve(typeof x === "string" ? x : fileURLToPath(x))), options);
342
+ }
package/package.json CHANGED
@@ -1,6 +1,115 @@
1
1
  {
2
2
  "name": "@intellectual-frontiers/system",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "The host system as one typed library: files, paths, the folders of a program, one run at a time, file watching, programs found by prefix, processes and their streams, Git, a program built into one binary, the operating system's scheduled jobs, and the terminal's streams; the same code on Bun and Node 26.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=26"
9
+ },
10
+ "sideEffects": false,
11
+ "types": "./dist/mod.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/mod.d.ts",
15
+ "bun": "./src/mod.ts",
16
+ "default": "./dist/mod.js"
17
+ },
18
+ "./errors": {
19
+ "types": "./dist/errors.d.ts",
20
+ "bun": "./src/errors.ts",
21
+ "default": "./dist/errors.js"
22
+ },
23
+ "./fs": {
24
+ "types": "./dist/fs.d.ts",
25
+ "bun": "./src/fs.ts",
26
+ "default": "./dist/fs.js"
27
+ },
28
+ "./path": {
29
+ "types": "./dist/path.d.ts",
30
+ "bun": "./src/path.ts",
31
+ "default": "./dist/path.js"
32
+ },
33
+ "./dirs": {
34
+ "types": "./dist/dirs.d.ts",
35
+ "bun": "./src/dirs.ts",
36
+ "default": "./dist/dirs.js"
37
+ },
38
+ "./lock": {
39
+ "types": "./dist/lock.d.ts",
40
+ "bun": "./src/lock.ts",
41
+ "default": "./dist/lock.js"
42
+ },
43
+ "./watch": {
44
+ "types": "./dist/watch.d.ts",
45
+ "bun": "./src/watch.ts",
46
+ "default": "./dist/watch.js"
47
+ },
48
+ "./discover": {
49
+ "types": "./dist/discover.d.ts",
50
+ "bun": "./src/discover.ts",
51
+ "default": "./dist/discover.js"
52
+ },
53
+ "./proc": {
54
+ "types": "./dist/proc.d.ts",
55
+ "bun": "./src/proc.ts",
56
+ "default": "./dist/proc.js"
57
+ },
58
+ "./git": {
59
+ "types": "./dist/git.d.ts",
60
+ "bun": "./src/git.ts",
61
+ "default": "./dist/git.js"
62
+ },
63
+ "./compile": {
64
+ "types": "./dist/compile.d.ts",
65
+ "bun": "./src/compile.ts",
66
+ "default": "./dist/compile.js"
67
+ },
68
+ "./schedule": {
69
+ "types": "./dist/schedule.d.ts",
70
+ "bun": "./src/schedule.ts",
71
+ "default": "./dist/schedule.js"
72
+ },
73
+ "./job-plan": {
74
+ "types": "./dist/job-plan.d.ts",
75
+ "bun": "./src/job-plan.ts",
76
+ "default": "./dist/job-plan.js"
77
+ },
78
+ "./tty": {
79
+ "types": "./dist/tty.d.ts",
80
+ "bun": "./src/tty.ts",
81
+ "default": "./dist/tty.js"
82
+ },
83
+ "./stdio": {
84
+ "types": "./dist/stdio.d.ts",
85
+ "bun": "./src/stdio.ts",
86
+ "default": "./dist/stdio.js"
87
+ }
88
+ },
89
+ "dependencies": {
90
+ "@intellectual-frontiers/core": "0.1.1",
91
+ "@intellectual-frontiers/crypto": "0.1.1",
92
+ "@intellectual-frontiers/formats": "0.1.1"
93
+ },
94
+ "peerDependencies": {
95
+ "@types/node": ">=26"
96
+ },
97
+ "files": [
98
+ "dist",
99
+ "src",
100
+ "README.md",
101
+ "LICENSE"
102
+ ],
103
+ "repository": {
104
+ "type": "git",
105
+ "url": "git+https://github.com/intellectual-frontiers/.github.git",
106
+ "directory": "commons/system"
107
+ },
108
+ "homepage": "https://github.com/intellectual-frontiers/.github/tree/main/commons/system",
109
+ "bugs": {
110
+ "url": "https://github.com/intellectual-frontiers/.github/issues"
111
+ },
112
+ "publishConfig": {
113
+ "access": "public"
114
+ }
115
+ }
package/src/compile.ts ADDED
@@ -0,0 +1,178 @@
1
+ // Spec: 0001-system FR-013
2
+ /**
3
+ * A program built into one binary with the pinned Bun (commons 0005-typescript-runtime FR-062): `bun build --compile`, for this computer or
4
+ * for a target given (`linux-x64`, `linux-arm64`, `darwin-x64`, `darwin-arm64`, `windows-x64`), with the files it embeds, giving the
5
+ * binary's path and SHA-256. Bun is found as `bun` on `PATH`, or given by its path; where an expected version is given, a Bun of another
6
+ * version is refused, so a build is made only by the pinned one. Everything that can go wrong is a `CompileError` in a `Result`.
7
+ *
8
+ * The argument vector is made by `compileArgv`, a pure function, so what is asked of Bun can be checked without running it; a program
9
+ * built this way runs itself again with `proc.selfCommand()` (FR-053).
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { compile } from "./compile.ts";
14
+ * const r = await compile({ entry: "src/main.ts", outfile: "dist/tool", target: "windows-x64" });
15
+ * if (r.kind === "ok") console.log(r.value.path, r.value.sha256); // dist/tool.exe, its SHA-256
16
+ * ```
17
+ *
18
+ * @module
19
+ */
20
+ import { absurd, err, ok, type Result } from "@intellectual-frontiers/core";
21
+ import type { Sha256 } from "@intellectual-frontiers/crypto/sha256";
22
+ import { exists, sha256File } from "./fs.ts";
23
+ import { resolve } from "./path.ts";
24
+ import { build, cwd as processCwd, type Arch, type Os, output, which } from "./proc.ts";
25
+
26
+ /** A system Bun builds a binary for. */
27
+ export type Target = "linux-x64" | "linux-arm64" | "darwin-x64" | "darwin-arm64" | "windows-x64";
28
+
29
+ /** Every target, in a fixed order. */
30
+ export const TARGETS: readonly Target[] = ["linux-x64", "linux-arm64", "darwin-x64", "darwin-arm64", "windows-x64"];
31
+
32
+ /** The target of a system, by `proc.build`'s names; undefined where Bun builds for no such system. */
33
+ export function targetOf(os: Os, arch: Arch): Target | undefined {
34
+ const key = `${os}/${arch}`;
35
+ switch (key) {
36
+ case "linux/x86_64":
37
+ return "linux-x64";
38
+ case "linux/aarch64":
39
+ return "linux-arm64";
40
+ case "darwin/x86_64":
41
+ return "darwin-x64";
42
+ case "darwin/aarch64":
43
+ return "darwin-arm64";
44
+ case "windows/x86_64":
45
+ return "windows-x64";
46
+ default:
47
+ return undefined;
48
+ }
49
+ }
50
+
51
+ /** The target of this computer; undefined where Bun builds for no such system. */
52
+ export function hostTarget(): Target | undefined {
53
+ return targetOf(build.os, build.arch);
54
+ }
55
+
56
+ /** Whether a target's binaries are Windows programs, named with `.exe`. */
57
+ export function isWindows(target: Target): boolean {
58
+ switch (target) {
59
+ case "windows-x64":
60
+ return true;
61
+ case "linux-x64":
62
+ case "linux-arm64":
63
+ case "darwin-x64":
64
+ case "darwin-arm64":
65
+ return false;
66
+ default:
67
+ return absurd(target);
68
+ }
69
+ }
70
+
71
+ /** What to build. */
72
+ export type CompileOptions = {
73
+ /** The program's entry point (a `.ts` or `.js` file). */
74
+ readonly entry: string;
75
+ /** Where the binary goes; `.exe` is added for Windows where it is not there, as Bun adds it. */
76
+ readonly outfile: string;
77
+ /** The system to build for; this computer where it is not given. */
78
+ readonly target?: Target;
79
+ /** Files embedded in the binary, beside the code its imports bring in. */
80
+ readonly files?: readonly string[];
81
+ /** Bun's path; `bun` on `PATH` where it is not given. */
82
+ readonly bun?: string;
83
+ /** The version Bun must be (the pin, such as `1.4.4`); any version where it is not given. */
84
+ readonly bunVersion?: string;
85
+ /** The folder the build runs in, against which relative paths are read; the process's working folder by default. */
86
+ readonly cwd?: string;
87
+ /** More of `bun build`'s options, put before the entry point (`--minify`, `--define=...`). */
88
+ readonly extraArgs?: readonly string[];
89
+ /** Stopping the build. */
90
+ readonly signal?: AbortSignal;
91
+ };
92
+
93
+ /** A binary built. */
94
+ export type Compiled = {
95
+ /** Its path, absolute. */
96
+ readonly path: string;
97
+ /** Its SHA-256. */
98
+ readonly sha256: Sha256;
99
+ /** The system it is for. */
100
+ readonly target: Target;
101
+ /** The version of Bun that built it. */
102
+ readonly bunVersion: string;
103
+ };
104
+
105
+ /** Why a binary was not built. */
106
+ export type CompileError =
107
+ | { readonly kind: "no-bun"; readonly message: string }
108
+ | { readonly kind: "wrong-bun"; readonly expected: string; readonly found: string }
109
+ | { readonly kind: "no-target"; readonly message: string }
110
+ | { readonly kind: "failed"; readonly code: number; readonly stderr: string }
111
+ | { readonly kind: "no-binary"; readonly path: string };
112
+
113
+ /** A sentence for a `CompileError`. */
114
+ export function describeCompileError(e: CompileError): string {
115
+ switch (e.kind) {
116
+ case "no-bun":
117
+ return e.message;
118
+ case "wrong-bun":
119
+ return `Bun ${e.found} is not the pinned ${e.expected}`;
120
+ case "no-target":
121
+ return e.message;
122
+ case "failed":
123
+ return `bun build --compile failed (${e.code}): ${e.stderr.trim()}`;
124
+ case "no-binary":
125
+ return `bun build --compile wrote no binary at ${e.path}`;
126
+ default:
127
+ return absurd(e);
128
+ }
129
+ }
130
+
131
+ /** The binary's path for a target: `outfile`, with `.exe` added for Windows where it is not there. */
132
+ export function binaryPath(outfile: string, target: Target): string {
133
+ return isWindows(target) && !/\.exe$/i.test(outfile) ? `${outfile}.exe` : outfile;
134
+ }
135
+
136
+ /**
137
+ * The argument vector that builds the binary (pure): `bun build --compile [--target=bun-<target>] --outfile=<path> [extra...] <entry>
138
+ * [files...]`. A target is named only where one is given; without it Bun builds for the computer it runs on. The files after the entry
139
+ * point are embedded in the binary.
140
+ */
141
+ export function compileArgv(bun: string, options: CompileOptions, outfile: string): readonly string[] {
142
+ return [
143
+ bun,
144
+ "build",
145
+ "--compile",
146
+ ...(options.target === undefined ? [] : [`--target=bun-${options.target}`]),
147
+ `--outfile=${outfile}`,
148
+ ...(options.extraArgs ?? []),
149
+ options.entry,
150
+ ...(options.files ?? []),
151
+ ];
152
+ }
153
+
154
+ /** Builds a program into one binary with Bun (FR-062) and gives its path and SHA-256; a `CompileError` where it cannot. */
155
+ export async function compile(options: CompileOptions): Promise<Result<Compiled, CompileError>> {
156
+ const target = options.target ?? hostTarget();
157
+ if (target === undefined) return err({ kind: "no-target", message: `Bun builds no binary for ${build.os}/${build.arch}` });
158
+ const bun = options.bun ?? which("bun");
159
+ if (bun === undefined) return err({ kind: "no-bun", message: "no bun on PATH" });
160
+ const where = options.cwd ?? processCwd();
161
+ const run = { cwd: where, ...(options.signal === undefined ? {} : { signal: options.signal }) };
162
+ let version: string;
163
+ try {
164
+ const v = await output([bun, "--version"], run);
165
+ version = new TextDecoder().decode(v.stdout).trim();
166
+ if (!v.success || version === "") return err({ kind: "no-bun", message: `${bun} --version failed (${v.code})` });
167
+ } catch (e) {
168
+ return err({ kind: "no-bun", message: `${bun}: ${e instanceof Error ? e.message : String(e)}` });
169
+ }
170
+ if (options.bunVersion !== undefined && version !== options.bunVersion) {
171
+ return err({ kind: "wrong-bun", expected: options.bunVersion, found: version });
172
+ }
173
+ const path = resolve(where, binaryPath(options.outfile, target));
174
+ const built = await output(compileArgv(bun, options, path), run);
175
+ if (!built.success) return err({ kind: "failed", code: built.code, stderr: new TextDecoder().decode(built.stderr) });
176
+ if (!(await exists(path))) return err({ kind: "no-binary", path });
177
+ return ok({ path, sha256: await sha256File(path), target, bunVersion: version });
178
+ }