@smoothbricks/nx-plugin 0.3.13 → 0.4.0

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/README.md CHANGED
@@ -14,6 +14,21 @@ with `tsconfig.lib.json` receives transformer-aware `tsc-js` and native `typeche
14
14
  - Cargo workspace targets from a neighboring workspace-root `Cargo.toml`
15
15
  - aggregate `build` and `lint` targets
16
16
 
17
+ ## Cargo Workspace Layouts
18
+
19
+ The plugin supports both Cargo placements without moving crate sources:
20
+
21
+ - **Package-rooted:** `packages/example/package.json` sits beside `packages/example/Cargo.toml`. The package owns the
22
+ whole Cargo target set, and commands keep `cwd: packages/example`.
23
+ - **Repository-rooted:** the repository `package.json` sits beside the one root `Cargo.toml`, whose members may live
24
+ below several `packages/*` projects. The root Nx project owns the single `cargo-fetch`, `cargo-test-compile`,
25
+ `cargo-lint`, mutation, bench, and sweep targets. Each crate's `cargo-test-<crate>` target and declared Wasm/N-API
26
+ output targets belong to the deepest Nx project directory containing that crate. All Cargo commands run from the
27
+ repository root, select the crate with `-p <crate>`, and share the root `target/`; cross-project dependencies keep the
28
+ runners in one serialization chain. Member and exclude patterns may use `*` and `?` in any path segment (for example,
29
+ `packages/*/crates/*`); unsupported patterns and member patterns that match no directory fail graph construction
30
+ instead of silently omitting crates.
31
+
17
32
  ## Nx Target Naming
18
33
 
19
34
  Target names are `{tool}-{output}` names. Use names like `tsc-js`, `tsdown-js`, and `cargo-wasm`; `build` and `lint` are
@@ -21,9 +36,9 @@ aggregates.
21
36
 
22
37
  Concrete targets come from concrete files:
23
38
 
24
- - `tsc-js` emits transformed JavaScript through a temporary JS-only `ttsc` config, then emits declarations and
25
- declaration maps from the original project with native `tsc`. Direct project references and every cached output lane
26
- are preserved.
39
+ - `tsc-js` emits transformed JavaScript through a temporary JS-only `ttsc` config, restores execute bits on outputs
40
+ declared by `package.json#bin`, then emits declarations and declaration maps from the original project with native
41
+ `tsc`. Direct project references and every cached output lane are preserved.
27
42
  - `typecheck` is inferred from `tsconfig.lib.json` and runs native `tsc -p tsconfig.lib.json --noEmit`.
28
43
  - `typecheck-tests` is inferred from `tsconfig.test.json` and runs `tsc -p tsconfig.test.json --noEmit`. It first
29
44
  rebuilds the current package's `tsc-js` output (or its non-TypeScript `build`) so self-imports resolve after `clean`.
@@ -32,13 +47,14 @@ Concrete targets come from concrete files:
32
47
  the corresponding watch command and makes it depend on `typecheck-tests`.
33
48
  - A workspace-root `Cargo.toml` provides `cargo-test`, `test`, `cargo-lint`, `mutation`, and `bench`.
34
49
  `cargo-test-compile` is one workspace `cargo test --no-run`. Each member crate gets a cached `cargo-test-<package>`
35
- run (`cargo nextest run --workspace -E 'package(<crate>)'`, 30s per-test timeout like `bun test --timeout=30000`)
36
- whose inputs are that crate and its path deps, so unchanged crates are skipped. The filterset, rather than
37
- `--package <crate>`, is what makes the run cheap: `--package` re-resolves features for that crate alone, which
38
- fingerprints differently from the workspace build `cargo-test-compile` already paid for and rebuilds it inside the
39
- bounded window. Those runs are chained so two cargos never share `target/`; `napi-debug` sits on that chain after
40
- compile. Clippy uses `--target-dir target/cargo-lint` so lint can overlap tests. Workspaces with `cdylib` member
41
- crates also receive the cacheable `cargo-wasm` output target.
50
+ run (30s per-test timeout like `bun test --timeout=30000`) whose inputs are that crate and its path deps, so unchanged
51
+ crates are skipped. Package-rooted workspaces use `cargo nextest run --workspace -E 'package(<crate>)'`;
52
+ repository-rooted workspaces additionally use `-p <crate>` to bind the runner to the project that owns the crate.
53
+ Per-crate runners accept an empty nextest selection because a valid workspace member may have no tests and a hash
54
+ partition may legitimately be empty. Those runs are chained across project boundaries so two cargos never share
55
+ `target/`; `napi-debug` sits on that chain after compile. Clippy uses `--target-dir target/cargo-lint` so lint can
56
+ overlap tests. A crate declaring `[package.metadata.smoothbricks.wasm-bindgen]` also receives the cacheable
57
+ `cargo-wasm` output target in its owning project.
42
58
  - A crate whose suite outgrows one bounded window declares `[package.metadata.smoothbricks.test] shards = N`, and gets
43
59
  `cargo-test-<package>-shard1..N`, each running `--partition hash:i/N` with the full bound. nextest assigns a test to a
44
60
  shard by hashing its name, so the shards stay an exact partition of the crate as tests and test binaries are added,
@@ -107,6 +123,41 @@ mode. Smoo validation creates/requires this config for test runners that do not
107
123
  against, but the package root `tsconfig.json` should not reference `./tsconfig.test.json`. Nx runs test typechecking
108
124
  through the inferred `typecheck-tests` target, not through `tsc --build`.
109
125
 
126
+ ## Ensure a Target Before Executing Its Binary
127
+
128
+ `ensureBuilt` checks a target and its task dependencies against Nx's local cache and the daemon's recorded output
129
+ hashes. A full hit returns without running tasks or printing output. A miss runs the task graph through Nx's in-process
130
+ runner with streaming output; only a workspace with the daemon disabled falls back to its checkout-local `nx` CLI.
131
+
132
+ ```typescript
133
+ import { ensureBuilt } from '@smoothbricks/nx-plugin/ensure-built';
134
+
135
+ const result = await ensureBuilt({ target: 'my-cli:build', cwd: workspaceRoot });
136
+ if (result.disposition === 'failed') {
137
+ if (result.signal !== null) {
138
+ process.kill(process.pid, result.signal);
139
+ }
140
+ process.exit(result.exitCode);
141
+ }
142
+ ```
143
+
144
+ The packaged `smoo-nx-exec` wrapper performs the build check and then replaces itself with the binary:
145
+
146
+ ```bash
147
+ smoo-nx-exec my-cli:build -- ./packages/my-cli/dist/my-cli argument
148
+ ```
149
+
150
+ It is deliberately not `nx run <target> && exec`:
151
+
152
+ - A hit costs one daemon round-trip and a local cache read, not an Nx CLI start.
153
+ - A hit is silent. `nx run` replays the cached log and prints its `[local cache]` banner, which a CLI wrapper must not
154
+ print.
155
+ - It execs the binary, preserving its argv, exit status, and signals. `nx run` has no notion of handing the process over
156
+ to another binary.
157
+
158
+ Pass `--workspace-root <dir>` before `--` when invoking the wrapper outside the workspace. The binary path resolves
159
+ against the caller's current directory.
160
+
110
161
  ## Bun Test Tracing Generator
111
162
 
112
163
  Configure a package for the Bun test tracing + no-emit test typechecking pattern used in this repo.
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=smoo-nx-exec.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"smoo-nx-exec.d.ts","sourceRoot":"","sources":["../../src/bin/smoo-nx-exec.ts"],"names":[],"mappings":""}
@@ -0,0 +1,117 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync } from 'node:fs';
3
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
4
+ import { inspect } from 'node:util';
5
+ import { describeMiss, ensureBuilt, parseTargetSelector } from '../ensure-built.js';
6
+ const USAGE = 'usage: smoo-nx-exec <project:target[:configuration]> [--workspace-root <dir>] -- <binary> [args...]';
7
+ /** Argument and environment problems all exit 2, the shell's "usage" code. */
8
+ function usageError(message) {
9
+ process.stderr.write(`smoo-nx-exec: ${message}\n${USAGE}\n`);
10
+ process.exit(2);
11
+ }
12
+ function describeError(error) {
13
+ if (error instanceof Error) {
14
+ return error.message;
15
+ }
16
+ if (typeof error === 'object' && error !== null && 'message' in error && typeof error.message === 'string') {
17
+ return error.message;
18
+ }
19
+ return typeof error === 'string'
20
+ ? error
21
+ : inspect(error, { breakLength: Number.POSITIVE_INFINITY, colors: false, depth: 5 });
22
+ }
23
+ /**
24
+ * Split `--flag=value` into two tokens so both spellings parse identically.
25
+ * Only leading `--` forms are split: a value may legitimately contain `=`.
26
+ */
27
+ function tokenize(args) {
28
+ const tokens = [];
29
+ for (const arg of args) {
30
+ const equals = arg.startsWith('--') ? arg.indexOf('=') : -1;
31
+ if (equals === -1) {
32
+ tokens.push(arg);
33
+ }
34
+ else {
35
+ tokens.push(arg.slice(0, equals), arg.slice(equals + 1));
36
+ }
37
+ }
38
+ return tokens;
39
+ }
40
+ function findWorkspaceRoot(from) {
41
+ let directory = from;
42
+ for (;;) {
43
+ if (existsSync(join(directory, 'nx.json'))) {
44
+ return directory;
45
+ }
46
+ const parent = dirname(directory);
47
+ if (parent === directory) {
48
+ return usageError(`no nx.json at or above ${from}; pass --workspace-root`);
49
+ }
50
+ directory = parent;
51
+ }
52
+ }
53
+ const argv = process.argv.slice(2);
54
+ const separator = argv.indexOf('--');
55
+ if (separator === -1) {
56
+ usageError('missing `--` before the binary to exec');
57
+ }
58
+ const command = argv.slice(separator + 1);
59
+ if (command.length === 0) {
60
+ usageError('no binary given after `--`');
61
+ }
62
+ let target;
63
+ let workspaceRootArg;
64
+ const tokens = tokenize(argv.slice(0, separator));
65
+ for (let index = 0; index < tokens.length; index += 1) {
66
+ const token = tokens[index];
67
+ if (token === '--workspace-root') {
68
+ index += 1;
69
+ workspaceRootArg = tokens[index] ?? usageError('--workspace-root needs a directory');
70
+ }
71
+ else if (token.startsWith('-')) {
72
+ usageError(`unknown flag ${token}`);
73
+ }
74
+ else if (target !== undefined) {
75
+ usageError(`more than one target given: ${target} and ${token}`);
76
+ }
77
+ else {
78
+ target = token;
79
+ }
80
+ }
81
+ if (target === undefined) {
82
+ usageError('no project:target given');
83
+ }
84
+ if (parseTargetSelector(target) === null) {
85
+ usageError(`'${target}' is not a project:target[:configuration] selector`);
86
+ }
87
+ // `execve` does no PATH lookup, so a bare name would fail as a missing file in
88
+ // the current directory. Say which mistake was made instead.
89
+ if (!command[0].includes('/')) {
90
+ usageError(`'${command[0]}' must be a path to the binary, not a name to look up on PATH`);
91
+ }
92
+ // Resolved against the directory the user is standing in, not the workspace
93
+ // root: this is their command line, and the exec'd process inherits their cwd.
94
+ const binary = isAbsolute(command[0]) ? command[0] : resolve(process.cwd(), command[0]);
95
+ const workspaceRoot = workspaceRootArg === undefined ? findWorkspaceRoot(process.cwd()) : resolve(process.cwd(), workspaceRootArg);
96
+ const result = await ensureBuilt({ target, cwd: workspaceRoot }).catch((error) => {
97
+ process.stderr.write(`smoo-nx-exec: ${describeError(error)}\n`);
98
+ process.exit(1);
99
+ });
100
+ if (result.disposition !== 'hit' && process.env.NX_VERBOSE_LOGGING === 'true') {
101
+ process.stderr.write(`smoo-nx-exec: ran ${target} because ${describeMiss(result.reason)}\n`);
102
+ }
103
+ if (result.disposition === 'failed') {
104
+ if (result.signal !== null) {
105
+ // Re-raise rather than translate, so a build killed by SIGINT leaves this
106
+ // process looking killed by SIGINT to whatever is watching it.
107
+ process.kill(process.pid, result.signal);
108
+ }
109
+ process.exit(result.exitCode);
110
+ }
111
+ if (process.execve === undefined) {
112
+ throw new Error('smoo-nx-exec needs process.execve, which requires a POSIX host on Node 24+ or Bun');
113
+ }
114
+ // `execve`, not spawn-and-wait: the built binary replaces this process, so it
115
+ // owns the terminal, the signals and the exit status directly, with no wrapper
116
+ // left behind to forward them.
117
+ process.execve(binary, [binary, ...command.slice(1)], process.env);
@@ -1 +1 @@
1
- {"version":3,"file":"bounded-test-policy.d.ts","sourceRoot":"","sources":["../src/bounded-test-policy.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,0BAA0B,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAErG,eAAO,MAAM,qBAAqB,yCAAyC,CAAC;AAC5E,eAAO,MAAM,uBAAuB,SAAU,CAAC;AAC/C,eAAO,MAAM,0BAA0B,QAAS,CAAC;AAKjD,eAAO,MAAM,gCAAgC,QAAS,CAAC;AAEvD,MAAM,WAAW,4BAA4B;IAC3C,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClC,EAAE,CAAC,EAAE;QACH,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;KACnD,CAAC;CACH;AAED,MAAM,WAAW,4BAA4B;IAC3C,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CACnD;AAED,MAAM,WAAW,sBAAsB;IACrC,IAAI,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,CACvD,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,0BAA+B,GACvC,sBAAsB,EAAE,CAwC1B;AAuHD,wBAAgB,4BAA4B,CAC1C,WAAW,EAAE,4BAA4B,EACzC,OAAO,EAAE,mCAAmC,GAC3C,OAAO,CAqBT;AAuHD,wBAAgB,sBAAsB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAElE;AAED,wBAAgB,kBAAkB,CAChC,WAAW,EAAE,4BAA4B,EACzC,cAAc,SAAa,EAC3B,WAAW,CAAC,EAAE,4BAA4B,GACzC,MAAM,CAER;AA+CD,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,SAAmC,GAAG,MAAM,CAa9G"}
@@ -311,6 +311,9 @@ function isNoopAggregateTarget(target) {
311
311
  }
312
312
  return Array.isArray(target.dependsOn) && target.dependsOn.length > 0;
313
313
  }
314
+ function isPositiveSafeInteger(value) {
315
+ return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
316
+ }
314
317
  function isBoundedExecutionTarget(executor, rawOptions, allowedCwds) {
315
318
  if (executor !== BOUNDED_TEST_EXECUTOR || !isRecord(rawOptions)) {
316
319
  return false;
@@ -322,8 +325,8 @@ function isBoundedExecutionTarget(executor, rawOptions, allowedCwds) {
322
325
  command === ensureBunTestTimeoutFlag(command) &&
323
326
  typeof rawOptions.cwd === 'string' &&
324
327
  allowedCwds.has(rawOptions.cwd) &&
325
- rawOptions.timeoutMs === BOUNDED_TEST_TIMEOUT_MS &&
326
- rawOptions.killAfterMs === BOUNDED_TEST_KILL_AFTER_MS);
328
+ isPositiveSafeInteger(rawOptions.timeoutMs) &&
329
+ isPositiveSafeInteger(rawOptions.killAfterMs));
327
330
  }
328
331
  function resolvedAggregateTestIsBounded(project) {
329
332
  if (!project?.targetDependencies || !project.targetExecutors || !project.targetOptions) {
@@ -7,8 +7,22 @@ export interface CargoWorkspacePackage {
7
7
  */
8
8
  testShards: number;
9
9
  }
10
+ export interface CargoWorkspaceProject {
11
+ name: string;
12
+ root: string;
13
+ }
14
+ export interface AttributedCargoWorkspacePackage extends CargoWorkspacePackage {
15
+ projectName: string;
16
+ projectRoot: string;
17
+ }
10
18
  export declare function listCargoWorkspacePackages(absoluteProjectRoot: string): CargoWorkspacePackage[];
11
- export declare function cargoPackageTestInputs(absoluteProjectRoot: string, memberDir: string): Promise<string[]>;
19
+ /**
20
+ * Assign each workspace crate to the most specific Nx project that contains
21
+ * its directory. The repository root is the fallback owner; a nested package
22
+ * wins by path depth so projects under `packages/*` own their own crates.
23
+ */
24
+ export declare function attributeCargoWorkspacePackages(packages: readonly CargoWorkspacePackage[], projects: readonly CargoWorkspaceProject[]): AttributedCargoWorkspacePackage[];
25
+ export declare function cargoPackageTestInputs(absoluteProjectRoot: string, memberDir: string, inputRoot?: string): Promise<string[]>;
12
26
  /**
13
27
  * The aggregate that actually runs a cargo workspace's tests. Named here because
14
28
  * both target inference and the policy that verifies `test` reaches it need the
@@ -1 +1 @@
1
- {"version":3,"file":"cargo-workspace.d.ts","sourceRoot":"","sources":["../src/cargo-workspace.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,CAAC;IACZ;;;OAGG;IACH,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,wBAAgB,0BAA0B,CAAC,mBAAmB,EAAE,MAAM,GAAG,qBAAqB,EAAE,CA8B/F;AAED,wBAAsB,sBAAsB,CAAC,mBAAmB,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAwB9G;AA6ED;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,eAAe,CAAC;AAE9C,wEAAwE;AACxE,eAAO,MAAM,yBAAyB,uBAAuB,CAAC;AAE9D;;;;GAIG;AACH,eAAO,MAAM,4BAA4B,eAAe,CAAC;AAEzD;;;GAGG;AACH,wBAAgB,0BAA0B,CAAC,WAAW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EAAwE;AACxE,eAAO,MAAM,yBAAyB,uBAAuB,CAAC;AAE9D;;;;GAIG;AACH,eAAO,MAAM,4BAA4B,eAAe,CAAC;AAEzD;;;GAGG;AACH,wBAAgB,0BAA0B,CAAC,WAAW,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,CAGtF;AAED;;;;GAIG;AACH,wBAAgB,8BAA8B,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAQhF;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,qBAAqB,CAAC,iBAAiB,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAoB9E;AAED,wBAAgB,oBAAoB,CAAC,aAAa,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAG1G"}
@@ -1,4 +1,4 @@
1
- import { existsSync, readFileSync } from 'node:fs';
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
2
  import { readFile } from 'node:fs/promises';
3
3
  import { join, normalize, posix, relative, sep } from 'node:path';
4
4
  import { parse as parseToml } from 'smol-toml';
@@ -11,12 +11,30 @@ export function listCargoWorkspacePackages(absoluteProjectRoot) {
11
11
  if (!isRecord(parsed) || !isRecord(parsed.workspace) || !Array.isArray(parsed.workspace.members)) {
12
12
  return [];
13
13
  }
14
- const packages = [];
14
+ const excludedDirs = new Set();
15
+ if (Array.isArray(parsed.workspace.exclude)) {
16
+ for (const excluded of parsed.workspace.exclude) {
17
+ if (typeof excluded === 'string' && excluded.length > 0) {
18
+ for (const excludedDir of expandCargoMemberDirs(absoluteProjectRoot, excluded, false)) {
19
+ excludedDirs.add(excludedDir);
20
+ }
21
+ }
22
+ }
23
+ }
24
+ const packageDirs = new Set();
15
25
  for (const member of parsed.workspace.members) {
16
26
  if (typeof member !== 'string' || member.length === 0) {
17
27
  continue;
18
28
  }
19
- const crateTomlPath = join(absoluteProjectRoot, member, 'Cargo.toml');
29
+ for (const memberDir of expandCargoMemberDirs(absoluteProjectRoot, member)) {
30
+ if (!isExcludedCargoMember(memberDir, excludedDirs)) {
31
+ packageDirs.add(memberDir);
32
+ }
33
+ }
34
+ }
35
+ const packages = [];
36
+ for (const memberDir of packageDirs) {
37
+ const crateTomlPath = join(absoluteProjectRoot, memberDir, 'Cargo.toml');
20
38
  if (!existsSync(crateTomlPath)) {
21
39
  continue;
22
40
  }
@@ -26,14 +44,101 @@ export function listCargoWorkspacePackages(absoluteProjectRoot) {
26
44
  }
27
45
  packages.push({
28
46
  name: crateParsed.package.name,
29
- dir: member.split('\\').join('/'),
47
+ dir: memberDir,
30
48
  testShards: readTestShards(crateParsed.package, crateTomlPath),
31
49
  });
32
50
  }
33
51
  packages.sort((left, right) => left.name.localeCompare(right.name));
34
52
  return packages;
35
53
  }
36
- export async function cargoPackageTestInputs(absoluteProjectRoot, memberDir) {
54
+ function isExcludedCargoMember(memberDir, excludedDirs) {
55
+ for (const excludedDir of excludedDirs) {
56
+ if (memberDir === excludedDir || memberDir.startsWith(`${excludedDir}/`)) {
57
+ return true;
58
+ }
59
+ }
60
+ return false;
61
+ }
62
+ /**
63
+ * Cargo accepts glob patterns at any depth in `workspace.members` and
64
+ * `workspace.exclude`. Walk one path segment at a time so patterns with
65
+ * wildcards in multiple segments cannot silently erase every crate from the
66
+ * Nx graph.
67
+ */
68
+ function expandCargoMemberDirs(absoluteProjectRoot, member, requireGlobMatch = true) {
69
+ const normalized = member.split('\\').join('/').replace(/\/+$/, '');
70
+ const segments = normalized.split('/');
71
+ if (normalized.length === 0 ||
72
+ normalized.startsWith('/') ||
73
+ segments.some((segment) => segment.length === 0 || segment === '.' || segment === '..')) {
74
+ throw new Error(`Cargo workspace member must be a non-empty relative path: ${member}`);
75
+ }
76
+ if (segments.some((segment) => segment === '**' || /[[\]{}!]/.test(segment))) {
77
+ throw new Error(`Cargo workspace member uses an unsupported glob pattern: ${member}`);
78
+ }
79
+ const hasGlob = segments.some((segment) => segment.includes('*') || segment.includes('?'));
80
+ let candidates = [''];
81
+ for (const segment of segments) {
82
+ if (!segment.includes('*') && !segment.includes('?')) {
83
+ candidates = candidates.map((candidate) => posix.join(candidate, segment));
84
+ continue;
85
+ }
86
+ const matcher = cargoGlobSegmentMatcher(segment);
87
+ const expanded = [];
88
+ for (const candidate of candidates) {
89
+ const absoluteParent = join(absoluteProjectRoot, candidate);
90
+ if (!existsSync(absoluteParent)) {
91
+ continue;
92
+ }
93
+ for (const entry of readdirSync(absoluteParent, { withFileTypes: true })) {
94
+ if (entry.isDirectory() && matcher.test(entry.name)) {
95
+ expanded.push(posix.join(candidate, entry.name));
96
+ }
97
+ }
98
+ }
99
+ candidates = expanded;
100
+ }
101
+ if (requireGlobMatch && hasGlob && candidates.length === 0) {
102
+ throw new Error(`Cargo workspace member glob matched no directories: ${member}`);
103
+ }
104
+ return candidates.sort((left, right) => left.localeCompare(right));
105
+ }
106
+ function cargoGlobSegmentMatcher(segment) {
107
+ let source = '^';
108
+ for (const character of segment) {
109
+ if (character === '*') {
110
+ source += '.*';
111
+ }
112
+ else if (character === '?') {
113
+ source += '.';
114
+ }
115
+ else {
116
+ source += character.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&');
117
+ }
118
+ }
119
+ return new RegExp(`${source}$`);
120
+ }
121
+ /**
122
+ * Assign each workspace crate to the most specific Nx project that contains
123
+ * its directory. The repository root is the fallback owner; a nested package
124
+ * wins by path depth so projects under `packages/*` own their own crates.
125
+ */
126
+ export function attributeCargoWorkspacePackages(packages, projects) {
127
+ const bySpecificity = [...projects].sort((left, right) => {
128
+ const leftDepth = left.root === '.' ? 0 : left.root.split('/').length;
129
+ const rightDepth = right.root === '.' ? 0 : right.root.split('/').length;
130
+ return rightDepth - leftDepth || left.name.localeCompare(right.name);
131
+ });
132
+ const attributed = [];
133
+ for (const pkg of packages) {
134
+ const owner = bySpecificity.find((project) => project.root === '.' || pkg.dir === project.root || pkg.dir.startsWith(`${project.root}/`));
135
+ if (owner) {
136
+ attributed.push({ ...pkg, projectName: owner.name, projectRoot: owner.root });
137
+ }
138
+ }
139
+ return attributed;
140
+ }
141
+ export async function cargoPackageTestInputs(absoluteProjectRoot, memberDir, inputRoot = '{projectRoot}') {
37
142
  const workspacePathDeps = await workspacePathDependencies(absoluteProjectRoot);
38
143
  const dirs = new Set([memberDir.split('\\').join('/')]);
39
144
  const crateParsed = parseToml(await readFile(join(absoluteProjectRoot, memberDir, 'Cargo.toml'), 'utf-8'));
@@ -51,11 +156,11 @@ export async function cargoPackageTestInputs(absoluteProjectRoot, memberDir) {
51
156
  }
52
157
  }
53
158
  }
54
- const inputs = ['{projectRoot}/Cargo.toml', '{projectRoot}/Cargo.lock'];
159
+ const inputs = [`${inputRoot}/Cargo.toml`, `${inputRoot}/Cargo.lock`];
55
160
  for (const dir of [...dirs].sort()) {
56
- inputs.push(`{projectRoot}/${dir}/**/*.rs`, `{projectRoot}/${dir}/Cargo.toml`);
161
+ inputs.push(`${inputRoot}/${dir}/**/*.rs`, `${inputRoot}/${dir}/Cargo.toml`);
57
162
  }
58
- inputs.push('{projectRoot}/**/.cargo/config.toml', '{projectRoot}/scripts/*.sh', '!{projectRoot}/**/target/**');
163
+ inputs.push(`${inputRoot}/**/.cargo/config.toml`, `${inputRoot}/scripts/*.sh`, `!${inputRoot}/**/target/**`);
59
164
  return inputs;
60
165
  }
61
166
  async function workspacePathDependencies(absoluteProjectRoot) {
@@ -0,0 +1,136 @@
1
+ import type { Task } from 'nx/src/config/task-graph';
2
+ /**
3
+ * A `project:target` or `project:target:configuration` selector.
4
+ *
5
+ * Configuration belongs in the selector rather than in a separate option
6
+ * because it is part of the cache key: `app:build` and `app:build:production`
7
+ * are two different tasks with two different hashes.
8
+ */
9
+ export interface TargetSelector {
10
+ readonly project: string;
11
+ readonly target: string;
12
+ readonly configuration: string | undefined;
13
+ }
14
+ /**
15
+ * Why the target could not be replayed from what is already on disk.
16
+ *
17
+ * Every variant names the task that ended the probe: in a dependency graph
18
+ * "something changed" is unactionable, and the useful question is always which
19
+ * of the twelve dependencies moved.
20
+ */
21
+ export type MissReason = {
22
+ readonly kind: 'uncacheable';
23
+ readonly taskId: string;
24
+ } | {
25
+ readonly kind: 'unhashable';
26
+ readonly taskId: string;
27
+ } | {
28
+ readonly kind: 'not-cached';
29
+ readonly taskId: string;
30
+ } | {
31
+ readonly kind: 'cached-failure';
32
+ readonly taskId: string;
33
+ readonly code: number;
34
+ } | {
35
+ readonly kind: 'stale-outputs';
36
+ readonly taskId: string;
37
+ } | {
38
+ readonly kind: 'cache-disabled';
39
+ readonly taskId: string;
40
+ } | {
41
+ readonly kind: 'no-daemon';
42
+ readonly taskId: string;
43
+ };
44
+ /**
45
+ * `hit` means nothing ran: every task in the graph was a recorded success and
46
+ * every recorded output is still byte-identical on disk, so the artifacts are
47
+ * what a fresh run would produce.
48
+ *
49
+ * `built` means the work was handed to Nx — which may have restored outputs
50
+ * from the local cache rather than recompiled anything. The line `hit` draws is
51
+ * "did this process have to do work", which is what a CLI wrapper needs in
52
+ * order to decide whether to stay quiet.
53
+ *
54
+ * `failed` is an operational outcome, not an exception: the target ran and did
55
+ * not succeed. A caller re-raises `signal` when there is one and exits with
56
+ * `exitCode` otherwise, so a Ctrl-C during a build stays a Ctrl-C.
57
+ */
58
+ export type EnsureBuiltResult = {
59
+ readonly disposition: 'hit';
60
+ } | {
61
+ readonly disposition: 'built';
62
+ readonly reason: MissReason;
63
+ } | {
64
+ readonly disposition: 'failed';
65
+ readonly reason: MissReason;
66
+ readonly exitCode: number;
67
+ readonly signal: NodeJS.Signals | null;
68
+ };
69
+ export interface EnsureBuiltOptions {
70
+ /** `project:target` or `project:target:configuration`. */
71
+ readonly target: string;
72
+ /**
73
+ * Nx workspace root. Required rather than discovered: a wrapper script knows
74
+ * its own checkout, and inferring from the caller's directory would silently
75
+ * bind whichever workspace they happen to be standing in.
76
+ */
77
+ readonly cwd: string;
78
+ /**
79
+ * How the run that happens on a miss reports progress. `stream` is the
80
+ * default and the only style offered: this facility fronts multi-minute
81
+ * compiles, and Nx's buffered styles emit nothing until a task finishes, so a
82
+ * silent terminal would read as a hang.
83
+ */
84
+ readonly onMiss?: 'stream';
85
+ }
86
+ export declare function parseTargetSelector(spec: string): TargetSelector | null;
87
+ export declare function describeMiss(reason: MissReason): string;
88
+ /**
89
+ * First reason the task set cannot be replayed, considering only recorded
90
+ * results — no filesystem access. `null` means every task is a recorded
91
+ * success, and the on-disk check is worth paying for.
92
+ *
93
+ * A cached *failure* counts as a miss even though Nx replays one when
94
+ * `NX_CACHE_FAILURES` is set: this facility exists to hand the process over to
95
+ * a binary, and replaying a failed build would hand over a stale one.
96
+ */
97
+ export declare function firstCacheMiss(tasks: readonly Task[], cachedCodeByHash: ReadonlyMap<string, number>): MissReason | null;
98
+ /**
99
+ * First task whose recorded outputs are no longer the bytes on disk.
100
+ *
101
+ * `matches[index]` is the daemon's verdict for `tasks[index]`. A short or
102
+ * ragged array counts as stale rather than as a hit: a missing verdict is not a
103
+ * positive one, and being wrong here means exec'ing a binary that was deleted.
104
+ */
105
+ export declare function firstStaleOutputs(tasks: readonly Task[], matches: readonly boolean[]): MissReason | null;
106
+ /**
107
+ * Make sure an Nx target's outputs are on disk, doing as little as possible
108
+ * when they already are.
109
+ *
110
+ * "Already built" is the hot path, because a checkout-local CLI wrapper pays it
111
+ * on every invocation. So it never spawns the `nx` CLI: the project graph, the
112
+ * task hashes and the on-disk output verification are daemon round-trips, the
113
+ * cache lookup is a local SQLite read, and Nx's task runner is only invoked
114
+ * once something is known to need running.
115
+ *
116
+ * With the daemon disabled there is no probe to make — hashing would have to
117
+ * build the project graph in this process, and no service holds the recorded
118
+ * output hashes to check the working tree against — so the target is handed to
119
+ * the workspace's own `nx` CLI unconditionally.
120
+ */
121
+ export declare function ensureBuilt(options: EnsureBuiltOptions): Promise<EnsureBuiltResult>;
122
+ export interface ChildExit {
123
+ readonly code: number | null;
124
+ readonly signal: NodeJS.Signals | null;
125
+ }
126
+ /**
127
+ * How a child `nx`'s exit becomes a result.
128
+ *
129
+ * A signal is reported as a signal, not flattened into a code, so the caller
130
+ * can re-raise it: a build stopped by Ctrl-C should leave the wrapper looking
131
+ * killed by Ctrl-C to whatever is watching, not merely unsuccessful. The
132
+ * numeric code comes from Nx's own `signalToCode` so it matches what `nx run`
133
+ * would have exited with.
134
+ */
135
+ export declare function cliExitOutcome(reason: MissReason, exit: ChildExit, signalToCode: (signal: NodeJS.Signals | null) => number): EnsureBuiltResult;
136
+ //# sourceMappingURL=ensure-built.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ensure-built.d.ts","sourceRoot":"","sources":["../src/ensure-built.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,0BAA0B,CAAC;AAkCrD;;;;;;GAMG;AACH,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,aAAa,EAAE,MAAM,GAAG,SAAS,CAAC;CAC5C;AAED;;;;;;GAMG;AACH,MAAM,MAAM,UAAU,GAClB;IAAE,QAAQ,CAAC,IAAI,EAAE,aAAa,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GACzD;IAAE,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GACxD;IAAE,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GACxD;IAAE,QAAQ,CAAC,IAAI,EAAE,gBAAgB,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GACnF;IAAE,QAAQ,CAAC,IAAI,EAAE,eAAe,CAAC;IAAC,QAAQ,CA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