@smoothbricks/nx-plugin 0.3.13 → 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,399 @@
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
+ function createWorkspaceNxRequire(workspaceRoot) {
7
+ const requireFromWorkspace = createRequire(join(workspaceRoot, 'package.json'));
8
+ return function requireNx(specifier) {
9
+ return requireFromWorkspace(specifier);
10
+ };
11
+ }
12
+ /** A full hit carries no payload, so it is the same value every time. */
13
+ const HIT = Object.freeze({ disposition: 'hit' });
14
+ const NO_TASK_RESULTS = Object.freeze({});
15
+ export function parseTargetSelector(spec) {
16
+ const parts = spec.split(':');
17
+ if (parts.length < 2 || parts.length > 3) {
18
+ return null;
19
+ }
20
+ for (const part of parts) {
21
+ if (part.length === 0) {
22
+ return null;
23
+ }
24
+ }
25
+ return { project: parts[0], target: parts[1], configuration: parts[2] };
26
+ }
27
+ export function describeMiss(reason) {
28
+ switch (reason.kind) {
29
+ case 'uncacheable':
30
+ return `${reason.taskId} is not cacheable, so it must run`;
31
+ case 'unhashable':
32
+ return `${reason.taskId} did not produce a task hash`;
33
+ case 'not-cached':
34
+ return `${reason.taskId} has no cached result for its current inputs`;
35
+ case 'cached-failure':
36
+ return `${reason.taskId} last failed with exit code ${reason.code}`;
37
+ case 'stale-outputs':
38
+ return `${reason.taskId} outputs are missing or modified on disk`;
39
+ case 'no-daemon':
40
+ return `the Nx daemon is disabled, so ${reason.taskId} cannot be checked without running it`;
41
+ }
42
+ }
43
+ /**
44
+ * First reason the task set cannot be replayed, considering only recorded
45
+ * results — no filesystem access. `null` means every task is a recorded
46
+ * success, and the on-disk check is worth paying for.
47
+ *
48
+ * A cached *failure* counts as a miss even though Nx replays one when
49
+ * `NX_CACHE_FAILURES` is set: this facility exists to hand the process over to
50
+ * a binary, and replaying a failed build would hand over a stale one.
51
+ */
52
+ export function firstCacheMiss(tasks, cachedCodeByHash) {
53
+ for (const task of tasks) {
54
+ if (!task.cache) {
55
+ return { kind: 'uncacheable', taskId: task.id };
56
+ }
57
+ // A custom hasher is outside Nx's type guarantees and may return an empty
58
+ // value. Without a hash there is no cache key to query.
59
+ if (!task.hash) {
60
+ return { kind: 'unhashable', taskId: task.id };
61
+ }
62
+ const code = cachedCodeByHash.get(task.hash);
63
+ if (code === undefined) {
64
+ return { kind: 'not-cached', taskId: task.id };
65
+ }
66
+ if (code !== 0) {
67
+ return { kind: 'cached-failure', taskId: task.id, code };
68
+ }
69
+ }
70
+ return null;
71
+ }
72
+ /**
73
+ * First task whose recorded outputs are no longer the bytes on disk.
74
+ *
75
+ * `matches[index]` is the daemon's verdict for `tasks[index]`. A short or
76
+ * ragged array counts as stale rather than as a hit: a missing verdict is not a
77
+ * positive one, and being wrong here means exec'ing a binary that was deleted.
78
+ */
79
+ export function firstStaleOutputs(tasks, matches) {
80
+ for (let index = 0; index < tasks.length; index += 1) {
81
+ if (matches[index] !== true) {
82
+ return { kind: 'stale-outputs', taskId: tasks[index].id };
83
+ }
84
+ }
85
+ return null;
86
+ }
87
+ /**
88
+ * Make sure an Nx target's outputs are on disk, doing as little as possible
89
+ * when they already are.
90
+ *
91
+ * "Already built" is the hot path, because a checkout-local CLI wrapper pays it
92
+ * on every invocation. So it never spawns the `nx` CLI: the project graph, the
93
+ * task hashes and the on-disk output verification are daemon round-trips, the
94
+ * cache lookup is a local SQLite read, and Nx's task runner is only invoked
95
+ * once something is known to need running.
96
+ *
97
+ * With the daemon disabled there is no probe to make — hashing would have to
98
+ * build the project graph in this process, and no service holds the recorded
99
+ * output hashes to check the working tree against — so the target is handed to
100
+ * the workspace's own `nx` CLI unconditionally.
101
+ */
102
+ export async function ensureBuilt(options) {
103
+ const selector = parseTargetSelector(options.target);
104
+ if (!selector) {
105
+ throw new Error(`ensureBuilt: '${options.target}' is not a project:target[:configuration] selector`);
106
+ }
107
+ // Resolved before the chdir below, so a relative `cwd` still means what the
108
+ // caller meant.
109
+ const workspaceRoot = resolve(options.cwd);
110
+ const callerCwd = process.cwd();
111
+ const callerEnv = { ...process.env };
112
+ try {
113
+ // `cd <root> && nx run ...` is the invocation whose hashes are in the
114
+ // cache. Everything below — plugin hooks, `runtime` inputs, and the hasher,
115
+ // which keys against `process.cwd()` — has to see the same directory or the
116
+ // probe keys differently from the CLI and never hits.
117
+ process.chdir(workspaceRoot);
118
+ return await ensureBuiltInWorkspace(workspaceRoot, selector, options.onMiss ?? 'stream');
119
+ }
120
+ finally {
121
+ // Nx configures itself through the environment and this function runs
122
+ // in-process, so without this the caller — and anything it goes on to exec
123
+ // — would inherit NX_WORKSPACE_ROOT_PATH, the stream/prefix flags, and
124
+ // whatever a plugin's preTasksExecution hook injected. The wrapper this
125
+ // replaces got that isolation for free by running Nx in a child.
126
+ process.chdir(callerCwd);
127
+ for (const key of Object.keys(process.env)) {
128
+ if (!(key in callerEnv)) {
129
+ delete process.env[key];
130
+ }
131
+ }
132
+ for (const [key, value] of Object.entries(callerEnv)) {
133
+ if (process.env[key] !== value) {
134
+ process.env[key] = value;
135
+ }
136
+ }
137
+ }
138
+ }
139
+ async function ensureBuiltInWorkspace(workspaceRoot, selector, onMiss) {
140
+ // The environment has precedence over nx.json. Avoid loading Nx at all on
141
+ // this explicit fallback path, which also lets a deliberately minimal
142
+ // checkout-local CLI stand in for Nx.
143
+ if (process.env.NX_DAEMON === 'false') {
144
+ return runViaCli(workspaceRoot, selector);
145
+ }
146
+ // Nx rejects daemon access when the client package's version differs from
147
+ // the workspace's running daemon. Resolve every runtime module from the
148
+ // target checkout rather than this package's own dependency: a reusable
149
+ // wrapper must keep using the daemon after the workspace takes an Nx patch.
150
+ const requireNx = createWorkspaceNxRequire(workspaceRoot);
151
+ bindWorkspaceRoot(workspaceRoot, requireNx);
152
+ const { daemonClient } = requireNx('nx/src/daemon/client/client');
153
+ if (!daemonClient.enabled()) {
154
+ return runViaCli(workspaceRoot, selector);
155
+ }
156
+ const { readNxJson } = requireNx('nx/src/config/nx-json');
157
+ const { splitArgsIntoNxArgsAndOverrides } = requireNx('nx/src/utils/command-line-utils');
158
+ const { setEnvVarsBasedOnArgs } = requireNx('nx/src/tasks-runner/run-command');
159
+ const hooks = requireNx('nx/src/project-graph/plugins/tasks-execution-hooks');
160
+ const nxJson = readNxJson();
161
+ // Reproduce `nx run <selector> --outputStyle=<style>` exactly. Task hashes
162
+ // are derived from these arguments, so anything hand-rolled here instead of
163
+ // routed through Nx's own argument normalization would key the cache
164
+ // differently from the CLI and turn every probe into a miss.
165
+ const { nxArgs, overrides } = splitArgsIntoNxArgsAndOverrides({ targets: [selector.target], configuration: selector.configuration, outputStyle: onMiss }, 'run-one', { printWarnings: false }, nxJson);
166
+ const loadDotEnvFiles = process.env.NX_LOAD_DOT_ENV_FILES !== 'false';
167
+ // Sets NX_LOAD_DOT_ENV_FILES and the stream/prefix flags, which the hasher
168
+ // reads through each task's environment. It has to happen before hashing or
169
+ // the probe keys differently from the CLI.
170
+ setEnvVarsBasedOnArgs(nxArgs, loadDotEnvFiles);
171
+ const runId = randomUUID();
172
+ const startTime = Date.now();
173
+ // Plugin `preTasksExecution` hooks inject environment variables, and declared
174
+ // `env` inputs hash against them. Skipping the hook would not merely cost
175
+ // hits: the run below would then execute with a different environment than
176
+ // the CLI does, record a hash the CLI never looks up, and thrash the cache.
177
+ await hooks.runPreTasksExecution({
178
+ id: runId,
179
+ workspaceRoot,
180
+ nxJsonConfiguration: nxJson,
181
+ argv: process.argv,
182
+ });
183
+ performance.mark('ensureBuilt:probe:start');
184
+ const reason = await probe(nxJson, nxArgs, overrides, selector, requireNx);
185
+ performance.measure('ensureBuilt:probe', 'ensureBuilt:probe:start');
186
+ const outcome = reason === null
187
+ ? { result: HIT, taskResults: NO_TASK_RESULTS }
188
+ : await runTarget(nxJson, nxArgs, overrides, selector, reason, requireNx);
189
+ await hooks.runPostTasksExecution({
190
+ id: runId,
191
+ taskResults: outcome.taskResults,
192
+ workspaceRoot,
193
+ nxJsonConfiguration: nxJson,
194
+ argv: process.argv,
195
+ startTime,
196
+ endTime: Date.now(),
197
+ });
198
+ return outcome.result;
199
+ }
200
+ /**
201
+ * Nx computes `workspaceRoot` once, at module load, from
202
+ * `NX_WORKSPACE_ROOT_PATH` or the current directory — and its daemon client is
203
+ * a module-level singleton that reads `nx.json` from that root. So the root has
204
+ * to be bound before the first Nx module loads, which is why this module
205
+ * imports Nx dynamically throughout. A static import at the top of the file
206
+ * would bind the caller's launch directory instead.
207
+ */
208
+ function bindWorkspaceRoot(workspaceRoot, requireNx) {
209
+ process.env.NX_WORKSPACE_ROOT_PATH = workspaceRoot;
210
+ if (process.env.NX_PERF_LOGGING === 'true') {
211
+ // Installs Nx's PerformanceObserver, which reports every `performance
212
+ // .measure` this module and Nx itself record. Loading it unconditionally
213
+ // would add an observer to hot paths that never want one.
214
+ requireNx('nx/src/utils/perf-logging');
215
+ }
216
+ const { workspaceRoot: boundRoot } = requireNx('nx/src/utils/workspace-root');
217
+ if (boundRoot !== workspaceRoot) {
218
+ // One process cannot serve two workspaces: the constant and the daemon
219
+ // client singleton are already bound. Say so rather than silently probing
220
+ // the wrong checkout.
221
+ throw new Error(`ensureBuilt: Nx is already bound to workspace root ${boundRoot}, cannot switch to ${workspaceRoot}`);
222
+ }
223
+ }
224
+ /** `null` when the target is already built; otherwise the first reason it is not. */
225
+ async function probe(nxJson, nxArgs, overrides, selector, requireNx) {
226
+ const { daemonClient } = requireNx('nx/src/daemon/client/client');
227
+ const { createTaskGraph } = requireNx('nx/src/tasks-runner/create-task-graph');
228
+ const { DaemonBasedTaskHasher } = requireNx('nx/src/hasher/task-hasher');
229
+ const { getTaskDetails, hashTasks } = requireNx('nx/src/hasher/hash-task');
230
+ const { getTaskSpecificEnv } = requireNx('nx/src/tasks-runner/task-env');
231
+ const { getCache } = requireNx('nx/src/tasks-runner/cache');
232
+ const { getRunnerOptions } = requireNx('nx/src/tasks-runner/run-command');
233
+ performance.mark('ensureBuilt:graph:start');
234
+ const { projectGraph } = await daemonClient.getProjectGraphAndSourceMaps();
235
+ requireProject(projectGraph, selector.project);
236
+ const taskGraph = createTaskGraph(projectGraph, {}, [selector.project], [selector.target], selector.configuration, overrides, false);
237
+ const tasks = Object.values(taskGraph.tasks);
238
+ performance.measure('ensureBuilt:graph', 'ensureBuilt:graph:start');
239
+ // `isCloudDefault: false` because these options are only read here by the
240
+ // hasher, which looks at `selectivelyHashTsConfig`; the cloud credentials the
241
+ // flag would add belong to the cloud runner, and the run path calls Nx's own
242
+ // `getRunner` to obtain them.
243
+ const runnerOptions = getRunnerOptions('default', nxJson, nxArgs, false);
244
+ const hasher = new DaemonBasedTaskHasher(daemonClient, runnerOptions);
245
+ performance.mark('ensureBuilt:hash:start');
246
+ // Every task, each against its own environment — per-project and per-target
247
+ // `.env` files and custom hashers that read env participate in the hash, so
248
+ // one shared environment would compute keys the CLI never wrote.
249
+ //
250
+ // `hashTasksThatDoNotDependOnOutputsOfOtherTasks` is the wrong helper here
251
+ // even though it is what Nx's runner warms up with: it deliberately skips
252
+ // tasks whose inputs include another task's outputs, leaving them unhashed
253
+ // for the orchestrator to hash once their dependencies finish. In a probe,
254
+ // "already built" means those outputs are already final, so hashing them now
255
+ // is both possible and exactly what the cache was keyed on. Skipping them
256
+ // instead would make every graph that uses `dependentTasksOutputFiles` — the
257
+ // normal shape for a multi-package build — permanently miss.
258
+ const perTaskEnvs = {};
259
+ for (const task of tasks) {
260
+ perTaskEnvs[task.id] = getTaskSpecificEnv(task, projectGraph);
261
+ }
262
+ await hashTasks(hasher, projectGraph, taskGraph, perTaskEnvs, getTaskDetails(), tasks);
263
+ performance.measure('ensureBuilt:hash', 'ensureBuilt:hash:start');
264
+ // Nx's own factory, but deliberately never `init()`ed: that is what makes
265
+ // this a local-only, side-effect-free question. `init()` attaches the remote
266
+ // cache — a network round-trip, and a download is precisely the work this
267
+ // probe exists to detect — and asserts that the cache directory matches the
268
+ // database. Neither matters here: a hit is only declared when the outputs on
269
+ // disk already match, so the cache directory is never read.
270
+ performance.mark('ensureBuilt:cache:start');
271
+ const cache = getCache(runnerOptions);
272
+ const cachedResults = await cache.getBatch(tasks.filter((task) => task.cache && task.hash));
273
+ const cachedCodeByHash = new Map();
274
+ for (const [hash, result] of cachedResults) {
275
+ cachedCodeByHash.set(hash, result.code);
276
+ }
277
+ const cacheMiss = firstCacheMiss(tasks, cachedCodeByHash);
278
+ performance.measure('ensureBuilt:cache', 'ensureBuilt:cache:start');
279
+ if (cacheMiss) {
280
+ return cacheMiss;
281
+ }
282
+ // A cache record only proves the task once succeeded with these inputs. The
283
+ // artifact this facility is about — the binary that is about to be exec'd —
284
+ // lives in the working tree, where anything may have deleted or rewritten it
285
+ // since. Only the daemon can settle that, because it holds the recorded
286
+ // output hashes.
287
+ const withOutputs = [];
288
+ const outputEntries = [];
289
+ for (const task of tasks) {
290
+ const hash = task.hash;
291
+ if (task.outputs.length === 0 || hash === undefined) {
292
+ continue;
293
+ }
294
+ withOutputs.push(task);
295
+ outputEntries.push({ outputs: task.outputs, hash });
296
+ }
297
+ performance.mark('ensureBuilt:outputs:start');
298
+ const matches = await daemonClient.outputsHashesMatchBatch(outputEntries);
299
+ performance.measure('ensureBuilt:outputs', 'ensureBuilt:outputs:start');
300
+ return firstStaleOutputs(withOutputs, matches);
301
+ }
302
+ async function runTarget(nxJson, nxArgs, overrides, selector, reason, requireNx) {
303
+ const { runCommandForTasks } = requireNx('nx/src/tasks-runner/run-command');
304
+ const { createProjectGraphAsync } = requireNx('nx/src/project-graph/project-graph');
305
+ const { signalToCode } = requireNx('nx/src/utils/exit-codes');
306
+ // `runCommandForTasks` derives its own task graph and hashes, so the probe's
307
+ // work is not reusable. That duplication is one daemon round-trip on a path
308
+ // that is about to run a build.
309
+ const projectGraph = await createProjectGraphAsync();
310
+ const { taskResults, completed } = await runCommandForTasks([requireProject(projectGraph, selector.project)], projectGraph, { nxJson }, nxArgs, overrides, selector.project, {}, { excludeTaskDependencies: false, loadDotEnvFiles: process.env.NX_LOAD_DOT_ENV_FILES !== 'false' });
311
+ if (!completed) {
312
+ // Nx's own encoding of an interrupted run: `runCommand` reports
313
+ // `signalToCode('SIGINT')` here. The runner does not surface which signal
314
+ // actually arrived, so there is none to forward — only the code Nx's CLI
315
+ // would have exited with.
316
+ return {
317
+ result: { disposition: 'failed', reason, exitCode: signalToCode('SIGINT'), signal: null },
318
+ taskResults,
319
+ };
320
+ }
321
+ for (const taskResult of Object.values(taskResults)) {
322
+ if (taskResult.status === 'failure' || taskResult.status === 'skipped') {
323
+ return { result: { disposition: 'failed', reason, exitCode: 1, signal: null }, taskResults };
324
+ }
325
+ }
326
+ return { result: { disposition: 'built', reason }, taskResults };
327
+ }
328
+ /**
329
+ * The daemon-disabled path: hand the target to the workspace's own `nx`, with
330
+ * stdio inherited.
331
+ *
332
+ * Inheriting rather than piping is the point. The wrapper this facility
333
+ * replaces piped Nx's output so it could read a cache marker out of the log and
334
+ * stay silent on a hit — a text heuristic over ANSI-coloured, format-unstable
335
+ * output. Without a daemon there is nothing to be silent about: no cheap probe
336
+ * exists, so the run is unconditional, the output is the run's own, and the
337
+ * child's exit status is forwarded verbatim.
338
+ */
339
+ async function runViaCli(workspaceRoot, selector) {
340
+ const nxCli = join(workspaceRoot, 'node_modules', '.bin', 'nx');
341
+ if (!existsSync(nxCli)) {
342
+ throw new Error(`ensureBuilt: the Nx daemon is disabled and ${nxCli} does not exist`);
343
+ }
344
+ const reason = { kind: 'no-daemon', taskId: `${selector.project}:${selector.target}` };
345
+ const targetSpec = selector.configuration
346
+ ? `${selector.project}:${selector.target}:${selector.configuration}`
347
+ : `${selector.project}:${selector.target}`;
348
+ const signalToCode = nxSignalToCode;
349
+ const child = spawn(nxCli, ['run', targetSpec, '--outputStyle=stream'], {
350
+ cwd: workspaceRoot,
351
+ stdio: 'inherit',
352
+ });
353
+ // `Promise.withResolvers` would read better but needs lib es2024; this
354
+ // package inherits lib es2022 from tsconfig.base.json.
355
+ const exit = await new Promise((settle, reject) => {
356
+ child.once('error', reject);
357
+ child.once('exit', (code, signal) => settle({ code, signal }));
358
+ });
359
+ return cliExitOutcome(reason, exit, signalToCode);
360
+ }
361
+ function nxSignalToCode(signal) {
362
+ switch (signal) {
363
+ case 'SIGHUP':
364
+ return 129;
365
+ case 'SIGINT':
366
+ return 130;
367
+ case 'SIGQUIT':
368
+ return 131;
369
+ case 'SIGTERM':
370
+ return 143;
371
+ default:
372
+ return 128;
373
+ }
374
+ }
375
+ /**
376
+ * How a child `nx`'s exit becomes a result.
377
+ *
378
+ * A signal is reported as a signal, not flattened into a code, so the caller
379
+ * can re-raise it: a build stopped by Ctrl-C should leave the wrapper looking
380
+ * killed by Ctrl-C to whatever is watching, not merely unsuccessful. The
381
+ * numeric code comes from Nx's own `signalToCode` so it matches what `nx run`
382
+ * would have exited with.
383
+ */
384
+ export function cliExitOutcome(reason, exit, signalToCode) {
385
+ if (exit.signal !== null) {
386
+ return { disposition: 'failed', reason, exitCode: signalToCode(exit.signal), signal: exit.signal };
387
+ }
388
+ if (exit.code !== 0) {
389
+ return { disposition: 'failed', reason, exitCode: exit.code ?? 1, signal: null };
390
+ }
391
+ return { disposition: 'built', reason };
392
+ }
393
+ function requireProject(projectGraph, project) {
394
+ const node = projectGraph.nodes[project];
395
+ if (!node) {
396
+ throw new Error(`ensureBuilt: no project named '${project}' in this workspace`);
397
+ }
398
+ return node;
399
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smoothbricks/nx-plugin",
3
- "version": "0.3.13",
3
+ "version": "0.3.14",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "main": "./loader.js",
@@ -43,12 +43,20 @@
43
43
  "import": "./dist/typecheck-test-policy.js",
44
44
  "default": "./dist/typecheck-test-policy.js"
45
45
  },
46
+ "./ensure-built": {
47
+ "types": "./dist/ensure-built.d.ts",
48
+ "import": "./dist/ensure-built.js",
49
+ "default": "./dist/ensure-built.js"
50
+ },
46
51
  "./cross-check-policy": {
47
52
  "types": "./dist/cross-check-policy.d.ts",
48
53
  "import": "./dist/cross-check-policy.js",
49
54
  "default": "./dist/cross-check-policy.js"
50
55
  }
51
56
  },
57
+ "bin": {
58
+ "smoothbricks-ensure-built": "./dist/bin/ensure-built.js"
59
+ },
52
60
  "generators": "./generators.json",
53
61
  "executors": "./executors.json",
54
62
  "scripts": {
@@ -0,0 +1,115 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync } from 'node:fs';
3
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
4
+
5
+ import { describeMiss, ensureBuilt, parseTargetSelector } from '../ensure-built.js';
6
+
7
+ const USAGE =
8
+ 'usage: smoothbricks-ensure-built <project:target[:configuration]> [--workspace-root <dir>] -- <binary> [args...]';
9
+
10
+ /** Argument and environment problems all exit 2, the shell's "usage" code. */
11
+ function usageError(message: string): never {
12
+ process.stderr.write(`smoothbricks-ensure-built: ${message}\n${USAGE}\n`);
13
+ process.exit(2);
14
+ }
15
+
16
+ /**
17
+ * Split `--flag=value` into two tokens so both spellings parse identically.
18
+ * Only leading `--` forms are split: a value may legitimately contain `=`.
19
+ */
20
+ function tokenize(args: readonly string[]): string[] {
21
+ const tokens: string[] = [];
22
+ for (const arg of args) {
23
+ const equals = arg.startsWith('--') ? arg.indexOf('=') : -1;
24
+ if (equals === -1) {
25
+ tokens.push(arg);
26
+ } else {
27
+ tokens.push(arg.slice(0, equals), arg.slice(equals + 1));
28
+ }
29
+ }
30
+ return tokens;
31
+ }
32
+
33
+ function findWorkspaceRoot(from: string): string {
34
+ let directory = from;
35
+ for (;;) {
36
+ if (existsSync(join(directory, 'nx.json'))) {
37
+ return directory;
38
+ }
39
+ const parent = dirname(directory);
40
+ if (parent === directory) {
41
+ return usageError(`no nx.json at or above ${from}; pass --workspace-root`);
42
+ }
43
+ directory = parent;
44
+ }
45
+ }
46
+
47
+ const argv = process.argv.slice(2);
48
+ const separator = argv.indexOf('--');
49
+ if (separator === -1) {
50
+ usageError('missing `--` before the binary to exec');
51
+ }
52
+ const command = argv.slice(separator + 1);
53
+ if (command.length === 0) {
54
+ usageError('no binary given after `--`');
55
+ }
56
+
57
+ let target: string | undefined;
58
+ let workspaceRootArg: string | undefined;
59
+ const tokens = tokenize(argv.slice(0, separator));
60
+ for (let index = 0; index < tokens.length; index += 1) {
61
+ const token = tokens[index];
62
+ if (token === '--workspace-root') {
63
+ index += 1;
64
+ workspaceRootArg = tokens[index] ?? usageError('--workspace-root needs a directory');
65
+ } else if (token.startsWith('-')) {
66
+ usageError(`unknown flag ${token}`);
67
+ } else if (target !== undefined) {
68
+ usageError(`more than one target given: ${target} and ${token}`);
69
+ } else {
70
+ target = token;
71
+ }
72
+ }
73
+ if (target === undefined) {
74
+ usageError('no project:target given');
75
+ }
76
+ if (parseTargetSelector(target) === null) {
77
+ usageError(`'${target}' is not a project:target[:configuration] selector`);
78
+ }
79
+
80
+ // `execve` does no PATH lookup, so a bare name would fail as a missing file in
81
+ // the current directory. Say which mistake was made instead.
82
+ if (!command[0].includes('/')) {
83
+ usageError(`'${command[0]}' must be a path to the binary, not a name to look up on PATH`);
84
+ }
85
+ // Resolved against the directory the user is standing in, not the workspace
86
+ // root: this is their command line, and the exec'd process inherits their cwd.
87
+ const binary = isAbsolute(command[0]) ? command[0] : resolve(process.cwd(), command[0]);
88
+
89
+ const workspaceRoot =
90
+ workspaceRootArg === undefined ? findWorkspaceRoot(process.cwd()) : resolve(process.cwd(), workspaceRootArg);
91
+
92
+ const result = await ensureBuilt({ target, cwd: workspaceRoot }).catch((error: unknown) => {
93
+ process.stderr.write(`smoothbricks-ensure-built: ${error instanceof Error ? error.message : String(error)}\n`);
94
+ process.exit(1);
95
+ });
96
+
97
+ if (result.disposition !== 'hit' && process.env.NX_VERBOSE_LOGGING === 'true') {
98
+ process.stderr.write(`smoothbricks-ensure-built: ran ${target} because ${describeMiss(result.reason)}\n`);
99
+ }
100
+ if (result.disposition === 'failed') {
101
+ if (result.signal !== null) {
102
+ // Re-raise rather than translate, so a build killed by SIGINT leaves this
103
+ // process looking killed by SIGINT to whatever is watching it.
104
+ process.kill(process.pid, result.signal);
105
+ }
106
+ process.exit(result.exitCode);
107
+ }
108
+
109
+ if (process.execve === undefined) {
110
+ throw new Error('smoothbricks-ensure-built needs process.execve, which requires a POSIX host on Node 24+ or Bun');
111
+ }
112
+ // `execve`, not spawn-and-wait: the built binary replaces this process, so it
113
+ // owns the terminal, the signals and the exit status directly, with no wrapper
114
+ // left behind to forward them.
115
+ process.execve(binary, [binary, ...command.slice(1)], process.env);