@smoothbricks/nx-plugin 0.3.4 → 0.3.5

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 +278 -28
  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 +157 -17
  28. package/src/index.ts +356 -30
  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 {
@@ -90,6 +152,7 @@ export default { createNodesV2 };
90
152
 
91
153
  interface PackageJson {
92
154
  name?: string;
155
+ napi?: Record<string, unknown>;
93
156
  scripts?: Record<string, unknown>;
94
157
  nx?: {
95
158
  name?: string;
@@ -103,22 +166,37 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
103
166
  const packageJson = await readPackageJson(join(workspaceRoot, packageJsonPath));
104
167
  const targets: Record<string, TargetConfiguration> = {};
105
168
  const validationTargets: string[] = [];
106
- const hasLibTsconfig = existsSync(join(absoluteProjectRoot, 'tsconfig.lib.json'));
169
+ const libTsconfigPath = join(absoluteProjectRoot, 'tsconfig.lib.json');
170
+ const hasLibTsconfig = existsSync(libTsconfigPath);
171
+ const cargoTomlPath = join(absoluteProjectRoot, 'Cargo.toml');
172
+ const isCargoWorkspace =
173
+ existsSync(cargoTomlPath) && CARGO_WORKSPACE_PATTERN.test(await readFile(cargoTomlPath, 'utf-8'));
174
+ const napiConfig = resolveNapiConfig(packageJson, packageJsonPath, absoluteProjectRoot, isCargoWorkspace);
175
+ const declaredTargets = packageJson.nx?.targets ?? {};
176
+ const cargoWasmConfig = await resolveCargoWasmConfig(absoluteProjectRoot, packageJsonPath);
177
+ const inferCargoWasm = cargoWasmConfig !== null && !('cargo-wasm' in declaredTargets);
107
178
  const packageLocalBuildOutputs = classifyPackageLocalBuildOutputs(packageJson);
108
- const hasOrdinaryBuildOutputTarget = hasLibTsconfig || packageLocalBuildOutputs.ordinary;
179
+ const hasOrdinaryBuildOutputTarget =
180
+ hasLibTsconfig || napiConfig !== null || cargoWasmConfig !== null || packageLocalBuildOutputs.ordinary;
109
181
  const hasAnyBuildOutputTarget = hasOrdinaryBuildOutputTarget || packageLocalBuildOutputs.platform;
110
182
 
111
183
  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.
184
+ // Dependency packages may publish bundled entries that raw tsc does not produce.
185
+ // Build every JavaScript output lane before resolving package exports, without pulling
186
+ // unrelated Wasm, N-API, native, or web outputs onto the compiler critical path.
187
+ //
188
+ // ttsc transforms the source program before declaration emit, so typia's
189
+ // generated implementation identifiers are not valid declaration inputs.
190
+ // The executor gives ttsc a JS-only overlay and emits declarations from the
191
+ // original project with native tsc.
114
192
  targets['tsc-js'] = {
115
- executor: 'nx:run-commands',
193
+ executor: '@smoothbricks/nx-plugin:typescript-emit',
116
194
  cache: true,
117
195
  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'],
196
+ outputs: inferTypescriptOutputs(libTsconfigPath, packageJsonPath),
197
+ dependsOn: ['^*-js', ...(cargoWasmConfig ? ['cargo-wasm'] : [])],
120
198
  options: {
121
- command: 'ttsc -p tsconfig.lib.json --emit',
199
+ tsConfig: 'tsconfig.lib.json',
122
200
  cwd: projectRoot,
123
201
  },
124
202
  };
@@ -127,9 +205,9 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
127
205
  cache: true,
128
206
  inputs: ['production', '^production', ...TYPESCRIPT_TOOLCHAIN_INPUTS, '{projectRoot}/tsconfig.lib.json'],
129
207
  outputs: [],
130
- dependsOn: ['^tsc-js'],
208
+ dependsOn: ['^*-js', ...(cargoWasmConfig ? ['cargo-wasm'] : [])],
131
209
  options: {
132
- command: 'ttsc -p tsconfig.lib.json --noEmit',
210
+ command: 'tsc -p tsconfig.lib.json --noEmit',
133
211
  cwd: projectRoot,
134
212
  },
135
213
  };
@@ -143,7 +221,7 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
143
221
  inputs: ['default', '^production', ...TYPESCRIPT_TOOLCHAIN_INPUTS, '{projectRoot}/tsconfig.test.json'],
144
222
  dependsOn: ['typecheck'],
145
223
  options: {
146
- command: 'ttsc -p tsconfig.test.json --noEmit',
224
+ command: 'tsc -p tsconfig.test.json --noEmit',
147
225
  cwd: projectRoot,
148
226
  },
149
227
  };
@@ -151,7 +229,7 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
151
229
  executor: 'nx:run-commands',
152
230
  continuous: true,
153
231
  options: {
154
- command: 'ttsc -p tsconfig.test.json --noEmit --watch',
232
+ command: 'tsc -p tsconfig.test.json --noEmit --watch',
155
233
  cwd: projectRoot,
156
234
  },
157
235
  };
@@ -172,11 +250,27 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
172
250
  validationTargets.push('typecheck');
173
251
  }
174
252
 
253
+ if (inferCargoWasm && cargoWasmConfig) {
254
+ targets['cargo-wasm'] = createCargoWasmTarget(projectRoot, cargoWasmConfig);
255
+ }
256
+
257
+ if (napiConfig) {
258
+ Object.assign(targets, createNapiTargets(projectRoot, napiConfig));
259
+ if (
260
+ !('napi-test' in (packageJson.nx?.targets ?? {})) &&
261
+ existsSync(join(absoluteProjectRoot, 'src/native.test.ts'))
262
+ ) {
263
+ targets['napi-test'] = createNapiTestTarget(
264
+ projectRoot,
265
+ existsSync(join(absoluteProjectRoot, 'bunfig.napi-test.toml')),
266
+ );
267
+ }
268
+ }
269
+
175
270
  // Member crates get their targets from the workspace-root package.json,
176
271
  // 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 ?? {};
272
+ if (isCargoWorkspace) {
273
+ const declared = declaredTargets;
180
274
  if (!('cargo-test' in declared)) {
181
275
  targets['cargo-test'] = createCargoTestTarget(projectRoot);
182
276
  }
@@ -193,7 +287,7 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
193
287
  };
194
288
  }
195
289
  validationTargets.push('cargo-lint');
196
- if (!('test' in declared) && typeof packageJson.scripts?.test !== 'string') {
290
+ if (!targets.test && !('test' in declared) && typeof packageJson.scripts?.test !== 'string') {
197
291
  // Execute Cargo directly: workspace targetDefaults may replace test.dependsOn.
198
292
  targets.test = createCargoTestTarget(projectRoot);
199
293
  }
@@ -231,7 +325,10 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
231
325
 
232
326
  if (targets['typecheck-tests']) {
233
327
  if (hasLibTsconfig) {
234
- targets['typecheck-tests'].dependsOn = ['typecheck'];
328
+ // Test configs may resolve the package's own `./index.js` through dist.
329
+ // Rebuild that current-project declaration output after clean, not only
330
+ // dependency-project outputs reached through typecheck.
331
+ targets['typecheck-tests'].dependsOn = ['tsc-js', 'typecheck'];
235
332
  } else if (targets.build) {
236
333
  targets['typecheck-tests'].dependsOn = ['build'];
237
334
  }
@@ -256,6 +353,234 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
256
353
  };
257
354
  }
258
355
 
356
+ interface ResolvedCargoWasmConfig {
357
+ libraryName: string;
358
+ manifestPath: string;
359
+ outputDirectory: string;
360
+ targets: Array<{ bindgenTarget: string; outputName: string }>;
361
+ }
362
+
363
+ const WASM_BINDGEN_OUTPUT_NAMES: Readonly<Record<string, string>> = {
364
+ bundler: 'bundler',
365
+ deno: 'deno',
366
+ module: 'module',
367
+ 'no-modules': 'no-modules',
368
+ nodejs: 'node',
369
+ web: 'web',
370
+ };
371
+
372
+ async function resolveCargoWasmConfig(
373
+ absoluteProjectRoot: string,
374
+ packageJsonPath: string,
375
+ ): Promise<ResolvedCargoWasmConfig | null> {
376
+ const manifestPaths = ['Cargo.toml'];
377
+ const cratesDirectory = join(absoluteProjectRoot, 'crates');
378
+ if (existsSync(cratesDirectory)) {
379
+ const crateEntries = await readdir(cratesDirectory, { withFileTypes: true });
380
+ for (const entry of crateEntries.sort((left, right) => left.name.localeCompare(right.name))) {
381
+ if (entry.isDirectory()) {
382
+ const manifestPath = posix.join('crates', entry.name, 'Cargo.toml');
383
+ if (existsSync(join(absoluteProjectRoot, manifestPath))) {
384
+ manifestPaths.push(manifestPath);
385
+ }
386
+ }
387
+ }
388
+ }
389
+
390
+ const resolved: ResolvedCargoWasmConfig[] = [];
391
+ for (const manifestPath of manifestPaths) {
392
+ const absoluteManifestPath = join(absoluteProjectRoot, manifestPath);
393
+ if (!existsSync(absoluteManifestPath)) {
394
+ continue;
395
+ }
396
+ const manifest: unknown = parseToml(await readFile(absoluteManifestPath, 'utf-8'));
397
+ const cargoPackage = isRecord(manifest) && isRecord(manifest.package) ? manifest.package : null;
398
+ const metadata = cargoPackage && isRecord(cargoPackage.metadata) ? cargoPackage.metadata : null;
399
+ const smoothbricks = metadata && isRecord(metadata.smoothbricks) ? metadata.smoothbricks : null;
400
+ const rawConfig = smoothbricks && isRecord(smoothbricks['wasm-bindgen']) ? smoothbricks['wasm-bindgen'] : null;
401
+ if (!rawConfig) {
402
+ continue;
403
+ }
404
+
405
+ const packageName = cargoPackage?.name;
406
+ if (typeof packageName !== 'string' || !/^[A-Za-z0-9_-]+$/.test(packageName)) {
407
+ throw new Error(`${packageJsonPath}: ${manifestPath} must declare a valid package.name for Wasm inference`);
408
+ }
409
+ const lib = isRecord(manifest) && isRecord(manifest.lib) ? manifest.lib : null;
410
+ const crateTypes = lib?.['crate-type'];
411
+ if (!Array.isArray(crateTypes) || !crateTypes.includes('cdylib')) {
412
+ throw new Error(`${packageJsonPath}: ${manifestPath} Wasm inference requires lib.crate-type to include cdylib`);
413
+ }
414
+ const rawLibraryName = lib?.name ?? packageName.replaceAll('-', '_');
415
+ if (typeof rawLibraryName !== 'string' || !/^[A-Za-z0-9_]+$/.test(rawLibraryName)) {
416
+ throw new Error(`${packageJsonPath}: ${manifestPath} must declare a valid Rust library name`);
417
+ }
418
+
419
+ const rawTargets = rawConfig.targets;
420
+ if (
421
+ !Array.isArray(rawTargets) ||
422
+ rawTargets.length === 0 ||
423
+ !rawTargets.every((target) => typeof target === 'string')
424
+ ) {
425
+ throw new Error(
426
+ `${packageJsonPath}: ${manifestPath} smoothbricks.wasm-bindgen.targets must be a non-empty string array`,
427
+ );
428
+ }
429
+ const bindgenTargets = [...new Set(rawTargets as string[])];
430
+ const targets = bindgenTargets.map((bindgenTarget) => {
431
+ const outputName = WASM_BINDGEN_OUTPUT_NAMES[bindgenTarget];
432
+ if (!outputName) {
433
+ throw new Error(`${packageJsonPath}: ${manifestPath} has unsupported wasm-bindgen target ${bindgenTarget}`);
434
+ }
435
+ return { bindgenTarget, outputName };
436
+ });
437
+
438
+ const rawOutputDirectory = rawConfig['out-dir'] ?? 'dist-wasm';
439
+ if (typeof rawOutputDirectory !== 'string' || !/^[A-Za-z0-9._/-]+$/.test(rawOutputDirectory)) {
440
+ throw new Error(
441
+ `${packageJsonPath}: ${manifestPath} smoothbricks.wasm-bindgen.out-dir must be a safe relative path`,
442
+ );
443
+ }
444
+ const outputDirectory = posix.normalize(rawOutputDirectory);
445
+ if (
446
+ outputDirectory === '.' ||
447
+ outputDirectory === '..' ||
448
+ outputDirectory.startsWith('../') ||
449
+ outputDirectory.startsWith('/')
450
+ ) {
451
+ throw new Error(
452
+ `${packageJsonPath}: ${manifestPath} smoothbricks.wasm-bindgen.out-dir must stay inside the project`,
453
+ );
454
+ }
455
+
456
+ resolved.push({ libraryName: rawLibraryName, manifestPath, outputDirectory, targets });
457
+ }
458
+
459
+ if (resolved.length > 1) {
460
+ throw new Error(`${packageJsonPath}: only one Cargo crate may declare smoothbricks.wasm-bindgen metadata`);
461
+ }
462
+ return resolved[0] ?? null;
463
+ }
464
+
465
+ interface ResolvedNapiConfig {
466
+ binaryName: string;
467
+ cargoPackage: string;
468
+ manifestPath: string;
469
+ targets: string[];
470
+ }
471
+
472
+ function inferTypescriptOutputs(tsconfigPath: string, packageJsonPath: string): string[] {
473
+ const tsconfig: unknown = readJsonFile(tsconfigPath);
474
+ const compilerOptions = isRecord(tsconfig) && isRecord(tsconfig.compilerOptions) ? tsconfig.compilerOptions : null;
475
+ const outDir = compilerOptions?.outDir;
476
+ if (typeof outDir !== 'string' || outDir.length === 0) {
477
+ return ['{projectRoot}/dist/**/*.{js,cjs,mjs,jsx,d.ts,d.cts,d.mts}{,.map}', '{projectRoot}/dist/**/*.tsbuildinfo'];
478
+ }
479
+
480
+ const normalized = posix.normalize(outDir.replaceAll('\\', '/'));
481
+ if (normalized === '.' || normalized === '..' || normalized.startsWith('../') || normalized.startsWith('/')) {
482
+ throw new Error(`${packageJsonPath}: tsconfig.lib.json compilerOptions.outDir must stay inside the project`);
483
+ }
484
+ return [`{projectRoot}/${normalized}`];
485
+ }
486
+
487
+ function resolveNapiConfig(
488
+ packageJson: PackageJson,
489
+ packageJsonPath: string,
490
+ absoluteProjectRoot: string,
491
+ isCargoWorkspace: boolean,
492
+ ): ResolvedNapiConfig | null {
493
+ if (!packageJson.napi) {
494
+ return null;
495
+ }
496
+ if (!isCargoWorkspace) {
497
+ throw new Error(`${packageJsonPath}: napi target inference requires a Cargo workspace beside package.json`);
498
+ }
499
+
500
+ const binaryName = packageJson.napi.binaryName;
501
+ if (typeof binaryName !== 'string' || !/^[A-Za-z0-9_-]+$/.test(binaryName)) {
502
+ throw new Error(`${packageJsonPath}: napi.binaryName must contain only letters, numbers, hyphens, or underscores`);
503
+ }
504
+ const rawTargets = packageJson.napi.targets;
505
+ if (
506
+ !Array.isArray(rawTargets) ||
507
+ rawTargets.length === 0 ||
508
+ !rawTargets.every((target) => typeof target === 'string')
509
+ ) {
510
+ throw new Error(`${packageJsonPath}: napi.targets must be a non-empty array of target triples`);
511
+ }
512
+ const targets = [...new Set(rawTargets as string[])];
513
+ for (const target of targets) {
514
+ if (!NAPI_TARGET_CONVENTIONS[target]) {
515
+ throw new Error(`${packageJsonPath}: unsupported inferred napi target ${target}`);
516
+ }
517
+ }
518
+
519
+ const cargoPackage = `${binaryName}-napi`;
520
+ const manifestPath = `crates/${cargoPackage}/Cargo.toml`;
521
+ if (!existsSync(join(absoluteProjectRoot, manifestPath))) {
522
+ throw new Error(`${packageJsonPath}: inferred N-API crate is missing at ${manifestPath}`);
523
+ }
524
+ return { binaryName, cargoPackage, manifestPath, targets };
525
+ }
526
+
527
+ function createNapiTargets(projectRoot: string, config: ResolvedNapiConfig): Record<string, TargetConfiguration> {
528
+ const commonCommand = `--manifest-path ${config.manifestPath} --package ${config.cargoPackage}`;
529
+ const targets: Record<string, TargetConfiguration> = {
530
+ 'cargo-napi': {
531
+ executor: 'nx:run-commands',
532
+ cache: true,
533
+ dependsOn: ['^build'],
534
+ inputs: NAPI_INPUTS,
535
+ outputs: ['{projectRoot}/dist/native/host'],
536
+ options: {
537
+ cwd: projectRoot,
538
+ command: `napi build --release --platform --no-js --dts ${config.binaryName}.napi.d.ts ${commonCommand} --output-dir dist/native/host`,
539
+ },
540
+ },
541
+ };
542
+
543
+ for (const triple of config.targets) {
544
+ const convention = NAPI_TARGET_CONVENTIONS[triple];
545
+ if (!convention) {
546
+ throw new Error(`Missing N-API target convention for ${triple}`);
547
+ }
548
+ const targetName = `napi-${convention.architecture}-${convention.targetFamily}`;
549
+ const outputDirectory = `dist/native/${convention.outputName}`;
550
+ const crossFlag = convention.useNapiCross ? ' --use-napi-cross' : '';
551
+ targets[targetName] = {
552
+ executor: 'nx:run-commands',
553
+ cache: true,
554
+ inputs: NAPI_INPUTS,
555
+ outputs: [`{projectRoot}/${outputDirectory}`],
556
+ options: {
557
+ cwd: projectRoot,
558
+ command: `napi build --release --platform --no-js --dts ${config.binaryName}.${convention.outputName}.d.ts --target ${triple}${crossFlag} ${commonCommand} --output-dir ${outputDirectory}`,
559
+ // @napi-rs recognizes Clang and supplies its downloaded GNU sysroot
560
+ // and toolchain flags. This keeps sccache enabled while avoiding the
561
+ // old bundled GCC, which rejects sccache's diagnostics-color flag.
562
+ ...(convention.useNapiCross ? { env: { TARGET_CC: 'clang', TARGET_CXX: 'clang++' } } : {}),
563
+ },
564
+ };
565
+ }
566
+ return targets;
567
+ }
568
+
569
+ function createNapiTestTarget(projectRoot: string, hasDedicatedBunfig: boolean): TargetConfiguration {
570
+ const configFlag = hasDedicatedBunfig ? ' --config=bunfig.napi-test.toml' : '';
571
+ return {
572
+ executor: '@smoothbricks/nx-plugin:bounded-exec',
573
+ cache: true,
574
+ dependsOn: ['cargo-test', 'cargo-napi', 'tsc-js', '^build', 'build'],
575
+ options: {
576
+ command: `bun${configFlag} test --timeout=30000 src/native.test.ts`,
577
+ cwd: projectRoot,
578
+ timeoutMs: 120000,
579
+ killAfterMs: 10000,
580
+ },
581
+ };
582
+ }
583
+
259
584
  async function readPackageJson(packageJsonPath: string): Promise<PackageJson> {
260
585
  const parsed: unknown = JSON.parse(await readFile(packageJsonPath, 'utf-8'));
261
586
  if (!isRecord(parsed)) {
@@ -264,6 +589,7 @@ async function readPackageJson(packageJsonPath: string): Promise<PackageJson> {
264
589
  const rawNx = isRecord(parsed.nx) ? parsed.nx : undefined;
265
590
  return {
266
591
  ...(typeof parsed.name === 'string' ? { name: parsed.name } : {}),
592
+ ...(isRecord(parsed.napi) ? { napi: parsed.napi } : {}),
267
593
  ...(isRecord(parsed.scripts) ? { scripts: parsed.scripts } : {}),
268
594
  ...(rawNx
269
595
  ? {
@@ -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
  }