@smoothbricks/nx-plugin 0.4.15 → 0.4.16

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 (114) hide show
  1. package/README.md +17 -0
  2. package/dist/deploy-policy.d.ts +26 -0
  3. package/dist/deploy-policy.d.ts.map +1 -0
  4. package/dist/deploy-policy.js +36 -0
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +153 -14
  7. package/dist/managed-assets.d.ts +3 -0
  8. package/dist/managed-assets.d.ts.map +1 -0
  9. package/dist/managed-assets.js +3 -0
  10. package/dist/managed-files/ci-workflow.d.ts +215 -0
  11. package/dist/managed-files/ci-workflow.d.ts.map +1 -0
  12. package/dist/managed-files/ci-workflow.js +1082 -0
  13. package/dist/managed-files/context.d.ts +51 -0
  14. package/dist/managed-files/context.d.ts.map +1 -0
  15. package/dist/managed-files/context.js +206 -0
  16. package/dist/managed-files/files.d.ts +53 -0
  17. package/dist/managed-files/files.d.ts.map +1 -0
  18. package/dist/managed-files/files.js +248 -0
  19. package/dist/managed-files/generator.d.ts +16 -0
  20. package/dist/managed-files/generator.d.ts.map +1 -0
  21. package/dist/managed-files/generator.js +41 -0
  22. package/dist/managed-files/github-runs-on.d.ts +19 -0
  23. package/dist/managed-files/github-runs-on.d.ts.map +1 -0
  24. package/dist/managed-files/github-runs-on.js +48 -0
  25. package/dist/managed-files/managed-content.d.ts +45 -0
  26. package/dist/managed-files/managed-content.d.ts.map +1 -0
  27. package/dist/managed-files/managed-content.js +102 -0
  28. package/dist/managed-files/managed-format.d.ts +37 -0
  29. package/dist/managed-files/managed-format.d.ts.map +1 -0
  30. package/dist/managed-files/managed-format.js +94 -0
  31. package/dist/managed-files/paths.d.ts +8 -0
  32. package/dist/managed-files/paths.d.ts.map +1 -0
  33. package/dist/managed-files/paths.js +46 -0
  34. package/dist/managed-files/pr-preview-cleanup-workflow.d.ts +5 -0
  35. package/dist/managed-files/pr-preview-cleanup-workflow.d.ts.map +1 -0
  36. package/dist/managed-files/pr-preview-cleanup-workflow.js +38 -0
  37. package/dist/managed-files/private-npm-policy.d.ts +7 -0
  38. package/dist/managed-files/private-npm-policy.d.ts.map +1 -0
  39. package/dist/managed-files/private-npm-policy.js +51 -0
  40. package/dist/managed-files/publish-workflow.d.ts +150 -0
  41. package/dist/managed-files/publish-workflow.d.ts.map +1 -0
  42. package/dist/managed-files/publish-workflow.js +989 -0
  43. package/dist/managed-files/tree.d.ts +30 -0
  44. package/dist/managed-files/tree.d.ts.map +1 -0
  45. package/dist/managed-files/tree.js +91 -0
  46. package/dist/platform-targets.d.ts +5 -0
  47. package/dist/platform-targets.d.ts.map +1 -0
  48. package/dist/platform-targets.js +4 -0
  49. package/dist/typecheck-test-policy.d.ts +5 -9
  50. package/dist/typecheck-test-policy.d.ts.map +1 -1
  51. package/dist/typecheck-test-policy.js +69 -99
  52. package/dist/workspace-config-policy.d.ts +2 -3
  53. package/dist/workspace-config-policy.d.ts.map +1 -1
  54. package/dist/workspace-config-policy.js +8 -3
  55. package/dist/workspace-manifest.d.ts +291 -0
  56. package/dist/workspace-manifest.d.ts.map +1 -0
  57. package/dist/workspace-manifest.js +6 -0
  58. package/dist/workspace-package-policy.d.ts +13 -0
  59. package/dist/workspace-package-policy.d.ts.map +1 -0
  60. package/dist/workspace-package-policy.js +24 -0
  61. package/generators.json +5 -0
  62. package/managed/raw/envrc +20 -0
  63. package/managed/raw/git-format-staged.yml +82 -0
  64. package/managed/raw/gitattributes +8 -0
  65. package/managed/raw/tooling/devenv +83 -0
  66. package/managed/raw/tooling/direnv/devenv.smoo.nix +422 -0
  67. package/managed/raw/tooling/direnv/github-actions-bootstrap.sh +251 -0
  68. package/managed/raw/tooling/direnv/merge-newer-pins.sh +48 -0
  69. package/managed/raw/tooling/direnv/repo-path +34 -0
  70. package/managed/raw/tooling/direnv/secret-references.ts +636 -0
  71. package/managed/raw/tooling/direnv/setup-environment.ts +585 -0
  72. package/managed/raw/tooling/direnv/toolchain-stamp.ts +88 -0
  73. package/managed/raw/tooling/git-hooks/commit-msg.sh +9 -0
  74. package/managed/raw/tooling/git-hooks/post-commit.sh +71 -0
  75. package/managed/raw/tooling/git-hooks/pre-commit.sh +18 -0
  76. package/managed/raw/tooling/git-hooks/pre-push.sh +48 -0
  77. package/managed/raw/tsconfig.lib.json +28 -0
  78. package/managed/templates/github/actions/cache-nix-devenv/action.yml +45 -0
  79. package/managed/templates/github/actions/cache-node-modules/action.yml +17 -0
  80. package/managed/templates/github/actions/cache-nx/action.yml +21 -0
  81. package/managed/templates/github/actions/cache-ttsc-plugins/action.yml +19 -0
  82. package/managed/templates/github/actions/save-nix-devenv/action.yml +32 -0
  83. package/managed/templates/github/actions/setup-devenv/action.yml +241 -0
  84. package/managed/templates/github/workflows/managed-files.yml +127 -0
  85. package/package.json +89 -5
  86. package/src/bun-bootstrap.test.ts +0 -6
  87. package/src/deploy-policy.ts +40 -0
  88. package/src/index.test.ts +225 -2
  89. package/src/index.ts +180 -14
  90. package/src/managed-assets.ts +4 -0
  91. package/src/managed-files/ci-workflow.ts +1365 -0
  92. package/src/managed-files/context.ts +240 -0
  93. package/src/managed-files/files.ts +324 -0
  94. package/src/managed-files/generator.test.ts +151 -0
  95. package/src/managed-files/generator.ts +60 -0
  96. package/src/managed-files/github-runs-on.ts +51 -0
  97. package/src/managed-files/managed-content.test.ts +147 -0
  98. package/src/managed-files/managed-content.ts +121 -0
  99. package/src/managed-files/managed-format.ts +102 -0
  100. package/src/managed-files/paths.ts +44 -0
  101. package/src/managed-files/pr-preview-cleanup-workflow.ts +44 -0
  102. package/src/managed-files/private-npm-policy.ts +62 -0
  103. package/src/managed-files/publish-workflow.ts +1523 -0
  104. package/src/managed-files/schema.json +8 -0
  105. package/src/managed-files/tree-permissions.test.ts +109 -0
  106. package/src/managed-files/tree.test.ts +123 -0
  107. package/src/managed-files/tree.ts +118 -0
  108. package/src/platform-targets.ts +4 -0
  109. package/src/typecheck-test-policy.test.ts +28 -3
  110. package/src/typecheck-test-policy.ts +46 -121
  111. package/src/workspace-config-policy.test.ts +14 -2
  112. package/src/workspace-config-policy.ts +9 -3
  113. package/src/workspace-manifest.ts +327 -0
  114. package/src/workspace-package-policy.ts +32 -0
@@ -0,0 +1,585 @@
1
+ #!/usr/bin/env bun
2
+ import {
3
+ chmodSync,
4
+ existsSync,
5
+ mkdirSync,
6
+ readdirSync,
7
+ readFileSync,
8
+ readlinkSync,
9
+ rmSync,
10
+ symlinkSync,
11
+ writeFileSync,
12
+ } from 'node:fs';
13
+ import { mkdir, rmdir, stat } from 'node:fs/promises';
14
+ import { createRequire } from 'node:module';
15
+ import path from 'node:path';
16
+ import { $ } from 'bun';
17
+ import {
18
+ type DeferredSecret,
19
+ dependentGroups,
20
+ maskSecretValues,
21
+ resolveSecretEnvironment,
22
+ SHELL_GROUP,
23
+ } from './secret-references.ts';
24
+
25
+ // DEVENV_ROOT is set by the devenv shell, which is how this script normally
26
+ // runs. CI jobs that install dependencies without building that shell (the
27
+ // publishing job installs Bun and Node directly) have no such variable, so fall
28
+ // back to the git top level rather than resolving "undefined/../.." two levels
29
+ // above the repository and failing with "could not find a package.json".
30
+ const devenvRoot = process.env.DEVENV_ROOT;
31
+
32
+ class CapturedCommandError extends Error {
33
+ constructor(
34
+ public readonly command: string,
35
+ public readonly exitCode: number,
36
+ public readonly stdout: Uint8Array,
37
+ public readonly stderr: Uint8Array,
38
+ ) {
39
+ super(`${command} failed with exit code ${exitCode}`);
40
+ }
41
+ }
42
+
43
+ // Every value resolved out of smoo.secrets below. The install inherits them,
44
+ // so whatever a failing child echoed is redacted before its captured output
45
+ // is replayed. Declared above the first replay site (resolveProjectRoot's own
46
+ // failure) because module consts are not hoisted: a reference from there to a
47
+ // const declared further down would report a temporal-dead-zone error instead
48
+ // of the failure it was called to report.
49
+ const resolvedSecretValues: string[] = [];
50
+
51
+ // The declared secrets shell entry deliberately did NOT resolve — see THE
52
+ // RULE in secret-references.ts: shell entry resolves the `shell` group and
53
+ // nothing else. Nonempty only when this repository declares a secret in
54
+ // another group that is absent from this environment. An installed checkout
55
+ // contacts no registry and Nx needs no cache to run, so this stays silent;
56
+ // it is printed by reportDegradedSetup, where an install has already failed
57
+ // and a 401 is one of the things it might have been.
58
+ const deferredSecrets: DeferredSecret[] = [];
59
+
60
+ async function resolveProjectRoot(): Promise<string> {
61
+ if (devenvRoot) {
62
+ return path.resolve(`${devenvRoot}/../..`);
63
+ }
64
+
65
+ const result = await $`git rev-parse --show-toplevel`.quiet().nothrow();
66
+ if (result.exitCode !== 0) {
67
+ const error = new CapturedCommandError(
68
+ 'git rev-parse --show-toplevel',
69
+ result.exitCode,
70
+ result.stdout,
71
+ result.stderr,
72
+ );
73
+ replayCapturedOutput(error);
74
+ throw error;
75
+ }
76
+ return new TextDecoder().decode(result.stdout).trim();
77
+ }
78
+
79
+ const projectRoot = await resolveProjectRoot();
80
+
81
+ // A legitimate concurrent setup finishes well within this; anything older is a
82
+ // leftover from an interrupted run (CTRL-C/kill before the finally-cleanup) and
83
+ // would otherwise wedge every future shell load behind the 120s spin + EEXIST.
84
+ // NOTE: must be declared ABOVE the top-level setup block below — module consts
85
+ // are not hoisted, and the lock loop runs during that block.
86
+ const STALE_LOCK_MS = 10 * 60_000;
87
+ // Unscoped require("typescript") must expose the TS6 compiler API for Nx.
88
+ // @typescript/native installs another package also named "typescript" (TS7). Bun's
89
+ // isolated linker RACES the node_modules/.bun/node_modules/typescript fallback link
90
+ // between the two versions on every install (verified nondeterministic on bun 1.3.14
91
+ // AND 1.4.0 — the #33834 alias-resolution fix did not cover it), so packages resolved
92
+ // from the .bun store (nx) sometimes get version.cjs without readConfigFile.
93
+ // After every install, force both unscoped typescript slots onto typescript@6.0.3.
94
+ // Keep @typescript/native for ttsc via TTSC_TSGO_BINARY. Do not retire this on a bun
95
+ // bump until https://github.com/oven-sh/bun/issues/40355 is fixed and re-verified.
96
+ const TYPESCRIPT_API_VERSION = '6.0.3';
97
+
98
+ // post-commit is the one hook slot smoo shares. Tools that nudge a backup or a
99
+ // mirror after every commit (git-backup, git-auto-remote) install themselves by
100
+ // appending a fenced block to whatever hook file is already there, so a symlink
101
+ // is doubly wrong here: it would delete their block, and their next install
102
+ // would write through the link into the managed template. Own a fenced block
103
+ // that calls the managed script instead, which is the convention they document.
104
+ // Declared above the bootstrap block below, which installs the hook: module
105
+ // consts are not hoisted, so declaring them beside installPostCommitHook would
106
+ // report a temporal-dead-zone error instead of installing anything.
107
+ const POST_COMMIT_BEGIN = '# >>> smoo post-commit >>>';
108
+ const POST_COMMIT_END = '# <<< smoo post-commit <<<';
109
+ const POST_COMMIT_BLOCK = [
110
+ POST_COMMIT_BEGIN,
111
+ '# Restore the index for the paths the commit just wrote: a partial commit',
112
+ '# (git commit --only -- <paths>) builds its tree from the worktree, so the',
113
+ '# pre-commit formatter never reaches the real index. Mechanism in the script.',
114
+ '"$(git rev-parse --show-toplevel)/tooling/git-hooks/post-commit.sh"',
115
+ POST_COMMIT_END,
116
+ ].join('\n');
117
+
118
+ // Go to project root
119
+ process.chdir(projectRoot);
120
+
121
+ try {
122
+ // Bootstrap only: install deps + wire local git hooks/config.
123
+ // Do not import workspace packages here — this script is what installs them,
124
+ // and package resolution/Typia transforms are not available yet.
125
+ if (process.env.CI) {
126
+ await resolveSecrets();
127
+ // Concurrent devenv activations share one node_modules, so the CI
128
+ // installs race exactly like local ones (EEXIST link failures under
129
+ // parallel shells). Serialize them under the same setup lock. Nothing
130
+ // that exits the process may run inside the callback: process.exit
131
+ // skips the finally that releases the lock and strands it, so failures
132
+ // are captured inside and reported outside.
133
+ let frozenError: unknown;
134
+ let fallbackError: unknown;
135
+ await withSetupLock(async () => {
136
+ try {
137
+ await runSetupCommand('bun install --frozen-lockfile', $`bun install --frozen-lockfile`, { quiet: false });
138
+ } catch (error) {
139
+ frozenError = error;
140
+ console.error('! Failed to install dependencies with frozen lockfile');
141
+ replayCapturedOutput(error);
142
+ try {
143
+ await runSetupCommand('bun install', $`bun install`, { quiet: false });
144
+ } catch (fallback) {
145
+ fallbackError = fallback;
146
+ }
147
+ }
148
+ });
149
+ if (fallbackError !== undefined) {
150
+ reportSetupFailure(fallbackError);
151
+ }
152
+ if (frozenError !== undefined) {
153
+ console.error('git diff after install:');
154
+ try {
155
+ await runSetupCommand('git diff', $`git diff`, { quiet: false });
156
+ } catch (diffError) {
157
+ // This diff is diagnostics for the install failure we are already
158
+ // reporting, so it must never become the failure: say it broke and keep
159
+ // the original exit path. Plain `git diff` exits 0 even when the
160
+ // lockfile drifted, so a non-zero here means git itself failed.
161
+ console.error(`! git diff failed: ${diffError instanceof Error ? diffError.message : String(diffError)}`);
162
+ }
163
+ process.exit(1);
164
+ }
165
+ } else {
166
+ // A local secret-resolution or install failure (a provider that is not
167
+ // signed in, an unpublished private package, a missing registry
168
+ // credential, a lockfile that needs `devenv update`) must not take the
169
+ // shell down with it: direnv drops the whole environment on a non-zero
170
+ // exit, and then bun, nx, op and every other tool needed to repair the
171
+ // install are gone too. Report it, finish what does not depend on the
172
+ // install, and load the shell. CI above stays strict.
173
+ const installError = await installLocalDependencies();
174
+ if (installError === undefined) {
175
+ // Pin unscoped typescript → API 6 for root and Bun's shared .bun hoist (Nx).
176
+ ensureTypeScriptApiPackage(projectRoot);
177
+ }
178
+ await applyWorkspaceGitConfig(projectRoot);
179
+ if (installError !== undefined) {
180
+ reportDegradedSetup(installError);
181
+ }
182
+ }
183
+ } catch (error) {
184
+ reportSetupFailure(error);
185
+ }
186
+
187
+ /**
188
+ * Provider-declared secrets (smoo.secrets) resolve before any install. The
189
+ * values land in THIS process environment only — bun install, the prepare
190
+ * scripts it runs, and every later child of this script inherit them (for
191
+ * example .npmrc `${VAR}` auth); the direnv shell itself does not, which is
192
+ * the point: this script must never act as a global shell export.
193
+ *
194
+ * `shell` is the group, and it is what keeps a credential only a deliberate
195
+ * command needs — a registry token, the Nx cache token — from running its
196
+ * provider command on every direnv reload. Such a variable comes back
197
+ * deferred instead of resolved, and an install proceeds without it — which
198
+ * is the normal case, because an installed checkout contacts no registry.
199
+ * The install that does need one fails, and reportDegradedSetup then names
200
+ * the variable and the exact command that supplies it.
201
+ */
202
+ async function resolveSecrets(): Promise<void> {
203
+ const resolution = await resolveSecretEnvironment({ root: projectRoot, group: SHELL_GROUP });
204
+ for (const [name, value] of Object.entries(resolution.values)) {
205
+ process.env[name] = value;
206
+ resolvedSecretValues.push(value);
207
+ }
208
+ deferredSecrets.push(...resolution.deferred);
209
+ }
210
+
211
+ async function installLocalDependencies(): Promise<unknown> {
212
+ try {
213
+ await resolveSecrets();
214
+ } catch (error) {
215
+ return error;
216
+ }
217
+ // bun install runs the root prepare script. Multiple concurrent direnv
218
+ // activations can otherwise race while mutating the same files under
219
+ // node_modules. Nothing that exits the process may run inside the callback
220
+ // (see the CI branch), so the failure is returned, not thrown.
221
+ let installError: unknown;
222
+ await withSetupLock(async () => {
223
+ try {
224
+ await runSetupCommand('bun install --no-summary', $`bun install --no-summary`);
225
+ } catch (error) {
226
+ installError = error;
227
+ }
228
+ });
229
+ return installError;
230
+ }
231
+
232
+ function ensureTypeScriptApiPackage(root: string): void {
233
+ const apiPackageRoot = findInstalledTypeScriptApiPackage(root);
234
+ if (!apiPackageRoot) {
235
+ throw new Error(
236
+ `typescript@${TYPESCRIPT_API_VERSION} was not installed under node_modules/.bun. ` +
237
+ `Keep root devDependency typescript@^${TYPESCRIPT_API_VERSION} (compiler API for Nx).`,
238
+ );
239
+ }
240
+
241
+ // Root bare require("typescript") and Bun store-local requires (nx lives under
242
+ // node_modules/.bun/...) must both see the API package — not @typescript/native's TS7.
243
+ forceSymlink(path.join(root, 'node_modules', 'typescript'), apiPackageRoot);
244
+ forceSymlink(path.join(root, 'node_modules', '.bun', 'node_modules', 'typescript'), apiPackageRoot);
245
+
246
+ assertTypescriptApiAt(path.join(root, 'node_modules', 'typescript'), apiPackageRoot);
247
+ assertTypescriptApiAt(path.join(root, 'node_modules', '.bun', 'node_modules', 'typescript'), apiPackageRoot);
248
+
249
+ const nativeBin = path.join(root, 'node_modules', '@typescript', 'native', 'bin', 'tsc');
250
+ const rootPackageJson = path.join(root, 'package.json');
251
+ const declaresNative =
252
+ existsSync(rootPackageJson) &&
253
+ (() => {
254
+ try {
255
+ const pkg = JSON.parse(readFileSync(rootPackageJson, 'utf8')) as {
256
+ devDependencies?: Record<string, string>;
257
+ dependencies?: Record<string, string>;
258
+ };
259
+ return (
260
+ typeof pkg.devDependencies?.['@typescript/native'] === 'string' ||
261
+ typeof pkg.dependencies?.['@typescript/native'] === 'string'
262
+ );
263
+ } catch {
264
+ return false;
265
+ }
266
+ })();
267
+ if (declaresNative && !existsSync(nativeBin)) {
268
+ throw new Error(
269
+ `Missing ${nativeBin}. package.json declares @typescript/native but it is not installed. ` +
270
+ 'Run bun install (or direnv reload). @typescript/native is the TypeScript 7 native compiler for ttsc.',
271
+ );
272
+ }
273
+ }
274
+
275
+ function findInstalledTypeScriptApiPackage(root: string): string | null {
276
+ const bunStore = path.join(root, 'node_modules', '.bun');
277
+ if (!existsSync(bunStore)) {
278
+ return null;
279
+ }
280
+ const exact = `typescript@${TYPESCRIPT_API_VERSION}`;
281
+ const names = readdirSync(bunStore)
282
+ .filter((name) => name === exact || name.startsWith(`${exact}+`) || name.startsWith('typescript@6.'))
283
+ .sort((a, b) => {
284
+ const aExact = a === exact || a.startsWith(`${exact}+`) ? 0 : 1;
285
+ const bExact = b === exact || b.startsWith(`${exact}+`) ? 0 : 1;
286
+ return aExact - bExact || a.localeCompare(b);
287
+ });
288
+ for (const name of names) {
289
+ const candidate = path.join(bunStore, name, 'node_modules', 'typescript');
290
+ if (existsSync(path.join(candidate, 'package.json'))) {
291
+ return candidate;
292
+ }
293
+ }
294
+ return null;
295
+ }
296
+
297
+ function forceSymlink(linkPath: string, targetPath: string): void {
298
+ mkdirSync(path.dirname(linkPath), { recursive: true });
299
+ const relativeTarget = path.relative(path.dirname(linkPath), targetPath);
300
+ let current: string | null = null;
301
+ try {
302
+ current = readlinkSync(linkPath);
303
+ } catch {
304
+ current = null;
305
+ }
306
+ if (
307
+ current === relativeTarget ||
308
+ (current !== null && path.resolve(path.dirname(linkPath), current) === targetPath)
309
+ ) {
310
+ return;
311
+ }
312
+ rmSync(linkPath, { recursive: true, force: true });
313
+ symlinkSync(relativeTarget, linkPath);
314
+ }
315
+
316
+ function assertTypescriptApiAt(typescriptRoot: string, expectedTarget: string): void {
317
+ if (!existsSync(typescriptRoot)) {
318
+ throw new Error(`Missing ${typescriptRoot} after linking TypeScript ${TYPESCRIPT_API_VERSION} API package`);
319
+ }
320
+ const requireFromInstall = createRequire(path.join(typescriptRoot, 'package.json'));
321
+ const typed = requireFromInstall(typescriptRoot) as { version?: string; readConfigFile?: unknown };
322
+ if (typeof typed.readConfigFile !== 'function' || typed.version !== TYPESCRIPT_API_VERSION) {
323
+ throw new Error(
324
+ `${typescriptRoot} must export TypeScript ${TYPESCRIPT_API_VERSION} compiler API (readConfigFile). ` +
325
+ `Resolved version ${typed.version ?? 'unknown'} (expected link target ${expectedTarget}). ` +
326
+ 'Bun isolated linking races .bun/node_modules/typescript between typescript@6 and ' +
327
+ "@typescript/native's TS7. See https://github.com/oven-sh/bun/issues/40355.",
328
+ );
329
+ }
330
+ }
331
+
332
+ /**
333
+ * Keep git hook wiring local to bootstrap. Runtime pin sync
334
+ * (`syncRootRuntimeVersions`) belongs to explicit monorepo tooling after the
335
+ * package graph exists — not the installer.
336
+ */
337
+ async function applyWorkspaceGitConfig(root: string): Promise<void> {
338
+ const gitDirResult = await $`git rev-parse --git-dir`.cwd(root).quiet().nothrow();
339
+ if (gitDirResult.exitCode !== 0) {
340
+ throw new CapturedCommandError(
341
+ 'git rev-parse --git-dir',
342
+ gitDirResult.exitCode,
343
+ gitDirResult.stdout,
344
+ gitDirResult.stderr,
345
+ );
346
+ }
347
+
348
+ const gitDir = path.resolve(root, new TextDecoder().decode(gitDirResult.stdout).trim());
349
+ const tooling = path.join(root, 'tooling');
350
+
351
+ await runSetupCommand(
352
+ `git config --local include.path ${path.join(tooling, 'workspace.gitconfig')}`,
353
+ $`git config --local include.path ${path.join(tooling, 'workspace.gitconfig')}`,
354
+ { quiet: false },
355
+ );
356
+
357
+ // Keep the newer runtime version pins on any merge (nvfetcher overlay +
358
+ // devenv.lock) so a mirror sync's `git am --3way` never stalls on a version
359
+ // conflict. Mapped by the managed .gitattributes (merge=smoo-newer-pins);
360
+ // implemented in tooling/direnv/merge-newer-pins.sh.
361
+ await runSetupCommand(
362
+ 'git config --local merge.smoo-newer-pins.name keep the newer devenv/nvfetcher runtime pins',
363
+ $`git config --local merge.smoo-newer-pins.name ${'keep the newer devenv/nvfetcher runtime pins'}`,
364
+ { quiet: false },
365
+ );
366
+ await runSetupCommand(
367
+ 'git config --local merge.smoo-newer-pins.driver bash tooling/direnv/merge-newer-pins.sh %O %A %B %P',
368
+ $`git config --local merge.smoo-newer-pins.driver ${'bash tooling/direnv/merge-newer-pins.sh %O %A %B %P'}`,
369
+ { quiet: false },
370
+ );
371
+ linkHook(gitDir, tooling, 'pre-commit');
372
+ installPostCommitHook(gitDir, tooling);
373
+ linkHook(gitDir, tooling, 'commit-msg');
374
+ linkHook(gitDir, tooling, 'pre-push');
375
+ }
376
+
377
+ function linkHook(gitDir: string, tooling: string, name: string): void {
378
+ const source = path.join(tooling, 'git-hooks', `${name}.sh`);
379
+ if (!existsSync(source)) {
380
+ throw new Error(`Missing ${name} hook source: ${source}`);
381
+ }
382
+
383
+ const target = path.join(gitDir, 'hooks', name);
384
+ if (readLinkOrNull(target) === source) {
385
+ return;
386
+ }
387
+
388
+ mkdirSync(path.dirname(target), { recursive: true });
389
+ rmSync(target, { force: true });
390
+ symlinkSync(source, target);
391
+ }
392
+
393
+ function installPostCommitHook(gitDir: string, tooling: string): void {
394
+ const source = path.join(tooling, 'git-hooks', 'post-commit.sh');
395
+ if (!existsSync(source)) {
396
+ throw new Error(`Missing post-commit hook source: ${source}`);
397
+ }
398
+
399
+ const target = path.join(gitDir, 'hooks', 'post-commit');
400
+ const link = readLinkOrNull(target);
401
+ if (link !== null) {
402
+ // Never append through a symlink: that writes into whatever it points at.
403
+ // Say which link went, so a hook belonging to something else can be put
404
+ // back as a block beside ours instead of vanishing silently.
405
+ console.warn(`Replaced symlinked post-commit hook (was ${link}) with a chainable block`);
406
+ }
407
+
408
+ // Every foreign block is preserved, ours is replaced rather than repeated,
409
+ // and the shebang is only ours to choose when the file did not exist.
410
+ const existing = link === null && existsSync(target) ? readFileSync(target, 'utf8') : '';
411
+ const kept = stripPostCommitBlock(existing).replace(/\s+$/, '');
412
+ const next = `${kept === '' ? '#!/usr/bin/env bash' : kept}\n\n${POST_COMMIT_BLOCK}\n`;
413
+ if (existing === next) {
414
+ // A hook that is not executable is a hook git silently skips.
415
+ chmodSync(target, 0o755);
416
+ return;
417
+ }
418
+
419
+ mkdirSync(path.dirname(target), { recursive: true });
420
+ rmSync(target, { force: true });
421
+ writeFileSync(target, next, { mode: 0o755 });
422
+ }
423
+
424
+ function stripPostCommitBlock(content: string): string {
425
+ const lines = content.split('\n');
426
+ const start = lines.findIndex((line) => line.trim() === POST_COMMIT_BEGIN);
427
+ if (start === -1) {
428
+ return content;
429
+ }
430
+
431
+ // A block whose end marker was lost runs to the end of the file: it is ours
432
+ // to replace either way, and leaving half of it behind would double it.
433
+ const offset = lines.slice(start + 1).findIndex((line) => line.trim() === POST_COMMIT_END);
434
+ const resume = offset === -1 ? lines.length : start + offset + 2;
435
+ return [...lines.slice(0, start), ...lines.slice(resume)].join('\n');
436
+ }
437
+
438
+ function readLinkOrNull(hookPath: string): string | null {
439
+ try {
440
+ return readlinkSync(hookPath);
441
+ } catch {
442
+ return null;
443
+ }
444
+ }
445
+
446
+ async function runSetupCommand(
447
+ command: string,
448
+ shell: ReturnType<typeof $>,
449
+ options: { quiet?: boolean } = {},
450
+ ): Promise<void> {
451
+ const result = await shell
452
+ .quiet(options.quiet ?? true)
453
+ .nothrow()
454
+ .cwd(projectRoot);
455
+ if (result.exitCode !== 0) {
456
+ throw new CapturedCommandError(command, result.exitCode, result.stdout, result.stderr);
457
+ }
458
+ }
459
+
460
+ async function withSetupLock<T>(fn: () => Promise<T>): Promise<T> {
461
+ const lockDir = path.join(projectRoot, 'tooling/direnv/.devenv/setup-environment.lock');
462
+ await acquireLock(lockDir);
463
+ try {
464
+ return await fn();
465
+ } finally {
466
+ await rmdir(lockDir).catch(() => undefined);
467
+ }
468
+ }
469
+
470
+ async function acquireLock(lockDir: string): Promise<void> {
471
+ const deadline = Date.now() + 120_000;
472
+ while (true) {
473
+ try {
474
+ await mkdir(lockDir, { recursive: false });
475
+ return;
476
+ } catch (error) {
477
+ if (!isFileExistsError(error) || Date.now() > deadline) {
478
+ throw error;
479
+ }
480
+ if (await isStaleLock(lockDir)) {
481
+ // Surface the self-heal so an interrupted-run leftover is visible in
482
+ // the direnv log rather than silently absorbed.
483
+ console.error(`! Breaking stale setup lock (${lockDir}) left by an interrupted run`);
484
+ // Best-effort: if a concurrent process breaks it first, the rmdir
485
+ // fails silently and the next mkdir attempt settles the race.
486
+ await rmdir(lockDir).catch(() => undefined);
487
+ continue;
488
+ }
489
+ await Bun.sleep(100);
490
+ }
491
+ }
492
+ }
493
+
494
+ async function isStaleLock(lockDir: string): Promise<boolean> {
495
+ try {
496
+ const info = await stat(lockDir);
497
+ return Date.now() - info.mtimeMs > STALE_LOCK_MS;
498
+ } catch (error) {
499
+ // Only "lock vanished" is expected here (a concurrent process released
500
+ // it); anything else must surface — a swallowed ReferenceError in this
501
+ // exact spot once disabled stale detection entirely.
502
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
503
+ return false; // gone — let the mkdir retry acquire it
504
+ }
505
+ throw error;
506
+ }
507
+ }
508
+
509
+ function isFileExistsError(error: unknown): boolean {
510
+ return error instanceof Error && 'code' in error && error.code === 'EEXIST';
511
+ }
512
+
513
+ function reportSetupFailure(error: unknown): never {
514
+ describeFailure('ERROR', error);
515
+ process.exit(1);
516
+ }
517
+
518
+ function reportDegradedSetup(error: unknown): void {
519
+ describeFailure('WARNING', error);
520
+ reportDeferredSecrets();
521
+ console.error(
522
+ 'The shell is loaded WITHOUT installed dependencies so the tools to repair this stay available.\n' +
523
+ 'Fix the cause above (missing registry credential, unpublished package, stale lockfile → `devenv update`),\n' +
524
+ 'then run `bun install` or `direnv reload`.',
525
+ );
526
+ console.error('---');
527
+ }
528
+
529
+ /**
530
+ * The declared secrets this shell entry deliberately did not resolve, named
531
+ * now that an install has actually failed. Printing them on a healthy shell
532
+ * entry would be noise on every reload — an installed checkout contacts no
533
+ * registry and needs none of them — while an install that failed may be
534
+ * exactly the 401 they explain, and then the useful output is the variable
535
+ * and the command that supplies it.
536
+ */
537
+ function reportDeferredSecrets(): void {
538
+ if (deferredSecrets.length === 0) {
539
+ return;
540
+ }
541
+ console.error('Secrets outside the `shell` group are not resolved at shell entry, by design:');
542
+ for (const secret of deferredSecrets) {
543
+ console.error(`- ${secret.name} (${secret.group}): ${secret.guidance}`);
544
+ }
545
+ // Only a group the install itself reads can explain this failure, and only
546
+ // for those is re-running the install the command worth printing. A group
547
+ // nothing here consumes — the Nx cache token — is listed above and left
548
+ // alone: it did not cause this and re-running the install with it would
549
+ // not fix it.
550
+ for (const group of dependentGroups(SHELL_GROUP)) {
551
+ if (!deferredSecrets.some((secret) => secret.group === group)) {
552
+ continue;
553
+ }
554
+ console.error(`The install reads group \`${group}\`; supply it to exactly that one command with:`);
555
+ console.error(` smoo secrets run ${group} bun install`);
556
+ }
557
+ }
558
+
559
+ function describeFailure(level: 'ERROR' | 'WARNING', error: unknown): void {
560
+ if (error instanceof CapturedCommandError) {
561
+ console.error(`--- ${level}: setup-environment.ts failed while running: ${error.command}`);
562
+ console.error(`exit code: ${error.exitCode}`);
563
+ } else {
564
+ console.error(`--- ${level}: setup-environment.ts failed: ${error}`);
565
+ }
566
+ replayCapturedOutput(error);
567
+ console.error('\n---');
568
+ }
569
+
570
+ function replayCapturedOutput(error: unknown): void {
571
+ if (!(error instanceof CapturedCommandError)) {
572
+ return;
573
+ }
574
+ // The install ran with every resolved secret in its environment, so its
575
+ // output is redacted before replay. Masking is same-length, which keeps the
576
+ // failure this replay exists to show intact.
577
+ const stdout = maskSecretValues(error.stdout, resolvedSecretValues);
578
+ const stderr = maskSecretValues(error.stderr, resolvedSecretValues);
579
+ if (stdout.length > 0) {
580
+ process.stdout.write(stdout);
581
+ }
582
+ if (stderr.length > 0) {
583
+ process.stderr.write(stderr);
584
+ }
585
+ }
@@ -0,0 +1,88 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Invalidate cmake build-script caches when the toolchain changes.
4
+ *
5
+ * cmake-rs keeps CMAKE_OSX_SYSROOT and the compilers in CMakeCache.txt from
6
+ * the FIRST configure and only clears a build directory when the source path
7
+ * moves. Every C/C++ build script's cache under target/ therefore encodes
8
+ * whichever toolchain the shell had when it was first configured, and it
9
+ * outlives every later fix to that shell: a nix-store sysroot cached on one
10
+ * day kept failing `ld: library 'c++' not found` after the shell stopped
11
+ * exporting it. Nx does not see this state either — it hashes inputs, not
12
+ * what a cache under target/ remembers.
13
+ *
14
+ * Runs at the end of shell entry, after the project's own enterShell resolved
15
+ * SDKROOT and the compilers. It records the toolchain identity the shell
16
+ * settled on and, when that identity differs from the recorded one, removes
17
+ * exactly the cargo build-script directories that hold a CMakeCache.txt, so
18
+ * cargo re-runs those scripts against the current toolchain. Nothing else
19
+ * under target/ is touched; a checkout without target/ has nothing to do.
20
+ */
21
+ import { existsSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
22
+ import { join, resolve } from 'node:path';
23
+ import { $ } from 'bun';
24
+
25
+ const root = resolve(`${process.env.DEVENV_ROOT ?? process.cwd()}/../..`);
26
+ const target = join(root, 'target');
27
+ if (existsSync(target)) {
28
+ const stamp = join(target, '.toolchain-stamp');
29
+ const identity = await toolchainIdentity();
30
+ const recorded = existsSync(stamp) ? readFileSync(stamp, 'utf8') : null;
31
+ if (recorded !== identity) {
32
+ const removed = removeCmakeBuildScriptDirs(target);
33
+ if (removed > 0) {
34
+ console.error(`devenv: toolchain identity changed; removed ${removed} cmake build-script cache(s) under target/`);
35
+ }
36
+ writeFileSync(stamp, identity);
37
+ }
38
+ }
39
+
40
+ async function toolchainIdentity(): Promise<string> {
41
+ const rustc = await $`rustc -Vv`.quiet().nothrow().text();
42
+ const cc = (await $`cc --version`.quiet().nothrow().text()).split('\n')[0] ?? '';
43
+ return [
44
+ rustc.trim(),
45
+ `SDKROOT=${process.env.SDKROOT ?? ''}`,
46
+ `DEVELOPER_DIR=${process.env.DEVELOPER_DIR ?? ''}`,
47
+ cc,
48
+ ].join('\n');
49
+ }
50
+
51
+ /**
52
+ * Removes every cargo build-script directory (`…/build/<crate>-<hash>`) whose
53
+ * `out/build/CMakeCache.txt` exists; returns the count. Only the `build/`
54
+ * directories cargo creates under a profile are scanned - never the compiled
55
+ * artifacts beside them - and the scan completes before anything is removed.
56
+ */
57
+ function removeCmakeBuildScriptDirs(target: string): number {
58
+ const stale: string[] = [];
59
+ for (const buildDir of cargoBuildDirs(target, 0)) {
60
+ for (const entry of readdirSync(buildDir, { withFileTypes: true })) {
61
+ if (entry.isDirectory() && existsSync(join(buildDir, entry.name, 'out', 'build', 'CMakeCache.txt'))) {
62
+ stale.push(join(buildDir, entry.name));
63
+ }
64
+ }
65
+ }
66
+ for (const dir of stale) {
67
+ rmSync(dir, { recursive: true, force: true });
68
+ }
69
+ return stale.length;
70
+ }
71
+
72
+ /** `target/[<lane>/][<triple>/]<profile>/build` - at most four levels below target/. */
73
+ function* cargoBuildDirs(dir: string, depth: number): Generator<string> {
74
+ if (depth > 4) {
75
+ return;
76
+ }
77
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
78
+ if (!entry.isDirectory()) {
79
+ continue;
80
+ }
81
+ const path = join(dir, entry.name);
82
+ if (entry.name === 'build' && depth > 0) {
83
+ yield path;
84
+ } else if (entry.name !== 'deps' && entry.name !== 'incremental' && entry.name !== '.fingerprint') {
85
+ yield* cargoBuildDirs(path, depth + 1);
86
+ }
87
+ }
88
+ }
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env bash
2
+ cd "$(git rev-parse --show-toplevel)"
3
+ TOOLING="$PWD/tooling"
4
+
5
+ export PATH="$("$TOOLING/direnv/repo-path")"
6
+
7
+ set -e -o pipefail
8
+
9
+ smoo monorepo validate-commit-msg --fix "$1"