@smoothbricks/nx-plugin 0.2.5 → 0.3.1

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.
package/src/index.ts CHANGED
@@ -11,6 +11,50 @@ const RESERVED_ZIG_STEPS = new Set(['all', 'clean', 'install', 'test']);
11
11
  const ZIG_STEP_PATTERN = /\bb\.step\(\s*["']([^"']+)["']\s*,/g;
12
12
  const VALID_ZIG_STEP_NAME = /^[A-Za-z0-9_-]+$/;
13
13
  const BUILD_OUTPUT_TARGET_PATTERN = /-(?:js|web|html|css|ios|android|native|napi|bun|wasm)$/;
14
+ const TYPESCRIPT_TOOLCHAIN_INPUTS = [
15
+ '{workspaceRoot}/package.json',
16
+ '{workspaceRoot}/bun.lock',
17
+ '{workspaceRoot}/patches/**/*',
18
+ '{workspaceRoot}/tsconfig.base.json',
19
+ ];
20
+
21
+ // Cargo workspace inference: a package.json sitting next to a Cargo.toml that
22
+ // declares [workspace] gets direct cargo-test/test targets, cargo-lint feeding
23
+ // the lint aggregate, mutation (cargo-mutants), bench, and — per cdylib member
24
+ // crate whose package name ends in `-wasm` — a cargo-wasm build producing
25
+ // dist/<crate>.wasm. Explicit nx.targets entries in the package.json always win
26
+ // over inference.
27
+ const CARGO_WORKSPACE_PATTERN = /^\s*\[workspace\]/m;
28
+ const CARGO_MEMBERS_PATTERN = /^\s*members\s*=\s*\[([^\]]*)\]/m;
29
+ const CARGO_MEMBER_ENTRY_PATTERN = /["']([^"']+)["']/g;
30
+ const CARGO_PACKAGE_NAME_PATTERN = /^\s*name\s*=\s*["']([^"']+)["']/m;
31
+ const CARGO_WASM_CRATE_NAME_PATTERN = /-wasm$/;
32
+ const CARGO_CDYLIB_CRATE_TYPE_PATTERN = /^\s*crate-type\s*=\s*\[[^\]]*["']cdylib["']/m;
33
+ const CARGO_WASM_RELEASE_PROFILE_PATTERN = /^\s*\[profile\.wasm-release\]/m;
34
+ const CARGO_INPUTS = [
35
+ '{projectRoot}/**/*.rs',
36
+ '{projectRoot}/**/Cargo.toml',
37
+ '{projectRoot}/Cargo.lock',
38
+ '{projectRoot}/.cargo/config.toml',
39
+ '!{projectRoot}/target/**',
40
+ ];
41
+
42
+ function createCargoTestTarget(projectRoot: string): TargetConfiguration {
43
+ return {
44
+ executor: '@smoothbricks/nx-plugin:bounded-exec',
45
+ cache: true,
46
+ inputs: CARGO_INPUTS,
47
+ options: {
48
+ command: 'cargo test --workspace',
49
+ cwd: projectRoot,
50
+ timeoutMs: 600000,
51
+ killAfterMs: 10000,
52
+ },
53
+ configurations: {
54
+ production: { command: 'cargo test --workspace --release' },
55
+ },
56
+ };
57
+ }
14
58
 
15
59
  export const createNodesV2: CreateNodesV2 = [
16
60
  '**/package.json',
@@ -39,8 +83,10 @@ export const createNodesV2: CreateNodesV2 = [
39
83
  export default { createNodesV2 };
40
84
 
41
85
  interface PackageJson {
86
+ name?: string;
42
87
  scripts?: Record<string, unknown>;
43
88
  nx?: {
89
+ name?: string;
44
90
  targets?: Record<string, unknown>;
45
91
  };
46
92
  }
@@ -54,13 +100,45 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
54
100
  const hasLibTsconfig = existsSync(join(absoluteProjectRoot, 'tsconfig.lib.json'));
55
101
  let hasBuildOutputTarget = hasLibTsconfig || hasPackageLocalBuildOutputTarget(packageJson);
56
102
 
103
+ if (hasLibTsconfig) {
104
+ // Official Nx target inference is disabled because its compiler surface only
105
+ // supports tsc/tsgo. Smoo owns the complete transformer-aware ttsc targets.
106
+ targets['tsc-js'] = {
107
+ executor: 'nx:run-commands',
108
+ cache: true,
109
+ inputs: ['production', '^production', ...TYPESCRIPT_TOOLCHAIN_INPUTS, '{projectRoot}/tsconfig.lib.json'],
110
+ outputs: [
111
+ '{projectRoot}/dist/**/*.{js,cjs,mjs,jsx,d.ts,d.cts,d.mts}{,.map}',
112
+ '{projectRoot}/dist/.build.tsbuildinfo',
113
+ ],
114
+ dependsOn: ['^tsc-js'],
115
+ options: {
116
+ command: 'ttsc -p tsconfig.lib.json --emit',
117
+ cwd: projectRoot,
118
+ },
119
+ };
120
+ targets.typecheck = {
121
+ executor: 'nx:run-commands',
122
+ cache: true,
123
+ inputs: ['production', '^production', ...TYPESCRIPT_TOOLCHAIN_INPUTS, '{projectRoot}/tsconfig.lib.json'],
124
+ outputs: [],
125
+ dependsOn: ['^tsc-js'],
126
+ options: {
127
+ command: 'ttsc -p tsconfig.lib.json --noEmit',
128
+ cwd: projectRoot,
129
+ },
130
+ };
131
+ }
132
+
57
133
  const hasTestTsconfig = existsSync(join(absoluteProjectRoot, 'tsconfig.test.json'));
58
134
  if (hasTestTsconfig) {
59
135
  targets['typecheck-tests'] = {
60
136
  executor: 'nx:run-commands',
61
137
  cache: true,
138
+ inputs: ['default', '^production', ...TYPESCRIPT_TOOLCHAIN_INPUTS, '{projectRoot}/tsconfig.test.json'],
139
+ dependsOn: ['typecheck'],
62
140
  options: {
63
- command: 'tsc --noEmit -p tsconfig.test.json',
141
+ command: 'ttsc -p tsconfig.test.json --noEmit',
64
142
  cwd: projectRoot,
65
143
  },
66
144
  };
@@ -68,7 +146,7 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
68
146
  executor: 'nx:run-commands',
69
147
  continuous: true,
70
148
  options: {
71
- command: 'tsc --noEmit -p tsconfig.test.json --watch',
149
+ command: 'ttsc -p tsconfig.test.json --noEmit --watch',
72
150
  cwd: projectRoot,
73
151
  },
74
152
  };
@@ -89,6 +167,73 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
89
167
  validationTargets.push('typecheck');
90
168
  }
91
169
 
170
+ const cargo = await readCargoWorkspace(absoluteProjectRoot);
171
+ if (cargo) {
172
+ const declared = packageJson.nx?.targets ?? {};
173
+ if (!('cargo-test' in declared)) {
174
+ targets['cargo-test'] = createCargoTestTarget(projectRoot);
175
+ }
176
+ if (!('cargo-lint' in declared)) {
177
+ targets['cargo-lint'] = {
178
+ executor: 'nx:run-commands',
179
+ cache: true,
180
+ inputs: CARGO_INPUTS,
181
+ options: {
182
+ commands: ['cargo fmt --all --check', 'cargo clippy --workspace --all-targets -- -D warnings'],
183
+ cwd: projectRoot,
184
+ parallel: false,
185
+ },
186
+ };
187
+ }
188
+ validationTargets.push('cargo-lint');
189
+ if (!('test' in declared) && typeof packageJson.scripts?.test !== 'string') {
190
+ // Execute Cargo directly: workspace targetDefaults may replace test.dependsOn.
191
+ targets.test = createCargoTestTarget(projectRoot);
192
+ }
193
+ if (!('mutation' in declared)) {
194
+ // Mutation runs are minutes-to-hours: never cached, never part of build/lint.
195
+ // CI runs these per-PR via `cargo mutants --in-diff` (see mutants.toml docs).
196
+ targets.mutation = {
197
+ executor: 'nx:run-commands',
198
+ cache: false,
199
+ options: { command: 'cargo mutants --workspace', cwd: projectRoot },
200
+ };
201
+ }
202
+ if (!('bench' in declared)) {
203
+ targets.bench = {
204
+ executor: 'nx:run-commands',
205
+ cache: false,
206
+ options: { command: 'cargo bench --workspace', cwd: projectRoot },
207
+ };
208
+ }
209
+ if (cargo.wasmCrates.length > 0 && !('cargo-wasm' in declared)) {
210
+ const profile = cargo.hasWasmReleaseProfile ? 'wasm-release' : 'release';
211
+ const buildAndCopy = (crate: string, profileName: string | null) => {
212
+ const artifact = crate.replace(/-/g, '_');
213
+ const profileFlag = profileName === null ? '' : ` --profile ${profileName}`;
214
+ const outputDirectory = profileName ?? 'debug';
215
+ return `cargo build${profileFlag} --target wasm32-unknown-unknown -p ${crate} && mkdir -p dist && cp target/wasm32-unknown-unknown/${outputDirectory}/${artifact}.wasm dist/${artifact}.wasm`;
216
+ };
217
+ targets['cargo-wasm'] = {
218
+ executor: 'nx:run-commands',
219
+ cache: true,
220
+ inputs: CARGO_INPUTS,
221
+ outputs: ['{projectRoot}/dist/**/*.wasm'],
222
+ options: {
223
+ commands: cargo.wasmCrates.map((crate) => buildAndCopy(crate, profile)),
224
+ cwd: projectRoot,
225
+ parallel: false,
226
+ },
227
+ configurations: {
228
+ development: {
229
+ commands: cargo.wasmCrates.map((crate) => buildAndCopy(crate, null)),
230
+ },
231
+ },
232
+ };
233
+ hasBuildOutputTarget = true;
234
+ }
235
+ }
236
+
92
237
  const zigSteps = await readZigSteps(absoluteProjectRoot, projectRoot);
93
238
  for (const step of zigSteps) {
94
239
  const targetName = `zig-${step}`;
@@ -134,21 +279,41 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
134
279
 
135
280
  if (validationTargets.length > 0) {
136
281
  targets.lint = {
137
- executor: 'nx:noop',
138
282
  cache: true,
139
283
  dependsOn: validationTargets,
140
284
  };
141
285
  }
142
286
 
287
+ const projectName = packageJson.nx?.name ?? packageJson.name;
288
+ if (typeof projectName !== 'string' || projectName.length === 0) {
289
+ throw new Error(`${packageJsonPath} must declare a non-empty package or nx project name`);
290
+ }
291
+
143
292
  return {
144
293
  projects: {
145
- [projectRoot]: { targets },
294
+ [projectRoot]: { name: projectName, targets },
146
295
  },
147
296
  };
148
297
  }
149
298
 
150
299
  async function readPackageJson(packageJsonPath: string): Promise<PackageJson> {
151
- return JSON.parse(await readFile(packageJsonPath, 'utf-8')) as PackageJson;
300
+ const parsed: unknown = JSON.parse(await readFile(packageJsonPath, 'utf-8'));
301
+ if (!isRecord(parsed)) {
302
+ throw new Error(`${packageJsonPath} must contain a JSON object`);
303
+ }
304
+ const rawNx = isRecord(parsed.nx) ? parsed.nx : undefined;
305
+ return {
306
+ ...(typeof parsed.name === 'string' ? { name: parsed.name } : {}),
307
+ ...(isRecord(parsed.scripts) ? { scripts: parsed.scripts } : {}),
308
+ ...(rawNx
309
+ ? {
310
+ nx: {
311
+ ...(typeof rawNx.name === 'string' ? { name: rawNx.name } : {}),
312
+ ...(isRecord(rawNx.targets) ? { targets: rawNx.targets } : {}),
313
+ },
314
+ }
315
+ : {}),
316
+ };
152
317
  }
153
318
 
154
319
  function inferTestWatchCommand(packageJson: PackageJson): string | null {
@@ -211,6 +376,46 @@ function hasPackageLocalBuildOutputTarget(packageJson: PackageJson): boolean {
211
376
  return Object.keys(targets).some((targetName) => BUILD_OUTPUT_TARGET_PATTERN.test(targetName));
212
377
  }
213
378
 
379
+ interface CargoWorkspace {
380
+ wasmCrates: string[];
381
+ hasWasmReleaseProfile: boolean;
382
+ }
383
+
384
+ async function readCargoWorkspace(absoluteProjectRoot: string): Promise<CargoWorkspace | null> {
385
+ const cargoTomlPath = join(absoluteProjectRoot, 'Cargo.toml');
386
+ if (!existsSync(cargoTomlPath)) {
387
+ return null;
388
+ }
389
+
390
+ const cargoToml = await readFile(cargoTomlPath, 'utf-8');
391
+ if (!CARGO_WORKSPACE_PATTERN.test(cargoToml)) {
392
+ // Member crates get their targets from the workspace-root package.json,
393
+ // never per-crate — one Nx project per Cargo workspace.
394
+ return null;
395
+ }
396
+
397
+ const wasmCrates: string[] = [];
398
+ const membersList = CARGO_MEMBERS_PATTERN.exec(cargoToml)?.[1] ?? '';
399
+ for (const match of membersList.matchAll(CARGO_MEMBER_ENTRY_PATTERN)) {
400
+ const memberTomlPath = join(absoluteProjectRoot, match[1], 'Cargo.toml');
401
+ if (!existsSync(memberTomlPath)) {
402
+ continue;
403
+ }
404
+ const memberToml = await readFile(memberTomlPath, 'utf-8');
405
+ const name = CARGO_PACKAGE_NAME_PATTERN.exec(memberToml)?.[1];
406
+ if (
407
+ name &&
408
+ CARGO_WASM_CRATE_NAME_PATTERN.test(name) &&
409
+ CARGO_CDYLIB_CRATE_TYPE_PATTERN.test(memberToml) &&
410
+ !wasmCrates.includes(name)
411
+ ) {
412
+ wasmCrates.push(name);
413
+ }
414
+ }
415
+
416
+ return { wasmCrates, hasWasmReleaseProfile: CARGO_WASM_RELEASE_PROFILE_PATTERN.test(cargoToml) };
417
+ }
418
+
214
419
  async function readZigSteps(absoluteProjectRoot: string, projectRoot: string): Promise<string[]> {
215
420
  const buildZigPath = join(absoluteProjectRoot, 'build.zig');
216
421
 
@@ -542,7 +542,11 @@ describe('per-package applyPackageTargets', () => {
542
542
  };
543
543
  const workspaceNames = new Set(['@scope/lib', '@scope/other']);
544
544
  expect(applyPackageTargets(pkg, 'packages/lib', workspaceNames)).toBe(true);
545
- const targets = (pkg.nx as Record<string, unknown>).targets as Record<string, unknown>;
545
+ const nx = pkg.nx;
546
+ if (!isRecord(nx) || !isRecord(nx.targets)) {
547
+ throw new Error('expected generated Nx targets');
548
+ }
549
+ const targets = nx.targets;
546
550
  expect(targets['build:ts']).toBeUndefined();
547
551
  expect(targets['tsc-js']).toBeDefined();
548
552
  });
@@ -918,3 +922,7 @@ async function writeJson(path: string, value: unknown): Promise<void> {
918
922
  await mkdir(dirname(path), { recursive: true });
919
923
  await writeFile(path, `${JSON.stringify(value, null, 2)}\n`);
920
924
  }
925
+
926
+ function isRecord(value: unknown): value is Record<string, unknown> {
927
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
928
+ }
@@ -122,30 +122,30 @@ describe('pure core: applyReleaseConfig', () => {
122
122
  const nxJson: Record<string, unknown> = {};
123
123
  expect(applyReleaseConfig(nxJson)).toBe(true);
124
124
 
125
- const release = nxJson.release as Record<string, unknown>;
125
+ const release = expectRecord(nxJson.release);
126
126
  expect(release.projectsRelationship).toBe('independent');
127
- const version = release.version as Record<string, unknown>;
127
+ const version = expectRecord(release.version);
128
128
  expect(version.specifierSource).toBe('conventional-commits');
129
129
  expect(version.currentVersionResolver).toBe('git-tag');
130
130
  expect(version.fallbackCurrentVersionResolver).toBe('disk');
131
131
  expect(version.versionActions).toBe(SMOO_NX_VERSION_ACTIONS);
132
132
  expect(version.preVersionCommand).toBeUndefined();
133
- const releaseTag = release.releaseTag as Record<string, unknown>;
133
+ const releaseTag = expectRecord(release.releaseTag);
134
134
  expect(releaseTag.pattern).toBe(SMOO_NX_RELEASE_TAG_PATTERN);
135
- const changelog = release.changelog as Record<string, unknown>;
135
+ const changelog = expectRecord(release.changelog);
136
136
  expect(changelog.automaticFromRef).toBe(true);
137
137
  expect(changelog.workspaceChangelog).toBe(false);
138
- const projectChangelogs = changelog.projectChangelogs as Record<string, unknown>;
138
+ const projectChangelogs = expectRecord(changelog.projectChangelogs);
139
139
  expect(projectChangelogs.createRelease).toBe(false);
140
140
  expect(projectChangelogs.file).toBe(false);
141
- const renderOptions = projectChangelogs.renderOptions as Record<string, unknown>;
141
+ const renderOptions = expectRecord(projectChangelogs.renderOptions);
142
142
  expect(renderOptions.authors).toBe(true);
143
143
  expect(renderOptions.applyUsernameToAuthors).toBe(true);
144
144
  });
145
145
 
146
146
  it('removes preVersionCommand', () => {
147
147
  const nxJson = validReleaseNxJson();
148
- const version = (nxJson.release as Record<string, unknown>).version as Record<string, unknown>;
148
+ const version = expectRecord(expectRecord(nxJson.release).version);
149
149
  version.preVersionCommand = 'nx run-many -t build';
150
150
  expect(applyReleaseConfig(nxJson)).toBe(true);
151
151
  expect(version.preVersionCommand).toBeUndefined();
@@ -195,9 +195,9 @@ describe('Tree: applyReleaseConfigTree', () => {
195
195
  expect(applyReleaseConfigTree(tree)).toBe(true);
196
196
 
197
197
  const nxJson = readJson(tree, 'nx.json');
198
- const release = nxJson.release as Record<string, unknown>;
198
+ const release = expectRecord(nxJson.release);
199
199
  expect(release.projectsRelationship).toBe('independent');
200
- const version = release.version as Record<string, unknown>;
200
+ const version = expectRecord(release.version);
201
201
  expect(version.specifierSource).toBe('conventional-commits');
202
202
 
203
203
  // Tree version now passes check
@@ -214,14 +214,14 @@ describe('Tree: applyReleaseConfigTree', () => {
214
214
  it('removes preVersionCommand via tree', () => {
215
215
  const tree = createTreeWithEmptyWorkspace();
216
216
  const nxJson = validReleaseNxJson();
217
- const version = (nxJson.release as Record<string, unknown>).version as Record<string, unknown>;
217
+ const version = expectRecord(expectRecord(nxJson.release).version);
218
218
  version.preVersionCommand = 'nx run-many -t build';
219
219
  writeJson(tree, 'nx.json', nxJson);
220
220
 
221
221
  expect(applyReleaseConfigTree(tree)).toBe(true);
222
222
 
223
223
  const fixed = readJson(tree, 'nx.json');
224
- const fixedVersion = (fixed.release as Record<string, unknown>).version as Record<string, unknown>;
224
+ const fixedVersion = expectRecord(expectRecord(fixed.release).version);
225
225
  expect(fixedVersion.preVersionCommand).toBeUndefined();
226
226
 
227
227
  expect(checkReleaseConfigTree(tree)).toEqual([]);
@@ -281,3 +281,14 @@ async function writeJsonFile(path: string, value: unknown): Promise<void> {
281
281
  await mkdir(dirname(path), { recursive: true });
282
282
  await writeFile(path, `${JSON.stringify(value, null, 2)}\n`);
283
283
  }
284
+
285
+ function expectRecord(value: unknown): Record<string, unknown> {
286
+ if (!isRecord(value)) {
287
+ throw new Error('expected object');
288
+ }
289
+ return value;
290
+ }
291
+
292
+ function isRecord(value: unknown): value is Record<string, unknown> {
293
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
294
+ }