@smoothbricks/nx-plugin 0.3.12 → 0.3.14

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.
@@ -0,0 +1,580 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { existsSync } from 'node:fs';
4
+ import { createRequire } from 'node:module';
5
+ import { join, resolve } from 'node:path';
6
+
7
+ import type { NxJsonConfiguration } from 'nx/src/config/nx-json';
8
+ import type { ProjectGraph, ProjectGraphProjectNode } from 'nx/src/config/project-graph';
9
+ import type { Task } from 'nx/src/config/task-graph';
10
+ import type { TaskResults } from 'nx/src/tasks-runner/life-cycle';
11
+ import type { NxArgs } from 'nx/src/utils/command-line-utils';
12
+
13
+ interface NxRuntimeModules {
14
+ readonly 'nx/src/config/nx-json': typeof import('nx/src/config/nx-json');
15
+ readonly 'nx/src/daemon/client/client': typeof import('nx/src/daemon/client/client');
16
+ readonly 'nx/src/hasher/hash-task': typeof import('nx/src/hasher/hash-task');
17
+ readonly 'nx/src/hasher/task-hasher': typeof import('nx/src/hasher/task-hasher');
18
+ readonly 'nx/src/project-graph/plugins/tasks-execution-hooks': typeof import('nx/src/project-graph/plugins/tasks-execution-hooks');
19
+ readonly 'nx/src/project-graph/project-graph': typeof import('nx/src/project-graph/project-graph');
20
+ readonly 'nx/src/tasks-runner/cache': typeof import('nx/src/tasks-runner/cache');
21
+ readonly 'nx/src/tasks-runner/create-task-graph': typeof import('nx/src/tasks-runner/create-task-graph');
22
+ readonly 'nx/src/tasks-runner/run-command': typeof import('nx/src/tasks-runner/run-command');
23
+ readonly 'nx/src/tasks-runner/task-env': typeof import('nx/src/tasks-runner/task-env');
24
+ readonly 'nx/src/utils/command-line-utils': typeof import('nx/src/utils/command-line-utils');
25
+ readonly 'nx/src/utils/exit-codes': typeof import('nx/src/utils/exit-codes');
26
+ readonly 'nx/src/utils/perf-logging': typeof import('nx/src/utils/perf-logging');
27
+ readonly 'nx/src/utils/workspace-root': typeof import('nx/src/utils/workspace-root');
28
+ }
29
+
30
+ type WorkspaceNxRequire = <Specifier extends keyof NxRuntimeModules>(
31
+ specifier: Specifier,
32
+ ) => NxRuntimeModules[Specifier];
33
+
34
+ function createWorkspaceNxRequire(workspaceRoot: string): WorkspaceNxRequire {
35
+ const requireFromWorkspace = createRequire(join(workspaceRoot, 'package.json'));
36
+ return function requireNx<Specifier extends keyof NxRuntimeModules>(
37
+ specifier: Specifier,
38
+ ): NxRuntimeModules[Specifier] {
39
+ return requireFromWorkspace(specifier);
40
+ };
41
+ }
42
+
43
+ /**
44
+ * A `project:target` or `project:target:configuration` selector.
45
+ *
46
+ * Configuration belongs in the selector rather than in a separate option
47
+ * because it is part of the cache key: `app:build` and `app:build:production`
48
+ * are two different tasks with two different hashes.
49
+ */
50
+ export interface TargetSelector {
51
+ readonly project: string;
52
+ readonly target: string;
53
+ readonly configuration: string | undefined;
54
+ }
55
+
56
+ /**
57
+ * Why the target could not be replayed from what is already on disk.
58
+ *
59
+ * Every variant names the task that ended the probe: in a dependency graph
60
+ * "something changed" is unactionable, and the useful question is always which
61
+ * of the twelve dependencies moved.
62
+ */
63
+ export type MissReason =
64
+ | { readonly kind: 'uncacheable'; readonly taskId: string }
65
+ | { readonly kind: 'unhashable'; readonly taskId: string }
66
+ | { readonly kind: 'not-cached'; readonly taskId: string }
67
+ | { readonly kind: 'cached-failure'; readonly taskId: string; readonly code: number }
68
+ | { readonly kind: 'stale-outputs'; readonly taskId: string }
69
+ | { readonly kind: 'no-daemon'; readonly taskId: string };
70
+
71
+ /**
72
+ * `hit` means nothing ran: every task in the graph was a recorded success and
73
+ * every recorded output is still byte-identical on disk, so the artifacts are
74
+ * what a fresh run would produce.
75
+ *
76
+ * `built` means the work was handed to Nx — which may have restored outputs
77
+ * from the local cache rather than recompiled anything. The line `hit` draws is
78
+ * "did this process have to do work", which is what a CLI wrapper needs in
79
+ * order to decide whether to stay quiet.
80
+ *
81
+ * `failed` is an operational outcome, not an exception: the target ran and did
82
+ * not succeed. A caller re-raises `signal` when there is one and exits with
83
+ * `exitCode` otherwise, so a Ctrl-C during a build stays a Ctrl-C.
84
+ */
85
+ export type EnsureBuiltResult =
86
+ | { readonly disposition: 'hit' }
87
+ | { readonly disposition: 'built'; readonly reason: MissReason }
88
+ | {
89
+ readonly disposition: 'failed';
90
+ readonly reason: MissReason;
91
+ readonly exitCode: number;
92
+ readonly signal: NodeJS.Signals | null;
93
+ };
94
+
95
+ export interface EnsureBuiltOptions {
96
+ /** `project:target` or `project:target:configuration`. */
97
+ readonly target: string;
98
+ /**
99
+ * Nx workspace root. Required rather than discovered: a wrapper script knows
100
+ * its own checkout, and inferring from the caller's directory would silently
101
+ * bind whichever workspace they happen to be standing in.
102
+ */
103
+ readonly cwd: string;
104
+ /**
105
+ * How the run that happens on a miss reports progress. `stream` is the
106
+ * default and the only style offered: this facility fronts multi-minute
107
+ * compiles, and Nx's buffered styles emit nothing until a task finishes, so a
108
+ * silent terminal would read as a hang.
109
+ */
110
+ readonly onMiss?: 'stream';
111
+ }
112
+
113
+ /** A full hit carries no payload, so it is the same value every time. */
114
+ const HIT: EnsureBuiltResult = Object.freeze({ disposition: 'hit' });
115
+
116
+ const NO_TASK_RESULTS: TaskResults = Object.freeze({});
117
+
118
+ export function parseTargetSelector(spec: string): TargetSelector | null {
119
+ const parts = spec.split(':');
120
+ if (parts.length < 2 || parts.length > 3) {
121
+ return null;
122
+ }
123
+ for (const part of parts) {
124
+ if (part.length === 0) {
125
+ return null;
126
+ }
127
+ }
128
+ return { project: parts[0], target: parts[1], configuration: parts[2] };
129
+ }
130
+
131
+ export function describeMiss(reason: MissReason): string {
132
+ switch (reason.kind) {
133
+ case 'uncacheable':
134
+ return `${reason.taskId} is not cacheable, so it must run`;
135
+ case 'unhashable':
136
+ return `${reason.taskId} did not produce a task hash`;
137
+ case 'not-cached':
138
+ return `${reason.taskId} has no cached result for its current inputs`;
139
+ case 'cached-failure':
140
+ return `${reason.taskId} last failed with exit code ${reason.code}`;
141
+ case 'stale-outputs':
142
+ return `${reason.taskId} outputs are missing or modified on disk`;
143
+ case 'no-daemon':
144
+ return `the Nx daemon is disabled, so ${reason.taskId} cannot be checked without running it`;
145
+ }
146
+ }
147
+
148
+ /**
149
+ * First reason the task set cannot be replayed, considering only recorded
150
+ * results — no filesystem access. `null` means every task is a recorded
151
+ * success, and the on-disk check is worth paying for.
152
+ *
153
+ * A cached *failure* counts as a miss even though Nx replays one when
154
+ * `NX_CACHE_FAILURES` is set: this facility exists to hand the process over to
155
+ * a binary, and replaying a failed build would hand over a stale one.
156
+ */
157
+ export function firstCacheMiss(
158
+ tasks: readonly Task[],
159
+ cachedCodeByHash: ReadonlyMap<string, number>,
160
+ ): MissReason | null {
161
+ for (const task of tasks) {
162
+ if (!task.cache) {
163
+ return { kind: 'uncacheable', taskId: task.id };
164
+ }
165
+ // A custom hasher is outside Nx's type guarantees and may return an empty
166
+ // value. Without a hash there is no cache key to query.
167
+ if (!task.hash) {
168
+ return { kind: 'unhashable', taskId: task.id };
169
+ }
170
+ const code = cachedCodeByHash.get(task.hash);
171
+ if (code === undefined) {
172
+ return { kind: 'not-cached', taskId: task.id };
173
+ }
174
+ if (code !== 0) {
175
+ return { kind: 'cached-failure', taskId: task.id, code };
176
+ }
177
+ }
178
+ return null;
179
+ }
180
+
181
+ /**
182
+ * First task whose recorded outputs are no longer the bytes on disk.
183
+ *
184
+ * `matches[index]` is the daemon's verdict for `tasks[index]`. A short or
185
+ * ragged array counts as stale rather than as a hit: a missing verdict is not a
186
+ * positive one, and being wrong here means exec'ing a binary that was deleted.
187
+ */
188
+ export function firstStaleOutputs(tasks: readonly Task[], matches: readonly boolean[]): MissReason | null {
189
+ for (let index = 0; index < tasks.length; index += 1) {
190
+ if (matches[index] !== true) {
191
+ return { kind: 'stale-outputs', taskId: tasks[index].id };
192
+ }
193
+ }
194
+ return null;
195
+ }
196
+
197
+ /**
198
+ * Make sure an Nx target's outputs are on disk, doing as little as possible
199
+ * when they already are.
200
+ *
201
+ * "Already built" is the hot path, because a checkout-local CLI wrapper pays it
202
+ * on every invocation. So it never spawns the `nx` CLI: the project graph, the
203
+ * task hashes and the on-disk output verification are daemon round-trips, the
204
+ * cache lookup is a local SQLite read, and Nx's task runner is only invoked
205
+ * once something is known to need running.
206
+ *
207
+ * With the daemon disabled there is no probe to make — hashing would have to
208
+ * build the project graph in this process, and no service holds the recorded
209
+ * output hashes to check the working tree against — so the target is handed to
210
+ * the workspace's own `nx` CLI unconditionally.
211
+ */
212
+ export async function ensureBuilt(options: EnsureBuiltOptions): Promise<EnsureBuiltResult> {
213
+ const selector = parseTargetSelector(options.target);
214
+ if (!selector) {
215
+ throw new Error(`ensureBuilt: '${options.target}' is not a project:target[:configuration] selector`);
216
+ }
217
+ // Resolved before the chdir below, so a relative `cwd` still means what the
218
+ // caller meant.
219
+ const workspaceRoot = resolve(options.cwd);
220
+ const callerCwd = process.cwd();
221
+ const callerEnv = { ...process.env };
222
+ try {
223
+ // `cd <root> && nx run ...` is the invocation whose hashes are in the
224
+ // cache. Everything below — plugin hooks, `runtime` inputs, and the hasher,
225
+ // which keys against `process.cwd()` — has to see the same directory or the
226
+ // probe keys differently from the CLI and never hits.
227
+ process.chdir(workspaceRoot);
228
+ return await ensureBuiltInWorkspace(workspaceRoot, selector, options.onMiss ?? 'stream');
229
+ } finally {
230
+ // Nx configures itself through the environment and this function runs
231
+ // in-process, so without this the caller — and anything it goes on to exec
232
+ // — would inherit NX_WORKSPACE_ROOT_PATH, the stream/prefix flags, and
233
+ // whatever a plugin's preTasksExecution hook injected. The wrapper this
234
+ // replaces got that isolation for free by running Nx in a child.
235
+ process.chdir(callerCwd);
236
+ for (const key of Object.keys(process.env)) {
237
+ if (!(key in callerEnv)) {
238
+ delete process.env[key];
239
+ }
240
+ }
241
+ for (const [key, value] of Object.entries(callerEnv)) {
242
+ if (process.env[key] !== value) {
243
+ process.env[key] = value;
244
+ }
245
+ }
246
+ }
247
+ }
248
+
249
+ async function ensureBuiltInWorkspace(
250
+ workspaceRoot: string,
251
+ selector: TargetSelector,
252
+ onMiss: 'stream',
253
+ ): Promise<EnsureBuiltResult> {
254
+ // The environment has precedence over nx.json. Avoid loading Nx at all on
255
+ // this explicit fallback path, which also lets a deliberately minimal
256
+ // checkout-local CLI stand in for Nx.
257
+ if (process.env.NX_DAEMON === 'false') {
258
+ return runViaCli(workspaceRoot, selector);
259
+ }
260
+ // Nx rejects daemon access when the client package's version differs from
261
+ // the workspace's running daemon. Resolve every runtime module from the
262
+ // target checkout rather than this package's own dependency: a reusable
263
+ // wrapper must keep using the daemon after the workspace takes an Nx patch.
264
+ const requireNx = createWorkspaceNxRequire(workspaceRoot);
265
+ bindWorkspaceRoot(workspaceRoot, requireNx);
266
+ const { daemonClient } = requireNx('nx/src/daemon/client/client');
267
+ if (!daemonClient.enabled()) {
268
+ return runViaCli(workspaceRoot, selector);
269
+ }
270
+
271
+ const { readNxJson } = requireNx('nx/src/config/nx-json');
272
+ const { splitArgsIntoNxArgsAndOverrides } = requireNx('nx/src/utils/command-line-utils');
273
+ const { setEnvVarsBasedOnArgs } = requireNx('nx/src/tasks-runner/run-command');
274
+ const hooks = requireNx('nx/src/project-graph/plugins/tasks-execution-hooks');
275
+
276
+ const nxJson = readNxJson();
277
+ // Reproduce `nx run <selector> --outputStyle=<style>` exactly. Task hashes
278
+ // are derived from these arguments, so anything hand-rolled here instead of
279
+ // routed through Nx's own argument normalization would key the cache
280
+ // differently from the CLI and turn every probe into a miss.
281
+ const { nxArgs, overrides } = splitArgsIntoNxArgsAndOverrides(
282
+ { targets: [selector.target], configuration: selector.configuration, outputStyle: onMiss },
283
+ 'run-one',
284
+ { printWarnings: false },
285
+ nxJson,
286
+ );
287
+ const loadDotEnvFiles = process.env.NX_LOAD_DOT_ENV_FILES !== 'false';
288
+ // Sets NX_LOAD_DOT_ENV_FILES and the stream/prefix flags, which the hasher
289
+ // reads through each task's environment. It has to happen before hashing or
290
+ // the probe keys differently from the CLI.
291
+ setEnvVarsBasedOnArgs(nxArgs, loadDotEnvFiles);
292
+
293
+ const runId = randomUUID();
294
+ const startTime = Date.now();
295
+ // Plugin `preTasksExecution` hooks inject environment variables, and declared
296
+ // `env` inputs hash against them. Skipping the hook would not merely cost
297
+ // hits: the run below would then execute with a different environment than
298
+ // the CLI does, record a hash the CLI never looks up, and thrash the cache.
299
+ await hooks.runPreTasksExecution({
300
+ id: runId,
301
+ workspaceRoot,
302
+ nxJsonConfiguration: nxJson,
303
+ argv: process.argv,
304
+ });
305
+
306
+ performance.mark('ensureBuilt:probe:start');
307
+ const reason = await probe(nxJson, nxArgs, overrides, selector, requireNx);
308
+ performance.measure('ensureBuilt:probe', 'ensureBuilt:probe:start');
309
+ const outcome =
310
+ reason === null
311
+ ? { result: HIT, taskResults: NO_TASK_RESULTS }
312
+ : await runTarget(nxJson, nxArgs, overrides, selector, reason, requireNx);
313
+ await hooks.runPostTasksExecution({
314
+ id: runId,
315
+ taskResults: outcome.taskResults,
316
+ workspaceRoot,
317
+ nxJsonConfiguration: nxJson,
318
+ argv: process.argv,
319
+ startTime,
320
+ endTime: Date.now(),
321
+ });
322
+ return outcome.result;
323
+ }
324
+
325
+ /**
326
+ * Nx computes `workspaceRoot` once, at module load, from
327
+ * `NX_WORKSPACE_ROOT_PATH` or the current directory — and its daemon client is
328
+ * a module-level singleton that reads `nx.json` from that root. So the root has
329
+ * to be bound before the first Nx module loads, which is why this module
330
+ * imports Nx dynamically throughout. A static import at the top of the file
331
+ * would bind the caller's launch directory instead.
332
+ */
333
+ function bindWorkspaceRoot(workspaceRoot: string, requireNx: WorkspaceNxRequire): void {
334
+ process.env.NX_WORKSPACE_ROOT_PATH = workspaceRoot;
335
+ if (process.env.NX_PERF_LOGGING === 'true') {
336
+ // Installs Nx's PerformanceObserver, which reports every `performance
337
+ // .measure` this module and Nx itself record. Loading it unconditionally
338
+ // would add an observer to hot paths that never want one.
339
+ requireNx('nx/src/utils/perf-logging');
340
+ }
341
+ const { workspaceRoot: boundRoot } = requireNx('nx/src/utils/workspace-root');
342
+ if (boundRoot !== workspaceRoot) {
343
+ // One process cannot serve two workspaces: the constant and the daemon
344
+ // client singleton are already bound. Say so rather than silently probing
345
+ // the wrong checkout.
346
+ throw new Error(
347
+ `ensureBuilt: Nx is already bound to workspace root ${boundRoot}, cannot switch to ${workspaceRoot}`,
348
+ );
349
+ }
350
+ }
351
+
352
+ /** `null` when the target is already built; otherwise the first reason it is not. */
353
+ async function probe(
354
+ nxJson: NxJsonConfiguration,
355
+ nxArgs: NxArgs,
356
+ overrides: Record<string, unknown>,
357
+ selector: TargetSelector,
358
+ requireNx: WorkspaceNxRequire,
359
+ ): Promise<MissReason | null> {
360
+ const { daemonClient } = requireNx('nx/src/daemon/client/client');
361
+ const { createTaskGraph } = requireNx('nx/src/tasks-runner/create-task-graph');
362
+ const { DaemonBasedTaskHasher } = requireNx('nx/src/hasher/task-hasher');
363
+ const { getTaskDetails, hashTasks } = requireNx('nx/src/hasher/hash-task');
364
+ const { getTaskSpecificEnv } = requireNx('nx/src/tasks-runner/task-env');
365
+ const { getCache } = requireNx('nx/src/tasks-runner/cache');
366
+ const { getRunnerOptions } = requireNx('nx/src/tasks-runner/run-command');
367
+
368
+ performance.mark('ensureBuilt:graph:start');
369
+ const { projectGraph } = await daemonClient.getProjectGraphAndSourceMaps();
370
+ requireProject(projectGraph, selector.project);
371
+ const taskGraph = createTaskGraph(
372
+ projectGraph,
373
+ {},
374
+ [selector.project],
375
+ [selector.target],
376
+ selector.configuration,
377
+ overrides,
378
+ false,
379
+ );
380
+ const tasks = Object.values(taskGraph.tasks);
381
+ performance.measure('ensureBuilt:graph', 'ensureBuilt:graph:start');
382
+
383
+ // `isCloudDefault: false` because these options are only read here by the
384
+ // hasher, which looks at `selectivelyHashTsConfig`; the cloud credentials the
385
+ // flag would add belong to the cloud runner, and the run path calls Nx's own
386
+ // `getRunner` to obtain them.
387
+ const runnerOptions = getRunnerOptions('default', nxJson, nxArgs, false);
388
+ const hasher = new DaemonBasedTaskHasher(daemonClient, runnerOptions);
389
+ performance.mark('ensureBuilt:hash:start');
390
+ // Every task, each against its own environment — per-project and per-target
391
+ // `.env` files and custom hashers that read env participate in the hash, so
392
+ // one shared environment would compute keys the CLI never wrote.
393
+ //
394
+ // `hashTasksThatDoNotDependOnOutputsOfOtherTasks` is the wrong helper here
395
+ // even though it is what Nx's runner warms up with: it deliberately skips
396
+ // tasks whose inputs include another task's outputs, leaving them unhashed
397
+ // for the orchestrator to hash once their dependencies finish. In a probe,
398
+ // "already built" means those outputs are already final, so hashing them now
399
+ // is both possible and exactly what the cache was keyed on. Skipping them
400
+ // instead would make every graph that uses `dependentTasksOutputFiles` — the
401
+ // normal shape for a multi-package build — permanently miss.
402
+ const perTaskEnvs: Record<string, NodeJS.ProcessEnv> = {};
403
+ for (const task of tasks) {
404
+ perTaskEnvs[task.id] = getTaskSpecificEnv(task, projectGraph);
405
+ }
406
+ await hashTasks(hasher, projectGraph, taskGraph, perTaskEnvs, getTaskDetails(), tasks);
407
+ performance.measure('ensureBuilt:hash', 'ensureBuilt:hash:start');
408
+
409
+ // Nx's own factory, but deliberately never `init()`ed: that is what makes
410
+ // this a local-only, side-effect-free question. `init()` attaches the remote
411
+ // cache — a network round-trip, and a download is precisely the work this
412
+ // probe exists to detect — and asserts that the cache directory matches the
413
+ // database. Neither matters here: a hit is only declared when the outputs on
414
+ // disk already match, so the cache directory is never read.
415
+ performance.mark('ensureBuilt:cache:start');
416
+ const cache = getCache(runnerOptions);
417
+ const cachedResults = await cache.getBatch(tasks.filter((task) => task.cache && task.hash));
418
+ const cachedCodeByHash = new Map<string, number>();
419
+ for (const [hash, result] of cachedResults) {
420
+ cachedCodeByHash.set(hash, result.code);
421
+ }
422
+ const cacheMiss = firstCacheMiss(tasks, cachedCodeByHash);
423
+ performance.measure('ensureBuilt:cache', 'ensureBuilt:cache:start');
424
+ if (cacheMiss) {
425
+ return cacheMiss;
426
+ }
427
+
428
+ // A cache record only proves the task once succeeded with these inputs. The
429
+ // artifact this facility is about — the binary that is about to be exec'd —
430
+ // lives in the working tree, where anything may have deleted or rewritten it
431
+ // since. Only the daemon can settle that, because it holds the recorded
432
+ // output hashes.
433
+ const withOutputs: Task[] = [];
434
+ const outputEntries: { outputs: string[]; hash: string }[] = [];
435
+ for (const task of tasks) {
436
+ const hash = task.hash;
437
+ if (task.outputs.length === 0 || hash === undefined) {
438
+ continue;
439
+ }
440
+ withOutputs.push(task);
441
+ outputEntries.push({ outputs: task.outputs, hash });
442
+ }
443
+ performance.mark('ensureBuilt:outputs:start');
444
+ const matches = await daemonClient.outputsHashesMatchBatch(outputEntries);
445
+ performance.measure('ensureBuilt:outputs', 'ensureBuilt:outputs:start');
446
+ return firstStaleOutputs(withOutputs, matches);
447
+ }
448
+
449
+ interface CompletedRun {
450
+ readonly result: EnsureBuiltResult;
451
+ readonly taskResults: TaskResults;
452
+ }
453
+
454
+ async function runTarget(
455
+ nxJson: NxJsonConfiguration,
456
+ nxArgs: NxArgs,
457
+ overrides: Record<string, unknown>,
458
+ selector: TargetSelector,
459
+ reason: MissReason,
460
+ requireNx: WorkspaceNxRequire,
461
+ ): Promise<CompletedRun> {
462
+ const { runCommandForTasks } = requireNx('nx/src/tasks-runner/run-command');
463
+ const { createProjectGraphAsync } = requireNx('nx/src/project-graph/project-graph');
464
+ const { signalToCode } = requireNx('nx/src/utils/exit-codes');
465
+ // `runCommandForTasks` derives its own task graph and hashes, so the probe's
466
+ // work is not reusable. That duplication is one daemon round-trip on a path
467
+ // that is about to run a build.
468
+ const projectGraph = await createProjectGraphAsync();
469
+ const { taskResults, completed } = await runCommandForTasks(
470
+ [requireProject(projectGraph, selector.project)],
471
+ projectGraph,
472
+ { nxJson },
473
+ nxArgs,
474
+ overrides,
475
+ selector.project,
476
+ {},
477
+ { excludeTaskDependencies: false, loadDotEnvFiles: process.env.NX_LOAD_DOT_ENV_FILES !== 'false' },
478
+ );
479
+ if (!completed) {
480
+ // Nx's own encoding of an interrupted run: `runCommand` reports
481
+ // `signalToCode('SIGINT')` here. The runner does not surface which signal
482
+ // actually arrived, so there is none to forward — only the code Nx's CLI
483
+ // would have exited with.
484
+ return {
485
+ result: { disposition: 'failed', reason, exitCode: signalToCode('SIGINT'), signal: null },
486
+ taskResults,
487
+ };
488
+ }
489
+ for (const taskResult of Object.values(taskResults)) {
490
+ if (taskResult.status === 'failure' || taskResult.status === 'skipped') {
491
+ return { result: { disposition: 'failed', reason, exitCode: 1, signal: null }, taskResults };
492
+ }
493
+ }
494
+ return { result: { disposition: 'built', reason }, taskResults };
495
+ }
496
+
497
+ /**
498
+ * The daemon-disabled path: hand the target to the workspace's own `nx`, with
499
+ * stdio inherited.
500
+ *
501
+ * Inheriting rather than piping is the point. The wrapper this facility
502
+ * replaces piped Nx's output so it could read a cache marker out of the log and
503
+ * stay silent on a hit — a text heuristic over ANSI-coloured, format-unstable
504
+ * output. Without a daemon there is nothing to be silent about: no cheap probe
505
+ * exists, so the run is unconditional, the output is the run's own, and the
506
+ * child's exit status is forwarded verbatim.
507
+ */
508
+ async function runViaCli(workspaceRoot: string, selector: TargetSelector): Promise<EnsureBuiltResult> {
509
+ const nxCli = join(workspaceRoot, 'node_modules', '.bin', 'nx');
510
+ if (!existsSync(nxCli)) {
511
+ throw new Error(`ensureBuilt: the Nx daemon is disabled and ${nxCli} does not exist`);
512
+ }
513
+ const reason: MissReason = { kind: 'no-daemon', taskId: `${selector.project}:${selector.target}` };
514
+ const targetSpec = selector.configuration
515
+ ? `${selector.project}:${selector.target}:${selector.configuration}`
516
+ : `${selector.project}:${selector.target}`;
517
+ const signalToCode = nxSignalToCode;
518
+ const child = spawn(nxCli, ['run', targetSpec, '--outputStyle=stream'], {
519
+ cwd: workspaceRoot,
520
+ stdio: 'inherit',
521
+ });
522
+ // `Promise.withResolvers` would read better but needs lib es2024; this
523
+ // package inherits lib es2022 from tsconfig.base.json.
524
+ const exit = await new Promise<ChildExit>((settle, reject) => {
525
+ child.once('error', reject);
526
+ child.once('exit', (code, signal) => settle({ code, signal }));
527
+ });
528
+ return cliExitOutcome(reason, exit, signalToCode);
529
+ }
530
+
531
+ function nxSignalToCode(signal: NodeJS.Signals | null): number {
532
+ switch (signal) {
533
+ case 'SIGHUP':
534
+ return 129;
535
+ case 'SIGINT':
536
+ return 130;
537
+ case 'SIGQUIT':
538
+ return 131;
539
+ case 'SIGTERM':
540
+ return 143;
541
+ default:
542
+ return 128;
543
+ }
544
+ }
545
+
546
+ export interface ChildExit {
547
+ readonly code: number | null;
548
+ readonly signal: NodeJS.Signals | null;
549
+ }
550
+
551
+ /**
552
+ * How a child `nx`'s exit becomes a result.
553
+ *
554
+ * A signal is reported as a signal, not flattened into a code, so the caller
555
+ * can re-raise it: a build stopped by Ctrl-C should leave the wrapper looking
556
+ * killed by Ctrl-C to whatever is watching, not merely unsuccessful. The
557
+ * numeric code comes from Nx's own `signalToCode` so it matches what `nx run`
558
+ * would have exited with.
559
+ */
560
+ export function cliExitOutcome(
561
+ reason: MissReason,
562
+ exit: ChildExit,
563
+ signalToCode: (signal: NodeJS.Signals | null) => number,
564
+ ): EnsureBuiltResult {
565
+ if (exit.signal !== null) {
566
+ return { disposition: 'failed', reason, exitCode: signalToCode(exit.signal), signal: exit.signal };
567
+ }
568
+ if (exit.code !== 0) {
569
+ return { disposition: 'failed', reason, exitCode: exit.code ?? 1, signal: null };
570
+ }
571
+ return { disposition: 'built', reason };
572
+ }
573
+
574
+ function requireProject(projectGraph: ProjectGraph, project: string): ProjectGraphProjectNode {
575
+ const node = projectGraph.nodes[project];
576
+ if (!node) {
577
+ throw new Error(`ensureBuilt: no project named '${project}' in this workspace`);
578
+ }
579
+ return node;
580
+ }
@@ -117,7 +117,7 @@ describe('@smoothbricks/nx-plugin:bounded-exec', () => {
117
117
  [
118
118
  'let ticks = 0;',
119
119
  'const timer = setInterval(() => {',
120
- ' console.log(`tick ${++ticks}`);',
120
+ ' console.log("tick " + ++ticks);',
121
121
  ' if (ticks === 6) {',
122
122
  ' clearInterval(timer);',
123
123
  ' }',
@@ -144,7 +144,7 @@ describe('@smoothbricks/nx-plugin:bounded-exec', () => {
144
144
  [
145
145
  'let ticks = 0;',
146
146
  'const timer = setInterval(() => {',
147
- ' console.error(`tick ${++ticks}`);',
147
+ ' console.error("tick " + ++ticks);',
148
148
  ' if (ticks === 5) {',
149
149
  ' clearInterval(timer);',
150
150
  ' }',