@intellectual-frontiers/system 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/proc.js ADDED
@@ -0,0 +1,589 @@
1
+ // Spec: 0001-system FR-009
2
+ /**
3
+ * The process and the programs it runs (commons 0005-typescript-runtime FR-022, FR-052, FR-053), on `node:process`, `node:child_process`
4
+ * and `node:os`, the same on Bun and on Node 26. The names are short and plain (`env.get`, `args`, `exit`, `cwd`, `build.os`, `build.target`,
5
+ * `ppid`, `output`, `spawn`, `unrefTimer`); `selfCommand` gives the argument vector for a program that runs itself again, from a script or
6
+ * from a compiled binary. A program is always run by its argument
7
+ * vector, never through a shell; one that cannot be found throws `NotFound`, and a non-zero exit is an outcome, not an error. Taken
8
+ * from erga's `lib/ts/process`, Stolos's `src/archon/core/exec.ts` and the setup's `proc.ts`.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { run } from "./proc.ts";
13
+ * const r = await run(["git", "--version"]);
14
+ * if (r.success) console.log(r.stdout.trim());
15
+ * ```
16
+ *
17
+ * @module
18
+ */
19
+ import { Buffer } from "node:buffer";
20
+ import { spawn as spawn_ } from "node:child_process";
21
+ import { statSync } from "node:fs";
22
+ import * as net from "node:net";
23
+ import * as os from "node:os";
24
+ import { basename, delimiter, join, resolve as resolvePath } from "node:path";
25
+ import process from "node:process";
26
+ import { Readable, Writable } from "node:stream";
27
+ import { setTimeout as nodeSetTimeout } from "node:timers";
28
+ import { absurd } from "@intellectual-frontiers/core";
29
+ import { InvalidData, mapError, NotFound, toError } from "./errors.js";
30
+ let tracer;
31
+ /** Installs the function that traces the programs this module runs (or, with `undefined`, removes it): a program is a `process` span where one is installed (0006-signals FR-018). */
32
+ export function setProcessTracer(t) {
33
+ tracer = t;
34
+ }
35
+ function traceProcess(argv, run) {
36
+ return tracer === undefined ? run({}) : tracer(argv, run);
37
+ }
38
+ /** The process's environment. */
39
+ export const env = {
40
+ /** A variable's value, or undefined where it is not set. */
41
+ get(key) {
42
+ return process.env[key];
43
+ },
44
+ /** A variable set for this process and the programs it runs. */
45
+ set(key, value) {
46
+ process.env[key] = value;
47
+ },
48
+ /** A variable removed. */
49
+ delete(key) {
50
+ Reflect.deleteProperty(process.env, key);
51
+ },
52
+ /** Whether a variable is set. */
53
+ has(key) {
54
+ return process.env[key] !== undefined;
55
+ },
56
+ /** Every variable that is set, as a plain object. */
57
+ toObject() {
58
+ const out = {};
59
+ for (const [k, v] of Object.entries(process.env))
60
+ if (v !== undefined)
61
+ out[k] = v;
62
+ return out;
63
+ },
64
+ };
65
+ /** The arguments the program was given, after the runtime's own and the script's path. */
66
+ export const args = Object.freeze(process.argv.slice(2));
67
+ /** The process ends now with `code` (0 by default). */
68
+ export function exit(code = 0) {
69
+ process.exit(code);
70
+ }
71
+ /** The process's working folder. */
72
+ export function cwd() {
73
+ return process.cwd();
74
+ }
75
+ /** The process's working folder changed. */
76
+ export function chdir(path) {
77
+ try {
78
+ process.chdir(path);
79
+ }
80
+ catch (e) {
81
+ throw mapError(e, path);
82
+ }
83
+ }
84
+ /** The process's id. */
85
+ export const pid = process.pid;
86
+ /** The id of the process's parent (FR-053); a function, as the parent changes where the first one ends. */
87
+ export function ppid() {
88
+ return process.ppid;
89
+ }
90
+ /** The path of the runtime's executable (bun or node). */
91
+ export function execPath() {
92
+ return process.execPath;
93
+ }
94
+ /** The computer's name. */
95
+ export function hostname() {
96
+ return os.hostname();
97
+ }
98
+ /** The account's home folder. */
99
+ export function homeDir() {
100
+ return os.homedir();
101
+ }
102
+ /** The account's user id, or undefined on Windows. */
103
+ export function uid() {
104
+ return typeof process.getuid === "function" ? process.getuid() : undefined;
105
+ }
106
+ /** Whether the process runs as root (never on Windows). */
107
+ export function isRoot() {
108
+ return uid() === 0;
109
+ }
110
+ /** The operating system's name for `node:process`'s `platform`. */
111
+ export function osOf(platform) {
112
+ switch (platform) {
113
+ case "linux":
114
+ case "darwin":
115
+ case "freebsd":
116
+ case "netbsd":
117
+ case "openbsd":
118
+ case "aix":
119
+ case "android":
120
+ return platform;
121
+ case "win32":
122
+ return "windows";
123
+ case "sunos":
124
+ return "solaris";
125
+ default:
126
+ return "other";
127
+ }
128
+ }
129
+ /** The processor's name for `node:process`'s `arch`. */
130
+ export function archOf(arch) {
131
+ switch (arch) {
132
+ case "x64":
133
+ return "x86_64";
134
+ case "arm64":
135
+ return "aarch64";
136
+ case "arm":
137
+ case "riscv64":
138
+ case "s390x":
139
+ case "ppc64":
140
+ return arch;
141
+ default:
142
+ return "other";
143
+ }
144
+ }
145
+ /**
146
+ * The target triple (as Rust and Bun name it) for an operating system and a processor (FR-053): `x86_64-unknown-linux-gnu`, `aarch64-apple-darwin`,
147
+ * `x86_64-pc-windows-msvc`, `aarch64-linux-android`, and `<arch>-unknown-<os>` for the rest.
148
+ */
149
+ export function tripleOf(os, arch) {
150
+ switch (os) {
151
+ case "linux":
152
+ return `${arch}-unknown-linux-gnu`;
153
+ case "darwin":
154
+ return `${arch}-apple-darwin`;
155
+ case "windows":
156
+ return `${arch}-pc-windows-msvc`;
157
+ case "android":
158
+ return `${arch}-linux-android`;
159
+ case "freebsd":
160
+ case "netbsd":
161
+ case "openbsd":
162
+ case "solaris":
163
+ case "aix":
164
+ case "other":
165
+ return `${arch}-unknown-${os}`;
166
+ default:
167
+ return absurd(os);
168
+ }
169
+ }
170
+ /** The platform this process runs on, with the target triple (FR-053). */
171
+ export const build = Object.freeze({
172
+ os: osOf(process.platform),
173
+ arch: archOf(process.arch),
174
+ target: tripleOf(osOf(process.platform), archOf(process.arch)),
175
+ });
176
+ /** Which runtime runs this code, from `process.versions`, which each of them fills: Bun, the default, or Node 26, the backup. */
177
+ export function runtimeName() {
178
+ const v = process.versions;
179
+ if (v["bun"] !== undefined)
180
+ return "bun";
181
+ return "node";
182
+ }
183
+ /** The version of the runtime that runs this code. */
184
+ export function runtimeVersion() {
185
+ const v = process.versions;
186
+ return v[runtimeName()] ?? process.version.replace(/^v/, "");
187
+ }
188
+ /** Whether a path is a file this account may run (on Windows, any file). */
189
+ export function isExecutable(path) {
190
+ try {
191
+ const s = statSync(path);
192
+ return s.isFile() && (process.platform === "win32" || (s.mode & 0o111) !== 0);
193
+ }
194
+ catch {
195
+ return false;
196
+ }
197
+ }
198
+ /** The program `name` on `PATH` (or the path itself where `name` has a separator), as `command -v` finds it; undefined where there is none. */
199
+ export function which(name, path = env.get("PATH") ?? "") {
200
+ const windows = process.platform === "win32";
201
+ const exts = windows ? ["", ...(env.get("PATHEXT") ?? ".EXE;.CMD;.BAT;.COM").split(";")] : [""];
202
+ const candidates = name.includes("/") || (windows && name.includes("\\"))
203
+ ? [name]
204
+ : path
205
+ .split(delimiter)
206
+ .filter((d) => d !== "")
207
+ .flatMap((d) => exts.map((e) => join(d, `${name}${e}`)));
208
+ return candidates.find(isExecutable);
209
+ }
210
+ const SIGNALS = {
211
+ SIGHUP: 1,
212
+ SIGINT: 2,
213
+ SIGQUIT: 3,
214
+ SIGABRT: 6,
215
+ SIGKILL: 9,
216
+ SIGPIPE: 13,
217
+ SIGALRM: 14,
218
+ SIGTERM: 15,
219
+ };
220
+ /** The number of a signal by its name (1 for one it does not know). */
221
+ export function signalNumber(name) {
222
+ return SIGNALS[name] ?? os.constants.signals[name] ?? 1;
223
+ }
224
+ const stdio = (s) => (s === "inherit" ? "inherit" : s === "null" ? "ignore" : "pipe");
225
+ /** The environment a program is given: this process's with `env` added, or `env` alone with `clearEnv`. */
226
+ const childEnv = (options) => (options.clearEnv === true ? { ...options.env } : { ...process.env, ...options.env });
227
+ /** An exit status as a shell reports it: 128 plus the signal's number where a signal ended the program. */
228
+ function exitStatus(code, signal) {
229
+ const status = signal !== null ? 128 + signalNumber(signal) : (code ?? 1);
230
+ return { code: status, success: status === 0, signal };
231
+ }
232
+ /** Byte arrays joined into one. */
233
+ function joined(parts) {
234
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
235
+ let at = 0;
236
+ for (const p of parts) {
237
+ out.set(p, at);
238
+ at += p.length;
239
+ }
240
+ return out;
241
+ }
242
+ /**
243
+ * A program run to its end, by its argument vector and never through a shell, with what it did. `NotFound` where there is no such program.
244
+ * Where a telemetry pipeline is installed, the run is a `process` span and the program is given its `TRACEPARENT` (0006-signals FR-018).
245
+ */
246
+ export function output(argv, options = {}) {
247
+ const [cmd, ...rest] = argv;
248
+ if (cmd === undefined || cmd === "")
249
+ return Promise.reject(new InvalidData("nothing to run: the argument vector is empty", "EINVAL"));
250
+ return traceProcess(argv, (trace) => spawnOutput(cmd, rest, Object.keys(trace).length === 0 ? options : { ...options, env: { ...trace, ...options.env } }));
251
+ }
252
+ function spawnOutput(cmd, rest, options) {
253
+ const input = options.input;
254
+ const feeds = input !== undefined;
255
+ return new Promise((resolve, reject) => {
256
+ let settled = false;
257
+ const child = spawn_(cmd, rest, {
258
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
259
+ env: childEnv(options),
260
+ stdio: [feeds ? "pipe" : options.stdin === "inherit" ? "inherit" : "ignore", stdio(options.stdout), stdio(options.stderr)],
261
+ windowsHide: true,
262
+ });
263
+ const kept = { stdout: [], stderr: [] };
264
+ const collect = (name, stream) => {
265
+ if (stream === null)
266
+ return;
267
+ const dec = new TextDecoder();
268
+ let rest = "";
269
+ stream.on("data", (chunk) => {
270
+ kept[name].push(chunk);
271
+ if (options.onLine === undefined)
272
+ return;
273
+ rest += dec.decode(chunk, { stream: true });
274
+ const lines = rest.split("\n");
275
+ rest = lines.pop() ?? "";
276
+ for (const l of lines)
277
+ options.onLine(name, l.replace(/\r$/, ""));
278
+ });
279
+ stream.on("end", () => {
280
+ rest += dec.decode();
281
+ if (options.onLine !== undefined && rest !== "")
282
+ options.onLine(name, rest.replace(/\r$/, ""));
283
+ });
284
+ };
285
+ collect("stdout", child.stdout);
286
+ collect("stderr", child.stderr);
287
+ let killer;
288
+ const stop = () => {
289
+ child.kill("SIGTERM");
290
+ killer = setTimeout(() => child.kill("SIGKILL"), options.killAfterMs ?? 5000);
291
+ };
292
+ options.signal?.addEventListener("abort", stop, { once: true });
293
+ if (options.signal?.aborted === true)
294
+ stop();
295
+ child.on("error", (e) => {
296
+ if (settled)
297
+ return;
298
+ settled = true;
299
+ options.signal?.removeEventListener("abort", stop);
300
+ if (killer !== undefined)
301
+ clearTimeout(killer);
302
+ reject(mapError(e, cmd));
303
+ });
304
+ child.on("close", (code, signal) => {
305
+ if (settled)
306
+ return;
307
+ settled = true;
308
+ options.signal?.removeEventListener("abort", stop);
309
+ if (killer !== undefined)
310
+ clearTimeout(killer);
311
+ resolve({ ...exitStatus(code, signal), stdout: joined(kept.stdout), stderr: joined(kept.stderr) });
312
+ });
313
+ if (input !== undefined && child.stdin !== null) {
314
+ child.stdin.on("error", () => {
315
+ /* the program closed its input early; what it did is still reported */
316
+ });
317
+ child.stdin.end(typeof input === "string" ? input : Buffer.from(input.buffer, input.byteOffset, input.byteLength));
318
+ }
319
+ });
320
+ }
321
+ /** A program run to its end, with its output as text (UTF-8). `NotFound` where there is no such program. */
322
+ export async function run(argv, options = {}) {
323
+ const r = await output(argv, options);
324
+ const dec = new TextDecoder();
325
+ return { code: r.code, success: r.success, signal: r.signal, stdout: dec.decode(r.stdout), stderr: dec.decode(r.stderr) };
326
+ }
327
+ /** A program's standard output, where it succeeds; an `Error` naming the program, its status and what it said, where it does not. */
328
+ export async function must(argv, options = {}) {
329
+ const r = await run(argv, options);
330
+ if (!r.success)
331
+ throw new Error(`${argv.join(" ")} failed (${r.code}): ${r.stderr.trim() || r.stdout.trim()}`);
332
+ return r.stdout;
333
+ }
334
+ /** The first line a program prints, trimmed; `""` where it fails or cannot be found. */
335
+ export async function firstLine(argv, options = {}) {
336
+ try {
337
+ const r = await run(argv, options);
338
+ return r.success ? (r.stdout.split("\n")[0] ?? "").trim() : "";
339
+ }
340
+ catch {
341
+ return "";
342
+ }
343
+ }
344
+ /** The value of `PATH` in an environment, whatever its case on Windows. */
345
+ function pathIn(environment) {
346
+ const direct = environment["PATH"];
347
+ if (direct !== undefined)
348
+ return direct;
349
+ const key = Object.keys(environment).find((k) => k.toUpperCase() === "PATH");
350
+ return key === undefined ? "" : (environment[key] ?? "");
351
+ }
352
+ /** Whether a program exists to run: a path (from `cwd`) that is executable, or a name found on the environment's `PATH`. */
353
+ function findable(cmd, environment, cwd) {
354
+ const pathLike = cmd.includes("/") || (process.platform === "win32" && cmd.includes("\\"));
355
+ return pathLike ? isExecutable(resolvePath(cwd ?? process.cwd(), cmd)) : which(cmd, pathIn(environment)) !== undefined;
356
+ }
357
+ /** Bytes to read to the end, joined; nothing where there is no stream. */
358
+ async function readAll(stream) {
359
+ if (stream === null)
360
+ return new Uint8Array(0);
361
+ const parts = [];
362
+ const reader = stream.getReader();
363
+ try {
364
+ for (;;) {
365
+ const r = await reader.read();
366
+ if (r.done)
367
+ break;
368
+ parts.push(r.value);
369
+ }
370
+ }
371
+ finally {
372
+ reader.releaseLock();
373
+ }
374
+ return joined(parts);
375
+ }
376
+ /**
377
+ * Starts a program by its argument vector, never through a shell, and gives its handle while it runs (FR-052). A program that cannot be found throws `NotFound` at once: a path that is not an executable file, or a name not
378
+ * on the `PATH` of the environment it is given. Where a telemetry pipeline is installed, the run is a `process` span that ends when the
379
+ * program does, and the program is given its `TRACEPARENT` (0006-signals FR-018), as for `output`.
380
+ *
381
+ * @example
382
+ * ```ts
383
+ * import { spawn } from "./proc.ts";
384
+ * await using child = spawn(["gzip", "-dc"], { stdin: "piped", stdout: "piped" });
385
+ * ```
386
+ */
387
+ export function spawn(argv, options = {}) {
388
+ const [cmd, ...rest] = argv;
389
+ if (cmd === undefined || cmd === "")
390
+ throw new InvalidData("nothing to run: the argument vector is empty", "EINVAL");
391
+ if (!findable(cmd, childEnv(options), options.cwd))
392
+ throw new NotFound(`no such program: ${cmd}`, "ENOENT", cmd);
393
+ const box = {};
394
+ const status = traceProcess(argv, (trace) => {
395
+ const started = startChild(cmd, rest, Object.keys(trace).length === 0 ? options : { ...options, env: { ...trace, ...options.env } });
396
+ box.started = started;
397
+ return started.exited;
398
+ });
399
+ // A program that could not be started rejects `status`; that is the caller's to see, never an unhandled rejection of its own.
400
+ status.catch(() => undefined);
401
+ const started = box.started;
402
+ // The span's function runs at once (kernel/signals.ts `span`), so the handle is there; this guards against a change to that.
403
+ if (started === undefined)
404
+ throw new Error("the program's handle was not made");
405
+ const { pipes } = started;
406
+ return {
407
+ ...pipes,
408
+ status,
409
+ output: async () => {
410
+ const [stdout, stderr, st] = await Promise.all([readAll(pipes.stdout), readAll(pipes.stderr), status]);
411
+ return { ...st, stdout, stderr };
412
+ },
413
+ kill: started.kill,
414
+ ref: started.ref,
415
+ unref: started.unref,
416
+ [Symbol.asyncDispose]: started.dispose,
417
+ };
418
+ }
419
+ function startChild(cmd, rest, options) {
420
+ const node = spawn_(cmd, rest, {
421
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
422
+ env: childEnv(options),
423
+ stdio: [stdio(options.stdin ?? "inherit"), stdio(options.stdout ?? "inherit"), stdio(options.stderr ?? "inherit")],
424
+ windowsHide: true,
425
+ });
426
+ let ended = false;
427
+ let killer;
428
+ const stop = () => {
429
+ if (ended)
430
+ return;
431
+ node.kill("SIGTERM");
432
+ killer ??= setTimeout(() => {
433
+ if (!ended)
434
+ node.kill("SIGKILL");
435
+ }, options.killAfterMs ?? 5000);
436
+ };
437
+ const exited = new Promise((resolve, reject) => {
438
+ const done = () => {
439
+ ended = true;
440
+ options.signal?.removeEventListener("abort", stop);
441
+ if (killer !== undefined)
442
+ clearTimeout(killer);
443
+ };
444
+ node.once("error", (e) => {
445
+ if (ended)
446
+ return;
447
+ done();
448
+ reject(mapError(e, cmd));
449
+ });
450
+ node.once("exit", (code, signal) => {
451
+ if (ended)
452
+ return;
453
+ done();
454
+ resolve(exitStatus(code, signal));
455
+ });
456
+ });
457
+ options.signal?.addEventListener("abort", stop, { once: true });
458
+ if (options.signal?.aborted === true)
459
+ stop();
460
+ node.stdin?.on("error", () => {
461
+ /* the program closed its input early; the writer sees the error, and the program's status says what it did */
462
+ });
463
+ // Node's streams become web streams; their types are `node:stream/web`'s, which are the same classes as the global ones.
464
+ const stdin = node.stdin === null ? null : Writable.toWeb(node.stdin);
465
+ const stdout = node.stdout === null ? null : Readable.toWeb(node.stdout);
466
+ const stderr = node.stderr === null ? null : Readable.toWeb(node.stderr);
467
+ // A pipe is a `net.Socket`, which can be unreferenced; the stream types do not say so.
468
+ const pipes = () => [node.stdin, node.stdout, node.stderr].flatMap((s) => (s === null ? [] : [s]));
469
+ return {
470
+ pipes: { pid: node.pid ?? 0, stdin, stdout, stderr },
471
+ exited,
472
+ kill: (signal = "SIGTERM") => {
473
+ if (!ended)
474
+ node.kill(signal);
475
+ },
476
+ ref: () => {
477
+ node.ref();
478
+ for (const p of pipes())
479
+ p.ref?.();
480
+ },
481
+ unref: () => {
482
+ node.unref();
483
+ for (const p of pipes())
484
+ p.unref?.();
485
+ },
486
+ dispose: async () => {
487
+ stop();
488
+ await exited.catch(() => undefined);
489
+ for (const p of [node.stdin, node.stdout, node.stderr])
490
+ p?.destroy();
491
+ },
492
+ };
493
+ }
494
+ /** A function called when the process receives the signal. */
495
+ export function addSignalListener(signal, handler) {
496
+ process.on(signal, handler);
497
+ }
498
+ /** A function no longer called for the signal. */
499
+ export function removeSignalListener(signal, handler) {
500
+ process.off(signal, handler);
501
+ }
502
+ /** A promise that settles after `ms` milliseconds; an aborted `signal` rejects it early with the signal's reason. */
503
+ export function sleep(ms, signal) {
504
+ return new Promise((resolve, reject) => {
505
+ if (signal?.aborted === true) {
506
+ reject(toError(signal.reason, "aborted"));
507
+ return;
508
+ }
509
+ const t = setTimeout(() => {
510
+ signal?.removeEventListener("abort", onAbort);
511
+ resolve();
512
+ }, ms);
513
+ const onAbort = () => {
514
+ clearTimeout(t);
515
+ reject(toError(signal?.reason, "aborted"));
516
+ };
517
+ signal?.addEventListener("abort", onAbort, { once: true });
518
+ });
519
+ }
520
+ /**
521
+ * Calls `callback` after `ms` milliseconds, with a timer that never keeps the process alive (FR-053): where nothing
522
+ * else is left to do, the process ends without waiting for it. It is made on `node:timers`, whose timers can be unreferenced on each
523
+ * runtime.
524
+ */
525
+ export function unrefTimer(callback, ms) {
526
+ const t = nodeSetTimeout(callback, ms);
527
+ t.unref();
528
+ const clear = () => clearTimeout(t);
529
+ return { clear, [Symbol.dispose]: clear };
530
+ }
531
+ /** The facts of this process, for `selfCommandOf`. */
532
+ export function selfFacts() {
533
+ return { runtime: runtimeName(), execPath: process.execPath, argv: [...process.argv], execArgv: [...process.execArgv] };
534
+ }
535
+ /** The names a runtime's own executable starts with (`bun`, `bun-debug`, `node`, `nodejs`, `node26`, `node.exe`, ...). */
536
+ const RUNTIME_EXECUTABLE = /^(?:bun|node)(?:[-._\d]|js|$)/i;
537
+ /**
538
+ * Whether the running program is a binary that holds its own code (FR-053), so that running it again needs no script. Either is enough:
539
+ * - Bun's own mark of a binary it compiled: the script's path, `process.argv[1]`, is in Bun's embedded file system (`/$bunfs/...`, or
540
+ * `B:\~BUN\...` on Windows), where it keeps the code it compiled in;
541
+ * - the executable, `process.execPath`, is not named as a runtime is (`bun`, `node`, with any version or `.exe`): the binaries
542
+ * that `bun build --compile` and Node's single executable applications make are named after the program.
543
+ */
544
+ export function isCompiled(facts) {
545
+ const script = facts.argv[1] ?? "";
546
+ if (script.startsWith("/$bunfs/") || /^[A-Za-z]:[\\/]~BUN[\\/]/.test(script))
547
+ return true;
548
+ return !RUNTIME_EXECUTABLE.test(basename(facts.execPath.replace(/\\/g, "/")));
549
+ }
550
+ /**
551
+ * The argument vector that runs the program again with `args` (FR-053): from a compiled binary,
552
+ * the binary alone; on Bun and Node, the runtime with its own options (`process.execArgv`) and the script. With no script (code given on the command line), the runtime alone.
553
+ */
554
+ export function selfCommandOf(facts, args = []) {
555
+ if (isCompiled(facts))
556
+ return [facts.execPath, ...args];
557
+ const script = facts.argv[1];
558
+ const scriptArgs = script === undefined ? [] : [script];
559
+ switch (facts.runtime) {
560
+ case "bun":
561
+ case "node":
562
+ return [facts.execPath, ...facts.execArgv, ...scriptArgs, ...args];
563
+ default:
564
+ return absurd(facts.runtime);
565
+ }
566
+ }
567
+ /** The argument vector that runs this program again with `args`, on Bun and Node and from a binary Bun compiled (FR-053). */
568
+ export function selfCommand(args = []) {
569
+ return selfCommandOf(selfFacts(), args);
570
+ }
571
+ /** Every address of every network interface of this computer (0005-typescript-runtime FR-056). */
572
+ export function networkInterfaces() {
573
+ const out = [];
574
+ for (const [name, infos] of Object.entries(os.networkInterfaces())) {
575
+ for (const i of infos ?? []) {
576
+ out.push({
577
+ name,
578
+ family: net.isIPv6(i.address) ? "IPv6" : "IPv4",
579
+ address: i.address,
580
+ netmask: i.netmask,
581
+ cidr: i.cidr,
582
+ scopeid: i.family === "IPv6" ? i.scopeid : null,
583
+ mac: i.mac,
584
+ internal: i.internal,
585
+ });
586
+ }
587
+ }
588
+ return out;
589
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * The operating system's own scheduled job, installed and removed (commons 0005-typescript-runtime FR-046): `installJob` plans the job
3
+ * with the kernel's `planJob`, writes its files under the home folder (making their folders, with their modes) and runs the commands that
4
+ * load it; `removeJob` runs the commands that unload it, removes its files and runs what follows (systemd's `daemon-reload`). Each file and
5
+ * each command is reported as an outcome, and the first failure that matters is a typed error carrying the outcomes until then; a
6
+ * command marked `mayFail` (nothing to unload) never stops the rest. The scheduler, the home folder, the user's id and the program that
7
+ * runs a command are parameters, defaulting to this computer's (`build.os`, `homeDir()`, `uid()`, `run`), so a test plans and installs any
8
+ * scheduler's job in a temporary folder with a fake runner, and no real systemctl, launchctl or schtasks runs. Taken from Stolos's
9
+ * `src/archon/export/schedule.ts` (`installJob`, `uninstallJob`), which took its file and command functions as dependencies and threw;
10
+ * here the files go through `./fs.ts`, the commands through `./proc.ts` or a given runner, and errors are values.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * import { jobName, schedule } from "./job-plan.js";
15
+ * import { installJob } from "./schedule.js";
16
+ * const name = jobName("backup");
17
+ * const when = schedule({ kind: "weekly", day: "sun", hour: 3, minute: 30 });
18
+ * if (name.kind === "ok" && when.kind === "ok") {
19
+ * const r = await installJob({ name: name.value, owner: { domain: "org.example", folder: "Example" }, argv: ["/usr/bin/backup"], workdir: "/srv", when: when.value });
20
+ * if (r.kind === "err") console.error(r.error.kind);
21
+ * }
22
+ * ```
23
+ *
24
+ * @module
25
+ */
26
+ import { type Result } from "@intellectual-frontiers/core";
27
+ import { type JobPlan, type JobSpec, type ScheduleError, type SchedulerOs } from "./job-plan.js";
28
+ /** What a command did: its exit status (127 where it could not be started) and what it said (standard error, else standard output, trimmed). */
29
+ export type StepResult = {
30
+ readonly code: number;
31
+ readonly output: string;
32
+ };
33
+ /** Runs one command by its argument vector; the default runs it with `./proc.ts`, a test gives a fake. Never rejects for a failure of the command. */
34
+ export type StepRunner = (argv: readonly string[]) => Promise<StepResult>;
35
+ /** The default runner: the program run with `run`, never through a shell; one that cannot be started gives status 127 and the reason. */
36
+ export declare const runStep: StepRunner;
37
+ /** Where and how to install or remove a job; every field defaults to this computer. */
38
+ export type JobOptions = {
39
+ /** The scheduler (`build.os` by default). */
40
+ readonly os?: SchedulerOs;
41
+ /** The user's home folder, under which the files go (`homeDir()` by default). */
42
+ readonly home?: string;
43
+ /** The user's numeric id, for launchctl's `gui/<uid>` domain (`uid()` by default). */
44
+ readonly uid?: number;
45
+ /** What runs each command (`runStep` by default). */
46
+ readonly runner?: StepRunner;
47
+ };
48
+ /** One thing done: a file written or removed (its absolute path, and whether it was there), or a command run (its status and output). */
49
+ export type Outcome = {
50
+ readonly kind: "wrote";
51
+ readonly path: string;
52
+ } | {
53
+ readonly kind: "removed";
54
+ readonly path: string;
55
+ readonly existed: boolean;
56
+ } | {
57
+ readonly kind: "ran";
58
+ readonly argv: readonly string[];
59
+ readonly code: number;
60
+ readonly output: string;
61
+ readonly mayFail: boolean;
62
+ };
63
+ /** A job installed or removed: its plan and what was done, in order. */
64
+ export type JobReport = {
65
+ readonly plan: JobPlan;
66
+ readonly outcomes: readonly Outcome[];
67
+ };
68
+ /** Why installing or removing stopped, with what was done until then. */
69
+ export type JobError = {
70
+ readonly kind: "unsupported";
71
+ readonly os: string;
72
+ readonly outcomes: readonly Outcome[];
73
+ } | {
74
+ readonly kind: "plan";
75
+ readonly error: ScheduleError;
76
+ readonly outcomes: readonly Outcome[];
77
+ } | {
78
+ readonly kind: "write";
79
+ readonly path: string;
80
+ readonly message: string;
81
+ readonly outcomes: readonly Outcome[];
82
+ } | {
83
+ readonly kind: "remove";
84
+ readonly path: string;
85
+ readonly message: string;
86
+ readonly outcomes: readonly Outcome[];
87
+ } | {
88
+ readonly kind: "step";
89
+ readonly argv: readonly string[];
90
+ readonly code: number;
91
+ readonly output: string;
92
+ readonly outcomes: readonly Outcome[];
93
+ };
94
+ /** A job error as one line. */
95
+ export declare function formatJobError(e: JobError): string;
96
+ /** A job scheduled: planned, its files written (their folders made, their modes set), then the commands that load it run. */
97
+ export declare function installJob(job: JobSpec, options?: JobOptions): Promise<Result<JobReport, JobError>>;
98
+ /** A job unscheduled: the commands that unload it run, its files removed (one already gone is no error), then what follows run. */
99
+ export declare function removeJob(job: JobSpec, options?: JobOptions): Promise<Result<JobReport, JobError>>;