@nshiab/setup-data-project 4.0.16 → 4.0.18

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/sda.mjs CHANGED
@@ -1,24 +1,53 @@
1
1
  #!/usr/bin/env node
2
2
  import { t as isObject } from "./jsonObject-B1ldqsgL.mjs";
3
3
  import { execFileSync, spawn, spawnSync } from "node:child_process";
4
- import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, watch, writeFileSync } from "node:fs";
4
+ import { appendFileSync, copyFileSync, createReadStream, existsSync, linkSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, utimesSync, watch, writeFileSync } from "node:fs";
5
5
  import { dirname, join, resolve, sep } from "node:path";
6
6
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
7
7
  import { parseArgs, stripVTControlCharacters, styleText } from "node:util";
8
8
  import { randomUUID } from "node:crypto";
9
9
  import { createInterface } from "node:readline";
10
+ import { once } from "node:events";
10
11
  //#region src/helpers/sdaLock.ts
11
12
  const SDA_LOCK_DIRECTORY = ".sda-cache/lock";
12
- function errorCode$2(error) {
13
+ const watcherHeartbeatInterval = 1e3;
14
+ const watcherHeartbeatMaxAge = 5e3;
15
+ var SdaLockBusyError = class extends Error {
16
+ watcher;
17
+ constructor(claim, directory) {
18
+ super(`${claim.command} is already running${claim.command?.endsWith("sda:watch") ? " and watching this project's files" : " an analysis for this project"} (PID ${claim.pid}). Wait for it to finish or stop it with Ctrl+C in its terminal, then try again.`);
19
+ if (claim.watchEntry) this.watcher = {
20
+ directory,
21
+ pid: claim.pid,
22
+ entry: claim.watchEntry
23
+ };
24
+ }
25
+ };
26
+ function errorCode$3(error) {
13
27
  return error instanceof Error && "code" in error ? error.code : void 0;
14
28
  }
15
- async function acquireSdaLock(command) {
29
+ function hasFreshWatcherHeartbeat(directory) {
30
+ const file = join(directory, "owner.json");
31
+ try {
32
+ const info = statSync(file, { throwIfNoEntry: false });
33
+ if (!info || Date.now() - info.mtimeMs >= watcherHeartbeatMaxAge) return false;
34
+ const record = JSON.parse(readFileSync(file, "utf8"));
35
+ return isObject(record) && record.watcherReady === true && typeof record.watchEntry === "string" && record.projectRoot === realpathSync(process.cwd());
36
+ } catch (error) {
37
+ if (errorCode$3(error) === "ENOENT") return false;
38
+ throw error;
39
+ }
40
+ }
41
+ async function acquireSdaLock(command, watchEntry) {
16
42
  const directory = resolve(SDA_LOCK_DIRECTORY);
17
43
  const id = `${process.pid}-${randomUUID()}`;
18
44
  const ownDirectory = join(directory, id);
45
+ const ownerFile = join(ownDirectory, "owner.json");
46
+ let heartbeat;
19
47
  mkdirSync(directory, { recursive: true });
20
48
  mkdirSync(ownDirectory);
21
49
  const release = () => {
50
+ clearInterval(heartbeat);
22
51
  rmSync(ownDirectory, {
23
52
  recursive: true,
24
53
  force: true
@@ -35,18 +64,20 @@ async function acquireSdaLock(command) {
35
64
  try {
36
65
  process.kill(pid, 0);
37
66
  } catch (error) {
38
- if (errorCode$2(error) !== "ESRCH") throw error;
39
- rmSync(path, {
40
- recursive: true,
41
- force: true
42
- });
43
- return;
67
+ if (errorCode$3(error) === "ESRCH") {
68
+ rmSync(path, {
69
+ recursive: true,
70
+ force: true
71
+ });
72
+ return;
73
+ }
74
+ if (errorCode$3(error) !== "EPERM") throw error;
44
75
  }
45
76
  let record;
46
77
  try {
47
78
  record = JSON.parse(readFileSync(join(path, "owner.json"), "utf8"));
48
79
  } catch (error) {
49
- if (errorCode$2(error) !== "ENOENT") throw error;
80
+ if (errorCode$3(error) !== "ENOENT") throw error;
50
81
  return existsSync(path) ? {
51
82
  id: candidate,
52
83
  pid,
@@ -58,7 +89,8 @@ async function acquireSdaLock(command) {
58
89
  id: candidate,
59
90
  pid,
60
91
  ticket: record.ticket,
61
- command: record.command
92
+ command: record.command,
93
+ watchEntry: typeof record.watchEntry === "string" ? record.watchEntry : void 0
62
94
  };
63
95
  }
64
96
  try {
@@ -67,13 +99,23 @@ async function acquireSdaLock(command) {
67
99
  const claim = readClaim(candidate);
68
100
  if (claim) ticket = Math.max(ticket, claim.ticket + 1);
69
101
  }
70
- writeFileSync(join(ownDirectory, "owner.tmp"), JSON.stringify({
102
+ const record = {
71
103
  ticket,
72
104
  command,
73
- projectRoot: realpathSync(process.cwd())
74
- }));
75
- renameSync(join(ownDirectory, "owner.tmp"), join(ownDirectory, "owner.json"));
105
+ projectRoot: realpathSync(process.cwd()),
106
+ watchEntry
107
+ };
108
+ function publishOwner(watcherReady) {
109
+ const temporary = join(ownDirectory, "owner.tmp");
110
+ writeFileSync(temporary, JSON.stringify({
111
+ ...record,
112
+ watcherReady
113
+ }));
114
+ renameSync(temporary, ownerFile);
115
+ }
116
+ publishOwner();
76
117
  const deadline = performance.now() + 5e3;
118
+ let owner;
77
119
  for (const candidate of readdirSync(directory)) {
78
120
  if (candidate === id) continue;
79
121
  let claim = readClaim(candidate);
@@ -82,9 +124,27 @@ async function acquireSdaLock(command) {
82
124
  await setTimeout$1(10);
83
125
  claim = readClaim(candidate);
84
126
  }
85
- if (claim && (claim.ticket < ticket || claim.ticket === ticket && claim.id < id)) throw new Error(`${claim.command} is already running${claim.command?.endsWith("sda:watch") ? " and watching this project's files" : " an analysis for this project"} (PID ${claim.pid}). Wait for it to finish or stop it with Ctrl+C in its terminal, then try again.`);
127
+ if (claim && (claim.ticket < ticket || claim.ticket === ticket && claim.id < id)) {
128
+ if (!owner || claim.ticket < owner.ticket || claim.ticket === owner.ticket && claim.id < owner.id) owner = claim;
129
+ }
130
+ }
131
+ if (owner) throw new SdaLockBusyError(owner, join(directory, owner.id));
132
+ function startWatcherHeartbeat(onError) {
133
+ publishOwner(true);
134
+ heartbeat = setInterval(() => {
135
+ try {
136
+ const now = /* @__PURE__ */ new Date();
137
+ utimesSync(ownerFile, now, now);
138
+ } catch (error) {
139
+ onError(error);
140
+ }
141
+ }, watcherHeartbeatInterval);
86
142
  }
87
- return release;
143
+ return {
144
+ directory: ownDirectory,
145
+ release,
146
+ startWatcherHeartbeat
147
+ };
88
148
  } catch (error) {
89
149
  release();
90
150
  throw error;
@@ -92,12 +152,77 @@ async function acquireSdaLock(command) {
92
152
  }
93
153
  //#endregion
94
154
  //#region src/helpers/sdaStatus.ts
95
- function errorCode$1(error) {
155
+ function errorCode$2(error) {
96
156
  return error instanceof Error && "code" in error ? error.code : void 0;
97
157
  }
158
+ function readProcessCommand(pid, owners) {
159
+ let command;
160
+ if (process.platform === "win32") {
161
+ if (owners.length !== 1) throw new Error(`PID ${pid} has no unambiguous SDA owner record.`);
162
+ const owner = JSON.parse(readFileSync(join(SDA_LOCK_DIRECTORY, owners[0], "owner.json"), "utf8"));
163
+ if (!isObject(owner) || typeof owner.projectRoot !== "string" || realpathSync(owner.projectRoot) !== realpathSync(process.cwd())) throw new Error(`PID ${pid} could not be verified as this project's SDA process.`);
164
+ const result = JSON.parse(execFileSync("powershell.exe", [
165
+ "-NoLogo",
166
+ "-NoProfile",
167
+ "-NonInteractive",
168
+ "-Command",
169
+ `[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new(\$false); (Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}' -ErrorAction Stop).CommandLine | ConvertTo-Json -Compress`
170
+ ], {
171
+ encoding: "utf8",
172
+ timeout: 1e4,
173
+ maxBuffer: 65536,
174
+ windowsHide: true,
175
+ stdio: [
176
+ "ignore",
177
+ "pipe",
178
+ "pipe"
179
+ ]
180
+ }));
181
+ if (typeof result !== "string" || !result.trim()) throw new Error(`PID ${pid} has no readable command line.`);
182
+ command = result;
183
+ } else if (process.platform === "darwin" || process.platform === "linux") command = execFileSync("ps", [
184
+ "-p",
185
+ String(pid),
186
+ "-o",
187
+ "command="
188
+ ], {
189
+ encoding: "utf8",
190
+ timeout: 5e3,
191
+ stdio: [
192
+ "ignore",
193
+ "pipe",
194
+ "pipe"
195
+ ]
196
+ }).trim();
197
+ else throw new Error("Active SDA processes cannot be verified on this platform.");
198
+ const executable = process.argv[1];
199
+ if (!executable || !command.includes(executable) && !command.includes(realpathSync(executable)) && !/(?:[\\/]@nshiab[\\/]setup-data-project[\\/]dist[\\/]sda\.mjs|[\\/]node_modules[\\/]\.bin[\\/]sda-run)(?:["\s]|$)/.test(command)) throw new Error(`PID ${pid} could not be verified as this project's SDA process.`);
200
+ if (process.platform === "darwin" || process.platform === "linux") {
201
+ const cwd = process.platform === "linux" ? realpathSync(`/proc/${pid}/cwd`) : execFileSync("lsof", [
202
+ "-a",
203
+ "-p",
204
+ String(pid),
205
+ "-d",
206
+ "cwd",
207
+ "-Fn"
208
+ ], {
209
+ encoding: "utf8",
210
+ timeout: 5e3,
211
+ stdio: [
212
+ "ignore",
213
+ "pipe",
214
+ "pipe"
215
+ ]
216
+ }).split("\n").find((line) => line.startsWith("n"))?.slice(1);
217
+ if (!cwd || realpathSync(cwd) !== realpathSync(process.cwd())) throw new Error(`PID ${pid} could not be verified as this project's SDA process.`);
218
+ }
219
+ return command;
220
+ }
98
221
  function printSdaStatus() {
99
222
  const run = `${process.versions.bun ? "bun" : "npm"} run`;
100
223
  const retry = `${run} sda:status`;
224
+ const watcherGuidance = `you can keep editing. The watcher formats source files, applies lint fixes, and reruns the analysis after changes. The user is likely watching the results live in their terminal while you work. Re-read a file before editing it again because the watcher may have changed it. Run ${run} sda to request a run from the watcher and receive its output and exit code when it finishes. Before handing off analysis code changes, start with ${run} sda:test. If formatting or lint checks fail, use ${run} sda:fix for automatic fixes. Resolve any remaining failures and rerun ${run} sda:test until it passes.`;
225
+ const watcherMessage = (pid) => `An SDA watcher is running (${run} sda:watch, PID ${pid}). While it runs, ${watcherGuidance}`;
101
226
  try {
102
227
  const claims = /* @__PURE__ */ new Map();
103
228
  try {
@@ -109,90 +234,38 @@ function printSdaStatus() {
109
234
  }
110
235
  }
111
236
  } catch (error) {
112
- if (errorCode$1(error) !== "ENOENT") throw error;
237
+ if (errorCode$2(error) !== "ENOENT") throw error;
113
238
  }
114
239
  const messages = [];
115
240
  for (const [pid, owners] of claims) {
116
241
  if (!Number.isInteger(pid) || pid <= 0 || pid > 2147483647) throw new Error("The recorded SDA PID is invalid.");
242
+ let command;
117
243
  try {
118
244
  process.kill(pid, 0);
245
+ command = readProcessCommand(pid, owners);
119
246
  } catch (error) {
120
- if (errorCode$1(error) === "ESRCH") continue;
247
+ const code = errorCode$2(error);
248
+ if (code === "ESRCH") continue;
249
+ if ((code === "EPERM" || code === "EACCES") && owners.length === 1 && hasFreshWatcherHeartbeat(join(".sda-cache/lock", owners[0]))) {
250
+ messages.push(watcherMessage(pid));
251
+ continue;
252
+ }
121
253
  throw error;
122
254
  }
123
- let command;
124
- if (process.platform === "win32") {
125
- if (owners.length !== 1) throw new Error(`PID ${pid} has no unambiguous SDA owner record.`);
126
- const owner = JSON.parse(readFileSync(join(SDA_LOCK_DIRECTORY, owners[0], "owner.json"), "utf8"));
127
- if (!isObject(owner) || typeof owner.projectRoot !== "string" || realpathSync(owner.projectRoot) !== realpathSync(process.cwd())) throw new Error(`PID ${pid} could not be verified as this project's SDA process.`);
128
- const result = JSON.parse(execFileSync("powershell.exe", [
129
- "-NoLogo",
130
- "-NoProfile",
131
- "-NonInteractive",
132
- "-Command",
133
- `[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new(\$false); (Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}' -ErrorAction Stop).CommandLine | ConvertTo-Json -Compress`
134
- ], {
135
- encoding: "utf8",
136
- timeout: 1e4,
137
- maxBuffer: 65536,
138
- windowsHide: true,
139
- stdio: [
140
- "ignore",
141
- "pipe",
142
- "pipe"
143
- ]
144
- }));
145
- if (typeof result !== "string" || !result.trim()) throw new Error(`PID ${pid} has no readable command line.`);
146
- command = result;
147
- } else if (process.platform === "darwin" || process.platform === "linux") {
148
- command = execFileSync("ps", [
149
- "-p",
150
- String(pid),
151
- "-o",
152
- "command="
153
- ], {
154
- encoding: "utf8",
155
- timeout: 5e3,
156
- stdio: [
157
- "ignore",
158
- "pipe",
159
- "pipe"
160
- ]
161
- }).trim();
162
- const cwd = process.platform === "linux" ? realpathSync(`/proc/${pid}/cwd`) : execFileSync("lsof", [
163
- "-a",
164
- "-p",
165
- String(pid),
166
- "-d",
167
- "cwd",
168
- "-Fn"
169
- ], {
170
- encoding: "utf8",
171
- timeout: 5e3,
172
- stdio: [
173
- "ignore",
174
- "pipe",
175
- "pipe"
176
- ]
177
- }).split("\n").find((line) => line.startsWith("n"))?.slice(1);
178
- if (!cwd || realpathSync(cwd) !== realpathSync(process.cwd())) throw new Error(`PID ${pid} could not be verified as this project's SDA process.`);
179
- } else throw new Error("Active SDA processes cannot be verified on this platform.");
180
- const executable = process.argv[1];
181
- if (!executable || !command.includes(executable) && !command.includes(realpathSync(executable)) && !/(?:[\\/]@nshiab[\\/]setup-data-project[\\/]dist[\\/]sda\.mjs|[\\/]node_modules[\\/]\.bin[\\/]sda-run)(?:["\s]|$)/.test(command)) throw new Error(`PID ${pid} could not be verified as this project's SDA process.`);
182
- messages.push(/(?:^|["\s])--watch(?:["\s]|$)/.test(command) ? `SDA watcher is running (${run} sda:watch, PID ${pid}). It automatically fixes files and reruns the analysis. If you are an agent, ask the user to stop it with Ctrl+C, then recheck with ${retry} before doing any work.` : `SDA analysis is running (${run} sda, PID ${pid}). Wait for it to finish. Recheck with ${retry} in 30 seconds before doing any work.`);
255
+ messages.push(/(?:^|["\s])--watch(?:["\s]|$)/.test(command) ? watcherMessage(pid) : `SDA analysis is running (${run} sda, PID ${pid}). Wait for it to finish before editing. Recheck with ${retry} after 3 seconds. If it is still running, recheck after 9 seconds, then every 27 seconds until it finishes.`);
183
256
  }
184
257
  for (const message of messages) console.log(message);
185
258
  if (messages.length) return 1;
186
259
  console.log("No active SDA process found. You can proceed.");
187
260
  return 0;
188
261
  } catch (error) {
189
- console.error(`Unable to verify SDA status: ${error instanceof Error ? error.message : String(error)} If you are an agent, ask the user to confirm that neither ${run} sda nor ${run} sda:watch is running and that you may proceed, then wait for their confirmation before doing any work.`);
262
+ console.error(`Unable to verify SDA status: ${error instanceof Error ? error.message : String(error)} If you are an agent, ask the user whether ${run} sda or ${run} sda:watch is running. Wait for a one-off analysis to finish. If a watcher is running, ${watcherGuidance}`);
190
263
  return 2;
191
264
  }
192
265
  }
193
266
  //#endregion
194
267
  //#region src/helpers/pipeFixOutput.ts
195
- function pipeFixOutput(output) {
268
+ function pipeFixOutput(output, writeLine = console.log) {
196
269
  createInterface({
197
270
  input: output,
198
271
  crlfDelay: Infinity
@@ -202,8 +275,8 @@ function pipeFixOutput(output) {
202
275
  const timing = plain.match(/^Finished in ([\d.]+)(ms|s) on \d+ files?( with \d+ rules)? using \d+ threads?\.$/);
203
276
  if (timing) {
204
277
  const label = timing[3] ? "Linting and type checking" : "Formatting";
205
- console.log(styleText("blue", `${label}: ${timing[1]} ${timing[2]}`));
206
- } else console.log(line);
278
+ writeLine(styleText("blue", `${label}: ${timing[1]} ${timing[2]}`));
279
+ } else writeLine(line);
207
280
  });
208
281
  }
209
282
  //#endregion
@@ -259,6 +332,146 @@ function createFileChanges(selected, excluded) {
259
332
  }
260
333
  return { check };
261
334
  }
335
+ const resultName = "watch-result.jsonl";
336
+ const requestName = /^request-(\d+)-[\da-f-]{36}$/;
337
+ const acknowledgeTimeout = 5e3;
338
+ const heartbeatInterval = 1e3;
339
+ const heartbeatTimeout = 1e4;
340
+ function errorCode$1(error) {
341
+ return error instanceof Error && "code" in error ? error.code : void 0;
342
+ }
343
+ function processIsGone(pid) {
344
+ try {
345
+ process.kill(pid, 0);
346
+ return false;
347
+ } catch (error) {
348
+ if (errorCode$1(error) === "ESRCH") return true;
349
+ if (errorCode$1(error) === "EPERM") return false;
350
+ throw error;
351
+ }
352
+ }
353
+ function linkResult(source, target) {
354
+ try {
355
+ linkSync(source, target);
356
+ } catch (error) {
357
+ if (errorCode$1(error) === "ENOENT") return;
358
+ const temporary = target + ".tmp";
359
+ try {
360
+ copyFileSync(source, temporary);
361
+ renameSync(temporary, target);
362
+ } catch (copyError) {
363
+ if (errorCode$1(copyError) !== "ENOENT") throw copyError;
364
+ }
365
+ }
366
+ }
367
+ function createWatchRequests(directory) {
368
+ const temporary = join(directory, "watch-result.tmp");
369
+ const latest = join(directory, resultName);
370
+ function pending() {
371
+ const requests = [];
372
+ for (const name of readdirSync(directory)) {
373
+ const match = requestName.exec(name);
374
+ if (!match) continue;
375
+ const pid = Number(match[1]);
376
+ if (!Number.isInteger(pid) || pid <= 0 || pid > 2147483647) continue;
377
+ const request = join(directory, name);
378
+ if (processIsGone(pid)) {
379
+ rmSync(request, {
380
+ recursive: true,
381
+ force: true
382
+ });
383
+ continue;
384
+ }
385
+ if (existsSync(join(request, resultName))) continue;
386
+ const heartbeat = join(request, "heartbeat");
387
+ const last = statSync(heartbeat, { throwIfNoEntry: false });
388
+ if (!last || Date.now() - last.mtimeMs >= heartbeatInterval) try {
389
+ writeFileSync(heartbeat, "");
390
+ } catch (error) {
391
+ if (errorCode$1(error) === "ENOENT") continue;
392
+ throw error;
393
+ }
394
+ requests.push(request);
395
+ }
396
+ return requests;
397
+ }
398
+ const start = () => writeFileSync(temporary, "");
399
+ const record = (chunk) => appendFileSync(temporary, JSON.stringify(chunk) + "\n");
400
+ function publish(requests, code) {
401
+ appendFileSync(temporary, JSON.stringify({ code }) + "\n");
402
+ renameSync(temporary, latest);
403
+ for (const request of requests) linkResult(latest, join(request, resultName));
404
+ }
405
+ return {
406
+ pending,
407
+ start,
408
+ record,
409
+ publish
410
+ };
411
+ }
412
+ async function replay(result) {
413
+ const input = createReadStream(result, { encoding: "utf8" });
414
+ const lines = createInterface({
415
+ input,
416
+ crlfDelay: Infinity
417
+ });
418
+ const closed = new Promise((resolve) => input.once("close", resolve));
419
+ let readError;
420
+ input.on("error", (error) => {
421
+ readError = error;
422
+ lines.close();
423
+ });
424
+ try {
425
+ for await (const line of lines) {
426
+ const value = JSON.parse(line);
427
+ if (isObject(value)) {
428
+ if (typeof value.code === "number" && Number.isInteger(value.code)) return value.code;
429
+ if (typeof value.text === "string" && (value.stream === "stdout" || value.stream === "stderr")) {
430
+ const output = process[value.stream];
431
+ if (!output.write(value.text)) await once(output, "drain");
432
+ continue;
433
+ }
434
+ }
435
+ throw new Error("The SDA watcher returned invalid output.");
436
+ }
437
+ if (readError) throw readError;
438
+ throw new Error("The SDA watcher result is missing its exit code.");
439
+ } finally {
440
+ lines.close();
441
+ input.destroy();
442
+ await closed;
443
+ }
444
+ }
445
+ async function requestWatchRun(watcher) {
446
+ const request = join(watcher.directory, `request-${process.pid}-${randomUUID()}`);
447
+ const result = join(request, resultName);
448
+ const heartbeat = join(request, "heartbeat");
449
+ const clean = () => rmSync(request, {
450
+ recursive: true,
451
+ force: true
452
+ });
453
+ mkdirSync(request);
454
+ process.once("exit", clean);
455
+ console.log(`Requesting an analysis run from the SDA watcher (PID ${watcher.pid})...`);
456
+ let lastHeartbeat;
457
+ let deadline = performance.now() + acknowledgeTimeout;
458
+ try {
459
+ for (;;) {
460
+ if (existsSync(result)) return await replay(result);
461
+ if (!existsSync(request) || processIsGone(watcher.pid)) throw new Error("The SDA watcher stopped before completing the requested run. Try again.");
462
+ const modified = statSync(heartbeat, { throwIfNoEntry: false })?.mtimeMs;
463
+ if (modified !== void 0 && modified !== lastHeartbeat) {
464
+ lastHeartbeat = modified;
465
+ deadline = performance.now() + heartbeatTimeout;
466
+ }
467
+ if (performance.now() >= deadline) throw new Error("The SDA watcher did not respond to the analysis request. Try again after checking the watcher.");
468
+ await setTimeout$1(100);
469
+ }
470
+ } finally {
471
+ process.removeListener("exit", clean);
472
+ clean();
473
+ }
474
+ }
262
475
  //#endregion
263
476
  //#region src/sda.ts
264
477
  const { positionals: [entry, ...paths], values } = parseArgs({
@@ -340,62 +553,74 @@ const bun = Boolean(process.versions.bun);
340
553
  const runCommand = (bun ? "bun run " : "npm run ") + (watchingTests ? "sda:test:watch" : watching ? "sda:watch" : "sda");
341
554
  const windows = process.platform === "win32";
342
555
  let releaseLock;
556
+ let watchRequests;
557
+ let requestTimer;
343
558
  let fixer;
344
559
  let running;
560
+ let runInProgress = false;
345
561
  let timer;
346
562
  let checking = false;
347
563
  let closing = false;
348
564
  let needsCheck = true;
349
565
  const changes = createFileChanges(selected, excluded);
350
566
  const watchers = /* @__PURE__ */ new Map();
351
- function launch(args, command = process.execPath, summarize = false) {
567
+ function launch(args, command = process.execPath, summarize = false, report) {
352
568
  const child = spawn(command, args, {
353
569
  argv0: windows && bun && command === process.execPath ? "bun" : void 0,
354
570
  stdio: [
355
571
  "inherit",
356
- summarize ? "pipe" : "inherit",
357
- "inherit"
572
+ summarize || report ? "pipe" : "inherit",
573
+ report ? "pipe" : "inherit"
358
574
  ],
359
575
  detached: !windows,
360
576
  shell: windows && command === "npm.cmd"
361
577
  });
362
- if (summarize && child.stdout) {
363
- const output = child.stdout;
364
- pipeFixOutput(output);
365
- child.once("exit", () => {
366
- const timeout = setTimeout(() => output.destroy(), 1e3);
367
- child.once("close", () => clearTimeout(timeout));
368
- });
369
- }
578
+ if (summarize && child.stdout) pipeFixOutput(child.stdout, report && ((line) => report("stdout", line + "\n")));
579
+ else if (report) child.stdout?.setEncoding("utf8").on("data", (text) => report("stdout", text));
580
+ if (report) child.stderr?.setEncoding("utf8").on("data", (text) => report("stderr", text));
581
+ if (child.stdout || child.stderr) child.once("exit", () => {
582
+ const timeout = setTimeout(() => {
583
+ child.stdout?.destroy();
584
+ child.stderr?.destroy();
585
+ }, 1e3);
586
+ child.once("close", () => clearTimeout(timeout));
587
+ });
370
588
  return {
371
589
  child,
372
590
  done: new Promise((resolve) => {
373
591
  child.once("error", (error) => {
374
- console.error(errorMessage(error));
592
+ if (report) report("stderr", errorMessage(error) + "\n");
593
+ else console.error(errorMessage(error));
375
594
  resolve(1);
376
595
  });
377
596
  child.once("close", resolve);
378
597
  })
379
598
  };
380
599
  }
381
- function launchScript(script, summarize = false) {
600
+ function launchScript(script, summarize = false, report) {
382
601
  return launch([
383
602
  "run",
384
603
  "--silent",
385
604
  script
386
- ], bun ? process.execPath : windows ? "npm.cmd" : "npm", summarize);
605
+ ], bun ? process.execPath : windows ? "npm.cmd" : "npm", summarize, report);
387
606
  }
388
607
  function announceWatchRun(message) {
389
- if (process.stdout.isTTY) process.stdout.write("\x1B[2J\x1B[H");
608
+ if (process.stdout.isTTY) {
609
+ const clearScrollback = watchingTests ? "" : "\x1B[3J";
610
+ process.stdout.write(`\u001b[2J${clearScrollback}\u001b[H`);
611
+ }
390
612
  console.log(`Watching SDA for changes...\n\n${message}`);
391
613
  }
392
- function watchJob(job, label, success) {
614
+ function watchJob(job, label, success, complete) {
393
615
  running = job;
616
+ runInProgress = true;
394
617
  job.done.then((result) => {
395
618
  if (closing || checking || running !== job) return;
619
+ runInProgress = false;
620
+ complete?.(result ?? 1);
396
621
  const outcome = result === 0 ? success : result === null ? "stopped" : `failed (exit code ${result})`;
397
622
  console.log(`\n${label} ${outcome}. Waiting for changes...`);
398
- });
623
+ }).catch(fail);
399
624
  }
400
625
  function refreshWatchers() {
401
626
  const directories = /* @__PURE__ */ new Map();
@@ -463,11 +688,14 @@ async function stop(job) {
463
688
  async function check() {
464
689
  if (closing || checking) return;
465
690
  const changed = changes.check();
466
- if (!needsCheck && !changed) return;
691
+ needsCheck ||= changed;
692
+ const requests = watchRequests?.pending();
693
+ if (!needsCheck && (runInProgress || !requests?.length)) return;
467
694
  checking = true;
468
695
  needsCheck = false;
469
696
  await stop(running);
470
697
  running = void 0;
698
+ runInProgress = false;
471
699
  if (closing) return;
472
700
  refreshWatchers();
473
701
  if (watchingTests) {
@@ -478,18 +706,36 @@ async function check() {
478
706
  return;
479
707
  }
480
708
  announceWatchRun("Running SDA checks and analysis...");
481
- fixer = launchScript("sda:fix", true);
709
+ watchRequests?.start();
710
+ const report = (stream, text) => {
711
+ process[stream].write(text);
712
+ if (closing) return;
713
+ try {
714
+ watchRequests?.record({
715
+ stream,
716
+ text
717
+ });
718
+ } catch (error) {
719
+ fail(error);
720
+ }
721
+ };
722
+ fixer = launchScript("sda:fix", true, report);
482
723
  const fixed = await fixer.done;
483
724
  if (closing) return;
484
725
  needsCheck = changes.check();
485
726
  refreshWatchers();
486
727
  fixer = void 0;
487
728
  checking = false;
729
+ const batch = watchRequests?.pending() ?? [];
730
+ const publish = (code) => watchRequests?.publish(batch, code);
488
731
  if (needsCheck) schedule();
489
732
  else if (fixed === 0) {
490
733
  console.log();
491
- watchJob(launch(bun ? ["run", entry] : ["--env-file=.env", entry]), "SDA analysis", "completed");
492
- } else console.log("Fix failed. Waiting for changes...");
734
+ watchJob(launch(bun ? ["run", entry] : ["--env-file=.env", entry], process.execPath, false, report), "SDA analysis", "completed", publish);
735
+ } else {
736
+ publish(fixed ?? 1);
737
+ console.log("Fix failed. Waiting for changes...");
738
+ }
493
739
  }
494
740
  function schedule() {
495
741
  clearTimeout(timer);
@@ -499,6 +745,7 @@ async function shutdown(code) {
499
745
  if (closing) return;
500
746
  closing = true;
501
747
  clearTimeout(timer);
748
+ clearInterval(requestTimer);
502
749
  for (const { watcher } of watchers.values()) watcher.close();
503
750
  await Promise.all([stop(fixer), stop(running)]);
504
751
  releaseLock?.();
@@ -532,14 +779,36 @@ async function runOnce() {
532
779
  await shutdown(await running.done ?? 1);
533
780
  }
534
781
  try {
535
- if (!watchingTests) releaseLock = await acquireSdaLock(runCommand);
782
+ if (!watchingTests) {
783
+ const lock = await acquireSdaLock(runCommand, watching ? resolve(entry) : void 0);
784
+ releaseLock = lock.release;
785
+ if (watching && !closing) {
786
+ const requests = createWatchRequests(lock.directory);
787
+ watchRequests = requests;
788
+ requestTimer = setInterval(() => {
789
+ if (closing) return;
790
+ try {
791
+ const pending = requests.pending();
792
+ if (!checking && !runInProgress && (needsCheck || pending.length)) schedule();
793
+ } catch (error) {
794
+ fail(error);
795
+ }
796
+ }, 100);
797
+ lock.startWatcherHeartbeat(fail);
798
+ }
799
+ }
536
800
  if (closing) releaseLock?.();
537
801
  else if (watching) {
538
802
  refreshWatchers();
539
803
  check().catch(fail);
540
804
  } else runOnce().catch(fail);
541
805
  } catch (error) {
542
- fail(/* @__PURE__ */ new Error("Cannot start " + runCommand + ": " + errorMessage(error)));
806
+ if (!watching && error instanceof SdaLockBusyError && error.watcher?.entry === resolve(entry)) try {
807
+ process.exitCode = await requestWatchRun(error.watcher);
808
+ } catch (requestError) {
809
+ fail(requestError);
810
+ }
811
+ else fail(/* @__PURE__ */ new Error("Cannot start " + runCommand + ": " + errorMessage(error)));
543
812
  }
544
813
  //#endregion
545
814
  export {};