@mostra/runtime 0.3.0 → 0.4.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.
@@ -1,26 +1,45 @@
1
1
  /**
2
- * The home's login service (D62, D63, RT-08): `mostra daemon install` registers the home's daemon
3
- * with the user's service manager, so an artifact answers at any hour, even after a reboot. A
4
- * launchd agent on macOS, a systemd user unit on Linux; either runs `mostra-runtime daemon
5
- * --always-on --home <home>`, which never exits for lack of work, and restarts it when it ends
6
- * unexpectedly. The unit carries no secret: the daemon reads them from the home (D44).
2
+ * The home's login service (D62, D63, RT-08, RT-11): `mostra daemon install` registers the home's
3
+ * daemon with the user's service manager, so an artifact answers at any hour, even after a reboot.
4
+ * A launchd agent on macOS, a systemd user unit on Linux, a Task Scheduler task at the user's logon
5
+ * on Windows (D151); each runs `mostra-runtime daemon --always-on --home <home>`, which never
6
+ * exits for lack of work, and restarts it when it ends unexpectedly. On Windows the task runs the
7
+ * daemon through `mostra-win-service`, a launcher without a console, so no window opens at logon,
8
+ * which also does the restarting (Task Scheduler's own setting didn't, VERIFIED_FACTS WP-W2). The
9
+ * definition carries no secret: the daemon reads them from the home (D44).
7
10
  */
8
- import { execFileSync } from "node:child_process";
9
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
11
+ import { execFile, execFileSync } from "node:child_process";
12
+ import { randomBytes } from "node:crypto";
13
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
10
14
  import { homedir } from "node:os";
11
- import { dirname, join } from "node:path";
12
- import { createDiagnostic, RpcError } from "@mostra/protocol";
13
- import { homeHash } from "../home/index.ts";
15
+ import { dirname, join, win32 } from "node:path";
16
+ import {
17
+ type ClientInfo,
18
+ createDiagnostic,
19
+ mostraShutdownMethod,
20
+ RpcError,
21
+ } from "@mostra/protocol";
22
+ import { homeHash, readLiveInstanceRecord } from "../home/index.ts";
14
23
  import type { Environment } from "../log.ts";
15
- import { OS } from "../platform/index.ts";
24
+ import {
25
+ currentUserSid,
26
+ isSameProcess,
27
+ OS,
28
+ serviceLauncherPath,
29
+ stopServiceLauncher,
30
+ } from "../platform/index.ts";
31
+ import { attach } from "../protocol-server/index.ts";
16
32
 
17
33
  /** Where a home's service is, and whether it is there. */
18
34
  export interface ServiceStatus {
19
- /** `launchd` (macOS) or `systemd` (Linux). */
20
- readonly manager: "launchd" | "systemd";
21
- /** The service's name: the launchd label, or the systemd unit. */
35
+ /** `launchd` (macOS), `systemd` (Linux) or `task-scheduler` (Windows). */
36
+ readonly manager: "launchd" | "systemd" | "task-scheduler";
37
+ /** The service's name: the launchd label, the systemd unit, or the scheduled task. */
22
38
  readonly name: string;
23
- /** The file that defines it. */
39
+ /**
40
+ * The file that defines it. On Windows the task's definition as Mostra registered it, kept in
41
+ * the home (`<home>\service\task.xml`): Task Scheduler keeps its own copy.
42
+ */
24
43
  readonly file: string;
25
44
  /** Whether the file exists. */
26
45
  readonly installed: boolean;
@@ -38,6 +57,10 @@ export interface ServiceSpec {
38
57
  readonly env?: Environment;
39
58
  /** The operating system (`OS` of the platform layer). */
40
59
  readonly platform?: string;
60
+ /** Windows: the user the task runs as, a SID; default the current user. */
61
+ readonly user?: string;
62
+ /** Windows: the launcher; default `mostra-win-service.exe` beside the helper. */
63
+ readonly launcher?: string;
41
64
  }
42
65
 
43
66
  function failed(message: string): RpcError {
@@ -70,6 +93,25 @@ export function serviceFor(spec: ServiceSpec): ServiceStatus {
70
93
  const file = join(config, "systemd", "user", name);
71
94
  return { manager: "systemd", name, file, installed: existsSync(file), command };
72
95
  }
96
+ if (platform === "win32") {
97
+ const file = win32.join(spec.home, "service", "task.xml");
98
+ return {
99
+ manager: "task-scheduler",
100
+ name: `mostra-${hash.toLowerCase()}`,
101
+ file,
102
+ installed: existsSync(file),
103
+ command: [
104
+ spec.launcher ?? launcherOrName(),
105
+ "--stop-event",
106
+ stopEventOf(file) ?? newStopEvent(hash),
107
+ "--log",
108
+ win32.join(spec.home, "logs", "service.log"),
109
+ ...windowsServiceVariables(env).flatMap(([name, value]) => ["--env", `${name}=${value}`]),
110
+ "--",
111
+ ...command,
112
+ ],
113
+ };
114
+ }
73
115
  throw new RpcError(
74
116
  createDiagnostic("MOSTRA_PLATFORM_UNSUPPORTED", {
75
117
  message: `Mostra can't install a login service on ${platform}.`,
@@ -77,18 +119,156 @@ export function serviceFor(spec: ServiceSpec): ServiceStatus {
77
119
  );
78
120
  }
79
121
 
122
+ /**
123
+ * What a Windows task passes on besides the user's logon environment, which Task Scheduler gives
124
+ * it: the development switch while Windows needs it (D150 item 7, until WP-W3), the helper a
125
+ * checkout names, and the locale and time zone, as the POSIX units carry theirs. Nothing secret.
126
+ */
127
+ function windowsServiceVariables(env: Environment): [string, string][] {
128
+ return ["MOSTRA_DEV_WINDOWS", "MOSTRA_WIN_HELPER", "LANG", "TZ"].flatMap((name) => {
129
+ const value = env[name];
130
+ return value ? [[name, value] as [string, string]] : [];
131
+ });
132
+ }
133
+
134
+ /**
135
+ * A new name for the event that asks a home's launcher to stop: in `Local\` (the logon session's
136
+ * namespace, the only one an ordinary user may create names in), with a random part, so nobody who
137
+ * can't read the task or the home can create it first (Opus review of WP-W2, finding 6).
138
+ */
139
+ const newStopEvent = (hash: string): string =>
140
+ `Local\\mostra-service-${hash.toLowerCase()}-${randomBytes(8).toString("hex")}`;
141
+
142
+ /** The stop event a definition Mostra wrote names, if the file is there. */
143
+ function stopEventOf(file: string): string | undefined {
144
+ try {
145
+ const text = readFileSync(file).toString("utf16le");
146
+ return /--stop-event (Local\\mostra-service-[0-9a-z]+-[0-9a-f]{16})\b/.exec(text)?.[1];
147
+ } catch {
148
+ return undefined;
149
+ }
150
+ }
151
+
152
+ /** The launcher's path, or its bare name where it isn't installed (a status only reads it). */
153
+ function launcherOrName(): string {
154
+ try {
155
+ return serviceLauncherPath();
156
+ } catch {
157
+ return "mostra-win-service.exe";
158
+ }
159
+ }
160
+
161
+ /** One word of a Windows command line, quoted as the Microsoft C runtime parses it. */
162
+ export function windowsArgument(word: string): string {
163
+ if (word !== "" && !/[\s"]/.test(word)) return word;
164
+ let out = '"';
165
+ let backslashes = 0;
166
+ for (const char of word) {
167
+ if (char === "\\") {
168
+ backslashes += 1;
169
+ continue;
170
+ }
171
+ out += "\\".repeat(char === '"' ? backslashes * 2 + 1 : backslashes) + char;
172
+ backslashes = 0;
173
+ }
174
+ return `${out}${"\\".repeat(backslashes * 2)}"`;
175
+ }
176
+
177
+ /** The Task Scheduler definition (schema 1.2) of a home's task. */
178
+ function taskFile(spec: ServiceSpec, status: ServiceStatus): string {
179
+ const user = xml(spec.user ?? currentUserSid());
180
+ const [program = "", ...args] = status.command;
181
+ return `<?xml version="1.0" encoding="UTF-16"?>
182
+ <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
183
+ <RegistrationInfo>
184
+ <Description>${xml(`Mostra daemon for ${spec.home}`)}</Description>
185
+ </RegistrationInfo>
186
+ <Triggers>
187
+ <LogonTrigger>
188
+ <Enabled>true</Enabled>
189
+ <UserId>${user}</UserId>
190
+ </LogonTrigger>
191
+ </Triggers>
192
+ <Principals>
193
+ <Principal id="Author">
194
+ <UserId>${user}</UserId>
195
+ <LogonType>InteractiveToken</LogonType>
196
+ <RunLevel>LeastPrivilege</RunLevel>
197
+ </Principal>
198
+ </Principals>
199
+ <Settings>
200
+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
201
+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
202
+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
203
+ <AllowHardTerminate>true</AllowHardTerminate>
204
+ <StartWhenAvailable>false</StartWhenAvailable>
205
+ <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
206
+ <IdleSettings>
207
+ <StopOnIdleEnd>false</StopOnIdleEnd>
208
+ <RestartOnIdle>false</RestartOnIdle>
209
+ </IdleSettings>
210
+ <AllowStartOnDemand>true</AllowStartOnDemand>
211
+ <Enabled>true</Enabled>
212
+ <Hidden>false</Hidden>
213
+ <RunOnlyIfIdle>false</RunOnlyIfIdle>
214
+ <WakeToRun>false</WakeToRun>
215
+ <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
216
+ <Priority>5</Priority>
217
+ </Settings>
218
+ <Actions Context="Author">
219
+ <Exec>
220
+ <Command>${xml(program)}</Command>
221
+ <Arguments>${xml(args.map(windowsArgument).join(" "))}</Arguments>
222
+ </Exec>
223
+ </Actions>
224
+ </Task>
225
+ `;
226
+ }
227
+
80
228
  /**
81
229
  * Whether `home` has a login service installed: its daemon then never exits for lack of work,
82
230
  * whoever started it, so a daemon started by hand before `install` keeps the artifacts answering.
83
231
  */
84
232
  export function hasLoginService(home: string, env: Environment = process.env): boolean {
85
233
  try {
86
- return serviceFor({ home, node: "", entry: "", env }).installed;
234
+ const status = serviceFor({ home, node: "", entry: "", env });
235
+ if (!status.installed) return false;
236
+ return status.manager !== "task-scheduler" || registeredLately(status);
87
237
  } catch {
88
238
  return false;
89
239
  }
90
240
  }
91
241
 
242
+ /** What the idle check last learnt of each task: whether Task Scheduler holds it, and when. */
243
+ const registrations = new Map<string, { registered?: boolean; at: number; asking: boolean }>();
244
+
245
+ /**
246
+ * Whether Task Scheduler held the task when last asked, asking again in the background at most
247
+ * once a minute: the idle check runs every few seconds and must never wait for `schtasks`. A task
248
+ * removed in Task Scheduler's own window then stops counting, so a daemon started by hand exits
249
+ * when idle again (Opus review of WP-W2, finding 5). Until the first answer, the definition in the
250
+ * home counts.
251
+ */
252
+ function registeredLately(status: ServiceStatus): boolean {
253
+ const interval = Number(process.env["MOSTRA_TEST_SERVICE_QUERY_MS"]) || 60_000;
254
+ const entry = registrations.get(status.name) ?? { at: Number.NEGATIVE_INFINITY, asking: false };
255
+ registrations.set(status.name, entry);
256
+ if (!entry.asking && Date.now() - entry.at >= interval) {
257
+ entry.asking = true;
258
+ execFile(
259
+ "schtasks",
260
+ ["/Query", "/TN", status.name],
261
+ { timeout: 30_000, windowsHide: true },
262
+ (error) => {
263
+ entry.registered = error === null;
264
+ entry.at = Date.now();
265
+ entry.asking = false;
266
+ },
267
+ );
268
+ }
269
+ return entry.registered ?? true;
270
+ }
271
+
92
272
  const xml = (text: string): string =>
93
273
  text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
94
274
 
@@ -118,6 +298,8 @@ function serviceEnvironment(env: Environment): Record<string, string> {
118
298
 
119
299
  /** The text of the service's file. */
120
300
  export function serviceFile(spec: ServiceSpec, status: ServiceStatus): string {
301
+ // The task runs in the user's own logon environment, as any program they start does.
302
+ if (status.manager === "task-scheduler") return taskFile(spec, status);
121
303
  const env = serviceEnvironment(spec.env ?? process.env);
122
304
  const log = join(spec.home, "logs", "service.log");
123
305
  if (status.manager === "launchd") {
@@ -179,6 +361,8 @@ WantedBy=default.target
179
361
  export interface ServiceOptions {
180
362
  /** Write the file only, without asking the service manager to start it (tests). */
181
363
  readonly noStart?: boolean;
364
+ /** Who asks, when a Windows uninstall stops the daemon over its pipe. */
365
+ readonly client?: ClientInfo;
182
366
  }
183
367
 
184
368
  function run(command: string, args: readonly string[]): void {
@@ -193,44 +377,169 @@ function run(command: string, args: readonly string[]): void {
193
377
 
194
378
  const uid = (): number => process.getuid?.() ?? 0;
195
379
 
380
+ /** The definition's bytes: Task Scheduler reads UTF-16 with its byte order mark. */
381
+ function encoded(status: ServiceStatus, text: string): Buffer | string {
382
+ return status.manager === "task-scheduler" ? Buffer.from(`\ufeff${text}`, "utf16le") : text;
383
+ }
384
+
385
+ /** The definition as written, decoded as {@link encoded} wrote it. */
386
+ function readDefinition(status: ServiceStatus): string {
387
+ const bytes = readFileSync(status.file);
388
+ if (status.manager !== "task-scheduler") return bytes.toString("utf8");
389
+ return bytes.toString("utf16le").replace(/^\ufeff/, "");
390
+ }
391
+
196
392
  /** Installs the home's daemon as a login service and starts it, replacing an earlier one. */
197
- export function installService(spec: ServiceSpec, options: ServiceOptions = {}): ServiceStatus {
198
- const status = serviceFor(spec);
393
+ export async function installService(
394
+ spec: ServiceSpec,
395
+ options: ServiceOptions = {},
396
+ ): Promise<ServiceStatus> {
397
+ // On Windows a launcher that isn't there is MOSTRA_ENV_HELPER_MISSING before anything is written.
398
+ const status = serviceFor(
399
+ (spec.platform ?? OS) === "win32" && spec.launcher === undefined
400
+ ? { ...spec, launcher: serviceLauncherPath() }
401
+ : spec,
402
+ );
199
403
  const text = serviceFile(spec, status);
404
+ // Windows: the home keeps the definition only once Task Scheduler took it, so a definition in
405
+ // the home names a task that was registered (Opus review of WP-W2, finding 5).
406
+ const registering = status.manager === "task-scheduler" && !options.noStart;
407
+ const written = registering ? `${status.file}.new` : status.file;
200
408
  try {
201
409
  mkdirSync(dirname(status.file), { recursive: true });
202
410
  mkdirSync(join(spec.home, "logs"), { recursive: true, mode: 0o700 });
203
- if (status.installed && !options.noStart) stopService(status);
204
- writeFileSync(status.file, text, { mode: 0o644 });
411
+ if (status.installed && !options.noStart) await stopService(status, spec.home, options);
412
+ writeFileSync(written, encoded(status, text), { mode: 0o644 });
205
413
  } catch (error) {
206
414
  if (error instanceof RpcError) throw error;
207
415
  throw failed(`Writing ${status.file} failed: ${(error as Error).message}`);
208
416
  }
417
+ if (registering) {
418
+ try {
419
+ run("schtasks", ["/Create", "/TN", status.name, "/XML", written, "/F"]);
420
+ renameSync(written, status.file);
421
+ } finally {
422
+ rmSync(written, { force: true });
423
+ }
424
+ registrations.delete(status.name);
425
+ }
209
426
  if (!options.noStart) {
210
427
  if (status.manager === "launchd") {
211
428
  run("launchctl", ["bootstrap", `gui/${uid()}`, status.file]);
212
- } else {
429
+ } else if (status.manager === "systemd") {
213
430
  run("systemctl", ["--user", "daemon-reload"]);
214
431
  run("systemctl", ["--user", "enable", "--now", status.name]);
432
+ } else {
433
+ // Registered above for the user's own logons, which needs no elevation (InteractiveToken),
434
+ // and started now, as launchd's RunAtLoad and systemd's `--now` start theirs.
435
+ run("schtasks", ["/Run", "/TN", status.name]);
215
436
  }
216
437
  }
217
438
  return { ...status, installed: true };
218
439
  }
219
440
 
220
- function stopService(status: ServiceStatus): void {
441
+ async function stopService(
442
+ status: ServiceStatus,
443
+ home: string,
444
+ options: ServiceOptions,
445
+ ): Promise<void> {
221
446
  try {
222
447
  if (status.manager === "launchd") run("launchctl", ["bootout", `gui/${uid()}/${status.name}`]);
223
- else run("systemctl", ["--user", "disable", "--now", status.name]);
448
+ else if (status.manager === "systemd")
449
+ run("systemctl", ["--user", "disable", "--now", status.name]);
450
+ else await stopTask(status, home, options);
224
451
  } catch {
225
452
  // Not loaded: nothing to stop.
226
453
  }
227
454
  }
228
455
 
229
- /** Stops and removes the home's login service; a home without one is left as it is. */
230
- export function uninstallService(spec: ServiceSpec, options: ServiceOptions = {}): ServiceStatus {
456
+ /**
457
+ * Stops and deletes a home's task, the daemon first and in order (D87), as launchd's `bootout`
458
+ * and systemd's `disable --now` send it SIGTERM:
459
+ * - through the launcher's stop event, when this logon session has it: the launcher gives the
460
+ * daemon Ctrl+Break, which the runtime handles as `mostra/shutdown`;
461
+ * - otherwise (the launcher runs in another session, as when the user is logged on at the console
462
+ * and uninstalls over SSH, or the home lost the definition naming the event) with
463
+ * `mostra/shutdown` over the home's pipe, which reaches the daemon from any session; its exit
464
+ * with code 0 ends the launcher (Opus review of WP-W2, finding 4);
465
+ *
466
+ * then the task is ended, which ends whatever its job still holds, and deleted.
467
+ */
468
+ async function stopTask(
469
+ status: ServiceStatus,
470
+ home: string,
471
+ options: ServiceOptions,
472
+ ): Promise<void> {
473
+ const event = status.installed
474
+ ? status.command[status.command.indexOf("--stop-event") + 1]
475
+ : undefined;
476
+ let signalled = false;
477
+ // A test stands for another session's launcher, whose event this session can't see.
478
+ if (event !== undefined && process.env["MOSTRA_TEST_SERVICE_STOP"] !== "pipe") {
479
+ try {
480
+ signalled = stopServiceLauncher(event).signalled;
481
+ } catch {
482
+ // The helper couldn't ask: the pipe below stops the daemon.
483
+ }
484
+ }
485
+ if (!signalled) await shutDownInstance(home, options.client);
486
+ try {
487
+ run("schtasks", ["/End", "/TN", status.name]);
488
+ } catch {
489
+ // Not running.
490
+ }
491
+ run("schtasks", ["/Delete", "/TN", status.name, "/F"]);
492
+ registrations.delete(status.name);
493
+ }
494
+
495
+ /** Asks the home's running daemon, if any, to stop (`mostra/shutdown`), and waits until it has. */
496
+ async function shutDownInstance(home: string, client: ClientInfo | undefined): Promise<void> {
497
+ const record = await readLiveInstanceRecord(home);
498
+ if (record === undefined || record.mode !== "daemon") return;
499
+ try {
500
+ const session = await attach(record.socket, client ?? { name: "mostra-service", version: "0" });
501
+ await session.client.peer
502
+ .call(mostraShutdownMethod, {}, { timeoutMs: 10_000 })
503
+ .catch(() => undefined);
504
+ session.client.close();
505
+ } catch {
506
+ // Unreachable: ending the task stops it.
507
+ return;
508
+ }
509
+ const deadline = Date.now() + 20_000;
510
+ while (Date.now() < deadline && (await isSameProcess(record.pid, record.startTime))) {
511
+ await new Promise((resolve) => setTimeout(resolve, 100));
512
+ }
513
+ }
514
+
515
+ /** Whether Task Scheduler holds the home's task. */
516
+ function taskRegistered(status: ServiceStatus): boolean {
517
+ try {
518
+ run("schtasks", ["/Query", "/TN", status.name]);
519
+ return true;
520
+ } catch {
521
+ return false;
522
+ }
523
+ }
524
+
525
+ /**
526
+ * Stops and removes the home's login service; a home without one is left as it is. On Windows a
527
+ * task Task Scheduler still holds is removed though the home lost its definition (restored from a
528
+ * backup, removed by hand), or the task would keep starting the daemon at every logon (Opus review
529
+ * of WP-W2, finding 5).
530
+ */
531
+ export async function uninstallService(
532
+ spec: ServiceSpec,
533
+ options: ServiceOptions = {},
534
+ ): Promise<ServiceStatus> {
231
535
  const status = serviceFor(spec);
232
- if (!status.installed) return status;
233
- if (!options.noStart) stopService(status);
536
+ const orphaned =
537
+ !status.installed &&
538
+ status.manager === "task-scheduler" &&
539
+ !options.noStart &&
540
+ taskRegistered(status);
541
+ if (!status.installed && !orphaned) return status;
542
+ if (!options.noStart) await stopService(status, spec.home, options);
234
543
  rmSync(status.file, { force: true });
235
544
  if (!options.noStart && status.manager === "systemd") {
236
545
  try {
@@ -242,10 +551,20 @@ export function uninstallService(spec: ServiceSpec, options: ServiceOptions = {}
242
551
  return { ...status, installed: false };
243
552
  }
244
553
 
245
- /** Whether the home has a login service whose file runs this home's daemon (`mostra doctor`). */
246
- export function serviceStatus(spec: ServiceSpec): ServiceStatus & { readonly current: boolean } {
554
+ /**
555
+ * Whether the home has a login service whose file runs this home's daemon (`mostra doctor`); on
556
+ * Windows also whether Task Scheduler holds its task (`registered`).
557
+ */
558
+ export function serviceStatus(
559
+ spec: ServiceSpec,
560
+ ): ServiceStatus & { readonly current: boolean; readonly registered?: boolean } {
247
561
  const status = serviceFor(spec);
248
- if (!status.installed) return { ...status, current: false };
249
- const text = readFileSync(status.file, "utf8");
250
- return { ...status, current: text === serviceFile(spec, status) };
562
+ const registered =
563
+ status.manager === "task-scheduler" ? { registered: taskRegistered(status) } : {};
564
+ if (!status.installed) return { ...status, current: false, ...registered };
565
+ return {
566
+ ...status,
567
+ current: readDefinition(status) === serviceFile(spec, status),
568
+ ...registered,
569
+ };
251
570
  }
@@ -210,6 +210,19 @@ const PINGS_MISSED_BEFORE_STOP = 3;
210
210
  */
211
211
  const OOM_STALL_FRACTION = 0.8;
212
212
 
213
+ /**
214
+ * An exit code as people look it up: a Windows status (`0xC0000005`, an access violation) in
215
+ * hexadecimal, any other code as a number. Node.js reports a Windows status as an unsigned
216
+ * 32-bit number; on POSIX codes are below 256.
217
+ */
218
+ export function exitCodeText(code: number | null): string {
219
+ if (code === null) return "?";
220
+ if (code >= 0x80000000 || code < 0) {
221
+ return `0x${(code >>> 0).toString(16).toUpperCase().padStart(8, "0")}`;
222
+ }
223
+ return String(code);
224
+ }
225
+
213
226
  function crashed(message: string): RpcError {
214
227
  return new RpcError(createDiagnostic("MOSTRA_RUNTIME_WORKER_CRASHED", { message }));
215
228
  }
@@ -298,7 +311,7 @@ export function createWorkerPool(options: WorkerPoolOptions): WorkerPool {
298
311
  const how =
299
312
  exit.signal !== null
300
313
  ? `it was ended by ${exit.signal}`
301
- : `it exited with code ${exit.code ?? "?"}`;
314
+ : `it exited with code ${exitCodeText(exit.code)}`;
302
315
  return { kind: "crash", cause: last ? `${how}: ${last.slice(0, 300)}` : how };
303
316
  };
304
317
 
@@ -1 +0,0 @@
1
- {"version":3,"file":"child-BQc3arf7.js","names":[],"sources":["../src/processes/child.ts"],"sourcesContent":["/**\n * The child side of supervisor messaging, for Node children the process manager starts with an\n * IPC channel. It wires the JSON-RPC core to Node IPC and keeps the rule that a child never\n * outlives its supervisor: when the channel disconnects (the supervisor exited or was killed), the\n * child signals its own process group, so grandchildren go too, and exits (FAILURE_MODEL §2).\n *\n * ```ts\n * const supervisor = connectToSupervisor({ onRequest: (method, params) => handle(method, params) });\n * await supervisor.request(\"child/adopt\", { pid: pty.pid }); // a program in its own session\n * ```\n */\nimport { type JsonRpcParams, RpcPeer } from \"@mostra/protocol\";\n\n/** Options for {@link connectToSupervisor}. */\nexport interface SupervisorConnectionOptions {\n /** Answers the supervisor's requests. */\n readonly onRequest?: (method: string, params: unknown) => unknown;\n /** Receives the supervisor's notifications. */\n readonly onNotification?: (method: string, params: unknown) => void;\n}\n\n/** The child's end of the connection. */\nexport interface SupervisorConnection {\n /** Sends a request to the supervisor, such as `child/adopt`. */\n request(method: string, params?: JsonRpcParams): Promise<unknown>;\n /** Sends a notification to the supervisor. */\n notify(method: string, params?: JsonRpcParams): void;\n}\n\n/**\n * Connects a Node child to its supervisor over the IPC channel.\n *\n * @throws Error when the process wasn't started with an IPC channel.\n */\nexport function connectToSupervisor(\n options: SupervisorConnectionOptions = {},\n): SupervisorConnection {\n const send = process.send?.bind(process);\n if (!send)\n throw new Error(\"This process wasn't started by a Mostra supervisor (no IPC channel).\");\n const peer = new RpcPeer({\n send: (message) => {\n send(message);\n },\n ...(options.onRequest ? { onRequest: options.onRequest } : {}),\n ...(options.onNotification ? { onNotification: options.onNotification } : {}),\n });\n process.on(\"message\", (message) => peer.receive(message));\n process.on(\"disconnect\", () => {\n peer.close();\n exitWithGroup();\n });\n return {\n request: (method, params) => peer.request(method, params),\n notify: (method, params) => peer.notify(method, params),\n };\n}\n\n/**\n * Signals this child's whole process group (it leads it) and exits. On Windows there is no group\n * to signal: the child's gate ends its Job Object, descendants included, once the child exits.\n */\nfunction exitWithGroup(): void {\n try {\n process.kill(-process.pid, \"SIGTERM\");\n } catch {\n // The group is already gone.\n }\n process.exit(0);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkCA,SAAgB,oBACd,UAAuC,CAAC,GAClB;CACtB,MAAM,OAAO,QAAQ,MAAM,KAAK,OAAO;CACvC,IAAI,CAAC,MACH,MAAM,IAAI,MAAM,sEAAsE;CACxF,MAAM,OAAO,IAAI,QAAQ;EACvB,OAAO,YAAY;GACjB,KAAK,OAAO;EACd;EACA,GAAI,QAAQ,YAAY,EAAE,WAAW,QAAQ,UAAU,IAAI,CAAC;EAC5D,GAAI,QAAQ,iBAAiB,EAAE,gBAAgB,QAAQ,eAAe,IAAI,CAAC;CAC7E,CAAC;CACD,QAAQ,GAAG,YAAY,YAAY,KAAK,QAAQ,OAAO,CAAC;CACxD,QAAQ,GAAG,oBAAoB;EAC7B,KAAK,MAAM;EACX,cAAc;CAChB,CAAC;CACD,OAAO;EACL,UAAU,QAAQ,WAAW,KAAK,QAAQ,QAAQ,MAAM;EACxD,SAAS,QAAQ,WAAW,KAAK,OAAO,QAAQ,MAAM;CACxD;AACF;;;;;AAMA,SAAS,gBAAsB;CAC7B,IAAI;EACF,QAAQ,KAAK,CAAC,QAAQ,KAAK,SAAS;CACtC,QAAQ,CAER;CACA,QAAQ,KAAK,CAAC;AAChB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"files-KxzOxckl.js","names":["BUNDLE_NAME"],"sources":["../src/builder/types.ts","../src/platform/helper.ts","../src/platform/directories.ts","../src/platform/files.ts"],"sourcesContent":["/**\n * The builder's types, shared by the supervisor side (`index.ts`) and the builder child\n * (`child/`). Nothing here imports the bundler, so the supervisor can use them.\n */\nimport type { ArtifactManifest, Diagnostic } from \"@mostra/protocol\";\nimport type { FieldCoverage } from \"./coverage.ts\";\n\n/** One `\"use server\"` export (D54, D55): what the client stub calls and the worker runs. */\nexport interface ServerFunctionEntry {\n /** `<module>#<export>`, for example `actions.ts#sendReply`. */\n readonly id: string;\n /** The module's path inside the artifact. */\n readonly module: string;\n /** The export's name (`default` for a default export). */\n readonly export: string;\n /** Whether the function references `dryRun()` from `@mostra/server`, opting into `verify`'s smoke test (D55). */\n readonly dryRun: boolean;\n}\n\n/** One route of a `pages/` artifact (D57). */\nexport interface PageRoute {\n /** The React Router path: `/`, `/settings`, `/reports/:id`. */\n readonly path: string;\n /** The page's file inside the artifact. */\n readonly file: string;\n}\n\n/**\n * What a version contains, read by `verify`, the shell, the worker and `results` (INTERFACES §11).\n * Written as `registry.json` in the version directory. Later packages add keys (fields, WP-07).\n */\nexport interface VersionRegistry {\n readonly schemaVersion: 1;\n /** The entry, inside the artifact. */\n readonly entry: string;\n /** Every `\"use server\"` export. */\n readonly actions: readonly ServerFunctionEntry[];\n /**\n * The live sources `live.ts` exports (D56), each with `always` when its `defineLive` literal\n * says it (WP-08); absent when the builder couldn't tell, and the worker reports it.\n */\n readonly liveSources: readonly { readonly key: string; readonly always?: boolean }[];\n /** The routes of `pages/`, empty for a single-page artifact. */\n readonly pages: readonly PageRoute[];\n /** The terminal sessions the manifest declares, by name. */\n readonly terminals: readonly string[];\n /** The web demos the manifest declares, by name. */\n readonly demos: readonly string[];\n /**\n * The field IDs the version's code can use (D109). Absent in versions built before WP-07, which\n * cover every field ID.\n */\n readonly fields?: FieldCoverage;\n}\n\n/** What the supervisor asks the builder child to build (`builder/build`). */\nexport interface BuildRequest {\n /** The staging directory; the artifact's snapshot is in its `source/`. */\n readonly stagingDir: string;\n /** The entry, inside the snapshot. */\n readonly entry: string;\n /** Whether the entry has a default export: the page, or with `pages/` the layout. */\n readonly entryHasDefault: boolean;\n /** The artifact's manifest (with its title resolved). */\n readonly manifest: ArtifactManifest;\n /**\n * The version being built (D89: known from the digests before the build). The page carries it\n * (`<meta name=\"mostra-version\">`), so a frame tells its shell which version it loaded (D98\n * item 5). Same digests, same ID, so the build stays a function of its inputs.\n */\n readonly versionId: string;\n /** The `node_modules` the build links: the warm layout, or the artifact's lock layout (D95). */\n readonly nodeModules: string;\n /** Where the client build goes; a server build goes beside it in `server/`. */\n readonly outDir: string;\n /**\n * Tests only (`MOSTRA_TEST_FAULTS=builder:build:hang`, issue #18): the child never answers,\n * as a builder stuck in a plugin would, so the build limit or a kill ends it.\n */\n readonly hang?: true;\n}\n\n/** The builder child's answer. */\nexport type BuildResponse =\n | { readonly ok: true; readonly registry: VersionRegistry; readonly server: boolean }\n | { readonly ok: false; readonly diagnostics: readonly Diagnostic[] };\n\n/** The IPC method the supervisor calls on the builder child. */\nexport const BUILD_METHOD = \"builder/build\";\n\n/**\n * `mostra dev`'s child (D140 item 12): the supervisor asks the builder child for a Vite dev\n * server over a mirror of the artifact's source, reached only through the dev sandbox's gateway.\n */\nexport const DEV_METHOD = \"builder/dev\";\n/**\n * Supervisor to child: these files of the mirror changed (`{ changes: DevChange[] }`). The child\n * watches nothing itself: the supervisor, which keeps the mirror, says exactly what changed.\n */\nexport const DEV_CHANGED_METHOD = \"builder/dev.changed\";\n\n/** One file of the mirror that changed, relative to its `source/`. */\nexport interface DevChange {\n readonly file: string;\n readonly kind: \"add\" | \"change\" | \"unlink\";\n}\n\n/** Supervisor to child: tell every page to load again (a new server bundle runs now). */\nexport const DEV_RELOAD_METHOD = \"builder/dev.reload\";\n/** Child to supervisor: the server bundle was built again (or failed to build). */\nexport const DEV_SERVER_NOTIFICATION = \"builder/dev.server\";\n/** Child to supervisor: the client modules of these files were updated in place (HMR). */\nexport const DEV_UPDATE_NOTIFICATION = \"builder/dev.update\";\n\n/** What the dev child serves. */\nexport interface DevRequest {\n /** The dev root: generated files, `node_modules`, and the mirror of the source in `source/`. */\n readonly root: string;\n readonly entry: string;\n readonly entryHasDefault: boolean;\n readonly manifest: ArtifactManifest;\n /** The dev version's ID, in every page's `mostra-version` meta (D115). */\n readonly versionId: string;\n readonly nodeModules: string;\n /** Where the server bundle and `registry.json` go: the dev version's directory. */\n readonly outDir: string;\n /** The secret every request from the gateway carries; nothing else reaches the dev server. */\n readonly secret: string;\n}\n\n/** The header that carries {@link DevRequest.secret}. */\nexport const DEV_SECRET_HEADER = \"x-mostra-dev-secret\";\n\n/** A server build of the dev child: what `registry.json` now holds, or why it failed. */\nexport type DevServerBuild =\n | { readonly ok: true; readonly registry: VersionRegistry; readonly server: boolean }\n | { readonly ok: false; readonly diagnostics: readonly Diagnostic[] };\n\n/** The dev child's answer to {@link DEV_METHOD}: its loopback port and its first server build. */\nexport interface DevReady {\n readonly port: number;\n readonly build: DevServerBuild;\n}\n\n/**\n * The files written into the staging root so the bundler's upward searches stop there instead of\n * reaching directories above the home (VR-01): a `tsconfig.json` with the compile settings Mostra\n * chooses (an artifact's own `tsconfig.json`, part of its source, still applies to its files),\n * and a `package.json` that marks the build as ES modules. Their contents are part of\n * `buildConfigDigest`.\n */\nexport const STAGING_FILES: Readonly<Record<string, string>> = {\n \"tsconfig.json\": `${JSON.stringify(\n {\n compilerOptions: {\n target: \"ES2022\",\n useDefineForClassFields: true,\n jsx: \"react-jsx\",\n jsxImportSource: \"react\",\n experimentalDecorators: false,\n },\n },\n null,\n 2,\n )}\\n`,\n \"package.json\": `${JSON.stringify({ private: true, type: \"module\" }, null, 2)}\\n`,\n};\n\n/**\n * The declaration that types `useLive` from `live.ts` (D56): client code reads the source types\n * through `typeof import`, never by importing server code at run time. Written beside the build's\n * other generated files for the type check, never into the artifact's source.\n */\nexport const LIVE_DECLARATION: string = `// Generated by Mostra: the types of this artifact's live sources (D56).\nimport type { LiveValuesOf } from \"@mostra/react\";\n\ndeclare module \"@mostra/react\" {\n interface LiveSources extends LiveValuesOf<typeof import(\"../source/live\")> {}\n}\n`;\n","/**\n * Running `mostra-win`, the Windows platform helper (`crates/mostra-win`, WP-W1): finding it and\n * reading its one-line JSON answers. The runtime asks it for what Node.js can't do on Windows:\n * owner-only access control, process identity by creation time, the child gate and reaping, and\n * the owner-only control pipe. Only this module's Windows code calls it.\n */\nimport { execFileSync, spawn } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\n\n/** The name `bundle.json` gives a runtime bundle (D142). */\nconst BUNDLE_NAME = \"mostra-runtime-bundle\";\n\n/** The directory of `@mostra/runtime`'s `package.json`, wherever the code runs from. */\nexport function runtimeRoot(): string {\n let dir = dirname(fileURLToPath(import.meta.url));\n for (;;) {\n const manifest = join(dir, \"package.json\");\n if (existsSync(manifest)) {\n const { name } = JSON.parse(readFileSync(manifest, \"utf8\")) as { name?: string };\n if (name === \"@mostra/runtime\") return dir;\n }\n const parent = dirname(dir);\n if (parent === dir) throw new Error(\"Couldn't find @mostra/runtime's package.json.\");\n dir = parent;\n }\n}\n\n/** The runtime bundle the runtime sits in (four levels above its package), if any. */\nfunction enclosingBundle(root: string): string | undefined {\n const bundle = resolve(root, \"..\", \"..\", \"..\", \"..\");\n try {\n const info = JSON.parse(readFileSync(join(bundle, \"bundle.json\"), \"utf8\")) as {\n name?: unknown;\n };\n return info.name === BUNDLE_NAME ? bundle : undefined;\n } catch {\n return undefined;\n }\n}\n\nlet located: string | undefined;\n\n/**\n * The helper's path: `MOSTRA_WIN_HELPER`; else the runtime bundle's `bin/mostra-win.exe`; else,\n * in a development checkout, the one Cargo built (`target/release`, then `target/debug`). Throws\n * `MOSTRA_ENV_HELPER_MISSING` when none exists.\n */\nexport function helperPath(env: NodeJS.ProcessEnv = process.env): string {\n const override = env[\"MOSTRA_WIN_HELPER\"];\n if (override) {\n if (!existsSync(override))\n throw missing(`MOSTRA_WIN_HELPER names ${override}, which doesn't exist.`);\n return override;\n }\n if (located !== undefined) return located;\n const root = runtimeRoot();\n const bundle = enclosingBundle(root);\n const candidates =\n bundle !== undefined\n ? [join(bundle, \"bin\", \"mostra-win.exe\")]\n : [\"release\", \"debug\"].map((profile) =>\n resolve(root, \"..\", \"..\", \"target\", profile, \"mostra-win.exe\"),\n );\n const found = candidates.find((candidate) => existsSync(candidate));\n if (found === undefined) {\n throw missing(`Mostra's Windows helper isn't installed; looked for ${candidates.join(\", \")}.`);\n }\n located = found;\n return found;\n}\n\nfunction missing(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_ENV_HELPER_MISSING\", { message }));\n}\n\n/** What the helper answers. */\ntype Answer<T> =\n | { readonly ok: true; readonly result: T }\n | { readonly ok: false; readonly error: { readonly message: string; readonly os?: number } };\n\n/** A failure the helper reported, with the Windows error code when there is one. */\nexport class HelperError extends Error {\n readonly os: number | undefined;\n constructor(command: string, message: string, os: number | undefined) {\n super(`mostra-win ${command}: ${message}`);\n this.os = os;\n }\n}\n\nfunction parse<T>(command: string, stdout: string): T {\n const line = stdout.trim().split(\"\\n\").at(-1) ?? \"\";\n let answer: Answer<T>;\n try {\n answer = JSON.parse(line) as Answer<T>;\n } catch {\n throw new HelperError(\n command,\n `answered something that isn't JSON: ${line.slice(0, 200)}`,\n undefined,\n );\n }\n if (!answer.ok)\n throw new HelperError(command, answer.error.message, answer.error.os ?? undefined);\n return answer.result;\n}\n\n/** Runs a helper command and returns its result; for the calls that must finish before going on. */\nexport function runHelper<T>(args: readonly string[]): T {\n const helper = helperPath();\n let stdout: string;\n try {\n stdout = execFileSync(helper, args, {\n encoding: \"utf8\",\n windowsHide: true,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n } catch (error) {\n const failed = error as { stdout?: string; message: string };\n if (failed.stdout) return parse<T>(args[0] ?? \"\", failed.stdout);\n throw new HelperError(args[0] ?? \"\", failed.message, undefined);\n }\n return parse<T>(args[0] ?? \"\", stdout);\n}\n\n/** Runs a helper command without blocking the event loop. */\nexport function runHelperAsync<T>(args: readonly string[]): Promise<T> {\n const helper = helperPath();\n return new Promise((resolvePromise, reject) => {\n const child = spawn(helper, args, { windowsHide: true, stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n let stdout = \"\";\n let stderr = \"\";\n child.stdout.setEncoding(\"utf8\");\n child.stderr.setEncoding(\"utf8\");\n child.stdout.on(\"data\", (chunk: string) => {\n stdout += chunk;\n });\n child.stderr.on(\"data\", (chunk: string) => {\n stderr += chunk;\n });\n child.once(\"error\", reject);\n child.once(\"close\", () => {\n try {\n resolvePromise(parse<T>(args[0] ?? \"\", stdout || stderr));\n } catch (error) {\n reject(error);\n }\n });\n });\n}\n","/**\n * Where a home and its control endpoint live on each operating system, and how a directory is\n * made owner-only (DATA_MODEL §1; D82, D84, D85; RT-10). Resolving a path never touches the file\n * system; `ownedDirectory` creates or checks one.\n *\n * - macOS: the home defaults to `~/.mostra`, the runtime directory to `~/.mostra/run`.\n * - Linux: `${XDG_DATA_HOME:-~/.local/share}/mostra`; `$XDG_RUNTIME_DIR/mostra` when that\n * directory is the user's and private, else `${XDG_STATE_HOME:-~/.local/state}/mostra/run`.\n * - Windows: `%LOCALAPPDATA%\\mostra`. The control endpoint is a named pipe, which lives in no\n * directory, so there is no runtime directory and `MOSTRA_RUNTIME_DIR` doesn't apply.\n *\n * Owner-only means mode 0700 on POSIX, and on Windows a protected access list that grants only the\n * user and `SYSTEM`, inherited by everything inside (the helper's `secure-dir`).\n */\nimport { chmodSync, mkdirSync, realpathSync, statSync } from \"node:fs\";\nimport { posix, win32 } from \"node:path\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport { runHelper } from \"./helper.ts\";\n\n/** The operating systems the runtime knows. */\nexport type OperatingSystem = \"darwin\" | \"linux\" | \"win32\" | (string & {});\n\n/** The operating system this process runs on. Every other module asks here. */\nexport const OS: OperatingSystem = process.platform;\n\n/** Whether this process runs on Windows. */\nexport const WINDOWS: boolean = OS === \"win32\";\n\ntype Environment = Readonly<Record<string, string | undefined>>;\n\nconst nonEmpty = (value: string | undefined): string | undefined =>\n value === undefined || value === \"\" ? undefined : value;\n\n/** The path rules of an operating system, so resolution for another one can be computed and tested. */\nexport function pathsOf(os: OperatingSystem): typeof posix {\n return os === \"win32\" ? win32 : posix;\n}\n\n/** The home a platform uses when neither `--home` nor `MOSTRA_HOME` names one. */\nexport function defaultHome(os: OperatingSystem, env: Environment, userHome: string): string {\n if (os === \"darwin\") return posix.join(userHome, \".mostra\");\n if (os === \"win32\") {\n const local = nonEmpty(env[\"LOCALAPPDATA\"]);\n return win32.join(\n local !== undefined && win32.isAbsolute(local)\n ? local\n : win32.join(userHome, \"AppData\", \"Local\"),\n \"mostra\",\n );\n }\n const data = nonEmpty(env[\"XDG_DATA_HOME\"]);\n return posix.join(\n data !== undefined && posix.isAbsolute(data) ? data : posix.join(userHome, \".local\", \"share\"),\n \"mostra\",\n );\n}\n\n/** What the runtime directory resolution decided, and why. */\nexport interface RuntimeDirChoice {\n readonly dir: string;\n /** `override` (MOSTRA_RUNTIME_DIR), `xdg` (the safe XDG runtime directory) or `fallback`. */\n readonly source: \"override\" | \"xdg\" | \"fallback\";\n /** Why `$XDG_RUNTIME_DIR` wasn't used, when it was set. */\n readonly rejected?: string;\n}\n\n/**\n * The runtime directory for control sockets (D82), or `undefined` on Windows, whose control pipe\n * lives in the system's pipe namespace.\n */\nexport function runtimeDirFor(inputs: {\n readonly os: OperatingSystem;\n readonly env: Environment;\n readonly userHome: string;\n readonly cwd: string;\n}): RuntimeDirChoice | undefined {\n if (inputs.os === \"win32\") return undefined;\n const override = nonEmpty(inputs.env[\"MOSTRA_RUNTIME_DIR\"]);\n if (override !== undefined)\n return { dir: posix.resolve(inputs.cwd, override), source: \"override\" };\n if (inputs.os === \"darwin\")\n return { dir: posix.join(inputs.userHome, \".mostra\", \"run\"), source: \"fallback\" };\n const xdg = nonEmpty(inputs.env[\"XDG_RUNTIME_DIR\"]);\n let rejected: string | undefined;\n if (xdg !== undefined) {\n rejected = unsafeXdgRuntimeDir(xdg);\n if (rejected === undefined) return { dir: posix.join(xdg, \"mostra\"), source: \"xdg\" };\n }\n const state = nonEmpty(inputs.env[\"XDG_STATE_HOME\"]);\n const base =\n state !== undefined && posix.isAbsolute(state)\n ? state\n : posix.join(inputs.userHome, \".local\", \"state\");\n const dir = posix.join(base, \"mostra\", \"run\");\n return rejected === undefined\n ? { dir, source: \"fallback\" }\n : { dir, source: \"fallback\", rejected };\n}\n\n/** The current user's ID on POSIX. */\nfunction uid(): number {\n return process.getuid?.() ?? -1;\n}\n\n/** Why `$XDG_RUNTIME_DIR` can't be used, or `undefined` when it can (XDG Base Directory spec). */\nfunction unsafeXdgRuntimeDir(dir: string): string | undefined {\n if (!posix.isAbsolute(dir)) return \"it isn't an absolute path\";\n let stats: ReturnType<typeof statSync>;\n try {\n stats = statSync(dir);\n } catch {\n return \"it doesn't exist\";\n }\n if (!stats.isDirectory()) return \"it isn't a directory\";\n if (stats.uid !== uid()) return \"another user owns it\";\n if ((stats.mode & 0o077) !== 0) return \"other users can access it\";\n return undefined;\n}\n\n/** The longest control socket path the operating system accepts, in bytes (VERIFIED_FACTS). */\nexport function socketPathLimit(os: OperatingSystem): number {\n return os === \"darwin\" ? 103 : 107;\n}\n\n/** The outcome of {@link ownedDirectory}. */\nexport interface PreparedDirectory {\n /** The directory's real path. */\n readonly realPath: string;\n /** Whether Mostra created it. */\n readonly created: boolean;\n /**\n * What it allowed before Mostra made it owner-only, when it did: the octal mode on POSIX, the\n * security descriptor (SDDL) on Windows.\n */\n readonly tightenedFrom?: string;\n}\n\nfunction notOwned(path: string, why: string): RpcError {\n return new RpcError(\n createDiagnostic(\"MOSTRA_HOME_NOT_OWNED\", { message: `Mostra can't use ${path}: ${why}.` }),\n );\n}\n\n/**\n * Makes `path` a directory only its owner can use (D85): creates it owner-only when missing,\n * tightens one the user owns, and throws `MOSTRA_HOME_NOT_OWNED` for one owned by another user or\n * a path that isn't a directory. Symlinks are followed.\n */\nexport function ownedDirectory(path: string): PreparedDirectory {\n if (WINDOWS) return ownedDirectoryWindows(path);\n try {\n return preparePosix(path);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === \"ENOTDIR\" || code === \"EEXIST\")\n throw notOwned(path, \"a part of the path isn't a directory\");\n if (code === \"EACCES\" || code === \"EPERM\")\n throw notOwned(path, \"you have no permission to use it\");\n throw error;\n }\n}\n\nfunction preparePosix(path: string): PreparedDirectory {\n let created = false;\n try {\n statSync(path);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n mkdirSync(path, { recursive: true, mode: 0o700 });\n created = true;\n }\n const realPath = realpathSync(path);\n const stats = statSync(realPath);\n if (!stats.isDirectory()) throw notOwned(path, \"it isn't a directory\");\n if (stats.uid !== uid()) throw notOwned(path, `it belongs to user ${stats.uid}, not to you`);\n const mode = stats.mode & 0o777;\n if (mode !== 0o700) {\n chmodSync(realPath, 0o700);\n return created ? { realPath, created } : { realPath, created, tightenedFrom: mode.toString(8) };\n }\n return { realPath, created };\n}\n\ntype Secured =\n | { readonly secured: \"created\" | \"kept\" }\n | { readonly secured: \"tightened\"; readonly from: string }\n | { readonly refused: \"not-owned\"; readonly owner: string }\n | { readonly refused: \"not-directory\" };\n\nfunction ownedDirectoryWindows(path: string): PreparedDirectory {\n let answer: Secured;\n try {\n answer = runHelper<Secured>([\"secure-dir\", path]);\n } catch (error) {\n // Access denied while creating or reading it: someone else's directory, or one above it.\n if ((error as { os?: number }).os === 5)\n throw notOwned(path, \"you have no permission to use it\");\n throw error;\n }\n if (\"refused\" in answer) {\n throw notOwned(\n path,\n answer.refused === \"not-owned\"\n ? `it belongs to ${answer.owner}, not to you`\n : \"it isn't a directory\",\n );\n }\n const realPath = realpathSync.native(path);\n if (answer.secured === \"tightened\")\n return { realPath, created: false, tightenedFrom: answer.from };\n return { realPath, created: answer.secured === \"created\" };\n}\n","/**\n * File operations whose semantics differ between POSIX and Windows (FAILURE_MODEL §3, RT-10):\n *\n * - **Renames.** Windows refuses to replace or move a file another process has open without\n * sharing deletion, and antivirus scanners and the search indexer open new files for a moment\n * after they are written. A rename that meets a sharing violation is tried again for a short\n * while (`EPERM`, `EACCES`, `EBUSY`), never weakened into a copy: the step stays atomic or fails.\n * - **Syncing.** Windows syncs a file only through a handle open for writing.\n * - **Directory links.** A directory symlink needs a privilege most Windows users don't hold;\n * junctions need none, and Node.js and pnpm resolve through them like symlinks.\n * - **Sealing.** A sealed version is read-only for everyone (0444 files and 0555 directories on\n * POSIX; on Windows an access list granting only reading, applied by the helper). Its owner can\n * always unseal it, as on POSIX.\n * - **Names.** Windows file names are case-insensitive: two names that differ only in case are\n * one file.\n */\nimport { closeSync, type Dirent, fsyncSync, openSync, renameSync, statSync } from \"node:fs\";\nimport {\n chmod,\n lstat,\n mkdir,\n readdir,\n readFile,\n readlink,\n realpath,\n rename,\n rm,\n rmdir,\n symlink,\n unlink,\n writeFile,\n} from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport { WINDOWS } from \"./directories.ts\";\nimport { runHelperAsync } from \"./helper.ts\";\n\n/** Errors a Windows rename or removal meets while another process briefly holds the file. */\nconst TRANSIENT = new Set([\"EPERM\", \"EACCES\", \"EBUSY\", \"ENOTEMPTY\"]);\n/** How long a rename keeps trying through sharing violations. */\nconst RETRY_MS = 3000;\n\nconst errno = (error: unknown): string | undefined => (error as NodeJS.ErrnoException).code;\n\nconst sleep = (ms: number): Promise<void> => new Promise((done) => setTimeout(done, ms));\n\nfunction sleepSync(ms: number): void {\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);\n}\n\n/**\n * Renames `from` to `to`, replacing a file at `to` (POSIX `rename`). On Windows a sharing\n * violation is retried with backoff for up to 3 s before it is thrown.\n */\nexport async function renamePath(from: string, to: string): Promise<void> {\n const deadline = Date.now() + RETRY_MS;\n for (let wait = 10; ; wait = Math.min(wait * 2, 250)) {\n try {\n await rename(from, to);\n return;\n } catch (error) {\n if (!WINDOWS || !TRANSIENT.has(errno(error) ?? \"\") || Date.now() >= deadline) throw error;\n await sleep(wait);\n }\n }\n}\n\n/** {@link renamePath}, blocking. */\nexport function renamePathSync(from: string, to: string): void {\n const deadline = Date.now() + RETRY_MS;\n for (let wait = 10; ; wait = Math.min(wait * 2, 250)) {\n try {\n renameSync(from, to);\n return;\n } catch (error) {\n if (!WINDOWS || !TRANSIENT.has(errno(error) ?? \"\") || Date.now() >= deadline) throw error;\n sleepSync(wait);\n }\n }\n}\n\n/**\n * Syncs a file or a directory to disk. A file that can't be synced fails the caller (its bytes\n * would not be durable); a directory may not support it on some file systems (Windows can't open\n * one this way at all), and only that case is tolerated.\n */\nexport function fsyncPath(path: string, directory = false): void {\n if (directory && WINDOWS) {\n // NTFS journals directory changes, and Windows can't sync a directory; it must exist, though.\n statSync(path);\n return;\n }\n let fd: number | undefined;\n try {\n // Windows flushes a file only through a handle that may write (VERIFIED_FACTS, WP-W1).\n fd = openSync(path, WINDOWS ? \"r+\" : \"r\");\n fsyncSync(fd);\n } catch (error) {\n const code = errno(error);\n const unsupported = [\"EINVAL\", \"ENOTSUP\", \"EISDIR\", \"EPERM\", \"EACCES\"];\n if (!directory || !unsupported.includes(code ?? \"\")) throw error;\n } finally {\n if (fd !== undefined) closeSync(fd);\n }\n}\n\n/**\n * Makes `path` a link to the `node_modules`-like directory `target`: a symlink on POSIX; on\n * Windows a {@link linkFarm}, since a junction to the directory would break the relative links\n * inside it (pnpm's), which Windows resolves against the path they were reached by (VERIFIED_FACTS,\n * WP-W1).\n */\nexport async function linkDirectory(target: string, path: string): Promise<void> {\n if (WINDOWS) await linkFarm(target, path);\n else await symlink(target, path, \"dir\");\n}\n\n/** The marker a link farm keeps: what it mirrors, and the entries it mirrored. */\nconst FARM_MARKER = \".mostra-link\";\n\n/** Every entry of a `node_modules`-like directory, scoped ones as `@scope/name`, dot entries left out. */\nasync function farmEntries(target: string): Promise<{ name: string; real: string }[]> {\n const names: string[] = [];\n for (const entry of await readdir(target, { withFileTypes: true })) {\n if (entry.name.startsWith(\".\")) continue;\n if (entry.name.startsWith(\"@\") && entry.isDirectory()) {\n for (const scoped of await readdir(join(target, entry.name)))\n names.push(`${entry.name}/${scoped}`);\n } else names.push(entry.name);\n }\n const entries: { name: string; real: string }[] = [];\n for (const name of names.sort()) {\n try {\n entries.push({ name, real: await realpath(join(target, ...name.split(\"/\"))) });\n } catch {\n // A dangling link brings nothing in, as through a directory link.\n }\n }\n return entries;\n}\n\n/**\n * A directory that stands for `target`: one junction per entry, to the entry's real path, so every\n * link inside resolves from where it really is, and a marker naming what it mirrors. Built aside\n * and renamed into place, so `path` is either missing or complete. Used on Windows; it works on\n * POSIX too, where the tests exercise it.\n */\nexport async function linkFarm(target: string, path: string): Promise<void> {\n const source = resolve(target);\n const entries = await farmEntries(source);\n const building = `${path}.${process.pid}.${Date.now()}.farm`;\n await mkdir(building, { recursive: true });\n try {\n for (const entry of entries) {\n const at = join(building, ...entry.name.split(\"/\"));\n if (entry.name.includes(\"/\")) await mkdir(join(at, \"..\"), { recursive: true });\n await symlink(entry.real, at, \"junction\");\n }\n await writeFile(\n join(building, FARM_MARKER),\n `${JSON.stringify({ target: source, entries })}\\n`,\n );\n await renamePath(building, path);\n } catch (error) {\n await removeFarm(building).catch(() => {});\n throw error;\n }\n}\n\n/** Removes a link farm's junctions, never what they point to, then its directories. */\nasync function removeFarm(path: string): Promise<void> {\n for (const entry of await readdir(path, { withFileTypes: true }).catch(() => [])) {\n const at = join(path, entry.name);\n if (entry.isSymbolicLink()) await unlinkEntry(at);\n else if (entry.isDirectory()) await removeFarm(at);\n else await rm(at, { force: true });\n }\n await rmdir(path);\n}\n\n/** Removes one link: on Windows a junction is removed as the directory entry it is. */\nasync function unlinkEntry(path: string): Promise<void> {\n try {\n await unlink(path);\n } catch (error) {\n if (!WINDOWS || errno(error) !== \"EPERM\") throw error;\n await rmdir(path);\n }\n}\n\n/**\n * What the directory link `path` stands for, or `undefined` when it is missing, isn't a link, or\n * (a link farm) no longer mirrors its target's current entries.\n */\nexport async function linkTarget(path: string): Promise<string | undefined> {\n try {\n const info = await lstat(path);\n if (info.isSymbolicLink()) return resolve(join(path, \"..\"), await readlink(path));\n if (!info.isDirectory()) return undefined;\n const marker = JSON.parse(await readFile(join(path, FARM_MARKER), \"utf8\")) as {\n target: string;\n entries: { name: string; real: string }[];\n };\n const now = await farmEntries(marker.target);\n return JSON.stringify(now) === JSON.stringify(marker.entries) ? marker.target : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Points the directory link `path` at `target`, replacing what it pointed at with no moment\n * where `path` is missing on POSIX (a new link renamed over it). Windows can't rename a link over\n * an existing directory entry, so the old link is renamed aside first and removed after.\n */\nexport async function replaceDirectoryLink(target: string, path: string): Promise<void> {\n const fresh = `${path}.${process.pid}.${Date.now()}.new`;\n await linkDirectory(target, fresh);\n if (!WINDOWS) {\n await rename(fresh, path);\n return;\n }\n const aside = `${path}.${process.pid}.${Date.now()}.old`;\n let moved = false;\n try {\n await renamePath(path, aside);\n moved = true;\n } catch (error) {\n if (errno(error) !== \"ENOENT\") {\n await unlinkDirectory(fresh);\n throw error;\n }\n }\n await renamePath(fresh, path);\n if (moved) await unlinkDirectory(aside);\n}\n\n/**\n * `path` without the separators it ends in (a loop: a regular expression here is quadratic). On\n * POSIX a backslash is an ordinary character of a name, never a separator.\n */\nfunction trimSeparators(path: string): string {\n let end = path.length;\n while (end > 0 && (path[end - 1] === \"/\" || (WINDOWS && path[end - 1] === \"\\\\\"))) end--;\n return path.slice(0, end);\n}\n\n/** Whether a link points at `target` (paths compared as this file system compares them). */\nexport function samePath(a: string, b: string): boolean {\n const normal = (path: string): string =>\n nameKey(trimSeparators(resolve(path.startsWith(\"\\\\\\\\?\\\\\") ? path.slice(4) : path)));\n return normal(a) === normal(b);\n}\n\n/**\n * A path as a key for comparison: `/`-separated, without a trailing `/`, and on Windows in lower\n * case, since Windows names compare without case and bundlers spell `C:\\x` as `C:/x`. The key has\n * the path's length, so an index found in it holds in the path too.\n */\nexport function pathKey(path: string): string {\n // Only Windows spells a separator `\\\\`; on POSIX it is part of a name (Opus review of WP-W1).\n return nameKey(WINDOWS ? path.replaceAll(\"\\\\\", \"/\") : path);\n}\n\n/** Whether `file` is `dir` itself or lies under it, however either spells its separators. */\nexport function isUnder(file: string, dir: string): boolean {\n const key = pathKey(file);\n const root = trimSeparators(pathKey(dir));\n return key === root || key.startsWith(`${root}/`);\n}\n\n/** Removes a link made by {@link linkDirectory}, never what it points to. */\nexport async function unlinkDirectory(path: string): Promise<void> {\n let info: Awaited<ReturnType<typeof lstat>>;\n try {\n info = await lstat(path);\n } catch (error) {\n if (errno(error) === \"ENOENT\") return;\n throw error;\n }\n if (info.isDirectory() && !info.isSymbolicLink()) await removeFarm(path);\n else await unlinkEntry(path);\n}\n\n/** Calls `visit` for every entry under `dir`, children before their directory. */\nasync function walk(\n dir: string,\n visit: (path: string, isDirectory: boolean) => Promise<void>,\n): Promise<void> {\n const entries: Dirent[] = await readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const path = join(dir, entry.name);\n if (entry.isDirectory()) await walk(path, visit);\n await visit(path, entry.isDirectory());\n }\n}\n\n/**\n * Makes a tree read-only and syncs it to disk. On POSIX the top directory is left writable when\n * `keepTop` is set, since renaming a directory needs write access to it; on Windows the whole tree\n * is synced first and sealed in one step after it is in place ({@link sealPlaced}).\n */\nexport async function sealTree(dir: string, keepTop = false): Promise<void> {\n if (WINDOWS) {\n await walk(dir, async (path, isDirectory) => {\n if (!isDirectory) fsyncPath(path);\n });\n return;\n }\n await walk(dir, async (path, isDirectory) => {\n await chmod(path, isDirectory ? 0o555 : 0o444);\n fsyncPath(path, isDirectory);\n });\n if (!keepTop) await chmod(dir, 0o555);\n fsyncPath(dir, true);\n}\n\n/**\n * Finishes sealing a tree that is in its final place: on POSIX its top directory becomes 0555; on\n * Windows the whole tree gets the read-only access list (moving a sealed directory would need the\n * delete right the seal withholds).\n */\nexport async function sealPlaced(dir: string): Promise<void> {\n if (WINDOWS) {\n await runHelperAsync([\"seal\", dir]);\n return;\n }\n await chmod(dir, 0o555);\n fsyncPath(dir, true);\n}\n\n/** Removes a tree, sealed or not. Missing trees are fine. Links inside are removed, never followed. */\nexport async function removeTree(dir: string): Promise<void> {\n let info: Awaited<ReturnType<typeof lstat>>;\n try {\n info = await lstat(dir);\n } catch {\n return;\n }\n if (info.isDirectory() && !WINDOWS) {\n await chmod(dir, 0o755);\n await walk(dir, async (path, isDirectory) => {\n if (isDirectory) await chmod(path, 0o755);\n }).catch(() => {});\n }\n const deadline = Date.now() + RETRY_MS;\n let unsealed = false;\n for (let wait = 10; ; wait = Math.min(wait * 2, 250)) {\n try {\n await rm(dir, { recursive: true, force: true });\n return;\n } catch (error) {\n if (!WINDOWS || !TRANSIENT.has(errno(error) ?? \"\") || Date.now() >= deadline) throw error;\n // A sealed version refuses deletion until its access list is the owner's again; only\n // sealed trees need it, and they hold no links the reset could follow.\n if (!unsealed && info.isDirectory()) {\n unsealed = true;\n await runHelperAsync([\"unseal\", dir]).catch(() => {});\n continue;\n }\n await sleep(wait);\n }\n }\n}\n\n/** The form under which two file names are the same name on this file system. */\nexport function nameKey(name: string): string {\n return WINDOWS ? name.toLowerCase() : name;\n}\n"],"mappings":";;;;;;;;AAwFA,MAAa,eAAe;;;;;AAM5B,MAAa,aAAa;;;;;AAK1B,MAAa,qBAAqB;;AASlC,MAAa,oBAAoB;;AAEjC,MAAa,0BAA0B;;AAEvC,MAAa,0BAA0B;;AAmBvC,MAAa,oBAAoB;;;;;;;;AAoBjC,MAAa,gBAAkD;CAC7D,iBAAiB,GAAG,KAAK,UACvB,EACE,iBAAiB;EACf,QAAQ;EACR,yBAAyB;EACzB,KAAK;EACL,iBAAiB;EACjB,wBAAwB;CAC1B,EACF,GACA,MACA,CACF,EAAE;CACF,gBAAgB,GAAG,KAAK,UAAU;EAAE,SAA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