@smoothbricks/nx-plugin 0.4.14 → 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 (119) hide show
  1. package/README.md +20 -3
  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 +160 -37
  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/package-target-policy.d.ts +0 -1
  47. package/dist/package-target-policy.d.ts.map +1 -1
  48. package/dist/package-target-policy.js +50 -23
  49. package/dist/platform-targets.d.ts +5 -0
  50. package/dist/platform-targets.d.ts.map +1 -0
  51. package/dist/platform-targets.js +4 -0
  52. package/dist/typecheck-test-policy.d.ts +5 -9
  53. package/dist/typecheck-test-policy.d.ts.map +1 -1
  54. package/dist/typecheck-test-policy.js +69 -99
  55. package/dist/workspace-config-policy.d.ts +23 -3
  56. package/dist/workspace-config-policy.d.ts.map +1 -1
  57. package/dist/workspace-config-policy.js +35 -3
  58. package/dist/workspace-manifest.d.ts +291 -0
  59. package/dist/workspace-manifest.d.ts.map +1 -0
  60. package/dist/workspace-manifest.js +6 -0
  61. package/dist/workspace-package-policy.d.ts +13 -0
  62. package/dist/workspace-package-policy.d.ts.map +1 -0
  63. package/dist/workspace-package-policy.js +24 -0
  64. package/generators.json +5 -0
  65. package/managed/raw/envrc +20 -0
  66. package/managed/raw/git-format-staged.yml +82 -0
  67. package/managed/raw/gitattributes +8 -0
  68. package/managed/raw/tooling/devenv +83 -0
  69. package/managed/raw/tooling/direnv/devenv.smoo.nix +422 -0
  70. package/managed/raw/tooling/direnv/github-actions-bootstrap.sh +251 -0
  71. package/managed/raw/tooling/direnv/merge-newer-pins.sh +48 -0
  72. package/managed/raw/tooling/direnv/repo-path +34 -0
  73. package/managed/raw/tooling/direnv/secret-references.ts +636 -0
  74. package/managed/raw/tooling/direnv/setup-environment.ts +585 -0
  75. package/managed/raw/tooling/direnv/toolchain-stamp.ts +88 -0
  76. package/managed/raw/tooling/git-hooks/commit-msg.sh +9 -0
  77. package/managed/raw/tooling/git-hooks/post-commit.sh +71 -0
  78. package/managed/raw/tooling/git-hooks/pre-commit.sh +18 -0
  79. package/managed/raw/tooling/git-hooks/pre-push.sh +48 -0
  80. package/managed/raw/tsconfig.lib.json +28 -0
  81. package/managed/templates/github/actions/cache-nix-devenv/action.yml +45 -0
  82. package/managed/templates/github/actions/cache-node-modules/action.yml +17 -0
  83. package/managed/templates/github/actions/cache-nx/action.yml +21 -0
  84. package/managed/templates/github/actions/cache-ttsc-plugins/action.yml +19 -0
  85. package/managed/templates/github/actions/save-nix-devenv/action.yml +32 -0
  86. package/managed/templates/github/actions/setup-devenv/action.yml +241 -0
  87. package/managed/templates/github/workflows/managed-files.yml +127 -0
  88. package/package.json +89 -5
  89. package/src/bun-bootstrap.test.ts +0 -6
  90. package/src/deploy-policy.ts +40 -0
  91. package/src/index.test.ts +232 -9
  92. package/src/index.ts +187 -40
  93. package/src/managed-assets.ts +4 -0
  94. package/src/managed-files/ci-workflow.ts +1365 -0
  95. package/src/managed-files/context.ts +240 -0
  96. package/src/managed-files/files.ts +324 -0
  97. package/src/managed-files/generator.test.ts +151 -0
  98. package/src/managed-files/generator.ts +60 -0
  99. package/src/managed-files/github-runs-on.ts +51 -0
  100. package/src/managed-files/managed-content.test.ts +147 -0
  101. package/src/managed-files/managed-content.ts +121 -0
  102. package/src/managed-files/managed-format.ts +102 -0
  103. package/src/managed-files/paths.ts +44 -0
  104. package/src/managed-files/pr-preview-cleanup-workflow.ts +44 -0
  105. package/src/managed-files/private-npm-policy.ts +62 -0
  106. package/src/managed-files/publish-workflow.ts +1523 -0
  107. package/src/managed-files/schema.json +8 -0
  108. package/src/managed-files/tree-permissions.test.ts +109 -0
  109. package/src/managed-files/tree.test.ts +123 -0
  110. package/src/managed-files/tree.ts +118 -0
  111. package/src/package-target-policy.test.ts +4 -28
  112. package/src/package-target-policy.ts +55 -31
  113. package/src/platform-targets.ts +4 -0
  114. package/src/typecheck-test-policy.test.ts +28 -3
  115. package/src/typecheck-test-policy.ts +46 -121
  116. package/src/workspace-config-policy.test.ts +14 -2
  117. package/src/workspace-config-policy.ts +42 -3
  118. package/src/workspace-manifest.ts +327 -0
  119. package/src/workspace-package-policy.ts +32 -0
@@ -0,0 +1,1082 @@
1
+ /* biome-ignore-all lint/suspicious/noTemplateCurlyInString: GitHub Actions expressions are emitted literally. */
2
+ import { parse as parseYaml } from 'yaml';
3
+ import { cargoCrossTestArchiveFile, cargoCrossTestArchiveTargetName, cargoCrossTestTargetName, } from '../cross-check-policy.js';
4
+ import { PRODUCTION_PUSH_DEPLOY_TAG } from '../deploy-policy.js';
5
+ import { renderRunsOnLine } from './github-runs-on.js';
6
+ export var CiWorkflowStepKind;
7
+ (function (CiWorkflowStepKind) {
8
+ CiWorkflowStepKind["Checkout"] = "checkout";
9
+ CiWorkflowStepKind["SourceCheckouts"] = "source-checkouts";
10
+ CiWorkflowStepKind["SetupDevenv"] = "setup-devenv";
11
+ CiWorkflowStepKind["CargoCredentials"] = "cargo-credentials";
12
+ CiWorkflowStepKind["SetNxShas"] = "set-nx-shas";
13
+ CiWorkflowStepKind["RestoreNxCache"] = "restore-nx-cache";
14
+ CiWorkflowStepKind["Build"] = "build";
15
+ CiWorkflowStepKind["BrowserTests"] = "browser-tests";
16
+ CiWorkflowStepKind["Lint"] = "lint";
17
+ CiWorkflowStepKind["UnitTests"] = "unit-tests";
18
+ CiWorkflowStepKind["CrossToolchainPreflight"] = "cross-toolchain-preflight";
19
+ CiWorkflowStepKind["CrossTestArchives"] = "cross-test-archives";
20
+ CiWorkflowStepKind["UploadCrossTestArchives"] = "upload-cross-test-archives";
21
+ CiWorkflowStepKind["DownloadCrossTestArchives"] = "download-cross-test-archives";
22
+ CiWorkflowStepKind["CrossTests"] = "cross-tests";
23
+ CiWorkflowStepKind["ManagedFilesCheck"] = "managed-files-check";
24
+ CiWorkflowStepKind["ManagedFilesDispatch"] = "managed-files-dispatch";
25
+ CiWorkflowStepKind["Deploy"] = "deploy";
26
+ CiWorkflowStepKind["SaveNxCache"] = "save-nx-cache";
27
+ CiWorkflowStepKind["UploadTraceDbs"] = "upload-trace-dbs";
28
+ CiWorkflowStepKind["SaveNixDevenv"] = "save-nix-devenv";
29
+ })(CiWorkflowStepKind || (CiWorkflowStepKind = {}));
30
+ export function defineCiWorkflow(options) {
31
+ const steps = [{ kind: CiWorkflowStepKind.Checkout, name: '📥 Checkout' }];
32
+ if (options.cargoCredentials !== undefined) {
33
+ steps.push({ kind: CiWorkflowStepKind.CargoCredentials, name: 'Prepare Cargo credentials' });
34
+ }
35
+ if (options.sourceCheckouts?.length) {
36
+ steps.push({ kind: CiWorkflowStepKind.SourceCheckouts, name: '📦 Check out sibling sources' });
37
+ }
38
+ steps.push({ kind: CiWorkflowStepKind.SetupDevenv, name: '🧱 Setup Nix/devenv' }, { kind: CiWorkflowStepKind.SetNxShas, name: '🧭 Set Nx SHAs' }, { kind: CiWorkflowStepKind.RestoreNxCache, name: '🧠 Restore Nx cache' }, { kind: CiWorkflowStepKind.Build, name: '🔨 Build' });
39
+ if (options.deploy) {
40
+ steps.push({ kind: CiWorkflowStepKind.Deploy, name: '🚀 Deploy Stage' });
41
+ }
42
+ steps.push({ kind: CiWorkflowStepKind.Lint, name: '🔍 Lint' }, { kind: CiWorkflowStepKind.UnitTests, name: '🧪 Unit Tests' });
43
+ if (options.crossTestArchives?.length) {
44
+ if (options.platformProducer !== undefined) {
45
+ steps.push({
46
+ kind: CiWorkflowStepKind.CrossToolchainPreflight,
47
+ name: 'Check cross-platform toolchain prerequisites',
48
+ });
49
+ }
50
+ steps.push({ kind: CiWorkflowStepKind.CrossTestArchives, name: '🎯 Build cross-target test archives' });
51
+ // The artifact has exactly one consumer, the execution job below. A triple
52
+ // with no native runner here is already proved by the build above, so
53
+ // uploading its archive would ship a file nothing in the run downloads —
54
+ // and would move the artifact's root off the directory the download
55
+ // restores to.
56
+ if (darwinCrossTestArchives(options).length > 0) {
57
+ steps.push({ kind: CiWorkflowStepKind.UploadCrossTestArchives, name: '📤 Upload cross-target test archives' });
58
+ }
59
+ }
60
+ if (options.browserTests) {
61
+ steps.push({ kind: CiWorkflowStepKind.BrowserTests, name: '🌐 Browser Tests' });
62
+ }
63
+ steps.push({ kind: CiWorkflowStepKind.ManagedFilesCheck, name: '🩺 Check managed-file drift' }, { kind: CiWorkflowStepKind.ManagedFilesDispatch, name: '🔁 Dispatch managed-file drift healing' }, { kind: CiWorkflowStepKind.SaveNxCache, name: '💾 Save Nx cache' }, { kind: CiWorkflowStepKind.UploadTraceDbs, name: '📎 Upload trace DBs' }, { kind: CiWorkflowStepKind.SaveNixDevenv, name: '🧹 Cleanup and cache Nix/devenv' });
64
+ return steps.map((step, index) => ({ ...step, number: index + 2 }));
65
+ }
66
+ export function renderCiWorkflowYaml(options) {
67
+ const steps = defineCiWorkflow(options);
68
+ return [
69
+ renderCiWorkflowHeader(options),
70
+ renderCiWorkflowSteps(steps, options),
71
+ renderCrossTestExecutionJob(options),
72
+ renderE2eDeploymentJob(options),
73
+ renderProductionDeployJob(options),
74
+ ].join('');
75
+ }
76
+ function renderCiWorkflowHeader(options) {
77
+ return `name: CI
78
+
79
+ on:
80
+ push:
81
+ branches:
82
+ ${renderYamlList(options.pushBranches.map(yamlScalar), 6)}
83
+ pull_request:
84
+
85
+ permissions:
86
+ # actions:write lets the drift step dispatch the managed-files workflow.
87
+ actions: write
88
+ contents: read
89
+ ${options.deploy ? ' deployments: write\n' : ''} statuses: write
90
+
91
+ concurrency:
92
+ ${options.deploy
93
+ ? ` # One in-flight run per ref. Pushes to the staging push branch queue behind a
94
+ # running workflow instead of canceling it, so a newer push never cancels the
95
+ # deploy job mid-flight. Pull requests and other branches keep canceling
96
+ # superseded runs.
97
+ group: \${{ github.workflow }}-\${{ github.ref }}
98
+ cancel-in-progress: \${{ github.ref != ${stagingRefLiteral(options)} }}`
99
+ : ` # This workflow validates and never deploys, so there is no in-flight
100
+ # deployment for a newer push to protect: every ref cancels its superseded
101
+ # runs. Queuing them instead serializes the staging branch, and a burst of
102
+ # pushes then reports the newest commit one full run per queued push late.
103
+ group: \${{ github.workflow }}-\${{ github.ref }}
104
+ cancel-in-progress: true`}
105
+
106
+ defaults:
107
+ run:
108
+ working-directory: tooling/direnv
109
+
110
+ jobs:
111
+ main:
112
+ name: Validate
113
+ ${renderRunsOnLine(options.runsOn)}
114
+ timeout-minutes: 45
115
+ ${options.privateNpm?.readTokenEnv || options.cargoCredentials !== undefined || options.remoteCache !== undefined
116
+ ? ` # Fork PRs receive no secrets, so neither a private dependency install nor an
117
+ # authenticated remote cache read can run there.
118
+ if: \${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }}
119
+ `
120
+ : ''}${environmentLine(options.deploy ? options.environments?.staging : undefined)}${options.e2eDeployment
121
+ ? ` outputs:
122
+ deployment-stage: ${githubExpression('steps.deploy.outputs.stage')}
123
+ `
124
+ : ''} env:
125
+ GH_TOKEN: ${githubExpression('github.token')}
126
+ ${remoteCacheJobEnvLines(options.remoteCache)}${cargoCredentialJobEnvLines(options.cargoCredentials)}${privateNpmReadTokenJobEnv(options)} steps:
127
+ `;
128
+ }
129
+ function githubExpression(expression) {
130
+ return `$${`{{ ${expression} }}`}`;
131
+ }
132
+ /** Job env for `.npmrc` token expansion. Registry URL is not a GitHub variable. */
133
+ export function privateNpmReadTokenJobEnv(options) {
134
+ const tokenEnv = options.privateNpm?.readTokenEnv;
135
+ if (!tokenEnv) {
136
+ return '';
137
+ }
138
+ return ` ${tokenEnv}: ${githubExpression(`secrets.${tokenEnv}`)}\n`;
139
+ }
140
+ function renderCiWorkflowSteps(steps, options) {
141
+ const lines = [];
142
+ for (const step of steps) {
143
+ lines.push(...sectionLinesBefore(step));
144
+ lines.push(...commentLinesForStep(step));
145
+ lines.push(...yamlLinesForStep(step, options));
146
+ lines.push('');
147
+ }
148
+ return `${lines.join('\n').trimEnd()}\n`;
149
+ }
150
+ function sectionLinesBefore(step) {
151
+ if (step.kind === CiWorkflowStepKind.SetNxShas) {
152
+ return [' # --- Nx -----------------------------------------------------------------', ''];
153
+ }
154
+ if (step.kind === CiWorkflowStepKind.SaveNixDevenv) {
155
+ return [' # --- Cleanup ------------------------------------------------------------', ''];
156
+ }
157
+ return [];
158
+ }
159
+ function commentLinesForStep(step) {
160
+ if (step.kind === CiWorkflowStepKind.Checkout) {
161
+ return [' # Step 1: GitHub adds "Set up job" automatically', ' # Step 2'];
162
+ }
163
+ if (step.kind === CiWorkflowStepKind.CargoCredentials) {
164
+ return [
165
+ ` # Step ${step.number}`,
166
+ ' # Installs a host-gated git credential helper for private Cargo git',
167
+ ' # dependencies through GITHUB_ENV: CARGO_NET_GIT_FETCH_WITH_CLI makes',
168
+ ' # cargo shell out to git, whose per-process GIT_CONFIG_* environment',
169
+ ' # names the helper. The helper reads the token from the environment',
170
+ ' # when git calls it, answers only for the declared origins, and an',
171
+ ' # empty credential.helper reset keeps an ambient credential store',
172
+ ' # (osxkeychain, store) from persisting the token after a fetch. The',
173
+ ' # token never reaches a URL, argv, or stored git/cargo configuration.',
174
+ ];
175
+ }
176
+ if (step.kind === CiWorkflowStepKind.SetupDevenv) {
177
+ return [
178
+ ` # Step ${step.number}. Composite action internals do not affect top-level job step`,
179
+ ' # anchors; update the nx-smart --step values below if top-level steps move.',
180
+ ];
181
+ }
182
+ if (step.kind === CiWorkflowStepKind.SetNxShas) {
183
+ return [` # Step ${step.number}`, ' # Sets the base and head SHAs required for the nx affected commands'];
184
+ }
185
+ if (step.kind === CiWorkflowStepKind.SaveNxCache) {
186
+ return [
187
+ ` # Step ${step.number}`,
188
+ " # Nx's database cache needs artifact files and .nx/workspace-data DB",
189
+ ' # metadata restored together; GitHub Actions cache is only the archive',
190
+ ' # transport. Save runs only after prior required steps succeed on the default',
191
+ ' # branch, so PRs may restore shared cache but cannot publish it.',
192
+ ' #',
193
+ ' # Host-nix runners skip the transport entirely: setup-devenv puts their',
194
+ ' # Nx cache on the shared /var/cache/ci bind, which already survives the',
195
+ ' # job, so shipping it through the Actions cache would upload a copy of a',
196
+ ' # cache the next job reads directly.',
197
+ ];
198
+ }
199
+ return [` # Step ${step.number}`];
200
+ }
201
+ function yamlLinesForStep(step, options) {
202
+ switch (step.kind) {
203
+ case CiWorkflowStepKind.Checkout:
204
+ return [
205
+ ` - name: ${step.name}`,
206
+ ' uses: actions/checkout@v6.0.2',
207
+ ' with:',
208
+ ' filter: blob:none',
209
+ ' fetch-depth: 0',
210
+ ];
211
+ case CiWorkflowStepKind.SourceCheckouts:
212
+ return sourceCheckoutsStepLines(step, options.sourceCheckouts ?? []);
213
+ case CiWorkflowStepKind.CargoCredentials:
214
+ return cargoCredentialStepLines(step, normalizeCargoCredentials(options.cargoCredentials ?? {}));
215
+ case CiWorkflowStepKind.SetupDevenv:
216
+ // One step everywhere. setup-devenv detects host-nix (GARM) vs ephemeral
217
+ // and skips GH install/cache steps internally — same for ci/publish/managed.
218
+ return [` - name: ${step.name}`, ' id: setup', ' uses: ./.github/actions/setup-devenv'];
219
+ case CiWorkflowStepKind.SetNxShas:
220
+ return [
221
+ ` - name: ${step.name}`,
222
+ " if: github.server_url == 'https://github.com' || endsWith(github.api_url, '/api/v3')",
223
+ ' uses: nrwl/nx-set-shas@v5.0.1',
224
+ ' with:',
225
+ ' workflow-id: ci.yml',
226
+ ];
227
+ case CiWorkflowStepKind.RestoreNxCache:
228
+ return [
229
+ ` - name: ${step.name}`,
230
+ ' id: nx-cache',
231
+ // The shared bind is the cache on host runners; a restore there would
232
+ // overwrite it with an older archive.
233
+ " if: steps.setup.outputs.host-runner != 'true'",
234
+ ' uses: ./.github/actions/cache-nx',
235
+ ];
236
+ case CiWorkflowStepKind.Build:
237
+ return nxSmartStep(step, 'build', 'Build');
238
+ case CiWorkflowStepKind.BrowserTests:
239
+ return nxSmartStep(step, 'test-browser', 'Browser Tests');
240
+ case CiWorkflowStepKind.Lint:
241
+ return nxSmartStep(step, 'lint', 'Lint');
242
+ case CiWorkflowStepKind.UnitTests:
243
+ return nxSmartStep(step, 'test', 'Unit Tests');
244
+ case CiWorkflowStepKind.CrossToolchainPreflight:
245
+ // The repository's own preflight, the same one the publish workflow's
246
+ // cross artifact job runs — an SDK to provision, a linker to check.
247
+ // `working-directory: .` because this workflow's steps default to the
248
+ // direnv shell directory while a preflight is repository-relative.
249
+ return [
250
+ ` - name: ${step.name}`,
251
+ ' working-directory: .',
252
+ ...platformProducerStepEnvLines(options),
253
+ ' run: |',
254
+ ' set -euo pipefail',
255
+ ...crossToolchainPreflight(options).map((line) => ` ${line}`),
256
+ ];
257
+ case CiWorkflowStepKind.CrossTestArchives:
258
+ // Cross-COMPILES the workspace's test binaries for each declared foreign
259
+ // triple and packs them; runs nothing. `nx-run-many` rather than
260
+ // `nx-smart`, because an affected-graph selection would skip the archive
261
+ // on a commit that changed nothing Rust — and the sibling job that
262
+ // executes it has no way to build one.
263
+ return [
264
+ ` - name: ${step.name}`,
265
+ ...platformProducerStepEnvLines(options),
266
+ ` run: smoo github-ci nx-run-many --targets "${crossArchiveTargetNames(options).join(',')}"`,
267
+ ];
268
+ case CiWorkflowStepKind.UploadCrossTestArchives:
269
+ // Exactly the archives the sibling job EXECUTES, which is what keeps the
270
+ // artifact's root where the download expects it: upload-artifact roots an
271
+ // artifact at the least common ancestor of the files it uploaded, so a
272
+ // foreign triple's archive under another cargo workspace would raise that
273
+ // root to the repository and restore every path one directory too deep.
274
+ // retention-days: 1 — the only consumer is that job in this same run, and
275
+ // these archives are the whole workspace's test binaries.
276
+ return artifactStepLines(options.actionsProvider, step.name, 'upload', [
277
+ `name: ${CROSS_TEST_ARCHIVE_ARTIFACT}`,
278
+ 'path: |',
279
+ ...darwinCrossTestArchives(options).map((archive) => ` ${archive.path}`),
280
+ // error, not ignore: a missing archive means the cross build silently
281
+ // produced nothing, and the execute job would then have nothing to run
282
+ // and no reason to say so.
283
+ 'if-no-files-found: error',
284
+ 'retention-days: 1',
285
+ ]);
286
+ case CiWorkflowStepKind.DownloadCrossTestArchives:
287
+ // Restores each archive at the path its own Nx target declares as output,
288
+ // which is where the runner target reads it from. upload-artifact roots
289
+ // the artifact at the least common ancestor of what it uploaded, so the
290
+ // download path is that shared directory.
291
+ return artifactStepLines(options.actionsProvider, step.name, 'download', [
292
+ `name: ${CROSS_TEST_ARCHIVE_ARTIFACT}`,
293
+ `path: ${crossTestArchiveDirectory(options)}`,
294
+ ]);
295
+ case CiWorkflowStepKind.CrossTests:
296
+ // EXECUTES, and that is all it can do: every one of these targets is
297
+ // `nextest run --archive-file`, which extracts prebuilt binaries into its
298
+ // own temporary directory. nextest never invokes cargo on this path
299
+ // (measured), so nothing here can compile even if a toolchain is present.
300
+ return [
301
+ ` - name: ${step.name}`,
302
+ ` run: smoo github-ci nx-run-many --targets "${darwinCrossTestTargetNames(options).join(',')}"`,
303
+ ];
304
+ case CiWorkflowStepKind.ManagedFilesCheck:
305
+ // The authoritative drift check is nearly free here (devenv is already
306
+ // up). --warn never fails the job and publishes the step output
307
+ // `drifted=<count>` for the dispatch step below.
308
+ return [
309
+ ` - name: ${step.name}`,
310
+ ' id: managed-drift',
311
+ ' if:',
312
+ " ${{ github.event_name == 'push' && github.ref == format('refs/heads/{0}',",
313
+ ' github.event.repository.default_branch) }}',
314
+ ' run: smoo monorepo check --warn',
315
+ ];
316
+ case CiWorkflowStepKind.ManagedFilesDispatch:
317
+ // Dispatches the managed-files workflow, which maintains the persistent
318
+ // review PR. workflow_dispatch is exempt from GitHub's GITHUB_TOKEN
319
+ // recursion guard, so the default token suffices.
320
+ return [
321
+ ` - name: ${step.name}`,
322
+ " if: steps.managed-drift.outputs.drifted != '' && steps.managed-drift.outputs.drifted != '0'",
323
+ ' run: smoo github-ci dispatch-workflow --workflow managed-files.yml --ref "$GITHUB_REF_NAME"',
324
+ ];
325
+ case CiWorkflowStepKind.Deploy:
326
+ return [
327
+ ` - name: ${step.name}`,
328
+ ' id: deploy',
329
+ ' if: >-',
330
+ ' ${{',
331
+ " (github.event_name == 'pull_request' &&",
332
+ ' contains(fromJSON(\'["opened","reopened","synchronize"]\'), github.event.action) &&',
333
+ ' github.event.pull_request.head.repo.full_name == github.repository) ||',
334
+ ` (github.event_name == 'push' && github.ref == ${stagingRefLiteral(options)})`,
335
+ ' }}',
336
+ ...deployStepSecretEnvLines(options),
337
+ ` run: smoo github-ci nx-deploy --mode run-many --name "Deploy Stage" --step ${step.number}`,
338
+ ];
339
+ case CiWorkflowStepKind.SaveNxCache:
340
+ return [
341
+ ` - name: ${step.name}`,
342
+ ' if:',
343
+ " ${{ steps.setup.outputs.host-runner != 'true' && github.event_name == 'push' && github.ref ==",
344
+ " format('refs/heads/{0}', github.event.repository.default_branch) && steps.nx-cache.outputs.cache-hit != 'true'",
345
+ ' }}',
346
+ ' uses: actions/cache/save@v5.0.5',
347
+ ' with:',
348
+ ' path: |',
349
+ ' .nx/cache',
350
+ ' .nx/workspace-data/*.db*',
351
+ ' key: ${{ runner.os }}-${{ runner.arch }}-nx-db-v1-${{ github.sha }}',
352
+ ];
353
+ case CiWorkflowStepKind.UploadTraceDbs:
354
+ return artifactStepLines(options.actionsProvider, step.name, 'upload', [
355
+ 'name: trace-results-${{ github.run_id }}',
356
+ 'path: packages/*/.cache/trace-results.db*',
357
+ 'if-no-files-found: ignore',
358
+ 'retention-days: 14',
359
+ 'include-hidden-files: true',
360
+ ], 'always()');
361
+ case CiWorkflowStepKind.SaveNixDevenv:
362
+ return [
363
+ ` - name: ${step.name}`,
364
+ ' # always() still saves after a red job. Nix NAR is ephemeral-only;',
365
+ ' # devenv eval-cache also saves on host-nix when setup missed.',
366
+ ' if: always()',
367
+ ' uses: ./.github/actions/save-nix-devenv',
368
+ ' with:',
369
+ ' devenv-cache-hit: ${{ steps.setup.outputs.devenv-cache-hit }}',
370
+ ];
371
+ }
372
+ }
373
+ /**
374
+ * One clone command per declared sibling source, pinned to its configured
375
+ * ref. The step's `if` keeps fork PRs — which receive no secrets — from
376
+ * touching source-read credentials, and their builds would lack the private
377
+ * siblings anyway. The clone URL stays clean: authorization rides per git
378
+ * command through `GIT_CONFIG_*` environment config whose
379
+ * `http.<origin>.extraheader` key names the exact origin, so the token never
380
+ * reaches argv, a file, the sibling's stored `.git/config`, or any other
381
+ * host. The token itself is only ever a shell expansion of the step env.
382
+ */
383
+ export function sourceCheckoutsStepLines(step, checkouts) {
384
+ const lines = [` - name: ${step.name}`, ...SAME_REPO_GATE_FOLDED];
385
+ const tokenEnvs = [
386
+ ...new Set(checkouts.map((checkout) => checkout.tokenEnv).filter((env) => env !== undefined)),
387
+ ];
388
+ if (tokenEnvs.length > 0) {
389
+ lines.push(' env:');
390
+ for (const env of tokenEnvs) {
391
+ lines.push(` ${env}: ${githubExpression(`secrets.${env}`)}`);
392
+ }
393
+ }
394
+ lines.push(' run: |');
395
+ lines.push(' root="$GITHUB_WORKSPACE"');
396
+ for (const checkout of checkouts.map(normalizeSourceCheckout)) {
397
+ const destination = `"$root/${checkout.path}"`;
398
+ const auth = checkout.tokenEnv === undefined
399
+ ? []
400
+ : [
401
+ ` key='http.${new URL(checkout.repository).origin}/.extraheader'`,
402
+ ` val="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$${checkout.tokenEnv}" | base64 | tr -d '\\n')"`,
403
+ ' GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0="$key" GIT_CONFIG_VALUE_0="$val" \\',
404
+ ];
405
+ lines.push(...auth);
406
+ lines.push(` git clone --filter=blob:none ${checkout.repository} ${destination}`);
407
+ if (checkout.ref !== undefined) {
408
+ lines.push(...auth);
409
+ lines.push(` git -C ${destination} checkout --detach ${checkout.ref}`);
410
+ }
411
+ }
412
+ return lines;
413
+ }
414
+ /** Mechanism errors surface at managed-file render time, never inside CI. */
415
+ export function normalizeSourceCheckout(config) {
416
+ if (config.path === undefined || config.path === '' || config.path.startsWith('/')) {
417
+ throw new Error(`smoo.github.sourceCheckouts entry needs a path relative to the workspace root, got ${JSON.stringify(config.path)}`);
418
+ }
419
+ let url = null;
420
+ try {
421
+ url = config.repository === undefined ? null : new URL(config.repository);
422
+ }
423
+ catch {
424
+ url = null;
425
+ }
426
+ if (url === null ||
427
+ url.protocol !== 'https:' ||
428
+ url.username !== '' ||
429
+ url.password !== '' ||
430
+ url.search !== '' ||
431
+ url.hash !== '') {
432
+ throw new Error(`smoo.github.sourceCheckouts entry needs a credential-free https repository URL, got ${JSON.stringify(config.repository)}`);
433
+ }
434
+ if (config.tokenEnv !== undefined && !/^[A-Z_][A-Z0-9_]*$/.test(config.tokenEnv)) {
435
+ throw new Error(`smoo.github.sourceCheckouts entry needs an upper-case secret env name, got ${JSON.stringify(config.tokenEnv)}`);
436
+ }
437
+ return config;
438
+ }
439
+ /**
440
+ * Job env lines carrying the declared Nx remote cache. The pair rides the job
441
+ * env rather than a step because every Nx invocation in the job — build, lint,
442
+ * tests, deploy — reads it, and Nx enables the cache on a nonempty server
443
+ * alone: an empty or absent token would make it authenticate with nothing and
444
+ * fail every task on 401, which is why the job carries the same fork-PR gate
445
+ * as a private dependency install (see `renderCiWorkflowHeader`).
446
+ *
447
+ * A declared `internalServer` is the address managed runners use, exactly as a
448
+ * git origin's `internalMirror` is: both say this repository's runners sit
449
+ * inside that network, and shells outside it keep the public origin.
450
+ * Mechanism errors surface at managed-file render time, never inside CI.
451
+ */
452
+ export function remoteCacheJobEnvLines(config) {
453
+ if (config === undefined) {
454
+ return '';
455
+ }
456
+ const normalized = normalizeRemoteCache(config);
457
+ return [
458
+ ` NX_SELF_HOSTED_REMOTE_CACHE_SERVER: ${normalized.internalServer ?? normalized.server}\n`,
459
+ ` NX_SELF_HOSTED_REMOTE_CACHE_ACCESS_TOKEN: ${githubExpression(`secrets.${normalized.tokenSecret}`)}\n`,
460
+ ].join('');
461
+ }
462
+ /** Mechanism errors surface at managed-file render time, never inside CI. */
463
+ export function normalizeRemoteCache(config) {
464
+ assertCacheOrigin('server', config.server);
465
+ if (config.internalServer !== undefined) {
466
+ assertCacheOrigin('internalServer', config.internalServer);
467
+ if (config.internalServer === config.server) {
468
+ throw new Error(`smoo.remoteCache internalServer repeats server ${config.server}; drop internalServer or point it at the address internal runners reach`);
469
+ }
470
+ }
471
+ if (!/^[A-Z_][A-Z0-9_]*$/.test(config.tokenSecret)) {
472
+ throw new Error(`smoo.remoteCache needs an upper-case secret name for tokenSecret, got ${JSON.stringify(config.tokenSecret)}`);
473
+ }
474
+ return config;
475
+ }
476
+ /**
477
+ * A cache origin is exactly `scheme://host[:port]`. Nx appends
478
+ * `/v1/cache/<hash>` to it, so a trailing slash silently requests a doubled
479
+ * slash the server routes nowhere, and a path or credential would be dropped
480
+ * or leaked rather than honored.
481
+ */
482
+ function assertCacheOrigin(field, value) {
483
+ let url = null;
484
+ try {
485
+ url = new URL(value);
486
+ }
487
+ catch {
488
+ url = null;
489
+ }
490
+ if (url === null ||
491
+ (url.protocol !== 'https:' && url.protocol !== 'http:') ||
492
+ url.pathname !== '/' ||
493
+ value.endsWith('/') ||
494
+ url.username !== '' ||
495
+ url.password !== '' ||
496
+ url.search !== '' ||
497
+ url.hash !== '') {
498
+ throw new Error(`smoo.remoteCache ${field} needs a credential-free http(s) origin with no path and no trailing slash, got ${JSON.stringify(value)}`);
499
+ }
500
+ }
501
+ /**
502
+ * Job env lines carrying the declared Cargo credential secrets. Both registry
503
+ * tokens and git-origin tokens ride the job env so the credential helper is
504
+ * still in scope when cargo spawns git much later in the build. Fork PRs
505
+ * receive empty values and skip the helper step, so nothing answers for a
506
+ * private origin there.
507
+ */
508
+ export function cargoCredentialJobEnvLines(config) {
509
+ if (config === undefined) {
510
+ return '';
511
+ }
512
+ const tokenEnvs = distinctCargoTokenEnvs(normalizeCargoCredentials(config));
513
+ if (tokenEnvs.length === 0) {
514
+ return '';
515
+ }
516
+ return tokenEnvs.map((env) => ` ${env}: ${githubExpression(`secrets.${env}`)}\n`).join('');
517
+ }
518
+ /**
519
+ * The credential-transport step preflights every declared token, then writes a
520
+ * host-gated helper script into `$RUNNER_TEMP` for git origins and points the
521
+ * per-process `GIT_CONFIG_*` environment at it through GITHUB_ENV, plus
522
+ * `CARGO_NET_GIT_FETCH_WITH_CLI` so Cargo shells out to git. Runners whose
523
+ * egress requires a proxy export it as `HTTP(S)_PROXY`, which cargo honors
524
+ * natively but git never reads, so the step mirrors it into git config or
525
+ * Cargo git fetches bypass the proxy and fail to connect. Origins with an
526
+ * `internalMirror` are rewritten to the mirror with `url.<mirror>.insteadOf`
527
+ * and the helper answers the same credential for the mirror's host, since git
528
+ * passes helpers the rewritten URL. The helper reads the environment at call
529
+ * time and answers only for declared origins. Declared `sshOrigins` rewrite
530
+ * onto the same mirror and stay credential-free: the rewrite happens before
531
+ * transport, so git only ever asks for the mirror, and an SSH pin the runner
532
+ * has no key for fails loudly instead of collecting a token.
533
+ * Mechanism errors surface at managed-file render time, never inside CI.
534
+ */
535
+ export function cargoCredentialStepLines(step, config) {
536
+ const normalized = normalizeCargoCredentials(config);
537
+ const origins = normalized.gitOrigins ?? [];
538
+ const tokenEnvs = distinctCargoTokenEnvs(normalized);
539
+ const lines = [` - name: ${step.name}`, ...SAME_REPO_GATE_FOLDED];
540
+ lines.push(' env:');
541
+ for (const env of tokenEnvs) {
542
+ lines.push(` ${env}: ${githubExpression(`secrets.${env}`)}`);
543
+ }
544
+ lines.push(' run: |');
545
+ for (const env of tokenEnvs) {
546
+ lines.push(` : "\${${env}:?Missing ${env}; configure the repository secret before fetching Cargo dependencies}"`);
547
+ }
548
+ if (origins.length === 0) {
549
+ return lines;
550
+ }
551
+ lines.push(' helper="$RUNNER_TEMP/cargo-git-credential.sh"');
552
+ lines.push(' cat > "$helper" <<\'SMOO_CARGO_HELPER_EOF\'');
553
+ lines.push(' #!/bin/sh');
554
+ lines.push(' [ "$1" = get ] || exit 0');
555
+ lines.push(' # Host-gated credential answers for private Cargo git dependencies. The');
556
+ lines.push(' # token is read from the environment when git calls this helper; it is');
557
+ lines.push(' # never stored, echoed, or attached to any other origin.');
558
+ lines.push(' protocol=');
559
+ lines.push(' host=');
560
+ lines.push(' while IFS= read -r line && [ -n "$line" ]; do');
561
+ lines.push(' case "$line" in');
562
+ lines.push(' protocol=*) protocol=${line#protocol=} ;;');
563
+ lines.push(' host=*) host=${line#host=} ;;');
564
+ lines.push(' esac');
565
+ lines.push(' done');
566
+ lines.push(' key="${protocol}|${host}"');
567
+ lines.push(' case "$key" in');
568
+ for (const origin of origins) {
569
+ const url = new URL(origin.origin);
570
+ const host = url.host.replaceAll("'", "'\\''");
571
+ lines.push(` 'https|${host}'${url.port === '' ? `|'https|${host}:443'` : ''})`, ` printf 'username=x-access-token\\npassword=%s\\n' "$${origin.tokenEnv}" ;;`);
572
+ if (origin.internalMirror !== undefined) {
573
+ // Git passes helpers the rewritten URL, so the mirror answers with the
574
+ // same credential under its own scheme.
575
+ const mirror = new URL(origin.internalMirror);
576
+ const scheme = mirror.protocol === 'http:' ? 'http' : 'https';
577
+ const mirrorHost = mirror.host.replaceAll("'", "'\\''");
578
+ lines.push(` '${scheme}|${mirrorHost}'${mirror.port === '' ? `|'${scheme}|${mirror.hostname}:${scheme === 'http' ? '80' : '443'}'` : ''})`, ` printf 'username=x-access-token\\npassword=%s\\n' "$${origin.tokenEnv}" ;;`);
579
+ }
580
+ }
581
+ lines.push(' *) exit 0 ;;');
582
+ lines.push(' esac');
583
+ lines.push(' SMOO_CARGO_HELPER_EOF');
584
+ lines.push(' chmod 700 "$helper"');
585
+ lines.push(' {');
586
+ lines.push(' echo "CARGO_NET_GIT_FETCH_WITH_CLI=true"');
587
+ lines.push(' # An empty value clears any ambient credential helper (osxkeychain,');
588
+ lines.push(' # store) so a successful fetch cannot persist the token anywhere.');
589
+ lines.push(' echo "GIT_CONFIG_KEY_0=credential.helper"');
590
+ lines.push(' echo "GIT_CONFIG_VALUE_0="');
591
+ lines.push(' echo "GIT_CONFIG_KEY_1=credential.helper"');
592
+ lines.push(' echo "GIT_CONFIG_VALUE_1=$helper"');
593
+ lines.push(' # Cargo honors proxy env natively; git does not read it. Mirror the');
594
+ lines.push(' # runner proxy into git config so Cargo git fetches take the same');
595
+ lines.push(' # route instead of failing to connect. Absent on direct networks,');
596
+ lines.push(' # so this block is a no-op there.');
597
+ lines.push(' idx=2');
598
+ lines.push(' https_proxy_value="${HTTPS_PROXY:-${https_proxy:-}}"');
599
+ lines.push(' http_proxy_value="${HTTP_PROXY:-${http_proxy:-${https_proxy_value:-}}}"');
600
+ lines.push(' if [ -n "$https_proxy_value" ]; then');
601
+ lines.push(' echo "GIT_CONFIG_KEY_${idx}=https.proxy"');
602
+ lines.push(' echo "GIT_CONFIG_VALUE_${idx}=${https_proxy_value}"');
603
+ lines.push(' idx=$((idx + 1))');
604
+ lines.push(' fi');
605
+ lines.push(' if [ -n "$http_proxy_value" ]; then');
606
+ lines.push(' echo "GIT_CONFIG_KEY_${idx}=http.proxy"');
607
+ lines.push(' echo "GIT_CONFIG_VALUE_${idx}=${http_proxy_value}"');
608
+ lines.push(' idx=$((idx + 1))');
609
+ lines.push(' fi');
610
+ lines.push(' # Internal mirrors rewrite the declared origin prefix so runners');
611
+ lines.push(' # that cannot reach the public URL fetch over guest networking.');
612
+ if (origins.some((origin) => origin.sshOrigins !== undefined)) {
613
+ lines.push(' # The same forge over SSH, as Cargo and uv pin it: git matches');
614
+ lines.push(' # insteadOf values as literal URL prefixes, so every declared');
615
+ lines.push(' # spelling rewrites onto the mirror on its own line.');
616
+ }
617
+ for (const origin of origins) {
618
+ if (origin.internalMirror === undefined) {
619
+ continue;
620
+ }
621
+ const mirrorUrl = new URL(origin.internalMirror);
622
+ const mirrorBase = `${mirrorUrl.protocol}//${mirrorUrl.host}/`.replaceAll("'", "'\\''");
623
+ for (const prefix of mirrorRewritePrefixes(origin)) {
624
+ lines.push(' echo "GIT_CONFIG_KEY_${idx}=url.' + mirrorBase + '.insteadOf"');
625
+ lines.push(' echo "GIT_CONFIG_VALUE_${idx}=' + prefix.replaceAll("'", "'\\''") + '"');
626
+ lines.push(' idx=$((idx + 1))');
627
+ }
628
+ }
629
+ lines.push(' echo "GIT_CONFIG_COUNT=${idx}"');
630
+ lines.push(' } >> "$GITHUB_ENV"');
631
+ return lines;
632
+ }
633
+ /**
634
+ * Every URL prefix a mirrored origin rewrites from: the declared https origin
635
+ * first, then each declared SSH spelling of the same forge. One `insteadOf`
636
+ * value per prefix, because git matches them as literal prefixes and derives
637
+ * no spelling from another. Rendering runs after `normalizeCargoCredentials`,
638
+ * which parsed and refused every malformed entry.
639
+ */
640
+ function mirrorRewritePrefixes(origin) {
641
+ const originUrl = new URL(origin.origin);
642
+ return [
643
+ `${originUrl.protocol}//${originUrl.host}/`,
644
+ ...(origin.sshOrigins ?? []).map((spelling) => sshRewritePrefix(new URL(spelling))),
645
+ ];
646
+ }
647
+ /**
648
+ * The SSH spelling as a rewritable prefix: userinfo is part of the spelling
649
+ * git matches, and the trailing slash keeps `ssh://host:2223` from also
650
+ * rewriting `ssh://host:22230/`.
651
+ */
652
+ function sshRewritePrefix(spelling) {
653
+ return `ssh://${spelling.username === '' ? '' : `${spelling.username}@`}${spelling.host}/`;
654
+ }
655
+ function distinctCargoTokenEnvs(config) {
656
+ const seen = new Set();
657
+ for (const env of config.registryTokenEnvs ?? []) {
658
+ seen.add(env);
659
+ }
660
+ for (const origin of config.gitOrigins ?? []) {
661
+ seen.add(origin.tokenEnv);
662
+ }
663
+ return [...seen];
664
+ }
665
+ /** Mechanism errors surface at managed-file render time, never inside CI. */
666
+ export function normalizeCargoCredentials(config) {
667
+ for (const env of config.registryTokenEnvs ?? []) {
668
+ if (!/^CARGO_REGISTRIES_[A-Z0-9_]+_TOKEN$/.test(env)) {
669
+ throw new Error(`smoo.github.cargoCredentials needs upper-case secret env names matching CARGO_REGISTRIES_<NAME>_TOKEN for registryTokenEnvs, got ${JSON.stringify(env)}`);
670
+ }
671
+ }
672
+ const hosts = new Set();
673
+ const sshPrefixes = new Set();
674
+ for (const origin of config.gitOrigins ?? []) {
675
+ const host = new URL(normalizeCargoGitOrigin(origin).origin).host;
676
+ if (hosts.has(host)) {
677
+ throw new Error(`smoo.github.cargoCredentials repeats git origin host ${host}; declare one token per origin`);
678
+ }
679
+ hosts.add(host);
680
+ for (const spelling of origin.sshOrigins ?? []) {
681
+ // One spelling, one rewrite, whole config: a repeat renders two
682
+ // identical insteadOf keys and git silently keeps the last one read.
683
+ const prefix = sshRewritePrefix(assertSshOrigin(spelling));
684
+ if (sshPrefixes.has(prefix)) {
685
+ throw new Error(`smoo.github.cargoCredentials repeats the sshOrigins spelling ${prefix}; declare each spelling once, on the origin whose mirror rewrites it`);
686
+ }
687
+ sshPrefixes.add(prefix);
688
+ }
689
+ }
690
+ if ((config.registryTokenEnvs?.length ?? 0) === 0 && (config.gitOrigins?.length ?? 0) === 0) {
691
+ throw new Error('smoo.github.cargoCredentials needs at least one gitOrigins or registryTokenEnvs entry, got an empty configuration');
692
+ }
693
+ return config;
694
+ }
695
+ function normalizeCargoGitOrigin(origin) {
696
+ let url = null;
697
+ try {
698
+ url = origin.origin === undefined ? null : new URL(origin.origin);
699
+ }
700
+ catch {
701
+ url = null;
702
+ }
703
+ if (url === null ||
704
+ url.protocol !== 'https:' ||
705
+ url.pathname !== '/' ||
706
+ url.username !== '' ||
707
+ url.password !== '' ||
708
+ url.search !== '' ||
709
+ url.hash !== '') {
710
+ throw new Error(`smoo.github.cargoCredentials gitOrigins entry needs a credential-free https origin without a path, got ${JSON.stringify(origin.origin)}`);
711
+ }
712
+ if (!/^[A-Z_][A-Z0-9_]*$/.test(origin.tokenEnv)) {
713
+ throw new Error(`smoo.github.cargoCredentials gitOrigins entry needs an upper-case secret env name, got ${JSON.stringify(origin.tokenEnv)}`);
714
+ }
715
+ if (origin.internalMirror !== undefined) {
716
+ let mirror = null;
717
+ try {
718
+ mirror = new URL(origin.internalMirror);
719
+ }
720
+ catch {
721
+ mirror = null;
722
+ }
723
+ if (mirror === null ||
724
+ (mirror.protocol !== 'https:' && mirror.protocol !== 'http:') ||
725
+ mirror.pathname !== '/' ||
726
+ mirror.username !== '' ||
727
+ mirror.password !== '' ||
728
+ mirror.search !== '' ||
729
+ mirror.hash !== '') {
730
+ throw new Error(`smoo.github.cargoCredentials gitOrigins entry needs a credential-free http(s) internalMirror origin without a path, got ${JSON.stringify(origin.internalMirror)}`);
731
+ }
732
+ if (mirror.host === url.host && mirror.protocol === url.protocol) {
733
+ throw new Error(`smoo.github.cargoCredentials gitOrigins entry rewrites ${origin.origin} to itself; drop internalMirror or point it at the internal mirror`);
734
+ }
735
+ }
736
+ if (origin.sshOrigins !== undefined) {
737
+ if (origin.internalMirror === undefined) {
738
+ throw new Error(`smoo.github.cargoCredentials gitOrigins entry declares sshOrigins for ${origin.origin} without an internalMirror to rewrite them onto; an SSH spelling is a rewrite source and nothing else`);
739
+ }
740
+ if (origin.sshOrigins.length === 0) {
741
+ throw new Error(`smoo.github.cargoCredentials gitOrigins entry for ${origin.origin} declares an empty sshOrigins list; name every SSH spelling a lockfile can carry, or omit the field`);
742
+ }
743
+ for (const spelling of origin.sshOrigins) {
744
+ assertSshOrigin(spelling);
745
+ }
746
+ }
747
+ return origin;
748
+ }
749
+ /**
750
+ * One declared SSH spelling, parsed. Credential-free and path-free: a
751
+ * password here would be a secret committed in package.json, and a path
752
+ * would rewrite a single repository instead of the forge. scp syntax
753
+ * (`git@host:org/repo.git`) is no URL, so git cannot rewrite it from a Cargo
754
+ * or uv pin at all; the `ssh://` spelling is the one to declare.
755
+ */
756
+ function assertSshOrigin(spelling) {
757
+ let ssh = null;
758
+ try {
759
+ ssh = new URL(spelling);
760
+ }
761
+ catch {
762
+ ssh = null;
763
+ }
764
+ if (ssh === null ||
765
+ ssh.protocol !== 'ssh:' ||
766
+ ssh.host === '' ||
767
+ (ssh.pathname !== '' && ssh.pathname !== '/') ||
768
+ ssh.password !== '' ||
769
+ ssh.search !== '' ||
770
+ ssh.hash !== '') {
771
+ throw new Error(`smoo.github.cargoCredentials gitOrigins entry needs credential-free ssh:// sshOrigins without a path, got ${JSON.stringify(spelling)}`);
772
+ }
773
+ return ssh;
774
+ }
775
+ /**
776
+ * The same-repo gate as prettier folds it: the raw single line exceeds the
777
+ * print width, so the generator emits the folded form itself to keep the
778
+ * checked-in managed output byte-identical across regeneration and hooks.
779
+ */
780
+ export const SAME_REPO_GATE_FOLDED = [
781
+ ' if:',
782
+ " ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository",
783
+ ' }}',
784
+ ];
785
+ /** The first push branch is the one whose pushes deploy the staging stage. */
786
+ function stagingPushBranch(options) {
787
+ return options.pushBranches[0];
788
+ }
789
+ /**
790
+ * A YAML scalar for operator-configured names. Plain-safe names stay bare so
791
+ * generated output stays readable; anything YAML-significant is double-quoted
792
+ * (JSON string syntax is valid YAML for these values) rather than rejecting
793
+ * names the platform itself accepts.
794
+ */
795
+ function yamlScalar(value) {
796
+ if (/^[A-Za-z0-9_][A-Za-z0-9_./-]*$/.test(value) && parseYaml(value) === value) {
797
+ return value;
798
+ }
799
+ return JSON.stringify(value);
800
+ }
801
+ /**
802
+ * A `refs/heads/<branch>` GitHub expression literal. Single quotes double
803
+ * inside expression literals; the branch itself is never restricted here
804
+ * because git permits quotes in ref names.
805
+ */
806
+ function stagingRefLiteral(options) {
807
+ return `'refs/heads/${stagingPushBranch(options).replaceAll("'", "''")}'`;
808
+ }
809
+ function environmentLine(name) {
810
+ return name ? ` environment: ${yamlScalar(name)}\n` : '';
811
+ }
812
+ /**
813
+ * The step-scoped `env:` block for a deploy step. Step scope is the property
814
+ * being rendered, not an accident of indentation: job env would hand the
815
+ * deployment credentials to every other step in that job — checkout, setup,
816
+ * build, and in the publish workflow the pending-release repair and the npm
817
+ * publish itself.
818
+ *
819
+ * An explicit declaration wins over the provider default, so a repo whose
820
+ * Cloudflare credentials live under different repository secret names says so
821
+ * once in `deploySecrets` instead of being overridden here.
822
+ */
823
+ export function deployStepSecretEnvLines(config) {
824
+ const cloudflare = config.deployProvider === 'cloudflare'
825
+ ? { CLOUDFLARE_API_TOKEN: 'CLOUDFLARE_API_TOKEN', CLOUDFLARE_ACCOUNT_ID: 'CLOUDFLARE_ACCOUNT_ID' }
826
+ : {};
827
+ return secretEnvLines({ ...cloudflare, ...config.deploySecrets });
828
+ }
829
+ /** A step-level `env:` block mapping env var names to repository secrets; nothing when there are none. */
830
+ function secretEnvLines(secrets) {
831
+ const entries = Object.entries(secrets);
832
+ if (entries.length === 0)
833
+ return [];
834
+ return [
835
+ ' env:',
836
+ ...entries.map(([name, secret]) => ` ${name}: ${githubExpression(`secrets.${secret}`)}`),
837
+ ];
838
+ }
839
+ /** Optional lines as a newline-terminated block, or nothing, so templates never gain a blank line. */
840
+ function renderOptionalLines(lines) {
841
+ return lines.length > 0 ? `${lines.join('\n')}\n` : '';
842
+ }
843
+ function nxSmartStep(step, target, name) {
844
+ return [
845
+ ` - name: ${step.name}`,
846
+ ` run: smoo github-ci nx-smart --target ${target} --name "${name}" --step ${step.number}`,
847
+ ];
848
+ }
849
+ function renderYamlList(values, spaces) {
850
+ const indent = ' '.repeat(spaces);
851
+ return values.map((value) => `${indent}- ${value}`).join('\n');
852
+ }
853
+ function followUpStepNumbers(options, middleSteps = 1) {
854
+ let number = 3;
855
+ const cargo = options.cargoCredentials !== undefined ? number++ : undefined;
856
+ const sources = options.sourceCheckouts?.length ? number++ : undefined;
857
+ const setup = number++;
858
+ const middle = number;
859
+ number += middleSteps;
860
+ const cleanup = number++;
861
+ return { cargo, sources, setup, middle, cleanup };
862
+ }
863
+ /** Checkout plus every preflight the main job runs, numbered so later anchors track the configuration. */
864
+ function followUpSetupSteps(options, numbers) {
865
+ const steps = [{ kind: CiWorkflowStepKind.Checkout, name: '📥 Checkout', number: 2 }];
866
+ if (numbers.cargo !== undefined && options.cargoCredentials !== undefined) {
867
+ steps.push({ kind: CiWorkflowStepKind.CargoCredentials, name: 'Prepare Cargo credentials', number: numbers.cargo });
868
+ }
869
+ if (numbers.sources !== undefined) {
870
+ steps.push({
871
+ kind: CiWorkflowStepKind.SourceCheckouts,
872
+ name: '📦 Check out sibling sources',
873
+ number: numbers.sources,
874
+ });
875
+ }
876
+ steps.push({ kind: CiWorkflowStepKind.SetupDevenv, name: '🧱 Setup Nix/devenv', number: numbers.setup });
877
+ return steps;
878
+ }
879
+ /** The final cache-save step, at its configured anchor. */
880
+ function followUpCleanupStep(numbers) {
881
+ return [{ kind: CiWorkflowStepKind.SaveNixDevenv, name: '🧹 Cleanup and cache Nix/devenv', number: numbers.cleanup }];
882
+ }
883
+ /**
884
+ * How long the darwin execution job may take, download included. Generous
885
+ * because the archive is the whole workspace's test binaries, and bounded
886
+ * because the runner behind `macosRunsOn` may be one person's laptop: an
887
+ * unreachable runner queues, and this number is when the run says so.
888
+ */
889
+ const CROSS_TEST_JOB_TIMEOUT_MINUTES = 30;
890
+ /** Rust names every Apple-desktop triple this way; iOS and simulator do not. */
891
+ const DARWIN_TRIPLE_SUFFIX = '-apple-darwin';
892
+ /** One artifact carrying every triple's archive, scoped to the run that built it. */
893
+ const CROSS_TEST_ARCHIVE_ARTIFACT = `cross-test-archives-${githubExpression('github.run_id')}`;
894
+ /**
895
+ * Executes the cross-built test binaries on a machine where they are native.
896
+ *
897
+ * This job COMPILES NOTHING, and cannot: its only Rust input is the archive the
898
+ * Validate job uploaded, and `nextest run --archive-file` extracts prebuilt
899
+ * binaries rather than invoking cargo (measured: zero cargo invocations). It
900
+ * needs the checkout for the workspace `--workspace-remap .` points at and for
901
+ * Nx to resolve the target, and setup-devenv for `nx` and `cargo-nextest`
902
+ * themselves — the repository's ordinary shell, not a cross toolchain, no SDK,
903
+ * no `rustup target add`.
904
+ *
905
+ * `needs: main` and a success gate rather than `!cancelled()`: an archive that
906
+ * was never uploaded cannot be executed, and a job that starts anyway would
907
+ * fail on a missing artifact and report it as a test failure.
908
+ *
909
+ * Only `*-apple-darwin` archives run here, because macOS runner labels are the
910
+ * only native runner this declaration names. A repository declaring some other
911
+ * foreign triple still gets its archive BUILT — which proves that triple
912
+ * compiles — and no execution job, which is the honest rendering of having
913
+ * nowhere to run it.
914
+ */
915
+ function renderCrossTestExecutionJob(options) {
916
+ const archives = darwinCrossTestArchives(options);
917
+ if (archives.length === 0)
918
+ return '';
919
+ const numbers = followUpStepNumbers(options, 2);
920
+ const middleSteps = [
921
+ {
922
+ kind: CiWorkflowStepKind.DownloadCrossTestArchives,
923
+ name: '📥 Download cross-target test archives',
924
+ number: numbers.middle,
925
+ },
926
+ { kind: CiWorkflowStepKind.CrossTests, name: '🧪 Cross-Target Unit Tests', number: numbers.middle + 1 },
927
+ ];
928
+ return `
929
+ macos-cross-tests:
930
+ name: Unit Tests (${archives.map((archive) => archive.triple).join(', ')})
931
+ needs: main
932
+ ${options.macosRunsOn === undefined ? ' runs-on: macos-latest' : renderRunsOnLine(options.macosRunsOn)}
933
+ timeout-minutes: ${CROSS_TEST_JOB_TIMEOUT_MINUTES}
934
+ if: \${{ needs.main.result == 'success' }}
935
+ env:
936
+ GH_TOKEN: \${{ github.token }}
937
+ ${remoteCacheJobEnvLines(options.remoteCache)}${cargoCredentialJobEnvLines(options.cargoCredentials)}${privateNpmReadTokenJobEnv(options)} steps:
938
+ ${renderCiWorkflowSteps(followUpSetupSteps(options, numbers), options)}
939
+ ${renderCiWorkflowSteps(middleSteps, options)}
940
+ ${renderCiWorkflowSteps(followUpCleanupStep(numbers), options)}`;
941
+ }
942
+ /**
943
+ * The declared archives, checked against the naming the Nx graph would have
944
+ * produced. A path that is not `cargoCrossTestArchiveFile(triple)` under some
945
+ * project root cannot have come from that target, so it is refused here rather
946
+ * than uploaded as an artifact nothing on the other side can find.
947
+ */
948
+ function crossTestArchives(options) {
949
+ return (options.crossTestArchives ?? []).map((archive) => {
950
+ const suffix = cargoCrossTestArchiveFile(archive.triple);
951
+ const path = archive.path.split('\\').join('/');
952
+ if (!/^[a-z0-9][a-z0-9._-]*$/.test(archive.triple)) {
953
+ throw new Error(`smoo cross test archive triple must be a target triple, got ${JSON.stringify(archive.triple)}`);
954
+ }
955
+ if (path !== suffix && !path.endsWith(`/${suffix}`)) {
956
+ throw new Error(`smoo cross test archive for ${archive.triple} must be a repository-relative ${suffix}, got ${archive.path}`);
957
+ }
958
+ if (path.startsWith('/') || path.split('/').includes('..')) {
959
+ throw new Error(`smoo cross test archive path must stay inside the repository, got ${archive.path}`);
960
+ }
961
+ return { triple: archive.triple, path };
962
+ });
963
+ }
964
+ function crossArchiveTargetNames(options) {
965
+ return crossTestArchives(options).map((archive) => cargoCrossTestArchiveTargetName(archive.triple));
966
+ }
967
+ /**
968
+ * The declared preflight, as lines. A declaration with nothing in it is a
969
+ * mechanism error, and it surfaces here at render time rather than as a step
970
+ * whose `run:` block is empty.
971
+ */
972
+ function crossToolchainPreflight(options) {
973
+ const preflight = options.platformProducer?.preflight ?? '';
974
+ if (preflight.trim().length === 0) {
975
+ throw new Error('smoo.github.platformProducer requires a nonempty toolchain preflight command.');
976
+ }
977
+ return preflight.split('\n');
978
+ }
979
+ /** The producer environment, step-scoped, quoted exactly as the publish workflow quotes it. */
980
+ function platformProducerStepEnvLines(options) {
981
+ const entries = Object.entries(options.platformProducer?.env ?? {});
982
+ if (entries.length === 0)
983
+ return [];
984
+ return [' env:', ...entries.map(([name, value]) => ` ${name}: ${JSON.stringify(value)}`)];
985
+ }
986
+ function darwinCrossTestArchives(options) {
987
+ return crossTestArchives(options).filter((archive) => archive.triple.endsWith(DARWIN_TRIPLE_SUFFIX));
988
+ }
989
+ function darwinCrossTestTargetNames(options) {
990
+ return darwinCrossTestArchives(options).map((archive) => cargoCrossTestTargetName(archive.triple));
991
+ }
992
+ /**
993
+ * Where the download lands, and the artifact's root by construction: the upload
994
+ * step carries exactly these archives, and upload-artifact roots an artifact at
995
+ * the least common ancestor of the files it uploaded.
996
+ *
997
+ * One cargo workspace's triples all share `target/nextest` and travel together.
998
+ * Two workspaces that each declare a darwin triple do not: their common
999
+ * ancestor is above the directory the runner targets read from, so the pair is
1000
+ * refused here instead of restoring both archives one directory too high.
1001
+ */
1002
+ function crossTestArchiveDirectory(options) {
1003
+ const directories = new Set(darwinCrossTestArchives(options).map((archive) => archive.path.slice(0, archive.path.lastIndexOf('/') + 1) || './'));
1004
+ if (directories.size > 1) {
1005
+ throw new Error(`smoo cross test archives must share one directory to travel as one artifact, got ${[...directories].join(', ')}`);
1006
+ }
1007
+ const [directory] = [...directories];
1008
+ return (directory ?? './').replace(/\/$/, '');
1009
+ }
1010
+ function renderE2eDeploymentJob(options) {
1011
+ if (!options.e2eDeployment)
1012
+ return '';
1013
+ const numbers = followUpStepNumbers(options);
1014
+ return `
1015
+ e2e-deployment:
1016
+ name: E2E Tests (Deployed Stage)
1017
+ needs: main
1018
+ ${renderRunsOnLine(options.runsOn)}
1019
+ timeout-minutes: 15
1020
+ ${environmentLine(options.environments?.staging)} if: \${{ needs.main.result == 'success' && needs.main.outputs.deployment-stage != '' }}
1021
+ env:
1022
+ GH_TOKEN: \${{ github.token }}
1023
+ ${remoteCacheJobEnvLines(options.remoteCache)}${cargoCredentialJobEnvLines(options.cargoCredentials)}${privateNpmReadTokenJobEnv(options)} steps:
1024
+ ${renderCiWorkflowSteps(followUpSetupSteps(options, numbers), options)}
1025
+ # Step ${numbers.middle}
1026
+ - name: E2E Tests (Deployed Stage)
1027
+ ${renderOptionalLines(secretEnvLines(options.e2eSecrets ?? {}))} # prettier-ignore
1028
+ run: smoo github-ci nx-smart --target e2e-deployment --mode run-many --stage "\${{ needs.main.outputs.deployment-stage }}" --stream-output --name "E2E Tests (Deployed Stage)" --step ${numbers.middle}
1029
+
1030
+ ${renderCiWorkflowSteps(followUpCleanupStep(numbers), options)}`;
1031
+ }
1032
+ /**
1033
+ * Deploys the tagged projects to production on a push to the staging push branch, once Validate and the e2e job
1034
+ * succeed. `!cancelled()` lets the job evaluate its own gate when the e2e job was skipped rather than inheriting a skip.
1035
+ * A `'skipped'` e2e result is allowed so a repo without e2e-deployment projects still deploys production.
1036
+ */
1037
+ function renderProductionDeployJob(options) {
1038
+ if (!options.deploy || !options.productionOnPush)
1039
+ return '';
1040
+ const needs = options.e2eDeployment ? '[main, e2e-deployment]' : '[main]';
1041
+ const e2eGate = options.e2eDeployment
1042
+ ? " && (needs.e2e-deployment.result == 'success' || needs.e2e-deployment.result == 'skipped')"
1043
+ : '';
1044
+ const numbers = followUpStepNumbers(options);
1045
+ return `
1046
+ deploy-production:
1047
+ name: Deploy Production
1048
+ needs: ${needs}
1049
+ ${renderRunsOnLine(options.runsOn)}
1050
+ timeout-minutes: 30
1051
+ # prettier-ignore
1052
+ if: \${{ !cancelled() && github.event_name == 'push' && github.ref == ${stagingRefLiteral(options)} && needs.main.result == 'success'${e2eGate} }}
1053
+ ${environmentLine(options.environments?.production)} env:
1054
+ GH_TOKEN: \${{ github.token }}
1055
+ ${remoteCacheJobEnvLines(options.remoteCache)}${cargoCredentialJobEnvLines(options.cargoCredentials)}${privateNpmReadTokenJobEnv(options)} steps:
1056
+ ${renderCiWorkflowSteps(followUpSetupSteps(options, numbers), options)}
1057
+ # Step ${numbers.middle}
1058
+ - name: 🚀 Deploy Production
1059
+ ${renderOptionalLines(deployStepSecretEnvLines(options))} # prettier-ignore
1060
+ run: smoo github-ci nx-deploy --stage production --mode run-many --select-tag ${PRODUCTION_PUSH_DEPLOY_TAG} --name "Deploy Production" --step ${numbers.middle}
1061
+
1062
+ ${renderCiWorkflowSteps(followUpCleanupStep(numbers), options)}`;
1063
+ }
1064
+ export function artifactStepLines(provider, name, kind, inputs, condition = 'success()') {
1065
+ // GitHub resolves every action before evaluating step conditions, so a
1066
+ // Forgejo absolute action URL must never appear in a GitHub workflow.
1067
+ // Forgejo 15 supports v4 artifacts; its pinned clients remove the GHES gate.
1068
+ const action = provider === 'forgejo'
1069
+ ? kind === 'upload'
1070
+ ? 'https://code.forgejo.org/forgejo/upload-artifact@cb8afe72b42edc798abfb8fcb556cf660d894245'
1071
+ : 'https://code.forgejo.org/forgejo/download-artifact@769f970437aa3291b13f35dc23fc87967d7fb19f'
1072
+ : kind === 'upload'
1073
+ ? 'actions/upload-artifact@v7.0.1'
1074
+ : 'actions/download-artifact@v8.0.1';
1075
+ return [
1076
+ ` - name: ${name}`,
1077
+ ` if: ${condition}`,
1078
+ ` uses: ${action}`,
1079
+ ' with:',
1080
+ ...inputs.map((input) => ` ${input}`),
1081
+ ];
1082
+ }