@smoothbricks/nx-plugin 0.4.1 → 0.4.2

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.
@@ -1 +1 @@
1
- {"version":3,"file":"workspace-config-policy.d.ts","sourceRoot":"","sources":["../src/workspace-config-policy.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,0BAA0B,CAAC;AAGrD,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,eAAO,MAAM,yBAAyB,YACpC,MAAM,EACN,OAAO,EACP,QAAQ,EACR,OAAO,EACP,WAAW,EACX,UAAU,EACV,QAAQ,EACR,OAAO,EACP,QAAQ,CACA,CAAC;AAEX,eAAO,MAAM,2BAA2B,YAAI,SAAS,EAAE,OAAO,CAAU,CAAC;AACzE,eAAO,MAAM,2BAA2B,YAAI,SAAS,CAAU,CAAC;AAChE,eAAO,MAAM,qBAAqB,0CAA4E,CAAC;AAgB/G;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,aAAa,EAAE,CAuDrF;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAa7E;AAED;;GAEG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,IAAI,GAAG,aAAa,EAAE,CAKpE;AAED;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAU5D;AAED;;GAEG;AACH,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,MAAM,GAAG,aAAa,EAAE,CAYxE;AAED;;GAEG;AACH,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAWhE"}
1
+ {"version":3,"file":"workspace-config-policy.d.ts","sourceRoot":"","sources":["../src/workspace-config-policy.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,0BAA0B,CAAC;AAGrD,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,eAAO,MAAM,yBAAyB,YACpC,MAAM,EACN,OAAO,EACP,QAAQ,EACR,OAAO,EACP,WAAW,EACX,UAAU,EACV,QAAQ,EACR,OAAO,EACP,QAAQ,CACA,CAAC;AAEX,eAAO,MAAM,2BAA2B,YAAI,SAAS,EAAE,OAAO,CAAU,CAAC;AACzE,eAAO,MAAM,2BAA2B,YAAI,SAAS,CAAU,CAAC;AAChE,eAAO,MAAM,qBAAqB,0CAA4E,CAAC;AAgB/G;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,aAAa,EAAE,CA4DrF;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAe7E;AAED;;GAEG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,IAAI,GAAG,aAAa,EAAE,CAKpE;AAED;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAU5D;AAED;;GAEG;AACH,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,MAAM,GAAG,aAAa,EAAE,CAYxE;AAED;;GAEG;AACH,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAWhE"}
@@ -55,6 +55,9 @@ export function checkWorkspaceConfig(nxJson) {
55
55
  }
56
56
  // Build target default
57
57
  validateBuildTargetDefault(nxJson, 'nx.json', issues);
58
+ // Test target default: dependsOn is inferred per project (cargo-test vs ^build/build)
59
+ validateTestTargetDefault(nxJson, 'nx.json', issues);
60
+ validateLintTargetDefault(nxJson, 'nx.json', issues);
58
61
  // Clean target default
59
62
  validateCleanTargetDefault(nxJson, 'nx.json', issues);
60
63
  // Named input defaults
@@ -84,6 +87,8 @@ export function checkWorkspaceConfig(nxJson) {
84
87
  export function applyWorkspaceConfig(nxJson) {
85
88
  let changed = removeDisallowedTargetDefaults(nxJson);
86
89
  changed = applyBuildTargetDefault(nxJson) || changed;
90
+ changed = applyTestTargetDefault(nxJson) || changed;
91
+ changed = applyLintTargetDefault(nxJson) || changed;
87
92
  changed = applyCleanTargetDefault(nxJson) || changed;
88
93
  changed = applyNamedInputDefaults(nxJson) || changed;
89
94
  const currentPlugins = Array.isArray(nxJson.plugins) ? nxJson.plugins : [];
@@ -243,6 +248,55 @@ function applyBuildTargetDefault(nxJson) {
243
248
  }
244
249
  return changed;
245
250
  }
251
+ function validateTestTargetDefault(nxJson, nxJsonPath, issues) {
252
+ const targetDefaults = recordProperty(nxJson, 'targetDefaults');
253
+ const test = targetDefaults ? recordProperty(targetDefaults, 'test') : null;
254
+ // Same clobber as targetDefaults.build.dependsOn: Nx replaces an inferred
255
+ // list rather than merging, so a workspace-wide [^build, build] unwires
256
+ // cargo-test from every Rust test aggregate. Cache stays allowed.
257
+ if (test !== null && 'dependsOn' in test) {
258
+ issues.push({
259
+ path: nxJsonPath,
260
+ message: 'targetDefaults.test.dependsOn must not be set; @smoothbricks/nx-plugin infers the test aggregate',
261
+ });
262
+ }
263
+ }
264
+ function applyTestTargetDefault(nxJson) {
265
+ const targetDefaults = recordProperty(nxJson, 'targetDefaults');
266
+ const test = targetDefaults ? recordProperty(targetDefaults, 'test') : null;
267
+ if (test === null || !('dependsOn' in test)) {
268
+ return false;
269
+ }
270
+ delete test.dependsOn;
271
+ return true;
272
+ }
273
+ const inferredLintProperties = ['executor', 'options', 'dependsOn', 'outputs', 'inputs'];
274
+ function validateLintTargetDefault(nxJson, nxJsonPath, issues) {
275
+ const defaults = recordProperty(nxJson, 'targetDefaults');
276
+ const lint = defaults ? recordProperty(defaults, 'lint') : null;
277
+ for (const property of inferredLintProperties) {
278
+ if (lint !== null && property in lint) {
279
+ issues.push({
280
+ path: nxJsonPath,
281
+ message: `targetDefaults.lint.${property} must not be set; @smoothbricks/nx-plugin infers lint from project sources`,
282
+ });
283
+ }
284
+ }
285
+ }
286
+ function applyLintTargetDefault(nxJson) {
287
+ const defaults = recordProperty(nxJson, 'targetDefaults');
288
+ const lint = defaults ? recordProperty(defaults, 'lint') : null;
289
+ if (lint === null)
290
+ return false;
291
+ let changed = false;
292
+ for (const property of inferredLintProperties) {
293
+ if (property in lint) {
294
+ delete lint[property];
295
+ changed = true;
296
+ }
297
+ }
298
+ return changed;
299
+ }
246
300
  function applyCleanTargetDefault(nxJson) {
247
301
  const targetDefaults = getOrCreateRecord(nxJson, 'targetDefaults');
248
302
  const clean = getOrCreateRecord(targetDefaults, 'clean');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smoothbricks/nx-plugin",
3
- "version": "0.4.1",
3
+ "version": "0.4.2",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "main": "./loader.js",
@@ -55,7 +55,8 @@
55
55
  }
56
56
  },
57
57
  "bin": {
58
- "smoo-nx-exec": "./dist/bin/smoo-nx-exec.js"
58
+ "smoo-nx-exec": "./dist/bin/smoo-nx-exec.js",
59
+ "smoo-nx-cargo-hash": "./dist/bin/smoo-nx-cargo-hash.js"
59
60
  },
60
61
  "generators": "./generators.json",
61
62
  "executors": "./executors.json",
@@ -103,6 +104,11 @@
103
104
  "@nx/js": "latest",
104
105
  "nx": "latest",
105
106
  "smol-toml": "^1.6.1",
106
- "tslib": "^2.8.1"
107
+ "tslib": "^2.8.1",
108
+ "typia": "14.0.2"
109
+ },
110
+ "devDependencies": {
111
+ "@smoothbricks/lmao": "0.3.8",
112
+ "@smoothbricks/validation": "0.1.6"
107
113
  }
108
114
  }
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env node
2
+ import { resolve } from 'node:path';
3
+ import { hashCargoPathInputs } from '../cargo-source-hash.js';
4
+
5
+ const args = process.argv.slice(2);
6
+ if (args.length > 1) {
7
+ process.stderr.write('usage: smoo-nx-cargo-hash [Cargo.toml]\n');
8
+ process.exit(2);
9
+ }
10
+ try {
11
+ process.stdout.write(`${await hashCargoPathInputs(resolve(args[0] ?? 'Cargo.toml'), process.cwd())}\n`);
12
+ } catch (error) {
13
+ process.stderr.write(`smoo-nx-cargo-hash: ${error instanceof Error ? error.message : String(error)}\n`);
14
+ process.stderr.write(
15
+ 'Restore the declared Cargo path dependencies and locked offline dependency cache, then rerun the Nx target.\n',
16
+ );
17
+ process.exitCode = 1;
18
+ }
@@ -0,0 +1,51 @@
1
+ import { expect, it } from 'bun:test';
2
+ import { execFileSync } from 'node:child_process';
3
+ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { dirname, join } from 'node:path';
6
+ import { hashCargoPathInputs } from './cargo-source-hash.js';
7
+
8
+ it.each(['app', '.'])('invalidates transitive and inherited Cargo inputs with Nx rooted at %s', async (nxDirectory) => {
9
+ const root = await mkdtemp(join(tmpdir(), 'cargo-hash-'));
10
+ const app = join(root, 'app');
11
+ const manifest = join(app, 'Cargo.toml');
12
+ const nxRoot = join(root, nxDirectory);
13
+ async function put(path: string, text: string): Promise<void> {
14
+ const file = join(root, path);
15
+ await mkdir(dirname(file), { recursive: true });
16
+ await writeFile(file, text);
17
+ }
18
+ try {
19
+ await put(
20
+ 'app/Cargo.toml',
21
+ '[package]\nname="app"\nversion="0.1.0"\nedition="2021"\n[dependencies]\nbridge={path="../external/bridge"}\n[workspace]\n',
22
+ );
23
+ await put('app/src/lib.rs', 'pub fn run() {}\n');
24
+ await put(
25
+ 'external/Cargo.toml',
26
+ '[workspace]\nmembers=["bridge","leaf"]\nresolver="2"\n[workspace.package]\nedition="2021"\n',
27
+ );
28
+ await put(
29
+ 'external/bridge/Cargo.toml',
30
+ '[package]\nname="bridge"\nversion="0.1.0"\nedition.workspace=true\n[dependencies]\nleaf={path="../leaf"}\n',
31
+ );
32
+ await put('external/bridge/src/lib.rs', 'pub fn bridge() {}\n');
33
+ await put('external/leaf/Cargo.toml', '[package]\nname="leaf"\nversion="0.1.0"\nedition.workspace=true\n');
34
+ await put('external/leaf/src/lib.rs', 'pub fn leaf() -> u8 { 1 }\n');
35
+ execFileSync('cargo', ['generate-lockfile', '--offline', '--manifest-path', manifest], { stdio: 'pipe' });
36
+ const initial = await hashCargoPathInputs(manifest, nxRoot);
37
+ await put('external/leaf/src/lib.rs', 'pub fn leaf() -> u8 { 2 }\n');
38
+ const sourceChanged = await hashCargoPathInputs(manifest, nxRoot);
39
+ expect(sourceChanged).not.toBe(initial);
40
+ await put(
41
+ 'external/Cargo.toml',
42
+ '[workspace]\nmembers=["bridge","leaf"]\nresolver="2"\n[workspace.package]\nedition="2024"\n',
43
+ );
44
+ const inheritedChanged = await hashCargoPathInputs(manifest, nxRoot);
45
+ expect(inheritedChanged).not.toBe(sourceChanged);
46
+ await put('external/leaf/target/noise.rs', 'uncompiled build output');
47
+ expect(await hashCargoPathInputs(manifest, nxRoot)).toBe(inheritedChanged);
48
+ } finally {
49
+ await rm(root, { recursive: true, force: true });
50
+ }
51
+ });
@@ -0,0 +1,138 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { statSync } from 'node:fs';
4
+ import { lstat, readdir, readFile, readlink, realpath } from 'node:fs/promises';
5
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
6
+ import typia from 'typia';
7
+
8
+ interface CargoMetadata {
9
+ packages: {
10
+ source: string | null;
11
+ manifest_path: string;
12
+ targets: { src_path: string }[];
13
+ }[];
14
+ workspace_root: string;
15
+ }
16
+
17
+ const parseMetadata = typia.json.createAssertParse<CargoMetadata>();
18
+ const ignoredDirectories = new Set([
19
+ 'target',
20
+ '.git',
21
+ 'node_modules',
22
+ '.cache',
23
+ '.cowshed',
24
+ '.fseventsd',
25
+ '.TemporaryItems',
26
+ '.Trashes',
27
+ '.Spotlight-V100',
28
+ '.DocumentRevisions-V100',
29
+ ]);
30
+ const ancestorInputs = ['Cargo.toml', '.cargo/config', '.cargo/config.toml'];
31
+
32
+ /**
33
+ * Cargo owns resolution, including workspace inheritance, target dependencies,
34
+ * patches, and transitive path dependencies. A locked offline query observes
35
+ * that graph without fetching dependencies or changing the lockfile. Git and
36
+ * registry packages are immutable inputs already identified by Cargo.lock.
37
+ *
38
+ * This covers Rust sources and Cargo configuration, matching the plugin's
39
+ * in-workspace Rust inputs. Build scripts' other data/environment inputs remain
40
+ * explicit Nx inputs, just as they are for in-workspace crates.
41
+ */
42
+ export async function hashCargoPathInputs(manifestPath: string, workspaceRoot: string): Promise<string> {
43
+ const root = await realpath(workspaceRoot);
44
+ const metadata = parseMetadata(
45
+ execFileSync(
46
+ 'cargo',
47
+ ['metadata', '--format-version', '1', '--locked', '--offline', '--manifest-path', resolve(manifestPath)],
48
+ { cwd: root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, stdio: ['ignore', 'pipe', 'inherit'] },
49
+ ),
50
+ );
51
+ const cargoRoot = await realpath(metadata.workspace_root);
52
+ const directories = new Set<string>();
53
+ const files = new Set<string>();
54
+ const ancestors = new Set<string>();
55
+ const links = new Map<string, string>();
56
+ for (const pkg of metadata.packages) {
57
+ if (pkg.source !== null) continue;
58
+ const manifest = await realpath(pkg.manifest_path);
59
+ const directory = dirname(manifest);
60
+ const fromRoot = relative(root, directory);
61
+ const fromCargo = relative(cargoRoot, directory);
62
+ if (
63
+ fromRoot !== '..' &&
64
+ !fromRoot.startsWith(`..${sep}`) &&
65
+ !isAbsolute(fromRoot) &&
66
+ fromCargo !== '..' &&
67
+ !fromCargo.startsWith(`..${sep}`) &&
68
+ !isAbsolute(fromCargo) &&
69
+ !fromRoot.split(sep).includes('node_modules')
70
+ )
71
+ continue;
72
+ directories.add(directory);
73
+ files.add(manifest);
74
+ // Cargo resolves explicit package.workspace ownership as well as ancestor
75
+ // workspaces. Metadata's workspace_root describes only the invoking root.
76
+ const governingManifest = execFileSync(
77
+ 'cargo',
78
+ ['locate-project', '--workspace', '--manifest-path', manifest, '--message-format', 'plain'],
79
+ { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'] },
80
+ ).trim();
81
+ files.add(await realpath(governingManifest));
82
+ for (const target of pkg.targets) files.add(await realpath(target.src_path));
83
+ // An external member can inherit edition, lint policy, dependencies and
84
+ // profiles from a workspace above its package directory. Those manifests
85
+ // are not descendants of the source roots returned by Cargo metadata.
86
+ for (let ancestor = dirname(directory); !ancestors.has(ancestor); ancestor = dirname(ancestor)) {
87
+ ancestors.add(ancestor);
88
+ for (const name of ancestorInputs) {
89
+ const file = join(ancestor, name);
90
+ if (statSync(file, { throwIfNoEntry: false })?.isFile()) files.add(await realpath(file));
91
+ }
92
+ }
93
+ }
94
+
95
+ // Overlapping packages (a facade root plus its child crates) share one walk.
96
+ const visited = new Set<string>();
97
+ async function walk(directory: string): Promise<void> {
98
+ const canonical = await realpath(directory);
99
+ if (visited.has(canonical)) return;
100
+ visited.add(canonical);
101
+ for (const entry of await readdir(canonical, { withFileTypes: true })) {
102
+ if (ignoredDirectories.has(entry.name)) continue;
103
+ const path = join(canonical, entry.name);
104
+ if (entry.isSymbolicLink()) links.set(path, await readlink(path));
105
+ const info = entry.isSymbolicLink() ? await lstat(await realpath(path)) : entry;
106
+ if (info.isDirectory()) {
107
+ await walk(path);
108
+ } else if (
109
+ info.isFile() &&
110
+ (entry.name.endsWith('.rs') ||
111
+ entry.name === 'Cargo.toml' ||
112
+ (canonical.endsWith(`${sep}.cargo`) && (entry.name === 'config' || entry.name === 'config.toml')))
113
+ ) {
114
+ files.add(await realpath(path));
115
+ }
116
+ }
117
+ }
118
+ for (const directory of directories) await walk(directory);
119
+ const hash = createHash('sha256');
120
+ hash.update('cargo-path-inputs-v1\0');
121
+ for (const [path, target] of [...links].sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
122
+ hash.update(relative(root, path));
123
+ hash.update('\0symlink\0');
124
+ hash.update(target);
125
+ hash.update('\0');
126
+ }
127
+ for (const file of [...files].sort()) {
128
+ const bytes = await readFile(file);
129
+ // Both names and bytes matter: moving a module can change resolution even
130
+ // when its contents are unchanged. Length framing makes boundaries unique.
131
+ hash.update(relative(root, file));
132
+ hash.update('\0');
133
+ hash.update(String(bytes.length));
134
+ hash.update('\0');
135
+ hash.update(bytes);
136
+ }
137
+ return hash.digest('hex');
138
+ }