@smoothbricks/nx-plugin 0.3.4 → 0.3.6

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 (32) hide show
  1. package/README.md +40 -8
  2. package/dist/bounded-test-policy.d.ts +4 -2
  3. package/dist/bounded-test-policy.d.ts.map +1 -1
  4. package/dist/bounded-test-policy.js +93 -15
  5. package/dist/executors/typescript-emit/executor.d.ts +17 -0
  6. package/dist/executors/typescript-emit/executor.d.ts.map +1 -0
  7. package/dist/executors/typescript-emit/executor.js +61 -0
  8. package/dist/executors/typescript-emit/schema.d.ts +5 -0
  9. package/dist/executors/typescript-emit/schema.d.ts.map +1 -0
  10. package/dist/executors/typescript-emit/schema.js +1 -0
  11. package/dist/index.d.ts +1 -1
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +280 -29
  14. package/dist/package-target-policy.d.ts +2 -0
  15. package/dist/package-target-policy.d.ts.map +1 -1
  16. package/dist/package-target-policy.js +5 -1
  17. package/dist/workspace-config-policy.d.ts.map +1 -1
  18. package/dist/workspace-config-policy.js +11 -3
  19. package/executors.json +5 -0
  20. package/package.json +4 -3
  21. package/src/bounded-test-policy.test.ts +102 -2
  22. package/src/bounded-test-policy.ts +110 -17
  23. package/src/executors/typescript-emit/executor.test.ts +98 -0
  24. package/src/executors/typescript-emit/executor.ts +94 -0
  25. package/src/executors/typescript-emit/schema.json +19 -0
  26. package/src/executors/typescript-emit/schema.ts +4 -0
  27. package/src/index.test.ts +158 -17
  28. package/src/index.ts +358 -31
  29. package/src/package-target-policy.test.ts +17 -0
  30. package/src/package-target-policy.ts +5 -1
  31. package/src/workspace-config-policy.test.ts +41 -1
  32. package/src/workspace-config-policy.ts +12 -3
package/src/index.ts CHANGED
@@ -1,9 +1,15 @@
1
1
  import { existsSync } from 'node:fs';
2
- import { readFile } from 'node:fs/promises';
3
- import { dirname, join } from 'node:path';
4
-
5
- import type { CreateNodesResultV2, CreateNodesV2, TargetConfiguration } from 'nx/src/devkit-exports.js';
2
+ import { readdir, readFile } from 'node:fs/promises';
3
+ import { dirname, join, posix } from 'node:path';
4
+
5
+ import {
6
+ type CreateNodesResultV2,
7
+ type CreateNodesV2,
8
+ readJsonFile,
9
+ type TargetConfiguration,
10
+ } from 'nx/src/devkit-exports.js';
6
11
  import { AggregateCreateNodesError } from 'nx/src/project-graph/error-types.js';
12
+ import { parse as parseToml } from 'smol-toml';
7
13
 
8
14
  import { BUILD_OUTPUT_DEPENDENCIES, PLATFORM_TARGET_GLOBS } from './workspace-config-policy.js';
9
15
 
@@ -18,21 +24,77 @@ const TYPESCRIPT_TOOLCHAIN_INPUTS = [
18
24
  //#region smoo!n/rust-output-target-inference
19
25
  // Cargo workspace inference: a package.json sitting next to a Cargo.toml that
20
26
  // declares [workspace] gets direct cargo-test/test targets, cargo-lint feeding
21
- // the lint aggregate, mutation (cargo-mutants), and bench. Rust output targets
22
- // (cargo-wasm, cargo-napi, ...) are never inferred from crate metadata such as
23
- // cdylib crate-types — a native N-API cdylib is not a wasm build. Packages
24
- // declare output targets in package.json nx.targets, and those *-wasm/*-napi/
25
- // *-native output-family names feed the aggregate build and clean targets.
26
- // Explicit nx.targets entries always win over inference.
27
+ // the lint aggregate, mutation (cargo-mutants), and bench. Cargo output families
28
+ // use tool-native metadata: N-API comes from package.json napi metadata; Wasm
29
+ // comes from [package.metadata.smoothbricks.wasm-bindgen] in a crate manifest.
27
30
  const CARGO_WORKSPACE_PATTERN = /^\s*\[workspace\]/m;
28
31
  //#endregion
29
32
  const CARGO_INPUTS = [
30
33
  '{projectRoot}/**/*.rs',
31
34
  '{projectRoot}/**/Cargo.toml',
32
- '{projectRoot}/Cargo.lock',
33
- '{projectRoot}/.cargo/config.toml',
34
- '!{projectRoot}/target/**',
35
+ '{projectRoot}/**/Cargo.lock',
36
+ '{projectRoot}/**/.cargo/config.toml',
37
+ '!{projectRoot}/**/target/**',
35
38
  ];
39
+ const CARGO_OUTPUT_INPUTS = [...CARGO_INPUTS, '{projectRoot}/package.json', '{workspaceRoot}/bun.lock'];
40
+ const NAPI_INPUTS = CARGO_OUTPUT_INPUTS;
41
+
42
+ interface NapiTargetConvention {
43
+ architecture: string;
44
+ outputName: string;
45
+ targetFamily: 'linux' | 'macos';
46
+ useNapiCross: boolean;
47
+ }
48
+
49
+ const NAPI_TARGET_CONVENTIONS: Readonly<Record<string, NapiTargetConvention>> = {
50
+ 'aarch64-apple-darwin': {
51
+ architecture: 'arm64',
52
+ outputName: 'darwin-arm64',
53
+ targetFamily: 'macos',
54
+ useNapiCross: false,
55
+ },
56
+ 'x86_64-apple-darwin': {
57
+ architecture: 'x64',
58
+ outputName: 'darwin-x64',
59
+ targetFamily: 'macos',
60
+ useNapiCross: false,
61
+ },
62
+ 'aarch64-unknown-linux-gnu': {
63
+ architecture: 'arm64',
64
+ outputName: 'linux-arm64-gnu',
65
+ targetFamily: 'linux',
66
+ useNapiCross: true,
67
+ },
68
+ 'x86_64-unknown-linux-gnu': {
69
+ architecture: 'x64',
70
+ outputName: 'linux-x64-gnu',
71
+ targetFamily: 'linux',
72
+ useNapiCross: true,
73
+ },
74
+ };
75
+
76
+ function createCargoWasmTarget(projectRoot: string, config: ResolvedCargoWasmConfig): TargetConfiguration {
77
+ const cargoTargetDirectory = posix.join(posix.dirname(config.manifestPath), 'target/cargo-wasm');
78
+ const wasmInput = `${cargoTargetDirectory}/wasm32-unknown-unknown/release/${config.libraryName}.wasm`;
79
+ return {
80
+ executor: 'nx:run-commands',
81
+ cache: true,
82
+ dependsOn: ['^build'],
83
+ inputs: CARGO_OUTPUT_INPUTS,
84
+ outputs: [`{projectRoot}/${config.outputDirectory}`],
85
+ options: {
86
+ commands: [
87
+ `cargo build --release --target wasm32-unknown-unknown --target-dir ${cargoTargetDirectory} --manifest-path ${config.manifestPath}`,
88
+ ...config.targets.map(
89
+ ({ bindgenTarget, outputName }) =>
90
+ `wasm-bindgen --target ${bindgenTarget} --out-dir ${config.outputDirectory}/${outputName} ${wasmInput}`,
91
+ ),
92
+ ],
93
+ cwd: projectRoot,
94
+ parallel: false,
95
+ },
96
+ };
97
+ }
36
98
 
37
99
  function createCargoTestTarget(projectRoot: string): TargetConfiguration {
38
100
  return {
@@ -42,7 +104,8 @@ function createCargoTestTarget(projectRoot: string): TargetConfiguration {
42
104
  options: {
43
105
  command: 'cargo test --workspace',
44
106
  cwd: projectRoot,
45
- timeoutMs: 600000,
107
+ // Cold macOS Cargo workspaces can exceed ten minutes while still making progress.
108
+ timeoutMs: 1200000,
46
109
  killAfterMs: 10000,
47
110
  },
48
111
  configurations: {
@@ -90,6 +153,7 @@ export default { createNodesV2 };
90
153
 
91
154
  interface PackageJson {
92
155
  name?: string;
156
+ napi?: Record<string, unknown>;
93
157
  scripts?: Record<string, unknown>;
94
158
  nx?: {
95
159
  name?: string;
@@ -103,22 +167,37 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
103
167
  const packageJson = await readPackageJson(join(workspaceRoot, packageJsonPath));
104
168
  const targets: Record<string, TargetConfiguration> = {};
105
169
  const validationTargets: string[] = [];
106
- const hasLibTsconfig = existsSync(join(absoluteProjectRoot, 'tsconfig.lib.json'));
170
+ const libTsconfigPath = join(absoluteProjectRoot, 'tsconfig.lib.json');
171
+ const hasLibTsconfig = existsSync(libTsconfigPath);
172
+ const cargoTomlPath = join(absoluteProjectRoot, 'Cargo.toml');
173
+ const isCargoWorkspace =
174
+ existsSync(cargoTomlPath) && CARGO_WORKSPACE_PATTERN.test(await readFile(cargoTomlPath, 'utf-8'));
175
+ const napiConfig = resolveNapiConfig(packageJson, packageJsonPath, absoluteProjectRoot, isCargoWorkspace);
176
+ const declaredTargets = packageJson.nx?.targets ?? {};
177
+ const cargoWasmConfig = await resolveCargoWasmConfig(absoluteProjectRoot, packageJsonPath);
178
+ const inferCargoWasm = cargoWasmConfig !== null && !('cargo-wasm' in declaredTargets);
107
179
  const packageLocalBuildOutputs = classifyPackageLocalBuildOutputs(packageJson);
108
- const hasOrdinaryBuildOutputTarget = hasLibTsconfig || packageLocalBuildOutputs.ordinary;
180
+ const hasOrdinaryBuildOutputTarget =
181
+ hasLibTsconfig || napiConfig !== null || cargoWasmConfig !== null || packageLocalBuildOutputs.ordinary;
109
182
  const hasAnyBuildOutputTarget = hasOrdinaryBuildOutputTarget || packageLocalBuildOutputs.platform;
110
183
 
111
184
  if (hasLibTsconfig) {
112
- // Official Nx target inference is disabled because its compiler surface only
113
- // supports tsc/tsgo. Smoo owns the complete transformer-aware ttsc targets.
185
+ // Dependency packages may publish bundled entries that raw tsc does not produce.
186
+ // Build every JavaScript output lane before resolving package exports, without pulling
187
+ // unrelated Wasm, N-API, native, or web outputs onto the compiler critical path.
188
+ //
189
+ // ttsc transforms the source program before declaration emit, so typia's
190
+ // generated implementation identifiers are not valid declaration inputs.
191
+ // The executor gives ttsc a JS-only overlay and emits declarations from the
192
+ // original project with native tsc.
114
193
  targets['tsc-js'] = {
115
- executor: 'nx:run-commands',
194
+ executor: '@smoothbricks/nx-plugin:typescript-emit',
116
195
  cache: true,
117
196
  inputs: ['production', '^production', ...TYPESCRIPT_TOOLCHAIN_INPUTS, '{projectRoot}/tsconfig.lib.json'],
118
- outputs: ['{projectRoot}/dist/**/*.{js,cjs,mjs,jsx,d.ts,d.cts,d.mts}{,.map}'],
119
- dependsOn: ['^tsc-js'],
197
+ outputs: inferTypescriptOutputs(libTsconfigPath, packageJsonPath),
198
+ dependsOn: ['^*-js', ...(cargoWasmConfig ? ['cargo-wasm'] : [])],
120
199
  options: {
121
- command: 'ttsc -p tsconfig.lib.json --emit',
200
+ tsConfig: 'tsconfig.lib.json',
122
201
  cwd: projectRoot,
123
202
  },
124
203
  };
@@ -127,9 +206,9 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
127
206
  cache: true,
128
207
  inputs: ['production', '^production', ...TYPESCRIPT_TOOLCHAIN_INPUTS, '{projectRoot}/tsconfig.lib.json'],
129
208
  outputs: [],
130
- dependsOn: ['^tsc-js'],
209
+ dependsOn: ['^*-js', ...(cargoWasmConfig ? ['cargo-wasm'] : [])],
131
210
  options: {
132
- command: 'ttsc -p tsconfig.lib.json --noEmit',
211
+ command: 'tsc -p tsconfig.lib.json --noEmit',
133
212
  cwd: projectRoot,
134
213
  },
135
214
  };
@@ -143,7 +222,7 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
143
222
  inputs: ['default', '^production', ...TYPESCRIPT_TOOLCHAIN_INPUTS, '{projectRoot}/tsconfig.test.json'],
144
223
  dependsOn: ['typecheck'],
145
224
  options: {
146
- command: 'ttsc -p tsconfig.test.json --noEmit',
225
+ command: 'tsc -p tsconfig.test.json --noEmit',
147
226
  cwd: projectRoot,
148
227
  },
149
228
  };
@@ -151,7 +230,7 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
151
230
  executor: 'nx:run-commands',
152
231
  continuous: true,
153
232
  options: {
154
- command: 'ttsc -p tsconfig.test.json --noEmit --watch',
233
+ command: 'tsc -p tsconfig.test.json --noEmit --watch',
155
234
  cwd: projectRoot,
156
235
  },
157
236
  };
@@ -172,11 +251,27 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
172
251
  validationTargets.push('typecheck');
173
252
  }
174
253
 
254
+ if (inferCargoWasm && cargoWasmConfig) {
255
+ targets['cargo-wasm'] = createCargoWasmTarget(projectRoot, cargoWasmConfig);
256
+ }
257
+
258
+ if (napiConfig) {
259
+ Object.assign(targets, createNapiTargets(projectRoot, napiConfig));
260
+ if (
261
+ !('napi-test' in (packageJson.nx?.targets ?? {})) &&
262
+ existsSync(join(absoluteProjectRoot, 'src/native.test.ts'))
263
+ ) {
264
+ targets['napi-test'] = createNapiTestTarget(
265
+ projectRoot,
266
+ existsSync(join(absoluteProjectRoot, 'bunfig.napi-test.toml')),
267
+ );
268
+ }
269
+ }
270
+
175
271
  // Member crates get their targets from the workspace-root package.json,
176
272
  // never per-crate — one Nx project per Cargo workspace.
177
- const cargoTomlPath = join(absoluteProjectRoot, 'Cargo.toml');
178
- if (existsSync(cargoTomlPath) && CARGO_WORKSPACE_PATTERN.test(await readFile(cargoTomlPath, 'utf-8'))) {
179
- const declared = packageJson.nx?.targets ?? {};
273
+ if (isCargoWorkspace) {
274
+ const declared = declaredTargets;
180
275
  if (!('cargo-test' in declared)) {
181
276
  targets['cargo-test'] = createCargoTestTarget(projectRoot);
182
277
  }
@@ -193,7 +288,7 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
193
288
  };
194
289
  }
195
290
  validationTargets.push('cargo-lint');
196
- if (!('test' in declared) && typeof packageJson.scripts?.test !== 'string') {
291
+ if (!targets.test && !('test' in declared) && typeof packageJson.scripts?.test !== 'string') {
197
292
  // Execute Cargo directly: workspace targetDefaults may replace test.dependsOn.
198
293
  targets.test = createCargoTestTarget(projectRoot);
199
294
  }
@@ -231,7 +326,10 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
231
326
 
232
327
  if (targets['typecheck-tests']) {
233
328
  if (hasLibTsconfig) {
234
- targets['typecheck-tests'].dependsOn = ['typecheck'];
329
+ // Test configs may resolve the package's own `./index.js` through dist.
330
+ // Rebuild that current-project declaration output after clean, not only
331
+ // dependency-project outputs reached through typecheck.
332
+ targets['typecheck-tests'].dependsOn = ['tsc-js', 'typecheck'];
235
333
  } else if (targets.build) {
236
334
  targets['typecheck-tests'].dependsOn = ['build'];
237
335
  }
@@ -256,6 +354,234 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
256
354
  };
257
355
  }
258
356
 
357
+ interface ResolvedCargoWasmConfig {
358
+ libraryName: string;
359
+ manifestPath: string;
360
+ outputDirectory: string;
361
+ targets: Array<{ bindgenTarget: string; outputName: string }>;
362
+ }
363
+
364
+ const WASM_BINDGEN_OUTPUT_NAMES: Readonly<Record<string, string>> = {
365
+ bundler: 'bundler',
366
+ deno: 'deno',
367
+ module: 'module',
368
+ 'no-modules': 'no-modules',
369
+ nodejs: 'node',
370
+ web: 'web',
371
+ };
372
+
373
+ async function resolveCargoWasmConfig(
374
+ absoluteProjectRoot: string,
375
+ packageJsonPath: string,
376
+ ): Promise<ResolvedCargoWasmConfig | null> {
377
+ const manifestPaths = ['Cargo.toml'];
378
+ const cratesDirectory = join(absoluteProjectRoot, 'crates');
379
+ if (existsSync(cratesDirectory)) {
380
+ const crateEntries = await readdir(cratesDirectory, { withFileTypes: true });
381
+ for (const entry of crateEntries.sort((left, right) => left.name.localeCompare(right.name))) {
382
+ if (entry.isDirectory()) {
383
+ const manifestPath = posix.join('crates', entry.name, 'Cargo.toml');
384
+ if (existsSync(join(absoluteProjectRoot, manifestPath))) {
385
+ manifestPaths.push(manifestPath);
386
+ }
387
+ }
388
+ }
389
+ }
390
+
391
+ const resolved: ResolvedCargoWasmConfig[] = [];
392
+ for (const manifestPath of manifestPaths) {
393
+ const absoluteManifestPath = join(absoluteProjectRoot, manifestPath);
394
+ if (!existsSync(absoluteManifestPath)) {
395
+ continue;
396
+ }
397
+ const manifest: unknown = parseToml(await readFile(absoluteManifestPath, 'utf-8'));
398
+ const cargoPackage = isRecord(manifest) && isRecord(manifest.package) ? manifest.package : null;
399
+ const metadata = cargoPackage && isRecord(cargoPackage.metadata) ? cargoPackage.metadata : null;
400
+ const smoothbricks = metadata && isRecord(metadata.smoothbricks) ? metadata.smoothbricks : null;
401
+ const rawConfig = smoothbricks && isRecord(smoothbricks['wasm-bindgen']) ? smoothbricks['wasm-bindgen'] : null;
402
+ if (!rawConfig) {
403
+ continue;
404
+ }
405
+
406
+ const packageName = cargoPackage?.name;
407
+ if (typeof packageName !== 'string' || !/^[A-Za-z0-9_-]+$/.test(packageName)) {
408
+ throw new Error(`${packageJsonPath}: ${manifestPath} must declare a valid package.name for Wasm inference`);
409
+ }
410
+ const lib = isRecord(manifest) && isRecord(manifest.lib) ? manifest.lib : null;
411
+ const crateTypes = lib?.['crate-type'];
412
+ if (!Array.isArray(crateTypes) || !crateTypes.includes('cdylib')) {
413
+ throw new Error(`${packageJsonPath}: ${manifestPath} Wasm inference requires lib.crate-type to include cdylib`);
414
+ }
415
+ const rawLibraryName = lib?.name ?? packageName.replaceAll('-', '_');
416
+ if (typeof rawLibraryName !== 'string' || !/^[A-Za-z0-9_]+$/.test(rawLibraryName)) {
417
+ throw new Error(`${packageJsonPath}: ${manifestPath} must declare a valid Rust library name`);
418
+ }
419
+
420
+ const rawTargets = rawConfig.targets;
421
+ if (
422
+ !Array.isArray(rawTargets) ||
423
+ rawTargets.length === 0 ||
424
+ !rawTargets.every((target) => typeof target === 'string')
425
+ ) {
426
+ throw new Error(
427
+ `${packageJsonPath}: ${manifestPath} smoothbricks.wasm-bindgen.targets must be a non-empty string array`,
428
+ );
429
+ }
430
+ const bindgenTargets = [...new Set(rawTargets as string[])];
431
+ const targets = bindgenTargets.map((bindgenTarget) => {
432
+ const outputName = WASM_BINDGEN_OUTPUT_NAMES[bindgenTarget];
433
+ if (!outputName) {
434
+ throw new Error(`${packageJsonPath}: ${manifestPath} has unsupported wasm-bindgen target ${bindgenTarget}`);
435
+ }
436
+ return { bindgenTarget, outputName };
437
+ });
438
+
439
+ const rawOutputDirectory = rawConfig['out-dir'] ?? 'dist-wasm';
440
+ if (typeof rawOutputDirectory !== 'string' || !/^[A-Za-z0-9._/-]+$/.test(rawOutputDirectory)) {
441
+ throw new Error(
442
+ `${packageJsonPath}: ${manifestPath} smoothbricks.wasm-bindgen.out-dir must be a safe relative path`,
443
+ );
444
+ }
445
+ const outputDirectory = posix.normalize(rawOutputDirectory);
446
+ if (
447
+ outputDirectory === '.' ||
448
+ outputDirectory === '..' ||
449
+ outputDirectory.startsWith('../') ||
450
+ outputDirectory.startsWith('/')
451
+ ) {
452
+ throw new Error(
453
+ `${packageJsonPath}: ${manifestPath} smoothbricks.wasm-bindgen.out-dir must stay inside the project`,
454
+ );
455
+ }
456
+
457
+ resolved.push({ libraryName: rawLibraryName, manifestPath, outputDirectory, targets });
458
+ }
459
+
460
+ if (resolved.length > 1) {
461
+ throw new Error(`${packageJsonPath}: only one Cargo crate may declare smoothbricks.wasm-bindgen metadata`);
462
+ }
463
+ return resolved[0] ?? null;
464
+ }
465
+
466
+ interface ResolvedNapiConfig {
467
+ binaryName: string;
468
+ cargoPackage: string;
469
+ manifestPath: string;
470
+ targets: string[];
471
+ }
472
+
473
+ function inferTypescriptOutputs(tsconfigPath: string, packageJsonPath: string): string[] {
474
+ const tsconfig: unknown = readJsonFile(tsconfigPath);
475
+ const compilerOptions = isRecord(tsconfig) && isRecord(tsconfig.compilerOptions) ? tsconfig.compilerOptions : null;
476
+ const outDir = compilerOptions?.outDir;
477
+ if (typeof outDir !== 'string' || outDir.length === 0) {
478
+ return ['{projectRoot}/dist/**/*.{js,cjs,mjs,jsx,d.ts,d.cts,d.mts}{,.map}', '{projectRoot}/dist/**/*.tsbuildinfo'];
479
+ }
480
+
481
+ const normalized = posix.normalize(outDir.replaceAll('\\', '/'));
482
+ if (normalized === '.' || normalized === '..' || normalized.startsWith('../') || normalized.startsWith('/')) {
483
+ throw new Error(`${packageJsonPath}: tsconfig.lib.json compilerOptions.outDir must stay inside the project`);
484
+ }
485
+ return [`{projectRoot}/${normalized}`];
486
+ }
487
+
488
+ function resolveNapiConfig(
489
+ packageJson: PackageJson,
490
+ packageJsonPath: string,
491
+ absoluteProjectRoot: string,
492
+ isCargoWorkspace: boolean,
493
+ ): ResolvedNapiConfig | null {
494
+ if (!packageJson.napi) {
495
+ return null;
496
+ }
497
+ if (!isCargoWorkspace) {
498
+ throw new Error(`${packageJsonPath}: napi target inference requires a Cargo workspace beside package.json`);
499
+ }
500
+
501
+ const binaryName = packageJson.napi.binaryName;
502
+ if (typeof binaryName !== 'string' || !/^[A-Za-z0-9_-]+$/.test(binaryName)) {
503
+ throw new Error(`${packageJsonPath}: napi.binaryName must contain only letters, numbers, hyphens, or underscores`);
504
+ }
505
+ const rawTargets = packageJson.napi.targets;
506
+ if (
507
+ !Array.isArray(rawTargets) ||
508
+ rawTargets.length === 0 ||
509
+ !rawTargets.every((target) => typeof target === 'string')
510
+ ) {
511
+ throw new Error(`${packageJsonPath}: napi.targets must be a non-empty array of target triples`);
512
+ }
513
+ const targets = [...new Set(rawTargets as string[])];
514
+ for (const target of targets) {
515
+ if (!NAPI_TARGET_CONVENTIONS[target]) {
516
+ throw new Error(`${packageJsonPath}: unsupported inferred napi target ${target}`);
517
+ }
518
+ }
519
+
520
+ const cargoPackage = `${binaryName}-napi`;
521
+ const manifestPath = `crates/${cargoPackage}/Cargo.toml`;
522
+ if (!existsSync(join(absoluteProjectRoot, manifestPath))) {
523
+ throw new Error(`${packageJsonPath}: inferred N-API crate is missing at ${manifestPath}`);
524
+ }
525
+ return { binaryName, cargoPackage, manifestPath, targets };
526
+ }
527
+
528
+ function createNapiTargets(projectRoot: string, config: ResolvedNapiConfig): Record<string, TargetConfiguration> {
529
+ const commonCommand = `--manifest-path ${config.manifestPath} --package ${config.cargoPackage}`;
530
+ const targets: Record<string, TargetConfiguration> = {
531
+ 'cargo-napi': {
532
+ executor: 'nx:run-commands',
533
+ cache: true,
534
+ dependsOn: ['^build'],
535
+ inputs: NAPI_INPUTS,
536
+ outputs: ['{projectRoot}/dist/native/host'],
537
+ options: {
538
+ cwd: projectRoot,
539
+ command: `napi build --release --platform --no-js --dts ${config.binaryName}.napi.d.ts ${commonCommand} --output-dir dist/native/host`,
540
+ },
541
+ },
542
+ };
543
+
544
+ for (const triple of config.targets) {
545
+ const convention = NAPI_TARGET_CONVENTIONS[triple];
546
+ if (!convention) {
547
+ throw new Error(`Missing N-API target convention for ${triple}`);
548
+ }
549
+ const targetName = `napi-${convention.architecture}-${convention.targetFamily}`;
550
+ const outputDirectory = `dist/native/${convention.outputName}`;
551
+ const crossFlag = convention.useNapiCross ? ' --use-napi-cross' : '';
552
+ targets[targetName] = {
553
+ executor: 'nx:run-commands',
554
+ cache: true,
555
+ inputs: NAPI_INPUTS,
556
+ outputs: [`{projectRoot}/${outputDirectory}`],
557
+ options: {
558
+ cwd: projectRoot,
559
+ command: `napi build --release --platform --no-js --dts ${config.binaryName}.${convention.outputName}.d.ts --target ${triple}${crossFlag} ${commonCommand} --output-dir ${outputDirectory}`,
560
+ // @napi-rs recognizes Clang and supplies its downloaded GNU sysroot
561
+ // and toolchain flags. This keeps sccache enabled while avoiding the
562
+ // old bundled GCC, which rejects sccache's diagnostics-color flag.
563
+ ...(convention.useNapiCross ? { env: { TARGET_CC: 'clang', TARGET_CXX: 'clang++' } } : {}),
564
+ },
565
+ };
566
+ }
567
+ return targets;
568
+ }
569
+
570
+ function createNapiTestTarget(projectRoot: string, hasDedicatedBunfig: boolean): TargetConfiguration {
571
+ const configFlag = hasDedicatedBunfig ? ' --config=bunfig.napi-test.toml' : '';
572
+ return {
573
+ executor: '@smoothbricks/nx-plugin:bounded-exec',
574
+ cache: true,
575
+ dependsOn: ['cargo-test', 'cargo-napi', 'tsc-js', '^build', 'build'],
576
+ options: {
577
+ command: `bun${configFlag} test --timeout=30000 src/native.test.ts`,
578
+ cwd: projectRoot,
579
+ timeoutMs: 120000,
580
+ killAfterMs: 10000,
581
+ },
582
+ };
583
+ }
584
+
259
585
  async function readPackageJson(packageJsonPath: string): Promise<PackageJson> {
260
586
  const parsed: unknown = JSON.parse(await readFile(packageJsonPath, 'utf-8'));
261
587
  if (!isRecord(parsed)) {
@@ -264,6 +590,7 @@ async function readPackageJson(packageJsonPath: string): Promise<PackageJson> {
264
590
  const rawNx = isRecord(parsed.nx) ? parsed.nx : undefined;
265
591
  return {
266
592
  ...(typeof parsed.name === 'string' ? { name: parsed.name } : {}),
593
+ ...(isRecord(parsed.napi) ? { napi: parsed.napi } : {}),
267
594
  ...(isRecord(parsed.scripts) ? { scripts: parsed.scripts } : {}),
268
595
  ...(rawNx
269
596
  ? {
@@ -499,6 +499,23 @@ describe('per-package checkPackageTargets', () => {
499
499
  });
500
500
 
501
501
  describe('per-package applyPackageTargets', () => {
502
+ it('limits JavaScript output targets to dependency JavaScript outputs', () => {
503
+ const pkg: Record<string, unknown> = {
504
+ name: '@scope/lib',
505
+ dependencies: { '@scope/other': 'workspace:*' },
506
+ scripts: { compile: 'tsdown' },
507
+ nx: { name: 'lib' },
508
+ };
509
+ const workspaceNames = new Set(['@scope/lib', '@scope/other']);
510
+
511
+ expect(applyPackageTargets(pkg, 'packages/lib', workspaceNames)).toBe(true);
512
+ const nx = pkg.nx;
513
+ if (!isRecord(nx) || !isRecord(nx.targets) || !isRecord(nx.targets['tsdown-js'])) {
514
+ throw new Error('expected generated tsdown-js target');
515
+ }
516
+ expect(nx.targets['tsdown-js'].dependsOn).toEqual(['^*-js']);
517
+ });
518
+
502
519
  it('migrates colon targets and rewrites scripts', () => {
503
520
  const pkg: Record<string, unknown> = {
504
521
  name: '@scope/lib',
@@ -15,10 +15,12 @@ export { BUILD_OUTPUT_DEPENDENCIES, PLATFORM_TARGET_GLOBS } from './workspace-co
15
15
  export type { NxPolicyIssue };
16
16
 
17
17
  export interface ResolvedProjectTargets {
18
+ root?: string;
18
19
  targets: ReadonlySet<string>;
19
20
  buildDependsOn?: readonly string[];
20
21
  targetDependencies?: ReadonlyMap<string, readonly string[]>;
21
22
  targetExecutors?: ReadonlyMap<string, string>;
23
+ targetOptions?: ReadonlyMap<string, Readonly<Record<string, unknown>>>;
22
24
  targetScripts?: ReadonlyMap<string, string>;
23
25
  }
24
26
 
@@ -228,7 +230,9 @@ function isBuildOutputDependencyPattern(dependency: string): boolean {
228
230
  }
229
231
 
230
232
  function expectedTargetDependencies(targetName: string): string[] {
231
- return targetName === 'preview' ? ['build'] : ['^build'];
233
+ if (targetName === 'preview') return ['build'];
234
+ if (targetName.endsWith('-js')) return ['^*-js'];
235
+ return ['^build'];
232
236
  }
233
237
 
234
238
  function applyTargetDependencyPolicy(target: Record<string, unknown>, targetName: string): boolean {
@@ -114,6 +114,23 @@ describe('pure core: checkWorkspaceConfig', () => {
114
114
  expect(issues.some((i) => i.message.includes('must not use colon target names'))).toBe(true);
115
115
  });
116
116
 
117
+ it('rejects static test typecheck defaults that override per-project inference', () => {
118
+ const issues = checkWorkspaceConfig({
119
+ ...validNxJson(),
120
+ targetDefaults: {
121
+ ...validTargetDefaults(),
122
+ 'typecheck-tests': {
123
+ dependsOn: ['typecheck'],
124
+ options: { command: 'ttsc -p tsconfig.test.json --noEmit' },
125
+ },
126
+ },
127
+ });
128
+
129
+ expect(
130
+ issues.some((issue) => issue.message.includes('targetDefaults.typecheck-tests must not be configured')),
131
+ ).toBe(true);
132
+ });
133
+
117
134
  it('detects native TypeScript inference', () => {
118
135
  const issues = checkWorkspaceConfig({
119
136
  plugins: ['@nx/js/typescript', '@smoothbricks/nx-plugin'],
@@ -191,6 +208,22 @@ describe('pure core: applyWorkspaceConfig', () => {
191
208
  expect(expectRecord(nxJson.targetDefaults)['build:wasm']).toBeUndefined();
192
209
  });
193
210
 
211
+ it('removes static test typecheck defaults so inference owns clean-output prerequisites', () => {
212
+ const nxJson = {
213
+ ...validNxJson(),
214
+ targetDefaults: {
215
+ ...validTargetDefaults(),
216
+ 'typecheck-tests': {
217
+ dependsOn: ['typecheck'],
218
+ options: { command: 'ttsc -p tsconfig.test.json --noEmit' },
219
+ },
220
+ },
221
+ };
222
+
223
+ expect(applyWorkspaceConfig(nxJson)).toBe(true);
224
+ expect(expectRecord(nxJson.targetDefaults)['typecheck-tests']).toBeUndefined();
225
+ });
226
+
194
227
  it('fixes imprecise production inputs', () => {
195
228
  const nxJson: Record<string, unknown> = {
196
229
  plugins: validPlugins(),
@@ -324,7 +357,13 @@ describe('filesystem: checkWorkspaceConfigPolicy / applyWorkspaceConfigPolicy',
324
357
  try {
325
358
  await writeJsonFile(join(root, 'nx.json'), {
326
359
  plugins: [],
327
- targetDefaults: { build: { cache: false } },
360
+ targetDefaults: {
361
+ build: { cache: false },
362
+ 'typecheck-tests': {
363
+ dependsOn: ['typecheck'],
364
+ options: { command: 'ttsc -p tsconfig.test.json --noEmit' },
365
+ },
366
+ },
328
367
  namedInputs: validNamedInputs(),
329
368
  });
330
369
 
@@ -339,6 +378,7 @@ describe('filesystem: checkWorkspaceConfigPolicy / applyWorkspaceConfigPolicy',
339
378
  const pluginNames = readPluginNames(nxJson.plugins);
340
379
  expect(pluginNames).not.toContain('@nx/js/typescript');
341
380
  expect(pluginNames).toContain('@smoothbricks/nx-plugin');
381
+ expect(expectRecord(nxJson.targetDefaults)['typecheck-tests']).toBeUndefined();
342
382
 
343
383
  // No issues after fix
344
384
  expect(checkWorkspaceConfigPolicy(root)).toEqual([]);
@@ -28,6 +28,7 @@ const nxJsTypescriptPlugin = '@nx/js/typescript';
28
28
  const smoothBricksNxPlugin = '@smoothbricks/nx-plugin';
29
29
  const cleanOutputsExecutor = '@smoothbricks/nx-plugin:clean-outputs';
30
30
  const expectedSharedGlobalsNamedInput = ['{workspaceRoot}/.github/workflows/ci.yml'];
31
+ const inferredTestTypecheckTarget = 'typecheck-tests';
31
32
  const defaultProductionNamedInput = [
32
33
  '{projectRoot}/src/**/*',
33
34
  '{projectRoot}/package.json',
@@ -55,6 +56,14 @@ export function checkWorkspaceConfig(nxJson: Record<string, unknown>): NxPolicyI
55
56
  'Nx CLI syntax already uses project:target:configuration, so smoo Nx target names must be unambiguous tool-output names.',
56
57
  });
57
58
  }
59
+ if (targetName === inferredTestTypecheckTarget) {
60
+ issues.push({
61
+ path: 'nx.json',
62
+ message:
63
+ `targetDefaults.${inferredTestTypecheckTarget} must not be configured. ` +
64
+ 'Per-project inference selects current library or build outputs before test typechecking.',
65
+ });
66
+ }
58
67
  }
59
68
  }
60
69
 
@@ -94,7 +103,7 @@ export function checkWorkspaceConfig(nxJson: Record<string, unknown>): NxPolicyI
94
103
  * Mutates in place, returns whether anything changed.
95
104
  */
96
105
  export function applyWorkspaceConfig(nxJson: Record<string, unknown>): boolean {
97
- let changed = removeColonTargetDefaults(nxJson);
106
+ let changed = removeDisallowedTargetDefaults(nxJson);
98
107
  changed = applyBuildTargetDefault(nxJson) || changed;
99
108
  changed = applyCleanTargetDefault(nxJson) || changed;
100
109
  changed = applyNamedInputDefaults(nxJson) || changed;
@@ -272,14 +281,14 @@ function applyNamedInputDefaults(nxJson: Record<string, unknown>): boolean {
272
281
  return changed;
273
282
  }
274
283
 
275
- function removeColonTargetDefaults(nxJson: Record<string, unknown>): boolean {
284
+ function removeDisallowedTargetDefaults(nxJson: Record<string, unknown>): boolean {
276
285
  const targetDefaults = recordProperty(nxJson, 'targetDefaults');
277
286
  if (!targetDefaults) {
278
287
  return false;
279
288
  }
280
289
  let changed = false;
281
290
  for (const targetName of Object.keys(targetDefaults)) {
282
- if (targetName.includes(':')) {
291
+ if (targetName.includes(':') || targetName === inferredTestTypecheckTarget) {
283
292
  delete targetDefaults[targetName];
284
293
  changed = true;
285
294
  }