@smoothbricks/nx-plugin 0.3.10 → 0.3.12

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 (43) 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/executors/clean-outputs/executor.js +17 -3
  16. package/dist/executors/napi-cross-toolchain/executor.d.ts.map +1 -1
  17. package/dist/executors/napi-cross-toolchain/executor.js +8 -0
  18. package/dist/index.d.ts +2 -0
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +344 -57
  21. package/dist/package-target-policy.d.ts +2 -1
  22. package/dist/package-target-policy.d.ts.map +1 -1
  23. package/dist/package-target-policy.js +54 -13
  24. package/dist/workspace-config-policy.js +32 -35
  25. package/nextest.toml +42 -0
  26. package/package.json +2 -1
  27. package/src/bounded-test-policy.test.ts +304 -0
  28. package/src/bounded-test-policy.ts +218 -0
  29. package/src/cargo-workspace.ts +243 -0
  30. package/src/cross-check-policy.test.ts +24 -0
  31. package/src/cross-check-policy.ts +80 -1
  32. package/src/executors/bounded-exec/executor.test.ts +147 -3
  33. package/src/executors/bounded-exec/executor.ts +103 -53
  34. package/src/executors/bounded-exec/schema.json +7 -2
  35. package/src/executors/bounded-exec/schema.ts +13 -0
  36. package/src/executors/clean-outputs/executor.ts +17 -3
  37. package/src/executors/napi-cross-toolchain/executor.ts +8 -0
  38. package/src/index.test.ts +373 -25
  39. package/src/index.ts +390 -65
  40. package/src/package-target-policy.test.ts +50 -0
  41. package/src/package-target-policy.ts +58 -9
  42. package/src/workspace-config-policy.test.ts +15 -30
  43. package/src/workspace-config-policy.ts +32 -39
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
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
 
5
6
  import {
6
7
  type CreateNodesResultV2,
@@ -11,9 +12,30 @@ import {
11
12
  import { AggregateCreateNodesError } from 'nx/src/project-graph/error-types.js';
12
13
  import { parse as parseToml } from 'smol-toml';
13
14
 
14
- import { CARGO_CROSS_LINT_COMMAND, CARGO_CROSS_LINT_TARGET } from './cross-check-policy.js';
15
+ import { BOUNDED_TEST_KILL_AFTER_MS, BOUNDED_TEST_TIMEOUT_MS } from './bounded-test-policy.js';
16
+ import {
17
+ CARGO_TEST_COMPILE_TARGET,
18
+ CARGO_TEST_EXCEPTIONS_SUFFIX,
19
+ CARGO_TEST_TARGET,
20
+ cargoPackageTestInputs,
21
+ cargoTestPackageTargetName,
22
+ exceptionalTestFilter,
23
+ listCargoWorkspacePackages,
24
+ nextestConfigRelPath,
25
+ } from './cargo-workspace.js';
26
+ import {
27
+ CARGO_CROSS_LINT_COMMAND,
28
+ CARGO_CROSS_LINT_TARGET,
29
+ CARGO_FETCH_COMMAND,
30
+ CARGO_FETCH_TARGET,
31
+ CARGO_FROZEN_PREFIX,
32
+ CARGO_LINT_CLIPPY_COMMAND,
33
+ cargoFrozen,
34
+ } from './cross-check-policy.js';
15
35
  import { BUILD_OUTPUT_DEPENDENCIES, PLATFORM_TARGET_GLOBS } from './workspace-config-policy.js';
16
36
 
37
+ export { CARGO_TEST_COMPILE_TARGET };
38
+
17
39
  const BUILD_OUTPUT_TARGET_PATTERN = /-(?:js|web|html|css|android|native|napi|bun|wasm)$/;
18
40
  const TYPESCRIPT_TOOLCHAIN_INPUTS = [
19
41
  '{workspaceRoot}/package.json',
@@ -125,7 +147,9 @@ function createCargoWasmTarget(projectRoot: string, config: ResolvedCargoWasmCon
125
147
  outputs: [`{projectRoot}/${config.outputDirectory}`],
126
148
  options: {
127
149
  commands: [
128
- `cargo build --release --target wasm32-unknown-unknown --target-dir ${cargoTargetDirectory} --manifest-path ${config.manifestPath}`,
150
+ cargoFrozen(
151
+ `build --release --target wasm32-unknown-unknown --target-dir ${cargoTargetDirectory} --manifest-path ${config.manifestPath}`,
152
+ ),
129
153
  ...config.targets.map(
130
154
  ({ bindgenTarget, outputName }) =>
131
155
  `wasm-bindgen --target ${bindgenTarget} --out-dir ${config.outputDirectory}/${outputName} ${wasmInput}`,
@@ -137,24 +161,141 @@ function createCargoWasmTarget(projectRoot: string, config: ResolvedCargoWasmCon
137
161
  };
138
162
  }
139
163
 
164
+ /**
165
+ * Compilation is excluded from the bounded test window: a cold Cargo
166
+ * workspace can take many minutes to compile while still making progress,
167
+ * which is not a property of the tests. `cargo test --no-run` pays that cost
168
+ * in its own unbounded, cacheable target; the bounded runner then re-invokes
169
+ * cargo against a warm target directory, where only the suites' own runtime
170
+ * counts against the standard bound.
171
+ *
172
+ * Cargo flocks one `target/` per invocation. Nx must not run two cargo
173
+ * writers on that directory at once — that is a mutex, not a deadlock, and
174
+ * the second process sits in "Blocking waiting for file lock" until a
175
+ * timeout. Inference serializes writers that share the default target dir
176
+ * (`napi-debug` after compile, `cargo-test` after `napi-debug`). Clippy uses
177
+ * its own `--target-dir` so lint can overlap tests.
178
+ */
179
+ function createCargoTestCompileTarget(projectRoot: string): TargetConfiguration {
180
+ return {
181
+ executor: 'nx:run-commands',
182
+ cache: true,
183
+ inputs: CARGO_INPUTS,
184
+ options: {
185
+ command: cargoFrozen('test --workspace --no-run'),
186
+ cwd: projectRoot,
187
+ },
188
+ configurations: {
189
+ production: { command: cargoFrozen('test --workspace --release --no-run') },
190
+ },
191
+ };
192
+ }
193
+
140
194
  function createCargoTestTarget(projectRoot: string): TargetConfiguration {
141
195
  return {
142
196
  executor: '@smoothbricks/nx-plugin:bounded-exec',
143
197
  cache: true,
144
198
  inputs: CARGO_INPUTS,
199
+ dependsOn: [CARGO_TEST_COMPILE_TARGET],
145
200
  options: {
146
- command: 'cargo test --workspace',
201
+ command: cargoFrozen('test --workspace'),
147
202
  cwd: projectRoot,
148
- // Cold macOS Cargo workspaces can exceed ten minutes while still making progress.
149
- timeoutMs: 1200000,
150
- killAfterMs: 10000,
203
+ timeoutMs: BOUNDED_TEST_TIMEOUT_MS,
204
+ killAfterMs: BOUNDED_TEST_KILL_AFTER_MS,
151
205
  },
152
206
  configurations: {
153
- production: { command: 'cargo test --workspace --release' },
207
+ production: { command: cargoFrozen('test --workspace --release') },
154
208
  },
155
209
  };
156
210
  }
157
211
 
212
+ const PLUGIN_NEXTEST_CONFIG = fileURLToPath(new URL('../nextest.toml', import.meta.url));
213
+
214
+ /**
215
+ * One bounded target per crate; a crate that declares `smoothbricks.test.shards`
216
+ * gets one per shard plus one for the tests nextest.toml singles out.
217
+ *
218
+ * `--workspace -E 'package(X)'` rather than `--package X`. A filterset selects
219
+ * what RUNS; `--package` also re-resolves FEATURES for that crate alone, which
220
+ * fingerprints differently from the `cargo test --workspace --no-run` that
221
+ * `cargo-test-compile` already paid for, so cargo rebuilds the divergent half
222
+ * inside the bounded window. Measured on a hosted 3-core macOS runner that
223
+ * rebuild was 57.9s of a 120s budget — the tests were killed with 264 still to
224
+ * run while nothing was wrong with them. The two forms select the same tests;
225
+ * only the filterset reuses the compile target's artifacts.
226
+ *
227
+ * nextest.toml singles some tests out with an override, and each such class
228
+ * breaks a shard in its own way — a `test-group` is scoped to one nextest RUN
229
+ * so the hash would dissolve it, and a raised `slow-timeout` marks a test whose
230
+ * cost is not the suite's. Those are lifted OUT of the hash into one target and
231
+ * the shards run the exact complement, so which tests a shard holds stops
232
+ * depending on how the hash happened to fall.
233
+ *
234
+ * The two filtersets are exact complements, so their union is the crate whatever
235
+ * either one matches; an empty exception set (every real-APFS test is
236
+ * `cfg(target_os = "macos")`, so on Linux there are none) costs coverage
237
+ * nothing, which is why that target may pass having run zero tests. It cannot
238
+ * hide a lost test — only a pin that stopped matching, whose members then fall
239
+ * into the shards.
240
+ *
241
+ * Pieces chain rather than fan out, like the crates do: cargo flocks one
242
+ * `target/`, and chaining keeps even the pinned group from overlapping the
243
+ * shards on a machine-wide resource.
244
+ */
245
+ async function addPerPackageCargoTestTargets(
246
+ targets: Record<string, TargetConfiguration>,
247
+ projectRoot: string,
248
+ workspaceRoot: string,
249
+ absoluteProjectRoot: string,
250
+ ): Promise<string[]> {
251
+ const packages = listCargoWorkspacePackages(absoluteProjectRoot);
252
+ if (packages.length === 0) {
253
+ return [];
254
+ }
255
+ const configFile = nextestConfigRelPath(workspaceRoot, projectRoot, PLUGIN_NEXTEST_CONFIG);
256
+ const exceptional = exceptionalTestFilter(PLUGIN_NEXTEST_CONFIG);
257
+ const packageTargetNames: string[] = [];
258
+ let previous = CARGO_TEST_COMPILE_TARGET;
259
+ for (const pkg of packages) {
260
+ const inputs = await cargoPackageTestInputs(absoluteProjectRoot, pkg.dir);
261
+ const sharded = pkg.testShards > 1;
262
+ const pin = sharded && exceptional !== null ? exceptional : null;
263
+ const addTarget = (piece: string | undefined, selector: string, extra: string) => {
264
+ const targetName = cargoTestPackageTargetName(pkg.name, piece);
265
+ packageTargetNames.push(targetName);
266
+ targets[targetName] = {
267
+ executor: '@smoothbricks/nx-plugin:bounded-exec',
268
+ cache: true,
269
+ inputs,
270
+ dependsOn: [previous],
271
+ options: {
272
+ command: cargoFrozen(
273
+ `nextest run --workspace -E '${selector}'${extra} --user-config-file none --config-file ${configFile}`,
274
+ ),
275
+ cwd: projectRoot,
276
+ timeoutMs: BOUNDED_TEST_TIMEOUT_MS,
277
+ killAfterMs: BOUNDED_TEST_KILL_AFTER_MS,
278
+ },
279
+ };
280
+ previous = targetName;
281
+ };
282
+ const shardable = pin === null ? `package(${pkg.name})` : `package(${pkg.name}) and not (${pin})`;
283
+ for (let index = 1; index <= pkg.testShards; index += 1) {
284
+ // nextest hashes the test name, so a shard holds the same tests whatever
285
+ // else the filterset selects and whatever tests are added later.
286
+ addTarget(
287
+ sharded ? `shard${index}` : undefined,
288
+ shardable,
289
+ sharded ? ` --partition hash:${index}/${pkg.testShards}` : '',
290
+ );
291
+ }
292
+ if (pin !== null) {
293
+ addTarget(CARGO_TEST_EXCEPTIONS_SUFFIX, `package(${pkg.name}) and (${pin})`, ' --no-tests=pass');
294
+ }
295
+ }
296
+ return packageTargetNames;
297
+ }
298
+
158
299
  export const createNodesV2: CreateNodesV2 = [
159
300
  '**/package.json',
160
301
  async (projectConfigurationFiles, _options, context) => {
@@ -297,8 +438,7 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
297
438
  }
298
439
 
299
440
  if (napiConfig) {
300
- const napiTargets = createNapiTargets(projectRoot, napiConfig);
301
- Object.assign(targets, napiTargets.targets);
441
+ Object.assign(targets, createNapiTargets(projectRoot, napiConfig));
302
442
  if (
303
443
  !('napi-test' in (packageJson.nx?.targets ?? {})) &&
304
444
  existsSync(join(absoluteProjectRoot, 'src/native.test.ts'))
@@ -306,30 +446,78 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
306
446
  targets['napi-test'] = createNapiTestTarget(
307
447
  projectRoot,
308
448
  existsSync(join(absoluteProjectRoot, 'bunfig.napi-test.toml')),
309
- napiTargets.hostProvider,
310
449
  );
311
450
  }
312
451
  }
313
452
 
314
453
  // Member crates get their targets from the workspace-root package.json,
315
454
  // never per-crate — one Nx project per Cargo workspace.
455
+ //
456
+ // Every cargo tool target below is inferred unconditionally, INCLUDING when
457
+ // the package already declares that key in `nx.targets`. Nx merges a
458
+ // package-local declaration over an inference plugin's target one layer
459
+ // later — the precedence order is specified plugins → target defaults →
460
+ // default plugins, and the package.json reader is a default plugin — so a
461
+ // declaration only has to name the fields it changes:
462
+ //
463
+ // - `executor`, `cache`, `inputs`, `outputs`, `dependsOn`: the declared
464
+ // value REPLACES the inferred one, and every field the declaration omits
465
+ // is inherited from here.
466
+ // - `options` and `configurations`: merged key by key with declared keys
467
+ // winning, unless the declaration names a different executor — then its
468
+ // options mean something else and replace them wholesale.
469
+ // - `"dependsOn": ["...", "extra"]` expands the inferred list at the
470
+ // token's position. That is how a package ADDS an edge.
471
+ //
472
+ // Skipping inference for a declared key — what this used to do — is what made
473
+ // a one-line addition catastrophic: `nx.targets['cargo-test'] = { dependsOn:
474
+ // [...] }` left nothing to merge onto, and Nx normalizes a bare `dependsOn`
475
+ // to `executor: nx:noop` with empty options. That is the worst kind of green:
476
+ // `cargo-test` reaches its dependencies and runs no test binary.
477
+ // `checkWorkspaceCargoTestReachabilityPolicy` fails that shape, but the fix is
478
+ // to leave a base for the declaration to land on.
479
+ //
480
+ // The overlay is deliberately NOT re-implemented here. Applying it in this
481
+ // plugin as well would expand a `"..."` spread twice — once against the
482
+ // inferred list here, once when Nx merges the same declaration over this
483
+ // result — duplicating the very edges the spread exists to add.
484
+ //
485
+ // `dependsOn` REPLACES rather than unions. These lists are not a bag of
486
+ // independent wishes; they are the serialization chain that keeps two cargo
487
+ // writers off one flocked `target/` (see CARGO_TEST_COMPILE_TARGET), and their
488
+ // ORDER carries the invariant. A package that must re-route the chain — build
489
+ // its artifact ahead of the test run, or drop `cargo-test-compile` because it
490
+ // compiles differently — can only say so by replacing the list; a union would
491
+ // make every inferred edge unremovable and a corrected order unrepresentable.
492
+ // Additive intent already has a spelling (`"..."` above), so a plugin-local
493
+ // additive key would be a second convention beside a working one.
494
+ //
495
+ // The output families (`cargo-wasm`, `napi-*`) and the `test` aggregate stay
496
+ // all-or-nothing, because for those the package decides whether the target
497
+ // EXISTS — a packaging decision for output families, the bounded-test policy's
498
+ // rewrite for `test` — so there is no inferred base to partially override.
316
499
  if (isCargoWorkspace) {
317
- const declared = declaredTargets;
318
- if (!('cargo-test' in declared)) {
319
- targets['cargo-test'] = createCargoTestTarget(projectRoot);
320
- }
321
- if (!('cargo-lint' in declared)) {
322
- targets['cargo-lint'] = {
323
- executor: 'nx:run-commands',
324
- cache: true,
325
- inputs: CARGO_INPUTS,
326
- options: {
327
- commands: ['cargo fmt --all --check', 'cargo clippy --workspace --all-targets -- -D warnings'],
328
- cwd: projectRoot,
329
- parallel: false,
330
- },
331
- };
332
- }
500
+ targets[CARGO_TEST_COMPILE_TARGET] = createCargoTestCompileTarget(projectRoot);
501
+ const packageTargetNames = await addPerPackageCargoTestTargets(
502
+ targets,
503
+ projectRoot,
504
+ workspaceRoot,
505
+ absoluteProjectRoot,
506
+ );
507
+ targets[CARGO_TEST_TARGET] =
508
+ packageTargetNames.length > 0
509
+ ? { executor: 'nx:noop', cache: true, dependsOn: packageTargetNames }
510
+ : createCargoTestTarget(projectRoot);
511
+ targets['cargo-lint'] = {
512
+ executor: 'nx:run-commands',
513
+ cache: true,
514
+ inputs: CARGO_INPUTS,
515
+ options: {
516
+ commands: ['cargo fmt --all --check', CARGO_LINT_CLIPPY_COMMAND],
517
+ cwd: projectRoot,
518
+ parallel: false,
519
+ },
520
+ };
333
521
  validationTargets.push('cargo-lint');
334
522
  // The Linux arm of `cargo-lint`, as its own target. Rationale for the name,
335
523
  // the command and the absent cross test leg lives in ./cross-check-policy.ts.
@@ -349,45 +537,164 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
349
537
  // see, so it would silently skip projects — today's bug in a new costume. An
350
538
  // opt-in flag has the same failure mode by construction. Every Rust project is
351
539
  // in scope because CI compiles every Rust project on Linux; a project that
352
- // genuinely cannot cross-compile overrides the target by declaring it, which is
353
- // a visible edit to its package.json rather than a silent absence.
540
+ // genuinely cannot cross-compile overrides the target by declaring it with
541
+ // `executor: nx:noop`, which is a visible edit to its package.json rather
542
+ // than a silent absence.
354
543
  //
355
544
  // Deliberately NOT pushed to validationTargets: joining the lint aggregate
356
545
  // would make `bun run lint` — and CI's own Linux lint, already native — demand
357
546
  // the 0.4 GiB cross toolchain that the devenv profile exists to keep opt-in.
358
- if (!(CARGO_CROSS_LINT_TARGET in declared)) {
359
- targets[CARGO_CROSS_LINT_TARGET] = {
360
- executor: 'nx:run-commands',
547
+ targets[CARGO_CROSS_LINT_TARGET] = {
548
+ executor: 'nx:run-commands',
549
+ cache: true,
550
+ inputs: CARGO_INPUTS,
551
+ options: {
552
+ command: CARGO_CROSS_LINT_COMMAND,
553
+ cwd: projectRoot,
554
+ },
555
+ };
556
+ if (!targets.test && !('test' in declaredTargets) && typeof packageJson.scripts?.test !== 'string') {
557
+ targets.test = {
558
+ executor: 'nx:noop',
361
559
  cache: true,
362
- inputs: CARGO_INPUTS,
363
- options: {
364
- command: CARGO_CROSS_LINT_COMMAND,
365
- cwd: projectRoot,
366
- },
560
+ dependsOn: [CARGO_TEST_TARGET],
367
561
  };
368
562
  }
369
- if (!targets.test && !('test' in declared) && typeof packageJson.scripts?.test !== 'string') {
370
- // Execute Cargo directly: workspace targetDefaults may replace test.dependsOn.
371
- targets.test = createCargoTestTarget(projectRoot);
563
+ // Mutation runs are minutes-to-hours: never cached, never part of build/lint.
564
+ // CI runs these per-PR via `cargo mutants --in-diff` (see mutants.toml docs).
565
+ targets.mutation = {
566
+ executor: 'nx:run-commands',
567
+ cache: false,
568
+ options: { command: cargoFrozen('mutants --workspace'), cwd: projectRoot },
569
+ };
570
+ targets.bench = {
571
+ executor: 'nx:run-commands',
572
+ cache: false,
573
+ options: { command: cargoFrozen('bench --workspace'), cwd: projectRoot },
574
+ };
575
+ // Target-dir GC. Cargo never removes superseded artifacts, so a busy
576
+ // workspace grows tens of GB of stale variants no fingerprint references;
577
+ // sweeping by age prunes exactly that junk while the warm current
578
+ // surface — the gated asset — survives untouched. Never cached: the
579
+ // verdict is about this machine's disk, not the commit.
580
+ targets['cargo-sweep'] = {
581
+ executor: 'nx:run-commands',
582
+ cache: false,
583
+ options: { command: 'cargo sweep --time 7', cwd: projectRoot },
584
+ };
585
+ }
586
+
587
+ // Every `cargoFrozen` command needs a registry cache holding the whole locked
588
+ // graph, and offline cargo checks that at RESOLUTION — so a dev-dependency no
589
+ // build ever downloaded takes down `cargo --frozen build` just as surely as
590
+ // `cargo --frozen test`. On an ephemeral runner the only thing that had been
591
+ // populating that cache was a preceding NON-frozen `napi build`, which
592
+ // downloads normal dependencies and never dev-dependencies; a workspace no
593
+ // platform target reaches got nothing at all. `cargo-fetch` states the
594
+ // precondition instead of inheriting it from another target's side effects.
595
+ //
596
+ // Derived from the command text rather than a curated list of target names:
597
+ // the fact that makes a target need this is that it runs frozen cargo, so a
598
+ // frozen target added later is covered without anyone remembering to. The edge
599
+ // goes on EVERY frozen target, not just the head of the serialization chain,
600
+ // so re-routing that chain cannot strip a surviving target's precondition.
601
+ //
602
+ // A package that REPLACES one of these `dependsOn` lists drops the edge with
603
+ // it (see the merge rules above) and gets its cold-cache failure back; `"..."`
604
+ // keeps it.
605
+ const frozenCargoManifests = new Set<string>();
606
+ if (isCargoWorkspace) {
607
+ frozenCargoManifests.add('Cargo.toml');
608
+ }
609
+ if (inferCargoWasm && cargoWasmConfig) {
610
+ // A wasm-bindgen crate can sit in a nested Cargo workspace the project root
611
+ // is not a member of, so its graph is a second fetch, not the same one.
612
+ frozenCargoManifests.add(cargoWasmConfig.manifestPath);
613
+ }
614
+ if (frozenCargoManifests.size > 0) {
615
+ targets[CARGO_FETCH_TARGET] = {
616
+ executor: 'nx:run-commands',
617
+ // The download lands in CARGO_HOME, outside the workspace: a cache hit
618
+ // would skip work a cold registry still needs — same reason
619
+ // napi-toolchain-* is uncached. Nothing here is a workspace output, so
620
+ // there is nothing for Nx to restore in its place.
621
+ cache: false,
622
+ options: {
623
+ commands: [...frozenCargoManifests]
624
+ .sort()
625
+ .map((manifestPath) =>
626
+ manifestPath === 'Cargo.toml'
627
+ ? CARGO_FETCH_COMMAND
628
+ : `${CARGO_FETCH_COMMAND} --manifest-path ${manifestPath}`,
629
+ ),
630
+ cwd: projectRoot,
631
+ // Two fetches into one CARGO_HOME contend on its package-cache flock;
632
+ // serializing here spends the wait in Nx instead of inside cargo.
633
+ parallel: false,
634
+ },
635
+ };
636
+ for (const [name, target] of Object.entries(targets)) {
637
+ if (name === CARGO_FETCH_TARGET) {
638
+ continue;
639
+ }
640
+ const command: unknown = target.options?.command;
641
+ const commands: unknown = target.options?.commands;
642
+ const text = [
643
+ typeof command === 'string' ? command : '',
644
+ ...(Array.isArray(commands) ? commands.filter((entry) => typeof entry === 'string') : []),
645
+ ].join('\n');
646
+ if (!text.includes(CARGO_FROZEN_PREFIX)) {
647
+ continue;
648
+ }
649
+ const dependsOn = target.dependsOn ?? [];
650
+ if (!dependsOn.includes(CARGO_FETCH_TARGET)) {
651
+ target.dependsOn = [CARGO_FETCH_TARGET, ...dependsOn];
652
+ }
653
+ }
654
+ }
655
+
656
+ // Cargo flocks the package's default `target/`. Writers that share it must
657
+ // not be Nx siblings. Clippy is not in this set: it has its own --target-dir.
658
+ const napiDebug = targets['napi-debug'];
659
+ if (napiDebug && targets[CARGO_TEST_COMPILE_TARGET]) {
660
+ const dependsOn = napiDebug.dependsOn ?? [];
661
+ if (!dependsOn.includes(CARGO_TEST_COMPILE_TARGET)) {
662
+ napiDebug.dependsOn = [...dependsOn, CARGO_TEST_COMPILE_TARGET];
372
663
  }
373
- if (!('mutation' in declared)) {
374
- // Mutation runs are minutes-to-hours: never cached, never part of build/lint.
375
- // CI runs these per-PR via `cargo mutants --in-diff` (see mutants.toml docs).
376
- targets.mutation = {
377
- executor: 'nx:run-commands',
378
- cache: false,
379
- options: { command: 'cargo mutants --workspace', cwd: projectRoot },
380
- };
664
+ }
665
+ if (napiDebug) {
666
+ for (const [name, target] of Object.entries(targets)) {
667
+ if (!name.startsWith('cargo-test-') || name === CARGO_TEST_COMPILE_TARGET) {
668
+ continue;
669
+ }
670
+ const dependsOn = target.dependsOn ?? [];
671
+ if (dependsOn.includes(CARGO_TEST_COMPILE_TARGET) && !dependsOn.includes('napi-debug')) {
672
+ target.dependsOn = dependsOn.map((dep) => (dep === CARGO_TEST_COMPILE_TARGET ? 'napi-debug' : dep));
673
+ }
381
674
  }
382
- if (!('bench' in declared)) {
383
- targets.bench = {
384
- executor: 'nx:run-commands',
385
- cache: false,
386
- options: { command: 'cargo bench --workspace', cwd: projectRoot },
387
- };
675
+ const cargoTest = targets[CARGO_TEST_TARGET];
676
+ if (
677
+ cargoTest?.options &&
678
+ typeof cargoTest.options.command === 'string' &&
679
+ cargoTest.options.command.startsWith('cargo ')
680
+ ) {
681
+ const dependsOn = cargoTest.dependsOn ?? [];
682
+ if (!dependsOn.includes('napi-debug')) {
683
+ cargoTest.dependsOn = [...dependsOn, 'napi-debug'];
684
+ }
388
685
  }
389
686
  }
390
687
 
688
+ // No `outputs`, deliberately: this aggregate runs no command, so every file
689
+ // under dist belongs to the concrete target that emitted it. Claiming
690
+ // `{projectRoot}/dist` here would cache the children's bytes a second time
691
+ // under the aggregate's hash, and would make `smoo github-ci nx-run-many
692
+ // --collect-outputs` attribute to `build` whatever sits under dist — including
693
+ // platform-target artifacts the collect excludes on purpose and stale
694
+ // artifacts of targets that never ran. Two collected trees then claim one
695
+ // binary and `apply-outputs` rejects the overlap. `lint` and `test` are
696
+ // aggregates on the same terms. Same reason nx.json must not put `outputs` in
697
+ // targetDefaults.build (see validateBuildTargetDefault).
391
698
  if (hasOrdinaryBuildOutputTarget) {
392
699
  targets.build = {
393
700
  executor: 'nx:noop',
@@ -607,10 +914,7 @@ function resolveNapiConfig(
607
914
  return { binaryName, cargoPackage, manifestPath, targets };
608
915
  }
609
916
 
610
- function createNapiTargets(
611
- projectRoot: string,
612
- config: ResolvedNapiConfig,
613
- ): { targets: Record<string, TargetConfiguration>; hostProvider: string } {
917
+ function createNapiTargets(projectRoot: string, config: ResolvedNapiConfig): Record<string, TargetConfiguration> {
614
918
  const commonCommand = `--manifest-path ${config.manifestPath} --package ${config.cargoPackage}`;
615
919
  const hostPlatformTargetName = HOST_PLATFORM_SUFFIX === null ? null : `napi${HOST_PLATFORM_SUFFIX}`;
616
920
  let nativeHostTargetName: string | null = null;
@@ -624,9 +928,27 @@ function createNapiTargets(
624
928
  }
625
929
  }
626
930
  }
627
- const hostProvider = nativeHostTargetName ?? 'cargo-napi';
628
931
  const targets: Record<string, TargetConfiguration> = {};
629
932
 
933
+ // The addon the test suite loads. A dev-profile build shares target/debug
934
+ // with cargo-test's dependency graph, so after the tests compile this is
935
+ // nearly free — where the release platform build it replaces cost minutes
936
+ // and sat alone on the test critical path. The output lives OUTSIDE dist/
937
+ // because packages publish `files: ["dist"]` wholesale: a debug addon under
938
+ // dist/ would ship. native.ts resolves this directory only when the
939
+ // napi-test target sets NAPI_DEBUG_ADDON=1, so production loads never see it.
940
+ targets['napi-debug'] = {
941
+ executor: 'nx:run-commands',
942
+ cache: true,
943
+ dependsOn: ['^build'],
944
+ inputs: NAPI_INPUTS,
945
+ outputs: ['{projectRoot}/.cache/native-debug'],
946
+ options: {
947
+ cwd: projectRoot,
948
+ command: `napi build --platform --no-js --dts ${config.binaryName}.napi.d.ts ${commonCommand} --output-dir .cache/native-debug`,
949
+ },
950
+ };
951
+
630
952
  if (nativeHostTargetName === null) {
631
953
  // The platform target for this host triple is the same compilation, so a
632
954
  // second cargo-napi invocation only buys a duplicate dependency graph in
@@ -689,19 +1011,19 @@ function createNapiTargets(
689
1011
  },
690
1012
  };
691
1013
  }
692
- return { targets, hostProvider };
1014
+ return targets;
693
1015
  }
694
1016
 
695
- function createNapiTestTarget(
696
- projectRoot: string,
697
- hasDedicatedBunfig: boolean,
698
- hostProvider: string,
699
- ): TargetConfiguration {
1017
+ function createNapiTestTarget(projectRoot: string, hasDedicatedBunfig: boolean): TargetConfiguration {
700
1018
  const configFlag = hasDedicatedBunfig ? ' --config=../bunfig.napi-test.toml' : ' --config=../bunfig.toml';
701
1019
  return {
702
1020
  executor: '@smoothbricks/nx-plugin:bounded-exec',
703
1021
  cache: true,
704
- dependsOn: ['cargo-test', hostProvider, 'tsc-js', '^build', 'build'],
1022
+ // Deliberately NOT `build`: the aggregate drags the host-platform release
1023
+ // binaries onto the test critical path, and the tests assert behavior, not
1024
+ // optimization level. tsc-js supplies dist/ts for the suite's own imports;
1025
+ // napi-debug supplies the addon.
1026
+ dependsOn: ['cargo-test', 'napi-debug', 'tsc-js', '^build'],
705
1027
  options: {
706
1028
  // cwd is src/, not the package root: `bun test <arg>` treats the arg as a
707
1029
  // FILTER and scans the whole cwd tree for test files, and a Rust
@@ -710,6 +1032,9 @@ function createNapiTestTarget(
710
1032
  // config is passed explicitly.
711
1033
  command: `bun test${configFlag} --timeout=30000 native.test.ts`,
712
1034
  cwd: `${projectRoot}/src`,
1035
+ // Routes the package's native loader to the napi-debug artifact under
1036
+ // .cache/native-debug instead of the packaged dist/native tree.
1037
+ env: { NAPI_DEBUG_ADDON: '1' },
713
1038
  timeoutMs: 120000,
714
1039
  killAfterMs: 10000,
715
1040
  },
@@ -103,6 +103,56 @@ describe('package target policy', () => {
103
103
  }
104
104
  });
105
105
 
106
+ it('preserves cross-project dependsOn references in apply and check', async () => {
107
+ const root = await mkdtemp(join(tmpdir(), 'smoothbricks-pkg-target-'));
108
+ try {
109
+ await writeJson(join(root, 'package.json'), {
110
+ name: '@scope/root',
111
+ private: true,
112
+ workspaces: ['packages/*'],
113
+ });
114
+ await writeJson(join(root, 'packages/lib/package.json'), {
115
+ name: '@scope/lib',
116
+ dependencies: { '@scope/schema': 'workspace:*' },
117
+ nx: {
118
+ name: 'lib',
119
+ targets: {
120
+ // `wire-schema:build` is Nx's project:target syntax pointing at a real
121
+ // sibling project; only its suffix collides with this project's own
122
+ // `build`, which is exactly what the legacy colon-name migration used
123
+ // to swallow.
124
+ build: {
125
+ executor: 'nx:run-commands',
126
+ options: { command: 'tsc --build tsconfig.lib.json', cwd: '{projectRoot}' },
127
+ dependsOn: ['^build', 'wire-schema:build'],
128
+ },
129
+ },
130
+ },
131
+ });
132
+ await writeJson(join(root, 'packages/schema/package.json'), {
133
+ name: '@scope/schema',
134
+ nx: {
135
+ name: 'wire-schema',
136
+ targets: {
137
+ build: {
138
+ executor: 'nx:run-commands',
139
+ options: { command: 'bun run emit.ts', cwd: '{projectRoot}' },
140
+ },
141
+ },
142
+ },
143
+ });
144
+
145
+ applyPackageTargetPolicy(root);
146
+
147
+ const lib = JSON.parse(await readFile(join(root, 'packages/lib/package.json'), 'utf8'));
148
+ expect(lib.nx.targets.build.dependsOn).toEqual(['^build', 'wire-schema:build']);
149
+ const issues = checkPackageTargetPolicy(root);
150
+ expect(issues.filter((issue) => issue.message.includes('wire-schema:build'))).toEqual([]);
151
+ } finally {
152
+ await rm(root, { recursive: true, force: true });
153
+ }
154
+ });
155
+
106
156
  it('removes noop aggregate build targets matching resolved plugin output', async () => {
107
157
  const root = await mkdtemp(join(tmpdir(), 'smoothbricks-pkg-target-'));
108
158
  try {