@smoothbricks/nx-plugin 0.4.22 → 0.4.24

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 (72) hide show
  1. package/README.md +93 -33
  2. package/dist/bin/smoo-nx-exec.js +35 -11
  3. package/dist/bin/smoo-nx-nextest-extract.d.ts +3 -0
  4. package/dist/bin/smoo-nx-nextest-extract.d.ts.map +1 -0
  5. package/dist/bin/smoo-nx-nextest-extract.js +41 -0
  6. package/dist/cargo-closure-input.d.ts +63 -0
  7. package/dist/cargo-closure-input.d.ts.map +1 -0
  8. package/dist/cargo-closure-input.js +197 -0
  9. package/dist/cargo-source-hash.d.ts +37 -0
  10. package/dist/cargo-source-hash.d.ts.map +1 -1
  11. package/dist/cargo-source-hash.js +108 -190
  12. package/dist/cross-check-policy.d.ts +14 -0
  13. package/dist/cross-check-policy.d.ts.map +1 -1
  14. package/dist/cross-check-policy.js +15 -1
  15. package/dist/ensure-built.d.ts +3 -2
  16. package/dist/ensure-built.d.ts.map +1 -1
  17. package/dist/ensure-built.js +33 -56
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +152 -91
  20. package/dist/managed-files/ci-workflow.d.ts.map +1 -1
  21. package/dist/managed-files/ci-workflow.js +12 -15
  22. package/dist/managed-files/files.d.ts.map +1 -1
  23. package/dist/managed-files/files.js +10 -0
  24. package/dist/managed-files/publish-workflow.d.ts.map +1 -1
  25. package/dist/managed-files/publish-workflow.js +12 -6
  26. package/dist/manifest-hash.d.ts.map +1 -1
  27. package/dist/manifest-hash.js +24 -30
  28. package/dist/nextest-extraction.d.ts +101 -0
  29. package/dist/nextest-extraction.d.ts.map +1 -0
  30. package/dist/nextest-extraction.js +268 -0
  31. package/dist/package-target-policy.js +1 -1
  32. package/dist/platform-targets.d.ts +7 -0
  33. package/dist/platform-targets.d.ts.map +1 -1
  34. package/dist/platform-targets.js +7 -0
  35. package/dist/workspace-config-policy.d.ts +1 -1
  36. package/dist/workspace-config-policy.d.ts.map +1 -1
  37. package/dist/workspace-config-policy.js +1 -1
  38. package/managed/raw/envrc +38 -1
  39. package/managed/raw/tooling/direnv/developer-links.ts +201 -0
  40. package/managed/raw/tooling/direnv/devenv.smoo.nix +75 -51
  41. package/managed/raw/tooling/direnv/secret-references.ts +3 -1
  42. package/managed/raw/tooling/direnv/setup-environment.ts +562 -78
  43. package/managed/raw/tooling/direnv/shared-caches.sh +53 -0
  44. package/managed/raw/tooling/git-hooks/pre-push.sh +22 -1
  45. package/managed/templates/github/workflows/managed-files.yml +4 -3
  46. package/nextest.toml +5 -5
  47. package/package.json +4 -3
  48. package/src/__tests__/fixture-nx-env.ts +31 -0
  49. package/src/__tests__/in-process-nx-index.ts +9 -0
  50. package/src/bin/smoo-nx-exec.ts +40 -11
  51. package/src/bin/smoo-nx-nextest-extract.ts +43 -0
  52. package/src/bounded-test-policy.test.ts +4 -1
  53. package/src/cargo-closure-input.test.ts +184 -0
  54. package/src/cargo-closure-input.ts +247 -0
  55. package/src/cargo-source-hash.test.ts +8 -9
  56. package/src/cargo-source-hash.ts +146 -47
  57. package/src/cross-check-policy.ts +15 -3
  58. package/src/ensure-built.test.ts +65 -5
  59. package/src/ensure-built.ts +40 -85
  60. package/src/index.test.ts +222 -75
  61. package/src/index.ts +213 -101
  62. package/src/managed-files/ci-workflow.ts +12 -15
  63. package/src/managed-files/files.ts +10 -0
  64. package/src/managed-files/generator.test.ts +29 -0
  65. package/src/managed-files/publish-workflow.ts +17 -6
  66. package/src/manifest-hash.test.ts +21 -1
  67. package/src/manifest-hash.ts +26 -29
  68. package/src/nextest-extraction.test.ts +74 -0
  69. package/src/nextest-extraction.ts +329 -0
  70. package/src/package-target-policy.ts +1 -1
  71. package/src/platform-targets.ts +8 -0
  72. package/src/workspace-config-policy.ts +6 -1
@@ -1,18 +1,25 @@
1
1
  #!/usr/bin/env bun
2
+ import { dlopen, FFIType } from 'bun:ffi';
2
3
  import {
3
4
  chmodSync,
5
+ closeSync,
4
6
  existsSync,
5
7
  mkdirSync,
8
+ openSync,
6
9
  readdirSync,
7
10
  readFileSync,
8
11
  readlinkSync,
12
+ realpathSync,
9
13
  rmSync,
14
+ statSync,
10
15
  symlinkSync,
11
16
  writeFileSync,
12
17
  } from 'node:fs';
13
18
  import { createRequire } from 'node:module';
14
19
  import path from 'node:path';
20
+ import { parseArgs } from 'node:util';
15
21
  import { $ } from 'bun';
22
+ import { keepDeveloperLinks, reportDeveloperLinks } from './developer-links.ts';
16
23
  import {
17
24
  type DeferredSecret,
18
25
  dependentGroups,
@@ -108,6 +115,12 @@ const POST_COMMIT_BLOCK = [
108
115
  POST_COMMIT_END,
109
116
  ].join('\n');
110
117
 
118
+ // The managed devenv module passes `--python <interpreter>` for a uv project:
119
+ // the interpreter devenv's languages.python would use, as a store path, so the
120
+ // environment uv builds does not name this checkout's profile as its home.
121
+ // Declared above the bootstrap block for the same hoisting reason as above.
122
+ const { values: flags } = parseArgs({ options: { python: { type: 'string' } } });
123
+
111
124
  // Go to project root
112
125
  process.chdir(projectRoot);
113
126
 
@@ -115,42 +128,55 @@ try {
115
128
  // Bootstrap only: install deps + wire local git hooks/config.
116
129
  // Do not import workspace packages here — this script is what installs them,
117
130
  // and package resolution/Typia transforms are not available yet.
118
- if (process.env.CI) {
131
+ const bunInputs = bunInstallInputs();
132
+ const uvInputs = uvSyncInputs();
133
+ recordInstallInputs([...bunInputs, ...uvInputs]);
134
+ // A CI runner is GitHub Actions or Forgejo Actions, which mirrors every FORGEJO_*
135
+ // variable as GITHUB_*. Not `CI`: agent harnesses set CI=true on every command
136
+ // they run, and this branch installs unconditionally.
137
+ if (process.env.GITHUB_ACTIONS === 'true') {
138
+ const uv = uvInstaller(uvInputs, { locked: true });
119
139
  await resolveSecrets();
120
140
  // Failures are captured and reported below. Exiting in the catch would
121
- // skip the git-diff diagnostic that follows a frozen-lockfile miss.
122
- // bun install already races concurrent installs with an atomic cache
123
- // rename; this script does not add a second mutex around it.
124
- let frozenError: unknown;
125
- let fallbackError: unknown;
126
- try {
127
- await runSetupCommand('bun install --frozen-lockfile', $`bun install --frozen-lockfile`, { quiet: false });
128
- } catch (error) {
129
- frozenError = error;
130
- console.error('! Failed to install dependencies with frozen lockfile');
131
- replayCapturedOutput(error);
132
- try {
133
- await runSetupCommand('bun install', $`bun install`, { quiet: false });
134
- } catch (fallback) {
135
- fallbackError = fallback;
141
+ // skip the git-diff diagnostic that follows a frozen-lockfile miss. The
142
+ // exits inside the install lock are safe: the kernel releases it.
143
+ await withInstallLock(async () => {
144
+ let frozenError: unknown;
145
+ let fallbackError: unknown;
146
+ await keepDeveloperLinks(projectRoot, async () => {
147
+ try {
148
+ await runSetupCommand('bun install --frozen-lockfile', $`bun install --frozen-lockfile`, { quiet: false });
149
+ } catch (error) {
150
+ frozenError = error;
151
+ console.error('! Failed to install dependencies with frozen lockfile');
152
+ replayCapturedOutput(error);
153
+ try {
154
+ await runSetupCommand('bun install', $`bun install`, { quiet: false });
155
+ } catch (fallback) {
156
+ fallbackError = fallback;
157
+ }
158
+ }
159
+ });
160
+ if (fallbackError !== undefined) {
161
+ reportSetupFailure(fallbackError);
136
162
  }
137
- }
138
- if (fallbackError !== undefined) {
139
- reportSetupFailure(fallbackError);
140
- }
141
- if (frozenError !== undefined) {
142
- console.error('git diff after install:');
143
- try {
144
- await runSetupCommand('git diff', $`git diff`, { quiet: false });
145
- } catch (diffError) {
146
- // This diff is diagnostics for the install failure we are already
147
- // reporting, so it must never become the failure: say it broke and keep
148
- // the original exit path. Plain `git diff` exits 0 even when the
149
- // lockfile drifted, so a non-zero here means git itself failed.
150
- console.error(`! git diff failed: ${diffError instanceof Error ? diffError.message : String(diffError)}`);
163
+ if (frozenError !== undefined) {
164
+ console.error('git diff after install:');
165
+ try {
166
+ await runSetupCommand('git diff', $`git diff`, { quiet: false });
167
+ } catch (diffError) {
168
+ // This diff is diagnostics for the install failure we are already
169
+ // reporting, so it must never become the failure: say it broke and keep
170
+ // the original exit path. Plain `git diff` exits 0 even when the
171
+ // lockfile drifted, so a non-zero here means git itself failed.
172
+ console.error(`! git diff failed: ${diffError instanceof Error ? diffError.message : String(diffError)}`);
173
+ }
174
+ process.exit(1);
151
175
  }
152
- process.exit(1);
153
- }
176
+ if (uv !== null) {
177
+ await uv.install({ quiet: false });
178
+ }
179
+ });
154
180
  } else {
155
181
  // A local secret-resolution or install failure (a provider that is not
156
182
  // signed in, an unpublished private package, a missing registry
@@ -159,12 +185,23 @@ try {
159
185
  // exit, and then bun, nx, op and every other tool needed to repair the
160
186
  // install are gone too. Report it, finish what does not depend on the
161
187
  // install, and load the shell. CI above stays strict.
162
- const installError = await installLocalDependencies();
163
- if (installError === undefined) {
164
- // Pin unscoped typescript → API 6 for root and Bun's shared .bun hoist (Nx).
165
- ensureTypeScriptApiPackage(projectRoot);
166
- }
167
- await applyWorkspaceGitConfig(projectRoot);
188
+ const uv = uvInstaller(uvInputs, { locked: false });
189
+ const bun = bunInstaller(bunInputs);
190
+ const installError = await withInstallLock(async () => {
191
+ const pending = (uv === null ? [bun] : [bun, uv]).filter((installer) => !installer.isCurrent());
192
+ const error = await installLocalDependencies(pending);
193
+ if (!pending.includes(bun)) {
194
+ reportDeveloperLinks(projectRoot);
195
+ }
196
+ if (error === undefined) {
197
+ // Pin unscoped typescript → API 6 for root and Bun's shared .bun hoist (Nx).
198
+ ensureTypeScriptApiPackage(projectRoot);
199
+ }
200
+ // Under the same lock: the repository config and hooks are one more thing two shell
201
+ // entries would otherwise write at once.
202
+ await applyWorkspaceGitConfig(projectRoot);
203
+ return error;
204
+ });
168
205
  if (installError !== undefined) {
169
206
  reportDegradedSetup(installError);
170
207
  }
@@ -174,11 +211,12 @@ try {
174
211
  }
175
212
 
176
213
  /**
177
- * Provider-declared secrets (smoo.secrets) resolve before any install. The
214
+ * Provider-declared secrets (smoo.secrets) resolve before an install. The
178
215
  * values land in THIS process environment only — bun install, the prepare
179
216
  * scripts it runs, and every later child of this script inherit them (for
180
217
  * example .npmrc `${VAR}` auth); the direnv shell itself does not, which is
181
- * the point: this script must never act as a global shell export.
218
+ * the point: this script must never act as a global shell export. Nothing
219
+ * else here reads them, so a shell entry that installs nothing resolves none.
182
220
  *
183
221
  * `shell` is the group, and it is what keeps a credential only a deliberate
184
222
  * command needs — a registry token, the Nx cache token — from running its
@@ -197,21 +235,372 @@ async function resolveSecrets(): Promise<void> {
197
235
  deferredSecrets.push(...resolution.deferred);
198
236
  }
199
237
 
200
- async function installLocalDependencies(): Promise<unknown> {
238
+ /**
239
+ * Runs every installer whose inputs changed since its last successful run.
240
+ * Returned, not thrown: the caller still keeps the git config, then reports a
241
+ * degraded shell. The caller selects them under the install lock, so an
242
+ * installer another shell entry just ran is already current there.
243
+ */
244
+ async function installLocalDependencies(pending: readonly Installer[]): Promise<unknown> {
245
+ if (pending.length === 0) {
246
+ return undefined;
247
+ }
201
248
  try {
202
249
  await resolveSecrets();
203
250
  } catch (error) {
204
251
  return error;
205
252
  }
206
- // Returned, not thrown: the caller still wires git config, then reports a
207
- // degraded shell. Same reason as the CI branch — bun install's own rename
208
- // is the concurrency control, not a lock in this script.
253
+ for (const installer of pending) {
254
+ try {
255
+ await installer.install({ quiet: true });
256
+ } catch (error) {
257
+ return error;
258
+ }
259
+ }
260
+ return undefined;
261
+ }
262
+
263
+ /**
264
+ * One install at a time per checkout, across processes. Shell entries race
265
+ * whenever two shells load at once — a shell pool warming several, two
266
+ * terminals, an editor beside a terminal — and two installs into one
267
+ * node_modules collide on its links (`EEXIST … symlink`). The second entry
268
+ * waits, then finds the first entry's stamps current and installs nothing.
269
+ * The repository's git config and hooks are kept under the same lock, for the
270
+ * same reason.
271
+ *
272
+ * flock(2), not a lock directory or file the script creates and removes: the
273
+ * kernel releases it when the holder exits however it exits, so a killed
274
+ * shell entry cannot leave a lock behind for the next one to wait out. Bun
275
+ * has no flock binding, so it comes from libc; LOCK_EX and LOCK_NB have the
276
+ * same values on Darwin and Linux. The waiting entry says why it is waiting.
277
+ */
278
+ async function withInstallLock<T>(run: () => Promise<T>): Promise<T> {
279
+ const LOCK_EX = 2;
280
+ const LOCK_NB = 4;
281
+ const libc = dlopen(process.platform === 'darwin' ? '/usr/lib/libSystem.B.dylib' : 'libc.so.6', {
282
+ flock: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 },
283
+ });
284
+ const lockPath = path.join(projectRoot, 'node_modules', '.smoo-install.lock');
285
+ mkdirSync(path.dirname(lockPath), { recursive: true });
286
+ const fd = openSync(lockPath, 'a');
287
+ try {
288
+ if (libc.symbols.flock(fd, LOCK_EX | LOCK_NB) !== 0) {
289
+ console.error(`setup-environment: waiting for another shell entry's install in ${projectRoot}`);
290
+ while (libc.symbols.flock(fd, LOCK_EX | LOCK_NB) !== 0) {
291
+ await Bun.sleep(100);
292
+ }
293
+ }
294
+ return await run();
295
+ } finally {
296
+ closeSync(fd);
297
+ libc.close();
298
+ }
299
+ }
300
+
301
+ /**
302
+ * One dependency installer shell entry drives. Shell entry runs on every
303
+ * direnv reload, and an installer whose inputs did not change would only
304
+ * re-derive the tree it already wrote — for `bun install` in a large
305
+ * workspace that is most of an unchanged shell entry. So each installer
306
+ * records the digest of its inputs after a successful run, in a stamp that
307
+ * lives inside what it installed (deleting node_modules or the uv environment
308
+ * deletes the stamp with it), and runs again only when the digest moved. A
309
+ * failed run records nothing, so the next entry retries it.
310
+ */
311
+ interface Installer {
312
+ isCurrent(): boolean;
313
+ install(options: { quiet: boolean }): Promise<void>;
314
+ }
315
+
316
+ interface InstallStamp {
317
+ /** sha256 over the installer's identity and the bytes of every input file. */
318
+ readonly inputs: string;
319
+ }
320
+
321
+ /**
322
+ * `bun install`. Its result is location-independent: the isolated linker
323
+ * links packages from the install cache by absolute path and workspace
324
+ * members by relative path, so a copy of this checkout at another path — a
325
+ * copy-on-write clone — is installed exactly when this one is. Besides the
326
+ * stamp, the TypeScript API package must still resolve through its link, the
327
+ * one package every managed repository installs, which catches a cache that
328
+ * was pruned out from under node_modules.
329
+ */
330
+ function bunInstaller(inputs: readonly string[]): Installer {
331
+ const stampPath = path.join(projectRoot, 'node_modules', '.smoo-install');
332
+ const identity = ['bun install', Bun.version, Bun.revision];
333
+ return {
334
+ isCurrent: () =>
335
+ readInstallStamp(stampPath)?.inputs === inputsDigest(identity, inputs) &&
336
+ findInstalledTypeScriptApiPackage(projectRoot) !== null,
337
+ install: async ({ quiet }) => {
338
+ await keepDeveloperLinks(projectRoot, () =>
339
+ runSetupCommand('bun install --no-summary', $`bun install --no-summary`, { quiet }),
340
+ );
341
+ writeInstallStamp(stampPath, { inputs: inputsDigest(identity, inputs) });
342
+ },
343
+ };
344
+ }
345
+
346
+ /**
347
+ * `uv sync` for a repository whose devenv shell enables uv: the managed
348
+ * module passes `--python` exactly then, devenv exports the environment's
349
+ * path as UV_PROJECT_ENVIRONMENT, and a root pyproject.toml is the uv
350
+ * project. Null for any other shell — the flag, not an inherited variable,
351
+ * decides, because an outer shell's UV_PROJECT_ENVIRONMENT leaks into a
352
+ * checkout that syncs nothing.
353
+ *
354
+ * Every package of the workspace and every dependency group is installed,
355
+ * which is what `bun install` does for the JavaScript half: a development
356
+ * shell carries the whole workspace. CI adds `--locked`, the counterpart of
357
+ * `--frozen-lockfile`.
358
+ *
359
+ * Like node_modules, the environment is location-independent, so a copy of
360
+ * this checkout at another path — a copy-on-write clone — is installed exactly
361
+ * when this one is, and its shell entry syncs nothing. uv would otherwise
362
+ * write a path into three places:
363
+ *
364
+ * - Entry-point and activation scripts name the environment. An environment
365
+ * created with `uv venv --relocatable` finds itself relative to each script
366
+ * instead, and `uv sync` keeps an existing environment relocatable, so one
367
+ * that is not — built before this, or by hand — is replaced.
368
+ * - The editable install of each workspace member is a `.pth` file holding the
369
+ * member's absolute source directory. Python resolves a relative `.pth` line
370
+ * against site-packages, so after every sync each line naming a directory in
371
+ * this checkout is rewritten relative to it.
372
+ * - The interpreter is a store path, which names this checkout's devenv profile
373
+ * unless devenv.smoo.nix clears languages.python.libraries (it does).
374
+ *
375
+ * The installed members' direct_url.json keeps the absolute URL each was
376
+ * installed from. Only uv reads it, when a changed input makes it sync, and it
377
+ * then reinstalls those members from this checkout. Where the environment sits
378
+ * in the checkout is part of the identity: the relative `.pth` lines hold only
379
+ * there.
380
+ */
381
+ function uvInstaller(inputs: readonly string[], options: { locked: boolean }): Installer | null {
382
+ const python = flags.python;
383
+ if (python === undefined || !existsSync(path.join(projectRoot, 'pyproject.toml'))) {
384
+ return null;
385
+ }
386
+ const environment = process.env.UV_PROJECT_ENVIRONMENT;
387
+ if (environment === undefined) {
388
+ throw new Error(
389
+ 'setup-environment.ts was given --python but UV_PROJECT_ENVIRONMENT is unset: ' +
390
+ "devenv's languages.python.uv exports it, and uv would otherwise build .venv at the project root.",
391
+ );
392
+ }
393
+ const stampPath = path.join(environment, '.smoo-sync');
394
+ const argv = ['sync', '--python', python, '--all-packages', '--all-groups', ...(options.locked ? ['--locked'] : [])];
395
+ const create = ['venv', '--relocatable', '--python', python, environment];
396
+ const uv = Bun.which('uv');
397
+ const identity = [
398
+ 'uv',
399
+ ...argv,
400
+ path.relative(projectRoot, environment),
401
+ uv === null ? 'uv not on PATH' : realpathSync(uv),
402
+ ];
403
+ return {
404
+ isCurrent: () => readInstallStamp(stampPath)?.inputs === inputsDigest(identity, inputs),
405
+ install: async ({ quiet }) => {
406
+ // An inherited VIRTUAL_ENV names some other environment; uv would warn
407
+ // that it does not match the project environment and ignore it.
408
+ const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => name !== 'VIRTUAL_ENV'));
409
+ // pyvenv.cfg records `relocatable = true` for an environment uv created
410
+ // with --relocatable. uv venv refuses a directory that already holds one.
411
+ const config = readFileIfPresent(path.join(environment, 'pyvenv.cfg'));
412
+ if (config === null || !/^relocatable\s*=\s*true\s*$/m.test(config.toString('utf8'))) {
413
+ rmSync(environment, { recursive: true, force: true });
414
+ await runSetupCommand(`uv ${create.join(' ')}`, $`uv ${create}`.env(env), { quiet });
415
+ }
416
+ await runSetupCommand(`uv ${argv.join(' ')}`, $`uv ${argv}`.env(env), { quiet });
417
+ relativizeCheckoutPaths(environment);
418
+ writeInstallStamp(stampPath, { inputs: inputsDigest(identity, inputs) });
419
+ },
420
+ };
421
+ }
422
+
423
+ /**
424
+ * Rewrite every `.pth` line in the environment's site-packages that names a
425
+ * directory inside this checkout as a path relative to that site-packages,
426
+ * which is how Python's `site` resolves a relative line. Every other line — an
427
+ * `import` line, a path outside the checkout, a directory that does not exist
428
+ * — stays as uv wrote it.
429
+ */
430
+ function relativizeCheckoutPaths(environment: string): void {
431
+ const root = `${realpathSync(projectRoot)}${path.sep}`;
432
+ const lib = path.join(environment, 'lib');
433
+ for (const python of existsSync(lib) ? readdirSync(lib) : []) {
434
+ const sitePackages = path.join(lib, python, 'site-packages');
435
+ if (!python.startsWith('python') || !existsSync(sitePackages)) {
436
+ continue;
437
+ }
438
+ const site = realpathSync(sitePackages);
439
+ for (const name of readdirSync(site).filter((entry) => entry.endsWith('.pth'))) {
440
+ const file = path.join(site, name);
441
+ const content = readFileSync(file, 'utf8');
442
+ const rewritten = content
443
+ .split('\n')
444
+ .map((line) => {
445
+ const target = path.isAbsolute(line) && existsSync(line) ? realpathSync(line) : null;
446
+ return target?.startsWith(root) ? path.relative(site, target) : line;
447
+ })
448
+ .join('\n');
449
+ if (rewritten !== content) {
450
+ writeFileSync(file, rewritten);
451
+ }
452
+ }
453
+ }
454
+ }
455
+
456
+ /**
457
+ * What `bun install` reads, relative to the project root and sorted: the root
458
+ * manifest (dependencies, catalogs, overrides, patchedDependencies), every
459
+ * workspace member's manifest, the lockfile, bunfig.toml, and the patch files
460
+ * it applies.
461
+ */
462
+ function bunInstallInputs(): string[] {
463
+ const manifest = parseOrUndefined(() => JSON.parse(readFileSync(path.join(projectRoot, 'package.json'), 'utf8')));
464
+ const workspaces = field(manifest, 'workspaces');
465
+ const patterns = Array.isArray(workspaces) ? stringList(workspaces) : stringList(field(workspaces, 'packages'));
466
+ const patchedDependencies = field(manifest, 'patchedDependencies');
467
+ const patches =
468
+ typeof patchedDependencies === 'object' && patchedDependencies !== null
469
+ ? stringList(Object.values(patchedDependencies))
470
+ : [];
471
+ const inputs = ['package.json', 'bun.lock', 'bun.lockb', 'bunfig.toml', ...workspaceFiles(patterns, 'package.json')];
472
+ return [...new Set([...inputs, ...patches])].sort();
473
+ }
474
+
475
+ /**
476
+ * What `uv sync` reads, relative to the project root and sorted: the root
477
+ * pyproject.toml, uv.lock, and every workspace member's pyproject.toml.
478
+ */
479
+ function uvSyncInputs(): string[] {
480
+ const pyproject = path.join(projectRoot, 'pyproject.toml');
481
+ const project = existsSync(pyproject)
482
+ ? parseOrUndefined(() => Bun.TOML.parse(readFileSync(pyproject, 'utf8')))
483
+ : undefined;
484
+ const workspace = field(field(field(project, 'tool'), 'uv'), 'workspace');
485
+ const patterns = [
486
+ ...stringList(field(workspace, 'members')),
487
+ ...stringList(field(workspace, 'exclude')).map((pattern) => `!${pattern}`),
488
+ ];
489
+ return [...new Set(['pyproject.toml', 'uv.lock', ...workspaceFiles(patterns, 'pyproject.toml')])].sort();
490
+ }
491
+
492
+ /**
493
+ * A manifest that does not parse contributes no members, never a failure
494
+ * here: its bytes are still an input, so the installer runs and reports the
495
+ * parse error itself, loudly and in its own words.
496
+ */
497
+ function parseOrUndefined(parse: () => unknown): unknown {
209
498
  try {
210
- await runSetupCommand('bun install --no-summary', $`bun install --no-summary`);
499
+ return parse();
500
+ } catch {
501
+ return undefined;
502
+ }
503
+ }
504
+
505
+ /** The member manifests a workspace glob list selects; `!pattern` excludes. */
506
+ function workspaceFiles(patterns: readonly string[], manifest: string): string[] {
507
+ const excluded = patterns
508
+ .filter((pattern) => pattern.startsWith('!'))
509
+ .map((pattern) => new Bun.Glob(pattern.slice(1)));
510
+ const files: string[] = [];
511
+ for (const pattern of patterns.filter((candidate) => !candidate.startsWith('!'))) {
512
+ for (const match of new Bun.Glob(path.posix.join(pattern, manifest)).scanSync({
513
+ cwd: projectRoot,
514
+ onlyFiles: true,
515
+ })) {
516
+ const member = path.posix.dirname(match);
517
+ if (!match.split('/').includes('node_modules') && !excluded.some((glob) => glob.match(member))) {
518
+ files.push(match);
519
+ }
520
+ }
521
+ }
522
+ return files;
523
+ }
524
+
525
+ function field(value: unknown, key: string): unknown {
526
+ return typeof value === 'object' && value !== null && Object.hasOwn(value, key) ? Reflect.get(value, key) : undefined;
527
+ }
528
+
529
+ function stringList(value: unknown): string[] {
530
+ return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];
531
+ }
532
+
533
+ /**
534
+ * Inputs enter the digest by their path relative to the project root, so the
535
+ * same bytes at another checkout path digest the same; so does every part of
536
+ * an installer's identity.
537
+ */
538
+ function inputsDigest(identity: readonly string[], inputs: readonly string[]): string {
539
+ const hasher = new Bun.CryptoHasher('sha256');
540
+ for (const part of identity) {
541
+ hasher.update(`${part}\0`);
542
+ }
543
+ for (const input of inputs) {
544
+ const bytes = readFileIfPresent(path.join(projectRoot, input));
545
+ hasher.update(`${input}\0${bytes === null ? 'absent' : `present ${bytes.byteLength}`}\0`);
546
+ if (bytes !== null) {
547
+ hasher.update(bytes);
548
+ }
549
+ }
550
+ return hasher.digest('hex');
551
+ }
552
+
553
+ function readInstallStamp(file: string): InstallStamp | null {
554
+ const bytes = readFileIfPresent(file);
555
+ if (bytes === null) {
556
+ return null;
557
+ }
558
+ // A torn or foreign stamp proves nothing was installed, which is what an
559
+ // absent one says too: the installer runs and writes a fresh one.
560
+ const inputs = field(
561
+ parseOrUndefined(() => JSON.parse(bytes.toString('utf8'))),
562
+ 'inputs',
563
+ );
564
+ return typeof inputs === 'string' ? { inputs } : null;
565
+ }
566
+
567
+ function writeInstallStamp(file: string, stamp: InstallStamp): void {
568
+ mkdirSync(path.dirname(file), { recursive: true });
569
+ writeFileSync(file, `${JSON.stringify(stamp)}\n`);
570
+ }
571
+
572
+ function readFileIfPresent(file: string): Buffer | null {
573
+ try {
574
+ return readFileSync(file);
211
575
  } catch (error) {
212
- return error;
576
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
577
+ return null;
578
+ }
579
+ throw error;
580
+ }
581
+ }
582
+
583
+ /**
584
+ * The files whose change must re-run shell entry's installs, one absolute
585
+ * path per line in $DEVENV_STATE/install-inputs. The managed .envrc watches
586
+ * each of them, so a shell direnv keeps loaded re-enters exactly when an
587
+ * installer would do something. The uv half is recorded whether or not this
588
+ * shell syncs one, so that adding a pyproject.toml is itself a change.
589
+ */
590
+ function recordInstallInputs(inputs: readonly string[]): void {
591
+ const state = process.env.DEVENV_STATE;
592
+ if (state === undefined) {
593
+ return;
594
+ }
595
+ const file = path.join(state, 'install-inputs');
596
+ const content = `${[...new Set(inputs)]
597
+ .sort()
598
+ .map((input) => path.join(projectRoot, input))
599
+ .join('\n')}\n`;
600
+ if (readFileIfPresent(file)?.toString('utf8') !== content) {
601
+ mkdirSync(state, { recursive: true });
602
+ writeFileSync(file, content);
213
603
  }
214
- return undefined;
215
604
  }
216
605
 
217
606
  function ensureTypeScriptApiPackage(root: string): void {
@@ -225,11 +614,17 @@ function ensureTypeScriptApiPackage(root: string): void {
225
614
 
226
615
  // Root bare require("typescript") and Bun store-local requires (nx lives under
227
616
  // node_modules/.bun/...) must both see the API package — not @typescript/native's TS7.
228
- forceSymlink(path.join(root, 'node_modules', 'typescript'), apiPackageRoot);
229
- forceSymlink(path.join(root, 'node_modules', '.bun', 'node_modules', 'typescript'), apiPackageRoot);
230
-
231
- assertTypescriptApiAt(path.join(root, 'node_modules', 'typescript'), apiPackageRoot);
232
- assertTypescriptApiAt(path.join(root, 'node_modules', '.bun', 'node_modules', 'typescript'), apiPackageRoot);
617
+ // A link this call did not have to write still points at the package it was
618
+ // verified against, so only a rewritten link pays for loading the compiler
619
+ // API again (a tenth of a second, on every shell entry that installs nothing).
620
+ const relinked = [
621
+ forceSymlink(path.join(root, 'node_modules', 'typescript'), apiPackageRoot),
622
+ forceSymlink(path.join(root, 'node_modules', '.bun', 'node_modules', 'typescript'), apiPackageRoot),
623
+ ];
624
+ if (relinked.includes(true)) {
625
+ assertTypescriptApiAt(path.join(root, 'node_modules', 'typescript'), apiPackageRoot);
626
+ assertTypescriptApiAt(path.join(root, 'node_modules', '.bun', 'node_modules', 'typescript'), apiPackageRoot);
627
+ }
233
628
 
234
629
  const nativeBin = path.join(root, 'node_modules', '@typescript', 'native', 'bin', 'tsc');
235
630
  const rootPackageJson = path.join(root, 'package.json');
@@ -279,7 +674,8 @@ function findInstalledTypeScriptApiPackage(root: string): string | null {
279
674
  return null;
280
675
  }
281
676
 
282
- function forceSymlink(linkPath: string, targetPath: string): void {
677
+ /** Points linkPath at targetPath; true when the link had to be (re)written. */
678
+ function forceSymlink(linkPath: string, targetPath: string): boolean {
283
679
  mkdirSync(path.dirname(linkPath), { recursive: true });
284
680
  const relativeTarget = path.relative(path.dirname(linkPath), targetPath);
285
681
  let current: string | null = null;
@@ -292,10 +688,11 @@ function forceSymlink(linkPath: string, targetPath: string): void {
292
688
  current === relativeTarget ||
293
689
  (current !== null && path.resolve(path.dirname(linkPath), current) === targetPath)
294
690
  ) {
295
- return;
691
+ return false;
296
692
  }
297
693
  rmSync(linkPath, { recursive: true, force: true });
298
694
  symlinkSync(relativeTarget, linkPath);
695
+ return true;
299
696
  }
300
697
 
301
698
  function assertTypescriptApiAt(typescriptRoot: string, expectedTarget: string): void {
@@ -317,9 +714,11 @@ function assertTypescriptApiAt(typescriptRoot: string, expectedTarget: string):
317
714
  /**
318
715
  * Keep git hook wiring local to bootstrap. Runtime pin sync
319
716
  * (`syncRootRuntimeVersions`) belongs to explicit monorepo tooling after the
320
- * package graph exists — not the installer.
717
+ * package graph exists — not the installer. Called under the install lock.
321
718
  */
322
719
  async function applyWorkspaceGitConfig(root: string): Promise<void> {
720
+ await keepRepositoryConfig(root);
721
+
323
722
  const gitDirResult = await $`git rev-parse --git-dir`.cwd(root).quiet().nothrow();
324
723
  if (gitDirResult.exitCode !== 0) {
325
724
  throw new CapturedCommandError(
@@ -332,27 +731,6 @@ async function applyWorkspaceGitConfig(root: string): Promise<void> {
332
731
 
333
732
  const gitDir = path.resolve(root, new TextDecoder().decode(gitDirResult.stdout).trim());
334
733
  const tooling = path.join(root, 'tooling');
335
-
336
- await runSetupCommand(
337
- `git config --local include.path ${path.join(tooling, 'workspace.gitconfig')}`,
338
- $`git config --local include.path ${path.join(tooling, 'workspace.gitconfig')}`,
339
- { quiet: false },
340
- );
341
-
342
- // Keep the newer runtime version pins on any merge (nvfetcher overlay +
343
- // devenv.lock) so a mirror sync's `git am --3way` never stalls on a version
344
- // conflict. Mapped by the managed .gitattributes (merge=smoo-newer-pins);
345
- // implemented in tooling/direnv/merge-newer-pins.sh.
346
- await runSetupCommand(
347
- 'git config --local merge.smoo-newer-pins.name keep the newer devenv/nvfetcher runtime pins',
348
- $`git config --local merge.smoo-newer-pins.name ${'keep the newer devenv/nvfetcher runtime pins'}`,
349
- { quiet: false },
350
- );
351
- await runSetupCommand(
352
- 'git config --local merge.smoo-newer-pins.driver bash tooling/direnv/merge-newer-pins.sh %O %A %B %P',
353
- $`git config --local merge.smoo-newer-pins.driver ${'bash tooling/direnv/merge-newer-pins.sh %O %A %B %P'}`,
354
- { quiet: false },
355
- );
356
734
  linkHook(gitDir, tooling, 'pre-commit');
357
735
  installPostCommitHook(gitDir, tooling);
358
736
  linkHook(gitDir, tooling, 'commit-msg');
@@ -431,17 +809,123 @@ function readLinkOrNull(hookPath: string): string | null {
431
809
  async function runSetupCommand(
432
810
  command: string,
433
811
  shell: ReturnType<typeof $>,
434
- options: { quiet?: boolean } = {},
812
+ options: { quiet?: boolean; cwd?: string } = {},
435
813
  ): Promise<void> {
436
814
  const result = await shell
437
815
  .quiet(options.quiet ?? true)
438
816
  .nothrow()
439
- .cwd(projectRoot);
817
+ .cwd(options.cwd ?? projectRoot);
440
818
  if (result.exitCode !== 0) {
441
819
  throw new CapturedCommandError(command, result.exitCode, result.stdout, result.stderr);
442
820
  }
443
821
  }
444
822
 
823
+ /**
824
+ * One value the repository's own config holds. `replaces` is a pattern over the
825
+ * key's existing values: the values it matches are this one's to replace, and
826
+ * every other value of the key stays. Without it the value replaces them all.
827
+ */
828
+ interface RepositorySetting {
829
+ readonly key: string;
830
+ readonly value: string;
831
+ readonly replaces?: string;
832
+ }
833
+
834
+ /**
835
+ * The repository config shell entry keeps, read first and written only where
836
+ * it differs.
837
+ *
838
+ * Shell entry runs on every direnv reload, and git writes a config by taking
839
+ * `config.lock` exclusively: of two shell entries writing at once — a shell
840
+ * pool warming a spare beside a command's own activation — one fails with
841
+ * `could not lock config file`. The caller holds the install lock, so no two
842
+ * entries write together, and an entry that finds the config already correct
843
+ * starts no writer at all.
844
+ *
845
+ * tooling/workspace.gitconfig is included by a path relative to the config
846
+ * file, so the include names this checkout wherever the checkout is. An
847
+ * absolute path names the checkout that first wrote it: a copy-on-write clone
848
+ * copies .git/config verbatim, and git refuses to run at all — `fatal: unable
849
+ * to access` — when an include exists but cannot be read, which is exactly
850
+ * what the original checkout is from inside a sandboxed clone. Every include
851
+ * of a workspace.gitconfig is replaced; any other include the user added
852
+ * stays.
853
+ *
854
+ * Reads and writes therefore go through nothing of git's repository
855
+ * discovery: the config file is located on disk and read and edited with
856
+ * `--file` from outside the repository, which loads no local config and so
857
+ * follows no stale include.
858
+ */
859
+ async function keepRepositoryConfig(root: string): Promise<void> {
860
+ const configFile = repositoryConfigFile(root);
861
+ const outside = path.parse(configFile).root;
862
+ const settings: RepositorySetting[] = [
863
+ {
864
+ key: 'include.path',
865
+ value: path.relative(path.dirname(configFile), path.join(root, 'tooling', 'workspace.gitconfig')),
866
+ replaces: '(^|/)tooling/workspace\\.gitconfig$',
867
+ },
868
+ // Keep the newer runtime version pins on any merge (nvfetcher overlay +
869
+ // devenv.lock) so a mirror sync's `git am --3way` never stalls on a
870
+ // version conflict. Mapped by the managed .gitattributes
871
+ // (merge=smoo-newer-pins); implemented in tooling/direnv/merge-newer-pins.sh.
872
+ { key: 'merge.smoo-newer-pins.name', value: 'keep the newer devenv/nvfetcher runtime pins' },
873
+ { key: 'merge.smoo-newer-pins.driver', value: 'bash tooling/direnv/merge-newer-pins.sh %O %A %B %P' },
874
+ ];
875
+ const keys = `^(${settings.map((setting) => setting.key.replaceAll('.', '\\.')).join('|')})$`;
876
+ const read = await $`git config --file ${configFile} --get-regexp ${keys}`.cwd(outside).quiet().nothrow();
877
+ // Exit 1 is git's "no such key": nothing is set yet.
878
+ if (read.exitCode !== 0 && read.exitCode !== 1) {
879
+ throw new CapturedCommandError(
880
+ `git config --file ${configFile} --get-regexp '${keys}'`,
881
+ read.exitCode,
882
+ read.stdout,
883
+ read.stderr,
884
+ );
885
+ }
886
+ const current = new Map<string, string[]>();
887
+ for (const line of read.stdout.toString().split('\n')) {
888
+ if (line === '') {
889
+ continue;
890
+ }
891
+ const space = line.indexOf(' ');
892
+ const key = space === -1 ? line : line.slice(0, space);
893
+ current.set(key, [...(current.get(key) ?? []), space === -1 ? '' : line.slice(space + 1)]);
894
+ }
895
+ for (const setting of settings) {
896
+ const replaced = setting.replaces === undefined ? null : new RegExp(setting.replaces);
897
+ const owned = (current.get(setting.key) ?? []).filter((value) => replaced?.test(value) ?? true);
898
+ if (owned.length === 1 && owned[0] === setting.value) {
899
+ continue;
900
+ }
901
+ const pattern = setting.replaces === undefined ? [] : [setting.replaces];
902
+ await runSetupCommand(
903
+ `git config --file ${configFile} --replace-all ${setting.key} ${setting.value}${pattern.map((value) => ` '${value}'`).join('')}`,
904
+ $`git config --file ${configFile} --replace-all ${setting.key} ${setting.value} ${pattern}`,
905
+ { quiet: false, cwd: outside },
906
+ );
907
+ }
908
+ }
909
+
910
+ /**
911
+ * The config file git reads as this checkout's local config: `.git/config`,
912
+ * or, when `.git` is a worktree's `gitdir:` pointer, the config in that
913
+ * worktree's common directory.
914
+ */
915
+ function repositoryConfigFile(root: string): string {
916
+ const dotGit = path.join(root, '.git');
917
+ if (statSync(dotGit).isDirectory()) {
918
+ return path.join(dotGit, 'config');
919
+ }
920
+ const pointer = /^gitdir: (.+)$/m.exec(readFileSync(dotGit, 'utf8'));
921
+ if (pointer?.[1] === undefined) {
922
+ throw new Error(`${dotGit} is neither a git directory nor a gitdir pointer`);
923
+ }
924
+ const gitDir = path.resolve(root, pointer[1].trim());
925
+ const commonDir = readFileIfPresent(path.join(gitDir, 'commondir'));
926
+ return path.join(commonDir === null ? gitDir : path.resolve(gitDir, commonDir.toString('utf8').trim()), 'config');
927
+ }
928
+
445
929
  function reportSetupFailure(error: unknown): never {
446
930
  describeFailure('ERROR', error);
447
931
  process.exit(1);