@smoothbricks/nx-plugin 0.3.9 → 0.3.11

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 (37) hide show
  1. package/README.md +7 -0
  2. package/dist/cross-check-policy.d.ts +65 -0
  3. package/dist/cross-check-policy.d.ts.map +1 -0
  4. package/dist/cross-check-policy.js +64 -0
  5. package/dist/executors/clean-outputs/executor.js +17 -3
  6. package/dist/executors/napi-cross-toolchain/executor.d.ts +42 -0
  7. package/dist/executors/napi-cross-toolchain/executor.d.ts.map +1 -0
  8. package/dist/executors/napi-cross-toolchain/executor.js +126 -0
  9. package/dist/executors/napi-cross-toolchain/schema.d.ts +4 -0
  10. package/dist/executors/napi-cross-toolchain/schema.d.ts.map +1 -0
  11. package/dist/executors/napi-cross-toolchain/schema.js +1 -0
  12. package/dist/generators/create-package/generator.d.ts.map +1 -1
  13. package/dist/generators/create-package/generator.js +77 -5
  14. package/dist/index.d.ts +13 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +122 -12
  17. package/dist/typecheck-test-policy.d.ts.map +1 -1
  18. package/dist/typecheck-test-policy.js +22 -2
  19. package/dist/workspace-config-policy.js +14 -0
  20. package/executors.json +5 -0
  21. package/generators.json +1 -1
  22. package/package.json +6 -1
  23. package/src/cross-check-policy.test.ts +81 -0
  24. package/src/cross-check-policy.ts +70 -0
  25. package/src/executors/clean-outputs/executor.ts +17 -3
  26. package/src/executors/napi-cross-toolchain/executor.test.ts +112 -0
  27. package/src/executors/napi-cross-toolchain/executor.ts +165 -0
  28. package/src/executors/napi-cross-toolchain/schema.json +15 -0
  29. package/src/executors/napi-cross-toolchain/schema.ts +3 -0
  30. package/src/generators/create-package/generator.test.ts +49 -0
  31. package/src/generators/create-package/generator.ts +88 -6
  32. package/src/generators/create-package/schema.d.ts +2 -1
  33. package/src/generators/create-package/schema.json +7 -2
  34. package/src/index.test.ts +92 -14
  35. package/src/index.ts +136 -12
  36. package/src/typecheck-test-policy.ts +24 -2
  37. package/src/workspace-config-policy.ts +14 -0
package/src/index.ts CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  import { AggregateCreateNodesError } from 'nx/src/project-graph/error-types.js';
12
12
  import { parse as parseToml } from 'smol-toml';
13
13
 
14
+ import { CARGO_CROSS_LINT_COMMAND, CARGO_CROSS_LINT_TARGET } from './cross-check-policy.js';
14
15
  import { BUILD_OUTPUT_DEPENDENCIES, PLATFORM_TARGET_GLOBS } from './workspace-config-policy.js';
15
16
 
16
17
  const BUILD_OUTPUT_TARGET_PATTERN = /-(?:js|web|html|css|android|native|napi|bun|wasm)$/;
@@ -21,6 +22,30 @@ const TYPESCRIPT_TOOLCHAIN_INPUTS = [
21
22
  '{workspaceRoot}/tsconfig.base.json',
22
23
  ];
23
24
 
25
+ // The aggregate `build` pulls in platform-suffixed binary targets for THIS
26
+ // machine only: `<tool>-<arch>-<os>` names matching the host (for example
27
+ // cli-arm64-macos on Apple Silicon) build locally as part of `nx build`, while
28
+ // every foreign platform stays publish-workflow-only. nx.json targetDefaults
29
+ // cannot express "current platform" — its dependsOn lists are static — so the
30
+ // inference plugin owns this edge.
31
+ const HOST_PLATFORM_SUFFIX: string | null = (() => {
32
+ const os = process.platform === 'darwin' ? 'macos' : process.platform === 'linux' ? 'linux' : null;
33
+ const arch = process.arch === 'arm64' ? 'arm64' : process.arch === 'x64' ? 'x64' : null;
34
+ return os !== null && arch !== null ? `-${arch}-${os}` : null;
35
+ })();
36
+
37
+ export function hostPlatformTargetNames(targetNames: Iterable<string>): string[] {
38
+ if (HOST_PLATFORM_SUFFIX === null) return [];
39
+ return [...new Set(targetNames)]
40
+ .filter(
41
+ // Binary targets only. A toolchain prerequisite carries the same platform
42
+ // suffix but produces no artifact: the cross builds that need it depend
43
+ // on it directly, so the aggregate stays a list of outputs.
44
+ (name) => name.endsWith(HOST_PLATFORM_SUFFIX) && !name.startsWith(NAPI_TOOLCHAIN_TARGET_PREFIX),
45
+ )
46
+ .sort();
47
+ }
48
+
24
49
  //#region smoo!n/rust-output-target-inference
25
50
  // Cargo workspace inference: a package.json sitting next to a Cargo.toml that
26
51
  // declares [workspace] gets direct cargo-test/test targets, cargo-lint feeding
@@ -78,6 +103,17 @@ const NAPI_TARGET_CONVENTIONS: Readonly<Record<string, NapiTargetConvention>> =
78
103
  },
79
104
  };
80
105
 
106
+ const NAPI_TOOLCHAIN_TARGET_PREFIX = 'napi-toolchain-';
107
+
108
+ /**
109
+ * Prerequisite target that extracts the cross toolchain one triple needs. The
110
+ * platform suffix keeps it inside its own platform family, so it can be a
111
+ * dependency of `napi-<arch>-linux` and package-local `cli-<arch>-linux`.
112
+ */
113
+ export function napiToolchainTargetName(convention: NapiTargetConvention): string {
114
+ return `${NAPI_TOOLCHAIN_TARGET_PREFIX}${convention.architecture}-${convention.targetFamily}`;
115
+ }
116
+
81
117
  function createCargoWasmTarget(projectRoot: string, config: ResolvedCargoWasmConfig): TargetConfiguration {
82
118
  const cargoTargetDirectory = posix.join(posix.dirname(config.manifestPath), 'target/cargo-wasm');
83
119
  const wasmInput = `${cargoTargetDirectory}/wasm32-unknown-unknown/release/${config.libraryName}.wasm`;
@@ -261,7 +297,8 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
261
297
  }
262
298
 
263
299
  if (napiConfig) {
264
- Object.assign(targets, createNapiTargets(projectRoot, napiConfig));
300
+ const napiTargets = createNapiTargets(projectRoot, napiConfig);
301
+ Object.assign(targets, napiTargets.targets);
265
302
  if (
266
303
  !('napi-test' in (packageJson.nx?.targets ?? {})) &&
267
304
  existsSync(join(absoluteProjectRoot, 'src/native.test.ts'))
@@ -269,6 +306,7 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
269
306
  targets['napi-test'] = createNapiTestTarget(
270
307
  projectRoot,
271
308
  existsSync(join(absoluteProjectRoot, 'bunfig.napi-test.toml')),
309
+ napiTargets.hostProvider,
272
310
  );
273
311
  }
274
312
  }
@@ -293,6 +331,41 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
293
331
  };
294
332
  }
295
333
  validationTargets.push('cargo-lint');
334
+ // The Linux arm of `cargo-lint`, as its own target. Rationale for the name,
335
+ // the command and the absent cross test leg lives in ./cross-check-policy.ts.
336
+ //
337
+ // Inferred rather than declared package-locally: the rule reserving
338
+ // package-local declaration for output families (`cargo-wasm`, `cargo-napi`)
339
+ // governs targets that PRODUCE artifacts, where "does this package ship this
340
+ // artifact" is a packaging decision no crate manifest can answer. This target
341
+ // emits nothing — clippy type-checks and discards — so it belongs with
342
+ // cargo-lint and cargo-test on the inferred validation side.
343
+ //
344
+ // The discriminator for "has cross-platform Rust" is deliberately the same
345
+ // `[workspace]` Cargo.toml that already grants cargo-lint, NOT a scan of
346
+ // sources for `cfg` arms and NOT an opt-in flag. A source scan looks more
347
+ // precise and is strictly worse: target-specific code arrives through
348
+ // DEPENDENCIES as well as own source, which no scan of this repo's files can
349
+ // see, so it would silently skip projects — today's bug in a new costume. An
350
+ // opt-in flag has the same failure mode by construction. Every Rust project is
351
+ // 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.
354
+ //
355
+ // Deliberately NOT pushed to validationTargets: joining the lint aggregate
356
+ // would make `bun run lint` — and CI's own Linux lint, already native — demand
357
+ // 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',
361
+ cache: true,
362
+ inputs: CARGO_INPUTS,
363
+ options: {
364
+ command: CARGO_CROSS_LINT_COMMAND,
365
+ cwd: projectRoot,
366
+ },
367
+ };
368
+ }
296
369
  if (!targets.test && !('test' in declared) && typeof packageJson.scripts?.test !== 'string') {
297
370
  // Execute Cargo directly: workspace targetDefaults may replace test.dependsOn.
298
371
  targets.test = createCargoTestTarget(projectRoot);
@@ -319,7 +392,11 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
319
392
  targets.build = {
320
393
  executor: 'nx:noop',
321
394
  cache: true,
322
- dependsOn: ['^build', ...BUILD_OUTPUT_DEPENDENCIES],
395
+ dependsOn: [
396
+ '^build',
397
+ ...BUILD_OUTPUT_DEPENDENCIES,
398
+ ...hostPlatformTargetNames([...Object.keys(declaredTargets), ...Object.keys(targets)]),
399
+ ],
323
400
  };
324
401
  }
325
402
  if (hasAnyBuildOutputTarget) {
@@ -530,10 +607,32 @@ function resolveNapiConfig(
530
607
  return { binaryName, cargoPackage, manifestPath, targets };
531
608
  }
532
609
 
533
- function createNapiTargets(projectRoot: string, config: ResolvedNapiConfig): Record<string, TargetConfiguration> {
610
+ function createNapiTargets(
611
+ projectRoot: string,
612
+ config: ResolvedNapiConfig,
613
+ ): { targets: Record<string, TargetConfiguration>; hostProvider: string } {
534
614
  const commonCommand = `--manifest-path ${config.manifestPath} --package ${config.cargoPackage}`;
535
- const targets: Record<string, TargetConfiguration> = {
536
- 'cargo-napi': {
615
+ const hostPlatformTargetName = HOST_PLATFORM_SUFFIX === null ? null : `napi${HOST_PLATFORM_SUFFIX}`;
616
+ let nativeHostTargetName: string | null = null;
617
+ if (hostPlatformTargetName !== null) {
618
+ for (const triple of config.targets) {
619
+ const convention = NAPI_TARGET_CONVENTIONS[triple];
620
+ const targetName = convention ? `napi-${convention.architecture}-${convention.targetFamily}` : null;
621
+ if (targetName === hostPlatformTargetName && !convention?.useNapiCross) {
622
+ nativeHostTargetName = targetName;
623
+ break;
624
+ }
625
+ }
626
+ }
627
+ const hostProvider = nativeHostTargetName ?? 'cargo-napi';
628
+ const targets: Record<string, TargetConfiguration> = {};
629
+
630
+ if (nativeHostTargetName === null) {
631
+ // The platform target for this host triple is the same compilation, so a
632
+ // second cargo-napi invocation only buys a duplicate dependency graph in
633
+ // target/release; native.ts already resolves the identical platform-suffixed
634
+ // filename from dist/native/<platform-dir> after dist/native/host.
635
+ targets['cargo-napi'] = {
537
636
  executor: 'nx:run-commands',
538
637
  cache: true,
539
638
  dependsOn: ['^build'],
@@ -543,8 +642,28 @@ function createNapiTargets(projectRoot: string, config: ResolvedNapiConfig): Rec
543
642
  cwd: projectRoot,
544
643
  command: `napi build --release --platform --no-js --dts ${config.binaryName}.napi.d.ts ${commonCommand} --output-dir dist/native/host`,
545
644
  },
546
- },
547
- };
645
+ };
646
+ }
647
+
648
+ for (const triple of config.targets) {
649
+ const convention = NAPI_TARGET_CONVENTIONS[triple];
650
+ if (!convention?.useNapiCross) {
651
+ continue;
652
+ }
653
+ // One toolchain target per triple, shared by every cross build that needs
654
+ // it: the inferred napi-<arch>-linux plus any package-local cli-<arch>-linux.
655
+ // Nx runs a shared dependency once, which is what stops those builds from
656
+ // racing inside the Bun store. See the executor for the failure it removes.
657
+ // The name carries the platform suffix so a Linux platform target's
658
+ // dependency closure stays Linux-only (package-target-policy).
659
+ targets[napiToolchainTargetName(convention)] = {
660
+ executor: '@smoothbricks/nx-plugin:napi-cross-toolchain',
661
+ // Extraction lands in ~/.napi-rs, outside the workspace: a cache hit
662
+ // would skip work a cold home directory still needs.
663
+ cache: false,
664
+ options: { triple },
665
+ };
666
+ }
548
667
 
549
668
  for (const triple of config.targets) {
550
669
  const convention = NAPI_TARGET_CONVENTIONS[triple];
@@ -557,6 +676,7 @@ function createNapiTargets(projectRoot: string, config: ResolvedNapiConfig): Rec
557
676
  targets[targetName] = {
558
677
  executor: 'nx:run-commands',
559
678
  cache: true,
679
+ ...(convention.useNapiCross ? { dependsOn: [napiToolchainTargetName(convention)] } : {}),
560
680
  inputs: NAPI_INPUTS,
561
681
  outputs: [`{projectRoot}/${outputDirectory}`],
562
682
  options: {
@@ -569,18 +689,22 @@ function createNapiTargets(projectRoot: string, config: ResolvedNapiConfig): Rec
569
689
  },
570
690
  };
571
691
  }
572
- return targets;
692
+ return { targets, hostProvider };
573
693
  }
574
694
 
575
- function createNapiTestTarget(projectRoot: string, hasDedicatedBunfig: boolean): TargetConfiguration {
695
+ function createNapiTestTarget(
696
+ projectRoot: string,
697
+ hasDedicatedBunfig: boolean,
698
+ hostProvider: string,
699
+ ): TargetConfiguration {
576
700
  const configFlag = hasDedicatedBunfig ? ' --config=../bunfig.napi-test.toml' : ' --config=../bunfig.toml';
577
701
  return {
578
702
  executor: '@smoothbricks/nx-plugin:bounded-exec',
579
703
  cache: true,
580
- dependsOn: ['cargo-test', 'cargo-napi', 'tsc-js', '^build', 'build'],
704
+ dependsOn: ['cargo-test', hostProvider, 'tsc-js', '^build', 'build'],
581
705
  options: {
582
- // cwd is src/, not the package root: `bun test <arg>` treats the arg as
583
- // a FILTER and scans the whole cwd tree for test files, and a Rust
706
+ // cwd is src/, not the package root: `bun test <arg>` treats the arg as a
707
+ // FILTER and scans the whole cwd tree for test files, and a Rust
584
708
  // package's cargo target/ directory turns that scan into tens of
585
709
  // seconds. bun only auto-loads bunfig from the cwd, so the package
586
710
  // config is passed explicitly.
@@ -346,6 +346,7 @@ export function applyTypecheckTestPolicyTree(tree: Tree): boolean {
346
346
  */
347
347
  export function checkTypecheckTestPolicy(root: string): NxPolicyIssue[] {
348
348
  const issues: NxPolicyIssue[] = [];
349
+ const workspaceNames = getWorkspacePackageNames(root);
349
350
  for (const packageJsonPath of listWorkspacePackageJsonPaths(root)) {
350
351
  const pkg = readJsonObject(packageJsonPath);
351
352
  if (!pkg) {
@@ -372,12 +373,33 @@ export function checkTypecheckTestPolicy(root: string): NxPolicyIssue[] {
372
373
  continue;
373
374
  }
374
375
 
375
- // tsconfig.test.json must have correct settings
376
+ // The checker and updater share one normalization function. Detailed invariant
377
+ // diagnostics win; otherwise report any subtler missing canonical field so
378
+ // `smoo monorepo check` cannot be green immediately before update rewrites it.
376
379
  const tsconfig = readJsonObject(tsconfigTestPath);
377
380
  if (tsconfig) {
378
- // Use absolute path for filesystem layer
379
381
  const absoluteIssues = checkTypecheckTestConfig(tsconfig, join(root, packagePath));
380
382
  issues.push(...absoluteIssues);
383
+ if (absoluteIssues.length === 0) {
384
+ const libTsconfig = readJsonObject(join(root, packagePath, 'tsconfig.lib.json'));
385
+ const tsconfigLibExtends = stringProperty(libTsconfig ?? {}, 'extends') ?? '../../tsconfig.base.json';
386
+ const libCompilerOptions = libTsconfig ? recordProperty(libTsconfig, 'compilerOptions') : null;
387
+ const referencePaths = collectTsconfigTestReferencePaths(root, packagePath, pkg, workspaceNames);
388
+ const normalized = structuredClone(tsconfig);
389
+ if (
390
+ applyTypecheckTestDefaults(normalized, {
391
+ testRunners,
392
+ tsconfigLibExtends,
393
+ libCompilerOptions: libCompilerOptions ?? undefined,
394
+ referencePaths,
395
+ })
396
+ ) {
397
+ issues.push({
398
+ path: tsconfigTestPath,
399
+ message: 'must match the canonical no-emit test typecheck configuration',
400
+ });
401
+ }
402
+ }
381
403
  }
382
404
 
383
405
  // tsconfig.json must NOT reference ./tsconfig.test.json
@@ -186,6 +186,16 @@ function validateBuildTargetDefault(
186
186
  if (build?.cache !== true) {
187
187
  issues.push({ path: nxJsonPath, message: 'targetDefaults.build.cache must be true' });
188
188
  }
189
+ // dependsOn is owned by the inference plugin: the inferred aggregate carries
190
+ // the output families PLUS this host's platform-suffixed binary targets, and
191
+ // Nx gives targetDefaults precedence over inferred values — a static list
192
+ // here would clobber the host-aware edge on every project.
193
+ if (build !== null && 'dependsOn' in build) {
194
+ issues.push({
195
+ path: nxJsonPath,
196
+ message: 'targetDefaults.build.dependsOn must not be set; @smoothbricks/nx-plugin infers build dependencies',
197
+ });
198
+ }
189
199
  const outputs = build?.outputs;
190
200
  if (!isValidBuildOutputs(outputs)) {
191
201
  issues.push({
@@ -276,6 +286,10 @@ function applyBuildTargetDefault(nxJson: Record<string, unknown>): boolean {
276
286
  if (!isValidBuildOutputs(build.outputs)) {
277
287
  changed = setStringArrayProperty(build, 'outputs', ['{projectRoot}/dist']) || changed;
278
288
  }
289
+ if ('dependsOn' in build) {
290
+ delete build.dependsOn;
291
+ changed = true;
292
+ }
279
293
  return changed;
280
294
  }
281
295