@smoothbricks/nx-plugin 0.4.15 → 0.4.17

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