@smoothbricks/nx-plugin 0.3.11 → 0.3.13

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.
Files changed (38) hide show
  1. package/README.md +23 -2
  2. package/dist/bounded-test-policy.d.ts +26 -0
  3. package/dist/bounded-test-policy.d.ts.map +1 -1
  4. package/dist/bounded-test-policy.js +194 -0
  5. package/dist/cargo-workspace.d.ts +67 -0
  6. package/dist/cargo-workspace.d.ts.map +1 -0
  7. package/dist/cargo-workspace.js +215 -0
  8. package/dist/cross-check-policy.d.ts +60 -1
  9. package/dist/cross-check-policy.d.ts.map +1 -1
  10. package/dist/cross-check-policy.js +65 -1
  11. package/dist/executors/bounded-exec/executor.d.ts.map +1 -1
  12. package/dist/executors/bounded-exec/executor.js +86 -51
  13. package/dist/executors/bounded-exec/schema.d.ts +13 -0
  14. package/dist/executors/bounded-exec/schema.d.ts.map +1 -1
  15. package/dist/index.d.ts +10 -5
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +455 -95
  18. package/dist/package-target-policy.d.ts +2 -1
  19. package/dist/package-target-policy.d.ts.map +1 -1
  20. package/dist/package-target-policy.js +54 -13
  21. package/dist/workspace-config-policy.js +32 -35
  22. package/nextest.toml +79 -0
  23. package/package.json +2 -1
  24. package/src/bounded-test-policy.test.ts +304 -0
  25. package/src/bounded-test-policy.ts +218 -0
  26. package/src/cargo-workspace.ts +243 -0
  27. package/src/cross-check-policy.test.ts +24 -0
  28. package/src/cross-check-policy.ts +80 -1
  29. package/src/executors/bounded-exec/executor.test.ts +147 -3
  30. package/src/executors/bounded-exec/executor.ts +103 -53
  31. package/src/executors/bounded-exec/schema.json +7 -2
  32. package/src/executors/bounded-exec/schema.ts +13 -0
  33. package/src/index.test.ts +531 -99
  34. package/src/index.ts +527 -104
  35. package/src/package-target-policy.test.ts +50 -0
  36. package/src/package-target-policy.ts +58 -9
  37. package/src/workspace-config-policy.test.ts +15 -30
  38. package/src/workspace-config-policy.ts +32 -39
package/dist/index.js CHANGED
@@ -1,11 +1,15 @@
1
1
  import { existsSync } from 'node:fs';
2
2
  import { readdir, readFile } from 'node:fs/promises';
3
3
  import { dirname, join, posix } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
4
5
  import { readJsonFile, } from 'nx/src/devkit-exports.js';
5
6
  import { AggregateCreateNodesError } from 'nx/src/project-graph/error-types.js';
6
7
  import { parse as parseToml } from 'smol-toml';
7
- import { CARGO_CROSS_LINT_COMMAND, CARGO_CROSS_LINT_TARGET } from './cross-check-policy.js';
8
- import { BUILD_OUTPUT_DEPENDENCIES, PLATFORM_TARGET_GLOBS } from './workspace-config-policy.js';
8
+ import { BOUNDED_TEST_KILL_AFTER_MS, BOUNDED_TEST_TIMEOUT_MS } from './bounded-test-policy.js';
9
+ import { CARGO_TEST_COMPILE_TARGET, CARGO_TEST_EXCEPTIONS_SUFFIX, CARGO_TEST_TARGET, cargoPackageTestInputs, cargoTestPackageTargetName, exceptionalTestFilter, listCargoWorkspacePackages, nextestConfigRelPath, } from './cargo-workspace.js';
10
+ import { CARGO_CROSS_LINT_COMMAND, CARGO_CROSS_LINT_TARGET, CARGO_FETCH_COMMAND, CARGO_FETCH_TARGET, CARGO_FROZEN_PREFIX, CARGO_LINT_CLIPPY_COMMAND, cargoFrozen, } from './cross-check-policy.js';
11
+ import { PLATFORM_TARGET_GLOBS } from './workspace-config-policy.js';
12
+ export { CARGO_TEST_COMPILE_TARGET };
9
13
  const BUILD_OUTPUT_TARGET_PATTERN = /-(?:js|web|html|css|android|native|napi|bun|wasm)$/;
10
14
  const TYPESCRIPT_TOOLCHAIN_INPUTS = [
11
15
  '{workspaceRoot}/package.json',
@@ -13,26 +17,42 @@ const TYPESCRIPT_TOOLCHAIN_INPUTS = [
13
17
  '{workspaceRoot}/patches/**/*',
14
18
  '{workspaceRoot}/tsconfig.base.json',
15
19
  ];
16
- // The aggregate `build` pulls in platform-suffixed binary targets for THIS
17
- // machine only: `<tool>-<arch>-<os>` names matching the host (for example
18
- // cli-arm64-macos on Apple Silicon) build locally as part of `nx build`, while
19
- // every foreign platform stays publish-workflow-only. nx.json targetDefaults
20
- // cannot express "current platform" — its dependsOn lists are static — so the
21
- // inference plugin owns this edge.
22
- const HOST_PLATFORM_SUFFIX = (() => {
23
- const os = process.platform === 'darwin' ? 'macos' : process.platform === 'linux' ? 'linux' : null;
24
- const arch = process.arch === 'arm64' ? 'arm64' : process.arch === 'x64' ? 'x64' : null;
25
- return os !== null && arch !== null ? `-${arch}-${os}` : null;
26
- })();
27
- export function hostPlatformTargetNames(targetNames) {
28
- if (HOST_PLATFORM_SUFFIX === null)
20
+ function napiPlatform(platform, architecture) {
21
+ const targetFamily = platform === 'darwin' ? 'macos' : platform === 'linux' ? 'linux' : null;
22
+ const targetArchitecture = architecture === 'arm64' ? 'arm64' : architecture === 'x64' ? 'x64' : null;
23
+ return targetFamily !== null && targetArchitecture !== null
24
+ ? { architecture: targetArchitecture, targetFamily }
25
+ : null;
26
+ }
27
+ function sameNapiPlatform(left, right) {
28
+ return left.architecture === right?.architecture && left.targetFamily === right.targetFamily;
29
+ }
30
+ function hostPlatformTargetNames(targetNames, hostPlatform) {
31
+ if (hostPlatform === null)
29
32
  return [];
33
+ const suffix = `-${hostPlatform.architecture}-${hostPlatform.targetFamily}`;
30
34
  return [...new Set(targetNames)]
31
35
  .filter(
32
36
  // Binary targets only. A toolchain prerequisite carries the same platform
33
37
  // suffix but produces no artifact: the cross builds that need it depend
34
38
  // on it directly, so the aggregate stays a list of outputs.
35
- (name) => name.endsWith(HOST_PLATFORM_SUFFIX) && !name.startsWith(NAPI_TOOLCHAIN_TARGET_PREFIX))
39
+ (name) => name.endsWith(suffix) && !name.startsWith(NAPI_TOOLCHAIN_TARGET_PREFIX))
40
+ .sort();
41
+ }
42
+ /**
43
+ * The reserved suffixes name targets that EMIT an artifact, and the `build`
44
+ * aggregate is a list of those. Handing Nx the raw `*-<family>` globs let it
45
+ * match on suffix alone, and one namespace collides by construction: a
46
+ * per-crate cargo test runner is named `cargo-test-<crate>`, so any crate whose
47
+ * name ends in an output family — `*-napi`, `*-wasm`, `*-native`, `*-js` — put
48
+ * its RUNNER in the aggregate. The runners are one serialized chain, so a
49
+ * single such crate made `build` pull an entire cargo test suite. Expanding the
50
+ * families here instead of delegating to Nx's matcher keeps the plugin's own
51
+ * `cargo-test-` namespace out of the aggregate however a crate is named.
52
+ */
53
+ function buildOutputTargetNames(targetNames) {
54
+ return [...new Set(targetNames)]
55
+ .filter((name) => BUILD_OUTPUT_TARGET_PATTERN.test(name) && !name.startsWith(`${CARGO_TEST_TARGET}-`))
36
56
  .sort();
37
57
  }
38
58
  //#region smoo!n/rust-output-target-inference
@@ -62,27 +82,33 @@ const NAPI_TARGET_CONVENTIONS = {
62
82
  architecture: 'arm64',
63
83
  outputName: 'darwin-arm64',
64
84
  targetFamily: 'macos',
65
- useNapiCross: false,
66
85
  },
67
86
  'x86_64-apple-darwin': {
68
87
  architecture: 'x64',
69
88
  outputName: 'darwin-x64',
70
89
  targetFamily: 'macos',
71
- useNapiCross: false,
72
90
  },
73
91
  'aarch64-unknown-linux-gnu': {
74
92
  architecture: 'arm64',
75
93
  outputName: 'linux-arm64-gnu',
76
94
  targetFamily: 'linux',
77
- useNapiCross: true,
78
95
  },
79
96
  'x86_64-unknown-linux-gnu': {
80
97
  architecture: 'x64',
81
98
  outputName: 'linux-x64-gnu',
82
99
  targetFamily: 'linux',
83
- useNapiCross: true,
84
100
  },
85
101
  };
102
+ const NATIVE_LINUX_COMPILER_ENV = Object.freeze({ CC: 'cc', CXX: 'c++' });
103
+ const CROSS_LINUX_COMPILER_ENV = Object.freeze({ TARGET_CC: 'clang', TARGET_CXX: 'clang++' });
104
+ function usesNapiCross(target, hostPlatform) {
105
+ return target.targetFamily === 'linux' && !sameNapiPlatform(target, hostPlatform);
106
+ }
107
+ function napiCompilerEnv(target, hostPlatform) {
108
+ if (target?.targetFamily !== 'linux')
109
+ return undefined;
110
+ return sameNapiPlatform(target, hostPlatform) ? NATIVE_LINUX_COMPILER_ENV : CROSS_LINUX_COMPILER_ENV;
111
+ }
86
112
  const NAPI_TOOLCHAIN_TARGET_PREFIX = 'napi-toolchain-';
87
113
  /**
88
114
  * Prerequisite target that extracts the cross toolchain one triple needs. The
@@ -103,7 +129,7 @@ function createCargoWasmTarget(projectRoot, config) {
103
129
  outputs: [`{projectRoot}/${config.outputDirectory}`],
104
130
  options: {
105
131
  commands: [
106
- `cargo build --release --target wasm32-unknown-unknown --target-dir ${cargoTargetDirectory} --manifest-path ${config.manifestPath}`,
132
+ cargoFrozen(`build --release --target wasm32-unknown-unknown --target-dir ${cargoTargetDirectory} --manifest-path ${config.manifestPath}`),
107
133
  ...config.targets.map(({ bindgenTarget, outputName }) => `wasm-bindgen --target ${bindgenTarget} --out-dir ${config.outputDirectory}/${outputName} ${wasmInput}`),
108
134
  ],
109
135
  cwd: projectRoot,
@@ -111,26 +137,128 @@ function createCargoWasmTarget(projectRoot, config) {
111
137
  },
112
138
  };
113
139
  }
140
+ /**
141
+ * Compilation is excluded from the bounded test window: a cold Cargo
142
+ * workspace can take many minutes to compile while still making progress,
143
+ * which is not a property of the tests. `cargo test --no-run` pays that cost
144
+ * in its own unbounded, cacheable target; the bounded runner then re-invokes
145
+ * cargo against a warm target directory, where only the suites' own runtime
146
+ * counts against the standard bound.
147
+ *
148
+ * Cargo flocks one `target/` per invocation. Nx must not run two cargo
149
+ * writers on that directory at once — that is a mutex, not a deadlock, and
150
+ * the second process sits in "Blocking waiting for file lock" until a
151
+ * timeout. Inference serializes writers that share the default target dir
152
+ * (`napi-debug` after compile, `cargo-test` after `napi-debug`). Clippy uses
153
+ * its own `--target-dir` so lint can overlap tests.
154
+ */
155
+ function createCargoTestCompileTarget(projectRoot) {
156
+ return {
157
+ executor: 'nx:run-commands',
158
+ cache: true,
159
+ inputs: CARGO_INPUTS,
160
+ options: {
161
+ command: cargoFrozen('test --workspace --no-run'),
162
+ cwd: projectRoot,
163
+ },
164
+ configurations: {
165
+ production: { command: cargoFrozen('test --workspace --release --no-run') },
166
+ },
167
+ };
168
+ }
114
169
  function createCargoTestTarget(projectRoot) {
115
170
  return {
116
171
  executor: '@smoothbricks/nx-plugin:bounded-exec',
117
172
  cache: true,
118
173
  inputs: CARGO_INPUTS,
174
+ dependsOn: [CARGO_TEST_COMPILE_TARGET],
119
175
  options: {
120
- command: 'cargo test --workspace',
176
+ command: cargoFrozen('test --workspace'),
121
177
  cwd: projectRoot,
122
- // Cold macOS Cargo workspaces can exceed ten minutes while still making progress.
123
- timeoutMs: 1200000,
124
- killAfterMs: 10000,
178
+ timeoutMs: BOUNDED_TEST_TIMEOUT_MS,
179
+ killAfterMs: BOUNDED_TEST_KILL_AFTER_MS,
125
180
  },
126
181
  configurations: {
127
- production: { command: 'cargo test --workspace --release' },
182
+ production: { command: cargoFrozen('test --workspace --release') },
128
183
  },
129
184
  };
130
185
  }
131
- export const createNodesV2 = [
132
- '**/package.json',
133
- async (projectConfigurationFiles, _options, context) => {
186
+ const PLUGIN_NEXTEST_CONFIG = fileURLToPath(new URL('../nextest.toml', import.meta.url));
187
+ /**
188
+ * One bounded target per crate; a crate that declares `smoothbricks.test.shards`
189
+ * gets one per shard plus one for the tests nextest.toml singles out.
190
+ *
191
+ * `--workspace -E 'package(X)'` rather than `--package X`. A filterset selects
192
+ * what RUNS; `--package` also re-resolves FEATURES for that crate alone, which
193
+ * fingerprints differently from the `cargo test --workspace --no-run` that
194
+ * `cargo-test-compile` already paid for, so cargo rebuilds the divergent half
195
+ * inside the bounded window. Measured on a hosted 3-core macOS runner that
196
+ * rebuild was 57.9s of a 120s budget — the tests were killed with 264 still to
197
+ * run while nothing was wrong with them. The two forms select the same tests;
198
+ * only the filterset reuses the compile target's artifacts.
199
+ *
200
+ * nextest.toml singles some tests out with an override, and each such class
201
+ * breaks a shard in its own way — a `test-group` is scoped to one nextest RUN
202
+ * so the hash would dissolve it, and a raised `slow-timeout` marks a test whose
203
+ * cost is not the suite's. Those are lifted OUT of the hash into one target and
204
+ * the shards run the exact complement, so which tests a shard holds stops
205
+ * depending on how the hash happened to fall.
206
+ *
207
+ * The two filtersets are exact complements, so their union is the crate whatever
208
+ * either one matches; an empty exception set (every real-APFS test is
209
+ * `cfg(target_os = "macos")`, so on Linux there are none) costs coverage
210
+ * nothing, which is why that target may pass having run zero tests. It cannot
211
+ * hide a lost test — only a pin that stopped matching, whose members then fall
212
+ * into the shards.
213
+ *
214
+ * Pieces chain rather than fan out, like the crates do: cargo flocks one
215
+ * `target/`, and chaining keeps even the pinned group from overlapping the
216
+ * shards on a machine-wide resource.
217
+ */
218
+ async function addPerPackageCargoTestTargets(targets, projectRoot, workspaceRoot, absoluteProjectRoot) {
219
+ const packages = listCargoWorkspacePackages(absoluteProjectRoot);
220
+ if (packages.length === 0) {
221
+ return [];
222
+ }
223
+ const configFile = nextestConfigRelPath(workspaceRoot, projectRoot, PLUGIN_NEXTEST_CONFIG);
224
+ const exceptional = exceptionalTestFilter(PLUGIN_NEXTEST_CONFIG);
225
+ const packageTargetNames = [];
226
+ let previous = CARGO_TEST_COMPILE_TARGET;
227
+ for (const pkg of packages) {
228
+ const inputs = await cargoPackageTestInputs(absoluteProjectRoot, pkg.dir);
229
+ const sharded = pkg.testShards > 1;
230
+ const pin = sharded && exceptional !== null ? exceptional : null;
231
+ const addTarget = (piece, selector, extra) => {
232
+ const targetName = cargoTestPackageTargetName(pkg.name, piece);
233
+ packageTargetNames.push(targetName);
234
+ targets[targetName] = {
235
+ executor: '@smoothbricks/nx-plugin:bounded-exec',
236
+ cache: true,
237
+ inputs,
238
+ dependsOn: [previous],
239
+ options: {
240
+ command: cargoFrozen(`nextest run --workspace -E '${selector}'${extra} --user-config-file none --config-file ${configFile}`),
241
+ cwd: projectRoot,
242
+ timeoutMs: BOUNDED_TEST_TIMEOUT_MS,
243
+ killAfterMs: BOUNDED_TEST_KILL_AFTER_MS,
244
+ },
245
+ };
246
+ previous = targetName;
247
+ };
248
+ const shardable = pin === null ? `package(${pkg.name})` : `package(${pkg.name}) and not (${pin})`;
249
+ for (let index = 1; index <= pkg.testShards; index += 1) {
250
+ // nextest hashes the test name, so a shard holds the same tests whatever
251
+ // else the filterset selects and whatever tests are added later.
252
+ addTarget(sharded ? `shard${index}` : undefined, shardable, sharded ? ` --partition hash:${index}/${pkg.testShards}` : '');
253
+ }
254
+ if (pin !== null) {
255
+ addTarget(CARGO_TEST_EXCEPTIONS_SUFFIX, `package(${pkg.name}) and (${pin})`, ' --no-tests=pass');
256
+ }
257
+ }
258
+ return packageTargetNames;
259
+ }
260
+ function createNodesHandler(hostPlatform) {
261
+ return async (projectConfigurationFiles, _options, context) => {
134
262
  const results = [];
135
263
  const errors = [];
136
264
  await Promise.all(projectConfigurationFiles.map(async (packageJsonPath) => {
@@ -141,7 +269,10 @@ export const createNodesV2 = [
141
269
  results.push([packageJsonPath, {}]);
142
270
  return;
143
271
  }
144
- results.push([packageJsonPath, await createProjectTargets(packageJsonPath, context.workspaceRoot)]);
272
+ results.push([
273
+ packageJsonPath,
274
+ await createProjectTargets(packageJsonPath, context.workspaceRoot, hostPlatform),
275
+ ]);
145
276
  }
146
277
  catch (error) {
147
278
  errors.push([packageJsonPath, error instanceof Error ? error : new Error(String(error))]);
@@ -151,14 +282,21 @@ export const createNodesV2 = [
151
282
  throw new AggregateCreateNodesError(errors, results);
152
283
  }
153
284
  return results;
154
- },
285
+ };
286
+ }
287
+ export function createNodesV2ForPlatform(platform, architecture) {
288
+ return ['**/package.json', createNodesHandler(napiPlatform(platform, architecture))];
289
+ }
290
+ export const createNodesV2 = [
291
+ '**/package.json',
292
+ (...args) => createNodesHandler(napiPlatform(process.platform, process.arch))(...args),
155
293
  ];
156
294
  function isManagedPackageJsonSource(packageJsonPath) {
157
295
  const normalized = packageJsonPath.replaceAll('\\', '/');
158
296
  return normalized.includes('/managed/raw/') || normalized.includes('/managed/templates/');
159
297
  }
160
298
  export default { createNodesV2 };
161
- async function createProjectTargets(packageJsonPath, workspaceRoot) {
299
+ async function createProjectTargets(packageJsonPath, workspaceRoot, hostPlatform) {
162
300
  const projectRoot = dirname(packageJsonPath);
163
301
  const absoluteProjectRoot = join(workspaceRoot, projectRoot);
164
302
  const packageJson = await readPackageJson(join(workspaceRoot, packageJsonPath));
@@ -248,32 +386,75 @@ async function createProjectTargets(packageJsonPath, workspaceRoot) {
248
386
  targets['cargo-wasm'] = createCargoWasmTarget(projectRoot, cargoWasmConfig);
249
387
  }
250
388
  if (napiConfig) {
251
- const napiTargets = createNapiTargets(projectRoot, napiConfig);
252
- Object.assign(targets, napiTargets.targets);
389
+ Object.assign(targets, createNapiTargets(projectRoot, napiConfig, hostPlatform));
253
390
  if (!('napi-test' in (packageJson.nx?.targets ?? {})) &&
254
391
  existsSync(join(absoluteProjectRoot, 'src/native.test.ts'))) {
255
- targets['napi-test'] = createNapiTestTarget(projectRoot, existsSync(join(absoluteProjectRoot, 'bunfig.napi-test.toml')), napiTargets.hostProvider);
392
+ targets['napi-test'] = createNapiTestTarget(projectRoot, existsSync(join(absoluteProjectRoot, 'bunfig.napi-test.toml')));
256
393
  }
257
394
  }
258
395
  // Member crates get their targets from the workspace-root package.json,
259
396
  // never per-crate — one Nx project per Cargo workspace.
397
+ //
398
+ // Every cargo tool target below is inferred unconditionally, INCLUDING when
399
+ // the package already declares that key in `nx.targets`. Nx merges a
400
+ // package-local declaration over an inference plugin's target one layer
401
+ // later — the precedence order is specified plugins → target defaults →
402
+ // default plugins, and the package.json reader is a default plugin — so a
403
+ // declaration only has to name the fields it changes:
404
+ //
405
+ // - `executor`, `cache`, `inputs`, `outputs`, `dependsOn`: the declared
406
+ // value REPLACES the inferred one, and every field the declaration omits
407
+ // is inherited from here.
408
+ // - `options` and `configurations`: merged key by key with declared keys
409
+ // winning, unless the declaration names a different executor — then its
410
+ // options mean something else and replace them wholesale.
411
+ // - `"dependsOn": ["...", "extra"]` expands the inferred list at the
412
+ // token's position. That is how a package ADDS an edge.
413
+ //
414
+ // Skipping inference for a declared key — what this used to do — is what made
415
+ // a one-line addition catastrophic: `nx.targets['cargo-test'] = { dependsOn:
416
+ // [...] }` left nothing to merge onto, and Nx normalizes a bare `dependsOn`
417
+ // to `executor: nx:noop` with empty options. That is the worst kind of green:
418
+ // `cargo-test` reaches its dependencies and runs no test binary.
419
+ // `checkWorkspaceCargoTestReachabilityPolicy` fails that shape, but the fix is
420
+ // to leave a base for the declaration to land on.
421
+ //
422
+ // The overlay is deliberately NOT re-implemented here. Applying it in this
423
+ // plugin as well would expand a `"..."` spread twice — once against the
424
+ // inferred list here, once when Nx merges the same declaration over this
425
+ // result — duplicating the very edges the spread exists to add.
426
+ //
427
+ // `dependsOn` REPLACES rather than unions. These lists are not a bag of
428
+ // independent wishes; they are the serialization chain that keeps two cargo
429
+ // writers off one flocked `target/` (see CARGO_TEST_COMPILE_TARGET), and their
430
+ // ORDER carries the invariant. A package that must re-route the chain — build
431
+ // its artifact ahead of the test run, or drop `cargo-test-compile` because it
432
+ // compiles differently — can only say so by replacing the list; a union would
433
+ // make every inferred edge unremovable and a corrected order unrepresentable.
434
+ // Additive intent already has a spelling (`"..."` above), so a plugin-local
435
+ // additive key would be a second convention beside a working one.
436
+ //
437
+ // The output families (`cargo-wasm`, `napi-*`) and the `test` aggregate stay
438
+ // all-or-nothing, because for those the package decides whether the target
439
+ // EXISTS — a packaging decision for output families, the bounded-test policy's
440
+ // rewrite for `test` — so there is no inferred base to partially override.
260
441
  if (isCargoWorkspace) {
261
- const declared = declaredTargets;
262
- if (!('cargo-test' in declared)) {
263
- targets['cargo-test'] = createCargoTestTarget(projectRoot);
264
- }
265
- if (!('cargo-lint' in declared)) {
266
- targets['cargo-lint'] = {
267
- executor: 'nx:run-commands',
268
- cache: true,
269
- inputs: CARGO_INPUTS,
270
- options: {
271
- commands: ['cargo fmt --all --check', 'cargo clippy --workspace --all-targets -- -D warnings'],
272
- cwd: projectRoot,
273
- parallel: false,
274
- },
275
- };
276
- }
442
+ targets[CARGO_TEST_COMPILE_TARGET] = createCargoTestCompileTarget(projectRoot);
443
+ const packageTargetNames = await addPerPackageCargoTestTargets(targets, projectRoot, workspaceRoot, absoluteProjectRoot);
444
+ targets[CARGO_TEST_TARGET] =
445
+ packageTargetNames.length > 0
446
+ ? { executor: 'nx:noop', cache: true, dependsOn: packageTargetNames }
447
+ : createCargoTestTarget(projectRoot);
448
+ targets['cargo-lint'] = {
449
+ executor: 'nx:run-commands',
450
+ cache: true,
451
+ inputs: CARGO_INPUTS,
452
+ options: {
453
+ commands: ['cargo fmt --all --check', CARGO_LINT_CLIPPY_COMMAND],
454
+ cwd: projectRoot,
455
+ parallel: false,
456
+ },
457
+ };
277
458
  validationTargets.push('cargo-lint');
278
459
  // The Linux arm of `cargo-lint`, as its own target. Rationale for the name,
279
460
  // the command and the absent cross test leg lives in ./cross-check-policy.ts.
@@ -293,52 +474,202 @@ async function createProjectTargets(packageJsonPath, workspaceRoot) {
293
474
  // see, so it would silently skip projects — today's bug in a new costume. An
294
475
  // opt-in flag has the same failure mode by construction. Every Rust project is
295
476
  // in scope because CI compiles every Rust project on Linux; a project that
296
- // genuinely cannot cross-compile overrides the target by declaring it, which is
297
- // a visible edit to its package.json rather than a silent absence.
477
+ // genuinely cannot cross-compile overrides the target by declaring it with
478
+ // `executor: nx:noop`, which is a visible edit to its package.json rather
479
+ // than a silent absence.
298
480
  //
299
481
  // Deliberately NOT pushed to validationTargets: joining the lint aggregate
300
482
  // would make `bun run lint` — and CI's own Linux lint, already native — demand
301
483
  // the 0.4 GiB cross toolchain that the devenv profile exists to keep opt-in.
302
- if (!(CARGO_CROSS_LINT_TARGET in declared)) {
303
- targets[CARGO_CROSS_LINT_TARGET] = {
304
- executor: 'nx:run-commands',
484
+ targets[CARGO_CROSS_LINT_TARGET] = {
485
+ executor: 'nx:run-commands',
486
+ cache: true,
487
+ inputs: CARGO_INPUTS,
488
+ options: {
489
+ command: CARGO_CROSS_LINT_COMMAND,
490
+ cwd: projectRoot,
491
+ },
492
+ };
493
+ if (!targets.test && !('test' in declaredTargets) && typeof packageJson.scripts?.test !== 'string') {
494
+ targets.test = {
495
+ executor: 'nx:noop',
305
496
  cache: true,
306
- inputs: CARGO_INPUTS,
307
- options: {
308
- command: CARGO_CROSS_LINT_COMMAND,
309
- cwd: projectRoot,
310
- },
497
+ dependsOn: [CARGO_TEST_TARGET],
311
498
  };
312
499
  }
313
- if (!targets.test && !('test' in declared) && typeof packageJson.scripts?.test !== 'string') {
314
- // Execute Cargo directly: workspace targetDefaults may replace test.dependsOn.
315
- targets.test = createCargoTestTarget(projectRoot);
500
+ // Mutation runs are minutes-to-hours: never cached, never part of build/lint.
501
+ // CI runs these per-PR via `cargo mutants --in-diff` (see mutants.toml docs).
502
+ targets.mutation = {
503
+ executor: 'nx:run-commands',
504
+ cache: false,
505
+ options: { command: cargoFrozen('mutants --workspace'), cwd: projectRoot },
506
+ };
507
+ targets.bench = {
508
+ executor: 'nx:run-commands',
509
+ cache: false,
510
+ options: { command: cargoFrozen('bench --workspace'), cwd: projectRoot },
511
+ };
512
+ // Target-dir GC. Cargo never removes superseded artifacts, so a busy
513
+ // workspace grows tens of GB of stale variants no fingerprint references;
514
+ // sweeping by age prunes exactly that junk while the warm current
515
+ // surface — the gated asset — survives untouched. Never cached: the
516
+ // verdict is about this machine's disk, not the commit.
517
+ targets['cargo-sweep'] = {
518
+ executor: 'nx:run-commands',
519
+ cache: false,
520
+ options: { command: 'cargo sweep --time 7', cwd: projectRoot },
521
+ };
522
+ }
523
+ // Every `cargoFrozen` command needs a registry cache holding the whole locked
524
+ // graph, and offline cargo checks that at RESOLUTION — so a dev-dependency no
525
+ // build ever downloaded takes down `cargo --frozen build` just as surely as
526
+ // `cargo --frozen test`. On an ephemeral runner the only thing that had been
527
+ // populating that cache was a preceding NON-frozen `napi build`, which
528
+ // downloads normal dependencies and never dev-dependencies; a workspace no
529
+ // platform target reaches got nothing at all. `cargo-fetch` states the
530
+ // precondition instead of inheriting it from another target's side effects.
531
+ //
532
+ // Derived from the command text rather than a curated list of target names:
533
+ // the fact that makes a target need this is that it runs frozen cargo, so a
534
+ // frozen target added later is covered without anyone remembering to. The edge
535
+ // goes on EVERY frozen target, not just the head of the serialization chain,
536
+ // so re-routing that chain cannot strip a surviving target's precondition.
537
+ //
538
+ // A package that REPLACES one of these `dependsOn` lists drops the edge with
539
+ // it (see the merge rules above) and gets its cold-cache failure back; `"..."`
540
+ // keeps it.
541
+ const frozenCargoManifests = new Set();
542
+ if (isCargoWorkspace) {
543
+ frozenCargoManifests.add('Cargo.toml');
544
+ }
545
+ if (inferCargoWasm && cargoWasmConfig) {
546
+ // A wasm-bindgen crate can sit in a nested Cargo workspace the project root
547
+ // is not a member of, so its graph is a second fetch, not the same one.
548
+ frozenCargoManifests.add(cargoWasmConfig.manifestPath);
549
+ }
550
+ if (frozenCargoManifests.size > 0) {
551
+ targets[CARGO_FETCH_TARGET] = {
552
+ executor: 'nx:run-commands',
553
+ // The download lands in CARGO_HOME, outside the workspace: a cache hit
554
+ // would skip work a cold registry still needs — same reason
555
+ // napi-toolchain-* is uncached. Nothing here is a workspace output, so
556
+ // there is nothing for Nx to restore in its place.
557
+ cache: false,
558
+ options: {
559
+ commands: [...frozenCargoManifests]
560
+ .sort()
561
+ .map((manifestPath) => manifestPath === 'Cargo.toml'
562
+ ? CARGO_FETCH_COMMAND
563
+ : `${CARGO_FETCH_COMMAND} --manifest-path ${manifestPath}`),
564
+ cwd: projectRoot,
565
+ // Two fetches into one CARGO_HOME contend on its package-cache flock;
566
+ // serializing here spends the wait in Nx instead of inside cargo.
567
+ parallel: false,
568
+ },
569
+ };
570
+ for (const [name, target] of Object.entries(targets)) {
571
+ if (name === CARGO_FETCH_TARGET) {
572
+ continue;
573
+ }
574
+ const command = target.options?.command;
575
+ const commands = target.options?.commands;
576
+ const text = [
577
+ typeof command === 'string' ? command : '',
578
+ ...(Array.isArray(commands) ? commands.filter((entry) => typeof entry === 'string') : []),
579
+ ].join('\n');
580
+ if (!text.includes(CARGO_FROZEN_PREFIX)) {
581
+ continue;
582
+ }
583
+ const dependsOn = target.dependsOn ?? [];
584
+ if (!dependsOn.includes(CARGO_FETCH_TARGET)) {
585
+ target.dependsOn = [CARGO_FETCH_TARGET, ...dependsOn];
586
+ }
316
587
  }
317
- if (!('mutation' in declared)) {
318
- // Mutation runs are minutes-to-hours: never cached, never part of build/lint.
319
- // CI runs these per-PR via `cargo mutants --in-diff` (see mutants.toml docs).
320
- targets.mutation = {
321
- executor: 'nx:run-commands',
322
- cache: false,
323
- options: { command: 'cargo mutants --workspace', cwd: projectRoot },
324
- };
588
+ }
589
+ // Cargo flocks the package's default `target/`. Writers that share it must
590
+ // not be Nx siblings. Clippy is not in this set: it has its own --target-dir.
591
+ const napiDebug = targets['napi-debug'];
592
+ if (napiDebug && targets[CARGO_TEST_COMPILE_TARGET]) {
593
+ const dependsOn = napiDebug.dependsOn ?? [];
594
+ if (!dependsOn.includes(CARGO_TEST_COMPILE_TARGET)) {
595
+ napiDebug.dependsOn = [...dependsOn, CARGO_TEST_COMPILE_TARGET];
325
596
  }
326
- if (!('bench' in declared)) {
327
- targets.bench = {
328
- executor: 'nx:run-commands',
329
- cache: false,
330
- options: { command: 'cargo bench --workspace', cwd: projectRoot },
331
- };
597
+ }
598
+ if (napiDebug) {
599
+ for (const [name, target] of Object.entries(targets)) {
600
+ if (!name.startsWith('cargo-test-') || name === CARGO_TEST_COMPILE_TARGET) {
601
+ continue;
602
+ }
603
+ const dependsOn = target.dependsOn ?? [];
604
+ if (dependsOn.includes(CARGO_TEST_COMPILE_TARGET) && !dependsOn.includes('napi-debug')) {
605
+ target.dependsOn = dependsOn.map((dep) => (dep === CARGO_TEST_COMPILE_TARGET ? 'napi-debug' : dep));
606
+ }
607
+ }
608
+ const cargoTest = targets[CARGO_TEST_TARGET];
609
+ if (cargoTest?.options &&
610
+ typeof cargoTest.options.command === 'string' &&
611
+ cargoTest.options.command.startsWith('cargo ')) {
612
+ const dependsOn = cargoTest.dependsOn ?? [];
613
+ if (!dependsOn.includes('napi-debug')) {
614
+ cargoTest.dependsOn = [...dependsOn, 'napi-debug'];
615
+ }
332
616
  }
333
617
  }
618
+ // `build` lists cargo-test-compile beside the host's platform binaries, and
619
+ // every one of those is a `napi build` — another cargo writer on the package's
620
+ // default `target/`, which cargo flocks.
621
+ //
622
+ // Only `cargo-napi` gets the ordering edge. A platform-suffixed target may NOT
623
+ // have one: `validatePlatformTargetDependencies` (package-target-policy.ts:674)
624
+ // walks each platform target's dependency closure and refuses any member of a
625
+ // different family, because the publish flow builds and collects one platform
626
+ // at a time — a `*-macos` collect that reached a familyless sibling would drag
627
+ // in work the macOS runner has no business doing. `cargo-napi` carries no
628
+ // platform suffix, so it is not scanned and the edge is legal there.
629
+ //
630
+ // The platform binaries therefore stay Nx siblings of cargo-test-compile and
631
+ // serialize on cargo's flock instead of on a graph edge. That is the same
632
+ // arrangement `cli-<arch>-<os>` and `napi-<arch>-<os>` already have with each
633
+ // other — both `napi build --release` on one target dir — so this adds a third
634
+ // participant to an existing wait, not a new hazard. The flock makes them wait;
635
+ // it does not corrupt anything, and these are unbounded `nx:run-commands`
636
+ // targets, so the wait is not charged against a test budget.
637
+ const cargoWriterNames = hostPlatformTargetNames([...Object.keys(declaredTargets), ...Object.keys(targets)], hostPlatform);
638
+ const cargoNapi = targets['cargo-napi'];
639
+ if (cargoNapi && targets[CARGO_TEST_COMPILE_TARGET]) {
640
+ const dependsOn = cargoNapi.dependsOn ?? [];
641
+ if (!dependsOn.includes(CARGO_TEST_COMPILE_TARGET)) {
642
+ cargoNapi.dependsOn = [...dependsOn, CARGO_TEST_COMPILE_TARGET];
643
+ }
644
+ }
645
+ // No `outputs`, deliberately: this aggregate runs no command, so every file
646
+ // under dist belongs to the concrete target that emitted it. Claiming
647
+ // `{projectRoot}/dist` here would cache the children's bytes a second time
648
+ // under the aggregate's hash, and would make `smoo github-ci nx-run-many
649
+ // --collect-outputs` attribute to `build` whatever sits under dist — including
650
+ // platform-target artifacts the collect excludes on purpose and stale
651
+ // artifacts of targets that never ran. Two collected trees then claim one
652
+ // binary and `apply-outputs` rejects the overlap. `lint` and `test` are
653
+ // aggregates on the same terms. Same reason nx.json must not put `outputs` in
654
+ // targetDefaults.build (see validateBuildTargetDefault).
334
655
  if (hasOrdinaryBuildOutputTarget) {
335
656
  targets.build = {
336
657
  executor: 'nx:noop',
337
658
  cache: true,
659
+ // `cargo-napi` is both an output family and a serialized cargo writer, so
660
+ // the two sources overlap; the Set keeps one edge per target while holding
661
+ // the order the families are listed in.
338
662
  dependsOn: [
339
- '^build',
340
- ...BUILD_OUTPUT_DEPENDENCIES,
341
- ...hostPlatformTargetNames([...Object.keys(declaredTargets), ...Object.keys(targets)]),
663
+ ...new Set([
664
+ '^build',
665
+ // Compiling the test executables is build work: it is unbounded and
666
+ // cacheable, while every RUNNER is a bounded-exec target reached only
667
+ // through the `test` aggregate. That split is what keeps a cold cargo
668
+ // workspace's compile time out of the bounded test window.
669
+ ...(targets[CARGO_TEST_COMPILE_TARGET] ? [CARGO_TEST_COMPILE_TARGET] : []),
670
+ ...buildOutputTargetNames([...Object.keys(declaredTargets), ...Object.keys(targets)]),
671
+ ...cargoWriterNames,
672
+ ]),
342
673
  ],
343
674
  };
344
675
  }
@@ -499,22 +830,41 @@ function resolveNapiConfig(packageJson, packageJsonPath, absoluteProjectRoot, is
499
830
  }
500
831
  return { binaryName, cargoPackage, manifestPath, targets };
501
832
  }
502
- function createNapiTargets(projectRoot, config) {
833
+ function createNapiTargets(projectRoot, config, hostPlatform) {
503
834
  const commonCommand = `--manifest-path ${config.manifestPath} --package ${config.cargoPackage}`;
504
- const hostPlatformTargetName = HOST_PLATFORM_SUFFIX === null ? null : `napi${HOST_PLATFORM_SUFFIX}`;
835
+ const hostPlatformTargetName = hostPlatform === null ? null : `napi-${hostPlatform.architecture}-${hostPlatform.targetFamily}`;
505
836
  let nativeHostTargetName = null;
506
837
  if (hostPlatformTargetName !== null) {
507
838
  for (const triple of config.targets) {
508
839
  const convention = NAPI_TARGET_CONVENTIONS[triple];
509
840
  const targetName = convention ? `napi-${convention.architecture}-${convention.targetFamily}` : null;
510
- if (targetName === hostPlatformTargetName && !convention?.useNapiCross) {
841
+ if (targetName === hostPlatformTargetName && convention && !usesNapiCross(convention, hostPlatform)) {
511
842
  nativeHostTargetName = targetName;
512
843
  break;
513
844
  }
514
845
  }
515
846
  }
516
- const hostProvider = nativeHostTargetName ?? 'cargo-napi';
517
847
  const targets = {};
848
+ const hostCompilerEnv = napiCompilerEnv(hostPlatform, hostPlatform);
849
+ // The addon the test suite loads. A dev-profile build shares target/debug
850
+ // with cargo-test's dependency graph, so after the tests compile this is
851
+ // nearly free — where the release platform build it replaces cost minutes
852
+ // and sat alone on the test critical path. The output lives OUTSIDE dist/
853
+ // because packages publish `files: ["dist"]` wholesale: a debug addon under
854
+ // dist/ would ship. native.ts resolves this directory only when the
855
+ // napi-test target sets NAPI_DEBUG_ADDON=1, so production loads never see it.
856
+ targets['napi-debug'] = {
857
+ executor: 'nx:run-commands',
858
+ cache: true,
859
+ dependsOn: ['^build'],
860
+ inputs: NAPI_INPUTS,
861
+ outputs: ['{projectRoot}/.cache/native-debug'],
862
+ options: {
863
+ cwd: projectRoot,
864
+ command: `napi build --platform --no-js --dts ${config.binaryName}.napi.d.ts ${commonCommand} --output-dir .cache/native-debug`,
865
+ ...(hostCompilerEnv ? { env: hostCompilerEnv } : {}),
866
+ },
867
+ };
518
868
  if (nativeHostTargetName === null) {
519
869
  // The platform target for this host triple is the same compilation, so a
520
870
  // second cargo-napi invocation only buys a duplicate dependency graph in
@@ -529,12 +879,13 @@ function createNapiTargets(projectRoot, config) {
529
879
  options: {
530
880
  cwd: projectRoot,
531
881
  command: `napi build --release --platform --no-js --dts ${config.binaryName}.napi.d.ts ${commonCommand} --output-dir dist/native/host`,
882
+ ...(hostCompilerEnv ? { env: hostCompilerEnv } : {}),
532
883
  },
533
884
  };
534
885
  }
535
886
  for (const triple of config.targets) {
536
887
  const convention = NAPI_TARGET_CONVENTIONS[triple];
537
- if (!convention?.useNapiCross) {
888
+ if (!convention || !usesNapiCross(convention, hostPlatform)) {
538
889
  continue;
539
890
  }
540
891
  // One toolchain target per triple, shared by every cross build that needs
@@ -558,31 +909,37 @@ function createNapiTargets(projectRoot, config) {
558
909
  }
559
910
  const targetName = `napi-${convention.architecture}-${convention.targetFamily}`;
560
911
  const outputDirectory = `dist/native/${convention.outputName}`;
561
- const crossFlag = convention.useNapiCross ? ' --use-napi-cross' : '';
912
+ const useNapiCross = usesNapiCross(convention, hostPlatform);
913
+ const crossFlag = useNapiCross ? ' --use-napi-cross' : '';
914
+ const compilerEnv = napiCompilerEnv(convention, hostPlatform);
562
915
  targets[targetName] = {
563
916
  executor: 'nx:run-commands',
564
917
  cache: true,
565
- ...(convention.useNapiCross ? { dependsOn: [napiToolchainTargetName(convention)] } : {}),
918
+ ...(useNapiCross ? { dependsOn: [napiToolchainTargetName(convention)] } : {}),
566
919
  inputs: NAPI_INPUTS,
567
920
  outputs: [`{projectRoot}/${outputDirectory}`],
568
921
  options: {
569
922
  cwd: projectRoot,
570
923
  command: `napi build --release --platform --no-js --dts ${config.binaryName}.${convention.outputName}.d.ts --target ${triple}${crossFlag} ${commonCommand} --output-dir ${outputDirectory}`,
571
- // @napi-rs recognizes Clang and supplies its downloaded GNU sysroot
572
- // and toolchain flags. This keeps sccache enabled while avoiding the
573
- // old bundled GCC, which rejects sccache's diagnostics-color flag.
574
- ...(convention.useNapiCross ? { env: { TARGET_CC: 'clang', TARGET_CXX: 'clang++' } } : {}),
924
+ // Genuine Linux cross-compiles use Clang plus napi-rs's downloaded
925
+ // GNU sysroot. A native Linux target uses Nix's cc wrapper so C build
926
+ // scripts resolve the host libc headers instead.
927
+ ...(compilerEnv ? { env: compilerEnv } : {}),
575
928
  },
576
929
  };
577
930
  }
578
- return { targets, hostProvider };
931
+ return targets;
579
932
  }
580
- function createNapiTestTarget(projectRoot, hasDedicatedBunfig, hostProvider) {
933
+ function createNapiTestTarget(projectRoot, hasDedicatedBunfig) {
581
934
  const configFlag = hasDedicatedBunfig ? ' --config=../bunfig.napi-test.toml' : ' --config=../bunfig.toml';
582
935
  return {
583
936
  executor: '@smoothbricks/nx-plugin:bounded-exec',
584
937
  cache: true,
585
- dependsOn: ['cargo-test', hostProvider, 'tsc-js', '^build', 'build'],
938
+ // Deliberately NOT `build`: the aggregate drags the host-platform release
939
+ // binaries onto the test critical path, and the tests assert behavior, not
940
+ // optimization level. tsc-js supplies dist/ts for the suite's own imports;
941
+ // napi-debug supplies the addon.
942
+ dependsOn: ['cargo-test', 'napi-debug', 'tsc-js', '^build'],
586
943
  options: {
587
944
  // cwd is src/, not the package root: `bun test <arg>` treats the arg as a
588
945
  // FILTER and scans the whole cwd tree for test files, and a Rust
@@ -591,6 +948,9 @@ function createNapiTestTarget(projectRoot, hasDedicatedBunfig, hostProvider) {
591
948
  // config is passed explicitly.
592
949
  command: `bun test${configFlag} --timeout=30000 native.test.ts`,
593
950
  cwd: `${projectRoot}/src`,
951
+ // Routes the package's native loader to the napi-debug artifact under
952
+ // .cache/native-debug instead of the packaged dist/native tree.
953
+ env: { NAPI_DEBUG_ADDON: '1' },
594
954
  timeoutMs: 120000,
595
955
  killAfterMs: 10000,
596
956
  },