@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,1523 @@
1
+ /* biome-ignore-all lint/suspicious/noTemplateCurlyInString: GitHub Actions expressions are emitted literally. */
2
+
3
+ import { LINUX_PLATFORM_TARGET_GLOBS, MACOS_PLATFORM_TARGET_GLOBS } from '../platform-targets.js';
4
+ import type {
5
+ PackageCargoCredentialsConfig,
6
+ PackagePrivateNpmConfig,
7
+ PackageRemoteCacheConfig,
8
+ PackageSmooGithub,
9
+ PackageSourceCheckoutConfig,
10
+ } from '../workspace-manifest.js';
11
+ import { isSmoothBricksCodebasePackageName } from '../workspace-package-policy.js';
12
+ import {
13
+ artifactStepLines,
14
+ CiWorkflowStepKind,
15
+ cargoCredentialJobEnvLines,
16
+ cargoCredentialStepLines,
17
+ type DeployStepSecretConfig,
18
+ deployStepSecretEnvLines,
19
+ remoteCacheJobEnvLines,
20
+ sourceCheckoutsStepLines,
21
+ } from './ci-workflow.js';
22
+ import { GITHUB_HOSTED_LINUX_RUNNER, renderRunsOnLine, type WorkflowRunsOn } from './github-runs-on.js';
23
+
24
+ export type PublishWorkflowBump = 'auto' | 'patch' | 'minor' | 'major' | 'prerelease';
25
+ export type PublishWorkflowCondition =
26
+ | 'plan-mode-not-none'
27
+ | 'version-mode-not-none'
28
+ | 'deploy-production'
29
+ | 'deploy-production-standalone'
30
+ | 'failure'
31
+ | 'always';
32
+ export type PublishWorkflowNxTarget = 'build' | 'lint' | 'test';
33
+ export type PublishWorkflowDeployStage = 'none' | 'production';
34
+
35
+ export enum PublishWorkflowStepKind {
36
+ Checkout = 'checkout',
37
+ SourceCheckouts = 'source-checkouts',
38
+ CargoCredentials = 'cargo-credentials',
39
+ SetupDevenv = 'setup-devenv',
40
+ ConfigureReleaseAuthor = 'configure-release-author',
41
+ BuildNxVersionActions = 'build-nx-version-actions',
42
+ RepairPendingReleases = 'repair-pending-releases',
43
+ PlanRelease = 'plan-release',
44
+ VersionRelease = 'version-release',
45
+ CheckManagedMonorepoFiles = 'check-managed-monorepo-files',
46
+ Build = 'build',
47
+ Lint = 'lint',
48
+ UnitTests = 'unit-tests',
49
+ UploadTraceDbs = 'upload-trace-dbs',
50
+ ValidateMonorepoConfig = 'validate-monorepo-config',
51
+ TagRelease = 'tag-release',
52
+ PublishRelease = 'publish-release',
53
+ DeployProduction = 'deploy-production',
54
+ SaveNixDevenv = 'save-nix-devenv',
55
+ }
56
+
57
+ export interface PublishWorkflowStep {
58
+ kind: PublishWorkflowStepKind;
59
+ name: string;
60
+ number: number;
61
+ id?: string;
62
+ condition?: PublishWorkflowCondition;
63
+ nxTarget?: PublishWorkflowNxTarget;
64
+ }
65
+
66
+ export interface PublishWorkflowDefinition {
67
+ steps: PublishWorkflowStep[];
68
+ }
69
+
70
+ export interface PublishWorkflowDefinitionOptions extends DeployStepSecretConfig {
71
+ deploy?: boolean;
72
+ /**
73
+ * Whether the repo owns packages this workflow can release. False drops the
74
+ * release half entirely: a repo publishing nothing has no version to gate a
75
+ * production deploy on, and every `smoo release` command throws without one.
76
+ */
77
+ release?: boolean;
78
+ repoName?: string;
79
+ platformTargetGlobs?: readonly string[];
80
+ /**
81
+ * Architectures the macOS platform job fans out over, one job per entry.
82
+ * Empty falls back to a single job selecting every macOS platform family.
83
+ */
84
+ macosPlatformArchitectures?: readonly string[];
85
+ /** Linux jobs only. Default ubuntu-latest. Same smoo.github.runsOn as CI. */
86
+ runsOn?: WorkflowRunsOn;
87
+ /** macOS platform job runs-on labels. Default macos-latest. Same smoo.github.macosRunsOn as CI. */
88
+ macosRunsOn?: WorkflowRunsOn;
89
+ platformProducer?: PackageSmooGithub['platformProducer'];
90
+ actionsProvider?: PackageSmooGithub['actionsProvider'];
91
+ /**
92
+ * Declared private-npm opt-in. The publish step is the only place receiving
93
+ * the publish token; the read token rides along for `.npmrc` `${TOKEN}`
94
+ * expansion. The registry URL is not a job env. No env is emitted without
95
+ * this configuration.
96
+ */
97
+ privateNpm?: PackagePrivateNpmConfig;
98
+ /** Declared sibling source checkouts cloned before SetupDevenv. */
99
+ sourceCheckouts?: PackageSourceCheckoutConfig[];
100
+ /**
101
+ * Declared Cargo private-dependency credentials. Private git origins add a
102
+ * host-gated credential helper step before SetupDevenv; the named secrets
103
+ * become job env because every later cargo fetch resolves them.
104
+ */
105
+ cargoCredentials?: PackageCargoCredentialsConfig;
106
+ /**
107
+ * Declared self-hosted Nx remote cache. Every job here runs Nx targets —
108
+ * the release-candidate build, the platform build, the publish gate — so
109
+ * each carries the server and access token and reuses what CI already
110
+ * built for the same hashes.
111
+ */
112
+ remoteCache?: PackageRemoteCacheConfig;
113
+ }
114
+
115
+ export interface PublishWorkflowInputs {
116
+ bump: PublishWorkflowBump;
117
+ deployStage: PublishWorkflowDeployStage;
118
+ dryRun: boolean;
119
+ }
120
+
121
+ export interface PublishWorkflowVersionOutputs {
122
+ mode: 'new' | 'none';
123
+ projects: string[];
124
+ }
125
+
126
+ export interface PublishWorkflowSetupOutputs {
127
+ nixCacheHit: string;
128
+ devenvCacheHit: string;
129
+ }
130
+
131
+ export interface PublishWorkflowCallbacks {
132
+ checkout(): Promise<void>;
133
+ setupDevenv(): Promise<PublishWorkflowSetupOutputs>;
134
+ configureReleaseAuthor(): Promise<void>;
135
+ buildNxVersionActions(): Promise<void>;
136
+ repairPendingReleases(input: { dryRun: boolean }): Promise<void>;
137
+ versionRelease(input: { bump: PublishWorkflowBump; dryRun: boolean }): Promise<PublishWorkflowVersionOutputs>;
138
+ /**
139
+ * The selection the bump WILL make, computed without writing anything, so the
140
+ * gates that run before the version commit know what to run over. Defaults to
141
+ * a dry-run `versionRelease` when a caller supplies none.
142
+ */
143
+ planRelease?(input: { bump: PublishWorkflowBump }): Promise<PublishWorkflowVersionOutputs>;
144
+ checkManagedMonorepoFiles(): Promise<void>;
145
+ nxRunMany(input: { target: PublishWorkflowNxTarget; projects: string[] }): Promise<void>;
146
+ uploadTraceDbs(): Promise<void>;
147
+ validateMonorepoConfig(): Promise<void>;
148
+ tagRelease(input: { dryRun: boolean }): Promise<void>;
149
+ publishRelease(input: { bump: PublishWorkflowBump; dryRun: boolean }): Promise<void>;
150
+ deployProduction(): Promise<void>;
151
+ saveNixDevenv(input: PublishWorkflowSetupOutputs): Promise<void>;
152
+ }
153
+
154
+ export interface PublishWorkflowRunContext {
155
+ inputs: PublishWorkflowInputs;
156
+ callbacks: PublishWorkflowCallbacks;
157
+ }
158
+
159
+ export interface PublishWorkflowRunResult {
160
+ version: PublishWorkflowVersionOutputs;
161
+ failed: boolean;
162
+ }
163
+
164
+ type PublishWorkflowStepInput = Omit<PublishWorkflowStep, 'number'>;
165
+
166
+ export function definePublishWorkflow(options: PublishWorkflowDefinitionOptions = {}): PublishWorkflowDefinition {
167
+ const versionMode = githubExpression('steps.version.outputs.mode');
168
+ // Steps that run before the bump must label themselves from the plan: the
169
+ // version step's outputs do not exist yet, so the interpolation renders empty.
170
+ const planMode = githubExpression('steps.plan.outputs.mode');
171
+ if (options.release === false) {
172
+ return { steps: defineDeployOnlyWorkflowSteps(options) };
173
+ }
174
+ const setupSteps: PublishWorkflowStepInput[] = [
175
+ { kind: PublishWorkflowStepKind.Checkout, name: '📥 Checkout' },
176
+ ...(options.cargoCredentials !== undefined
177
+ ? [{ kind: PublishWorkflowStepKind.CargoCredentials, name: CARGO_CREDENTIALS_STEP_NAME }]
178
+ : []),
179
+ ...(options.sourceCheckouts?.length
180
+ ? [{ kind: PublishWorkflowStepKind.SourceCheckouts, name: '📦 Check out sibling sources' }]
181
+ : []),
182
+ { kind: PublishWorkflowStepKind.SetupDevenv, name: '🧱 Setup Nix/devenv', id: 'setup' },
183
+ { kind: PublishWorkflowStepKind.ConfigureReleaseAuthor, name: '🤖 Configure release author' },
184
+ ];
185
+ if (isSmoothBricksCodebasePackageName(options.repoName)) {
186
+ setupSteps.push({
187
+ kind: PublishWorkflowStepKind.BuildNxVersionActions,
188
+ name: '🏗️ Build smoo Nx version actions',
189
+ });
190
+ }
191
+ const releaseSteps: PublishWorkflowStepInput[] = [
192
+ { kind: PublishWorkflowStepKind.TagRelease, name: '🏷️ Tag release' },
193
+ {
194
+ kind: PublishWorkflowStepKind.PublishRelease,
195
+ name: `📦 Publish release (${versionMode})`,
196
+ },
197
+ ];
198
+ if (options.deploy === true) {
199
+ releaseSteps.push({
200
+ kind: PublishWorkflowStepKind.DeployProduction,
201
+ name: '🚀 Deploy production',
202
+ condition: 'deploy-production',
203
+ });
204
+ }
205
+ return {
206
+ steps: numberWorkflowSteps([
207
+ ...setupSteps,
208
+ {
209
+ kind: PublishWorkflowStepKind.RepairPendingReleases,
210
+ name: '🧯 Repair pending releases',
211
+ },
212
+ // Plan first, gate second, bump third. Lint and test hash the source, so
213
+ // running them BEFORE the version commit means their task hashes match
214
+ // the ones ci already computed for the same source — the publish reuses
215
+ // that cache instead of re-running 189 tasks. Build stays after the bump
216
+ // on purpose: an artifact built from pre-bump sources would ship the
217
+ // previous version string.
218
+ { kind: PublishWorkflowStepKind.PlanRelease, name: '🧭 Plan release', id: 'plan' },
219
+ {
220
+ kind: PublishWorkflowStepKind.CheckManagedMonorepoFiles,
221
+ name: `✅ Check managed monorepo files (${planMode})`,
222
+ condition: 'plan-mode-not-none',
223
+ },
224
+ {
225
+ kind: PublishWorkflowStepKind.Lint,
226
+ name: `🔍 Lint (${planMode})`,
227
+ condition: 'plan-mode-not-none',
228
+ nxTarget: 'lint',
229
+ },
230
+ {
231
+ kind: PublishWorkflowStepKind.UnitTests,
232
+ name: `🧪 Unit Tests (${planMode})`,
233
+ condition: 'plan-mode-not-none',
234
+ nxTarget: 'test',
235
+ },
236
+ { kind: PublishWorkflowStepKind.VersionRelease, name: '🔢 Version release', id: 'version' },
237
+ {
238
+ kind: PublishWorkflowStepKind.Build,
239
+ name: `🔨 Build (${versionMode})`,
240
+ condition: 'version-mode-not-none',
241
+ nxTarget: 'build',
242
+ },
243
+ { kind: PublishWorkflowStepKind.UploadTraceDbs, name: '📎 Upload trace DBs', condition: 'failure' },
244
+ {
245
+ kind: PublishWorkflowStepKind.ValidateMonorepoConfig,
246
+ name: `✅ Validate monorepo config (${versionMode})`,
247
+ condition: 'version-mode-not-none',
248
+ },
249
+ ...releaseSteps,
250
+ {
251
+ kind: PublishWorkflowStepKind.SaveNixDevenv,
252
+ name: '🧹 Cleanup and cache Nix/devenv',
253
+ condition: 'always',
254
+ },
255
+ ]),
256
+ };
257
+ }
258
+
259
+ /**
260
+ * Repos that deploy but own no release packages. Build, lint and test are not
261
+ * dropped safety: `nx-deploy --verify` runs all three before it deploys.
262
+ */
263
+ function defineDeployOnlyWorkflowSteps(options: PublishWorkflowDefinitionOptions): PublishWorkflowStep[] {
264
+ return numberWorkflowSteps([
265
+ { kind: PublishWorkflowStepKind.Checkout, name: '📥 Checkout' },
266
+ ...(options.cargoCredentials !== undefined
267
+ ? [{ kind: PublishWorkflowStepKind.CargoCredentials, name: CARGO_CREDENTIALS_STEP_NAME }]
268
+ : []),
269
+ ...(options.sourceCheckouts?.length
270
+ ? [{ kind: PublishWorkflowStepKind.SourceCheckouts, name: '📦 Check out sibling sources' }]
271
+ : []),
272
+ { kind: PublishWorkflowStepKind.SetupDevenv, name: '🧱 Setup Nix/devenv', id: 'setup' },
273
+ {
274
+ kind: PublishWorkflowStepKind.DeployProduction,
275
+ name: '🚀 Deploy production',
276
+ condition: 'deploy-production-standalone',
277
+ },
278
+ { kind: PublishWorkflowStepKind.UploadTraceDbs, name: '📎 Upload trace DBs', condition: 'failure' },
279
+ {
280
+ kind: PublishWorkflowStepKind.SaveNixDevenv,
281
+ name: '🧹 Cleanup and cache Nix/devenv',
282
+ condition: 'always',
283
+ },
284
+ ]);
285
+ }
286
+
287
+ function numberWorkflowSteps(steps: PublishWorkflowStepInput[]): PublishWorkflowStep[] {
288
+ return steps.map((step, index) => ({ ...step, number: index + 2 }));
289
+ }
290
+
291
+ export async function runPublishWorkflow(
292
+ workflow: PublishWorkflowDefinition,
293
+ context: PublishWorkflowRunContext,
294
+ ): Promise<PublishWorkflowRunResult> {
295
+ let setupOutputs: PublishWorkflowSetupOutputs = { nixCacheHit: '', devenvCacheHit: '' };
296
+ let version: PublishWorkflowVersionOutputs = { mode: 'none', projects: [] };
297
+ let plan: PublishWorkflowVersionOutputs = { mode: 'none', projects: [] };
298
+ let failed = false;
299
+ let failure: unknown;
300
+ for (const step of workflow.steps) {
301
+ if (!shouldRunStep(step, version, failed, context.inputs, plan)) {
302
+ continue;
303
+ }
304
+ try {
305
+ switch (step.kind) {
306
+ case PublishWorkflowStepKind.Checkout:
307
+ await context.callbacks.checkout();
308
+ break;
309
+ case PublishWorkflowStepKind.SourceCheckouts:
310
+ case PublishWorkflowStepKind.CargoCredentials:
311
+ // The generated job runs these setup shells; runtime simulation has no callback.
312
+ break;
313
+ case PublishWorkflowStepKind.SetupDevenv:
314
+ setupOutputs = await context.callbacks.setupDevenv();
315
+ break;
316
+ case PublishWorkflowStepKind.ConfigureReleaseAuthor:
317
+ await context.callbacks.configureReleaseAuthor();
318
+ break;
319
+ case PublishWorkflowStepKind.BuildNxVersionActions:
320
+ await context.callbacks.buildNxVersionActions();
321
+ break;
322
+ case PublishWorkflowStepKind.RepairPendingReleases:
323
+ await context.callbacks.repairPendingReleases({
324
+ dryRun: context.inputs.dryRun,
325
+ });
326
+ break;
327
+ case PublishWorkflowStepKind.PlanRelease:
328
+ plan = context.callbacks.planRelease
329
+ ? await context.callbacks.planRelease({ bump: context.inputs.bump })
330
+ : await context.callbacks.versionRelease({ bump: context.inputs.bump, dryRun: true });
331
+ break;
332
+ case PublishWorkflowStepKind.VersionRelease:
333
+ version = await context.callbacks.versionRelease(context.inputs);
334
+ break;
335
+ case PublishWorkflowStepKind.CheckManagedMonorepoFiles:
336
+ await context.callbacks.checkManagedMonorepoFiles();
337
+ break;
338
+ case PublishWorkflowStepKind.Build:
339
+ case PublishWorkflowStepKind.Lint:
340
+ case PublishWorkflowStepKind.UnitTests:
341
+ if (!step.nxTarget) {
342
+ throw new Error(`Workflow step ${step.kind} is missing an Nx target.`);
343
+ }
344
+ // Lint and test run before the bump exists, so they select from the
345
+ // plan; build runs after it and selects from the written version.
346
+ await context.callbacks.nxRunMany({
347
+ target: step.nxTarget,
348
+ projects: step.kind === PublishWorkflowStepKind.Build ? version.projects : plan.projects,
349
+ });
350
+ break;
351
+ case PublishWorkflowStepKind.UploadTraceDbs:
352
+ await context.callbacks.uploadTraceDbs();
353
+ break;
354
+ case PublishWorkflowStepKind.ValidateMonorepoConfig:
355
+ await context.callbacks.validateMonorepoConfig();
356
+ break;
357
+ case PublishWorkflowStepKind.TagRelease:
358
+ await context.callbacks.tagRelease({ dryRun: context.inputs.dryRun });
359
+ break;
360
+ case PublishWorkflowStepKind.PublishRelease:
361
+ await context.callbacks.publishRelease({
362
+ bump: context.inputs.bump,
363
+ dryRun: context.inputs.dryRun,
364
+ });
365
+ break;
366
+ case PublishWorkflowStepKind.DeployProduction:
367
+ await context.callbacks.deployProduction();
368
+ break;
369
+ case PublishWorkflowStepKind.SaveNixDevenv:
370
+ await context.callbacks.saveNixDevenv(setupOutputs);
371
+ break;
372
+ }
373
+ } catch (error) {
374
+ failed = true;
375
+ failure = error;
376
+ }
377
+ }
378
+ if (failure) {
379
+ throw failure;
380
+ }
381
+ return { version, failed };
382
+ }
383
+
384
+ function shouldRunStep(
385
+ step: PublishWorkflowStep,
386
+ version: PublishWorkflowVersionOutputs,
387
+ failed: boolean,
388
+ inputs: PublishWorkflowInputs,
389
+ plan: PublishWorkflowVersionOutputs = version,
390
+ ): boolean {
391
+ if (step.condition === 'plan-mode-not-none') {
392
+ return plan.mode !== 'none';
393
+ }
394
+ if (step.condition === 'version-mode-not-none') {
395
+ return version.mode !== 'none';
396
+ }
397
+ if (step.condition === 'deploy-production') {
398
+ return version.mode !== 'none' && inputs.deployStage === 'production' && !inputs.dryRun;
399
+ }
400
+ if (step.condition === 'deploy-production-standalone') {
401
+ return inputs.deployStage === 'production' && !inputs.dryRun;
402
+ }
403
+ if (step.condition === 'failure') {
404
+ return failed;
405
+ }
406
+ return true;
407
+ }
408
+
409
+ /**
410
+ * The workflow as this generator composes it. The consumer's own formatter has
411
+ * the last word on the bytes that land on disk — see `formatManagedContent` —
412
+ * so nothing here encodes one repository's Prettier preferences.
413
+ */
414
+ export function renderPublishWorkflowYaml(options: PublishWorkflowDefinitionOptions = {}): string {
415
+ if (options.release === false) {
416
+ return `${renderPublishWorkflowHeader(options)}${renderPublishWorkflowSteps(definePublishWorkflow(options).steps, options)}`;
417
+ }
418
+ if (hasMacosPlatformTargets(options) && !skipsPublishHandoff(options)) {
419
+ return renderPlatformPublishWorkflowYaml(options);
420
+ }
421
+ // A linux-cross producer runs the Apple targets on the publisher's own
422
+ // runner. Splitting jobs then buys nothing and costs a real transfer: the
423
+ // outputs get tarred, uploaded, downloaded into a second checkout, and two
424
+ // more devenv setups pay for themselves twice. One job, no artifacts.
425
+ if (hasMacosPlatformTargets(options) || hasLinuxPlatformTargets(options)) {
426
+ return `${renderPublishWorkflowHeader(options)}${renderSingleJobPublishWorkflowSteps(
427
+ definePublishWorkflow(options).steps,
428
+ options,
429
+ )}`;
430
+ }
431
+ return `${renderPublishWorkflowHeader(options)}${renderPublishWorkflowSteps(definePublishWorkflow(options).steps, options)}`;
432
+ }
433
+
434
+ function renderPublishWorkflowHeader(options: PublishWorkflowDefinitionOptions): string {
435
+ const dryRunDescription =
436
+ options.release === false
437
+ ? 'Skip the deploy and report what would run.'
438
+ : 'Run release commands without writing versions, tags, publishes, or GitHub Releases.';
439
+ const bumpInput =
440
+ options.release === false
441
+ ? ''
442
+ : `
443
+ bump:
444
+ type: choice
445
+ description:
446
+ Use auto for conventional commits, or force a semver bump. Prerelease publishes to next; all others publish to
447
+ latest.
448
+ options: [auto, patch, minor, major, prerelease]
449
+ default: auto
450
+ projects:
451
+ type: string
452
+ description:
453
+ Comma-separated Nx projects to release, or all for every owned release package. Blank releases package-local
454
+ changes since the last release, whatever the bump mode is.
455
+ default: ''`;
456
+ const deployInput =
457
+ options.deploy === true
458
+ ? `
459
+ deploy_stage:
460
+ type: choice
461
+ description: Deploy live systems after a successful publish.
462
+ options: [none, production]
463
+ default: none`
464
+ : '';
465
+ return `name: Publish
466
+
467
+ on:
468
+ workflow_dispatch:
469
+ inputs:${bumpInput}
470
+ dry_run:
471
+ type: boolean
472
+ description: ${dryRunDescription}
473
+ default: false${deployInput}
474
+
475
+ permissions:
476
+ contents: write
477
+ id-token: write
478
+
479
+ concurrency:
480
+ group: release-${githubExpression('github.ref')}
481
+ cancel-in-progress: false
482
+
483
+ defaults:
484
+ run:
485
+ working-directory: tooling/direnv
486
+
487
+ jobs:
488
+ publish:
489
+ ${options.release === false ? renderRunsOnLine(options.runsOn) : publishJobRunsOnLine(options)}
490
+ env:
491
+ GH_TOKEN: ${githubExpression('github.token')}${remoteCacheJobEnv(options)}${cargoCredentialsJobEnv(options)}${privateNpmInstallJobEnv(options)}${platformProducerJobEnv(options)}
492
+ steps:
493
+ `;
494
+ }
495
+
496
+ function renderPublishWorkflowSteps(steps: PublishWorkflowStep[], options: PublishWorkflowDefinitionOptions): string {
497
+ const lines: string[] = [];
498
+ for (const step of steps) {
499
+ lines.push(...sectionLinesBefore(step));
500
+ lines.push(...commentLinesForStep(step));
501
+ lines.push(...yamlLinesForStep(step, options));
502
+ lines.push('');
503
+ }
504
+ return `${lines.join('\n').trimEnd()}\n`;
505
+ }
506
+
507
+ function sectionLinesBefore(step: PublishWorkflowStep): string[] {
508
+ if (step.kind === PublishWorkflowStepKind.Checkout) {
509
+ return [' # --- Setup --------------------------------------------------------------', ''];
510
+ }
511
+ if (step.kind === PublishWorkflowStepKind.CheckManagedMonorepoFiles) {
512
+ return [
513
+ ' # --- Validation ---------------------------------------------------------',
514
+ '',
515
+ ' # Release validation intentionally does not restore persisted Nx task',
516
+ ' # cache. Nx may reuse tasks produced earlier in this same job, but publish',
517
+ ' # never relies on task outputs restored from CI cache. version runs before',
518
+ ' # validation so the commit completed below is the commit that was checked.',
519
+ '',
520
+ ];
521
+ }
522
+ if (step.kind === PublishWorkflowStepKind.TagRelease) {
523
+ return [' # --- Release ------------------------------------------------------------', ''];
524
+ }
525
+ if (step.kind === PublishWorkflowStepKind.SaveNixDevenv) {
526
+ return [' # --- Cleanup ------------------------------------------------------------', ''];
527
+ }
528
+ return [];
529
+ }
530
+
531
+ function commentLinesForStep(step: PublishWorkflowStep): string[] {
532
+ if (step.kind === PublishWorkflowStepKind.Checkout) {
533
+ return [' # Step 1: GitHub adds "Set up job" automatically', ' # Step 2'];
534
+ }
535
+ if (step.kind === PublishWorkflowStepKind.SetupDevenv) {
536
+ return [
537
+ ` # Step ${step.number}. Composite action internals do not affect top-level job step`,
538
+ ' # anchors; update these comments if top-level steps move.',
539
+ ];
540
+ }
541
+ return [` # Step ${step.number}`];
542
+ }
543
+
544
+ function yamlLinesForStep(step: PublishWorkflowStep, options: PublishWorkflowDefinitionOptions): string[] {
545
+ switch (step.kind) {
546
+ case PublishWorkflowStepKind.Checkout:
547
+ return [
548
+ ` - name: ${step.name}`,
549
+ ' uses: actions/checkout@v6.0.2',
550
+ ' with:',
551
+ ' filter: blob:none',
552
+ ' fetch-depth: 0',
553
+ ];
554
+ case PublishWorkflowStepKind.SourceCheckouts:
555
+ return siblingSourceCheckoutStepLines(options);
556
+ case PublishWorkflowStepKind.CargoCredentials:
557
+ return cargoCredentialsStepLines(options);
558
+ case PublishWorkflowStepKind.SetupDevenv:
559
+ return [` - name: ${step.name}`, ' id: setup', ' uses: ./.github/actions/setup-devenv'];
560
+ case PublishWorkflowStepKind.ConfigureReleaseAuthor:
561
+ return [
562
+ ` - name: ${step.name}`,
563
+ ' run:',
564
+ ' git config user.name "github-actions[bot]" && git config user.email',
565
+ ' "41898282+github-actions[bot]@users.noreply.github.com"',
566
+ ];
567
+ case PublishWorkflowStepKind.BuildNxVersionActions:
568
+ return [
569
+ ` - name: ${step.name}`,
570
+ ' # Nx Release loads @smoothbricks/nx-plugin/version-actions through the',
571
+ ' # export map in its own node process, and versioning runs before the',
572
+ ' # build phase, so the hook must exist in dist first. Downstream',
573
+ ' # consumers install the published package and skip this bootstrap.',
574
+ ' #',
575
+ ' # `nx` cannot do it: the project graph loads this very plugin, so',
576
+ ' # `nx build nx-plugin` deadlocks on the executor it is building.',
577
+ ' # ttsc needs only the package tsconfig -- same bootstrap the devenv',
578
+ ' # shell runs (tooling/direnv/enter-shell.ts).',
579
+ ' working-directory: packages/nx-plugin',
580
+ ' run: ttsc -p tsconfig.lib.json --emit',
581
+ ];
582
+ case PublishWorkflowStepKind.RepairPendingReleases:
583
+ return [
584
+ ` - name: ${step.name}`,
585
+ ...privateNpmPublisherStepEnv(options),
586
+ ` run: smoo release repair-pending --dry-run "${githubExpression('inputs.dry_run')}"`,
587
+ ];
588
+ case PublishWorkflowStepKind.PlanRelease:
589
+ // The same selection the bump will make, computed without writing: the
590
+ // gates need `mode` and `projects` before any version commit exists.
591
+ return [
592
+ ` - name: ${step.name}`,
593
+ ' id: plan',
594
+ ' run:',
595
+ ` smoo release version --bump "${githubExpression('inputs.bump')}" --projects "${githubExpression('inputs.projects')}" --dry-run "true" --github-output`,
596
+ ' "$GITHUB_OUTPUT"',
597
+ ];
598
+ case PublishWorkflowStepKind.VersionRelease:
599
+ return [
600
+ ` - name: ${step.name}`,
601
+ ' id: version',
602
+ ' run:',
603
+ ` smoo release version --bump "${githubExpression('inputs.bump')}" --projects "${githubExpression('inputs.projects')}" --dry-run "${githubExpression('inputs.dry_run')}" --github-output`,
604
+ ' "$GITHUB_OUTPUT"',
605
+ ];
606
+ case PublishWorkflowStepKind.CheckManagedMonorepoFiles:
607
+ // Drift is derived state with its own remediation PR; publishing only
608
+ // blocks on actual package issues (smoo monorepo validate).
609
+ return conditionalRunStep(step, 'smoo monorepo check --warn');
610
+ case PublishWorkflowStepKind.Build:
611
+ return conditionalRunStep(
612
+ step,
613
+ `smoo github-ci nx-run-many --targets build --projects "${githubExpression('steps.version.outputs.projects')}"`,
614
+ );
615
+ case PublishWorkflowStepKind.Lint:
616
+ return conditionalRunStep(
617
+ step,
618
+ `smoo github-ci nx-run-many --targets lint --projects "${githubExpression('steps.plan.outputs.projects')}"`,
619
+ );
620
+ case PublishWorkflowStepKind.UnitTests:
621
+ return conditionalRunStep(
622
+ step,
623
+ `smoo github-ci nx-run-many --targets test --projects "${githubExpression('steps.plan.outputs.projects')}"`,
624
+ );
625
+ case PublishWorkflowStepKind.UploadTraceDbs:
626
+ return artifactStepLines(
627
+ options.actionsProvider,
628
+ step.name,
629
+ 'upload',
630
+ [
631
+ `name: trace-results-${githubExpression('github.run_id')}`,
632
+ 'path: packages/*/.cache/trace-results.db*',
633
+ 'if-no-files-found: ignore',
634
+ 'retention-days: 14',
635
+ 'include-hidden-files: true',
636
+ ],
637
+ 'failure()',
638
+ );
639
+ case PublishWorkflowStepKind.ValidateMonorepoConfig:
640
+ // Scoped to the release's candidates: the build phase and the packed-package
641
+ // checks cover what ships. Unscoped, validate compiled every project - on a
642
+ // release touching no Rust that was 3m30 of the cowshed CLI on the critical
643
+ // path, for a binary the release did not contain.
644
+ return conditionalRunStep(
645
+ step,
646
+ `smoo monorepo validate --projects "${githubExpression('steps.version.outputs.projects')}"`,
647
+ );
648
+ case PublishWorkflowStepKind.TagRelease:
649
+ return tagReleaseStepLines(step.name);
650
+ case PublishWorkflowStepKind.PublishRelease:
651
+ return [
652
+ ` - name: ${step.name}`,
653
+ ...privateNpmPublisherStepEnv(options),
654
+ ...(options.privateNpm
655
+ ? [' # Private publication uses the declared registry and step-scoped publisher credential.']
656
+ : [
657
+ ' # smoo packs with Bun, then publishes tarballs with npm. Existing',
658
+ ' # packages must already exist on npm and use trusted publishing/OIDC.',
659
+ ' # Missing package names are bootstrapped locally before trust setup.',
660
+ ]),
661
+ ` run: smoo release publish --bump "${githubExpression('inputs.bump')}" --dry-run "${githubExpression('inputs.dry_run')}"`,
662
+ ];
663
+ case PublishWorkflowStepKind.DeployProduction:
664
+ return deployProductionStep(step, options);
665
+ case PublishWorkflowStepKind.SaveNixDevenv:
666
+ return [
667
+ ` - name: ${step.name}`,
668
+ ' # success() is default; always() still saves GH Nix cache after a red job.',
669
+ ' if: always()',
670
+ ' uses: ./.github/actions/save-nix-devenv',
671
+ ' with:',
672
+ ` devenv-cache-hit: ${githubExpression('steps.setup.outputs.devenv-cache-hit')}`,
673
+ ];
674
+ }
675
+ }
676
+
677
+ /**
678
+ * The one place release tags come into existence. Release candidates version
679
+ * without tagging, so a candidate that fails Build, Lint, or Unit Tests leaves
680
+ * no ref behind and the next run recomputes the same version cleanly. Tagging
681
+ * here — after validation, immediately before the npm publish — preserves the
682
+ * "tagged but not published" state that `smoo release repair-pending`
683
+ * reconciles, because git and npm cannot be written atomically.
684
+ */
685
+ function tagReleaseStepLines(name: string): string[] {
686
+ return [
687
+ ` - name: ${name}`,
688
+ ' # Ordered before the publish below so an interrupted release stays',
689
+ ' # detectable by the repair step at the top of this job on a later run.',
690
+ ` run: smoo release tag --dry-run "${githubExpression('inputs.dry_run')}"`,
691
+ ];
692
+ }
693
+
694
+ function deployProductionStep(step: PublishWorkflowStep, options: PublishWorkflowDefinitionOptions): string[] {
695
+ const conditionLines =
696
+ step.condition === 'deploy-production-standalone'
697
+ ? [" if: ${{ inputs.deploy_stage == 'production' && inputs.dry_run != 'true' }}"]
698
+ : [
699
+ ' if:',
700
+ " ${{ steps.version.outputs.mode != 'none' && inputs.deploy_stage == 'production' && inputs.dry_run !=",
701
+ " 'true' }}",
702
+ ];
703
+ return [
704
+ ` - name: ${step.name}`,
705
+ ...conditionLines,
706
+ ...deployStepSecretEnvLines(options),
707
+ ' run: smoo github-ci nx-deploy --stage production --mode run-many --verify --name "Deploy Production"',
708
+ ];
709
+ }
710
+
711
+ function conditionalRunStep(step: PublishWorkflowStep, run: string): string[] {
712
+ // A step gated on the plan must read the PLAN's mode: it runs before the
713
+ // version step exists, and `steps.version.outputs.mode` is empty there, which
714
+ // silently skips the gate rather than running it.
715
+ const source = step.condition === 'plan-mode-not-none' ? 'plan' : 'version';
716
+ return [` - name: ${step.name}`, ` if: steps.${source}.outputs.mode != 'none'`, ` run: ${run}`];
717
+ }
718
+
719
+ function siblingSourceCheckoutStepLines(options: PublishWorkflowDefinitionOptions): string[] {
720
+ const checkouts = options.sourceCheckouts;
721
+ if (!checkouts?.length) {
722
+ return [];
723
+ }
724
+ return sourceCheckoutsStepLines(
725
+ { kind: CiWorkflowStepKind.SourceCheckouts, name: '📦 Check out sibling sources', number: 0 },
726
+ checkouts,
727
+ );
728
+ }
729
+
730
+ const CARGO_CREDENTIALS_STEP_NAME = 'Prepare Cargo credentials';
731
+
732
+ /**
733
+ * One credential-helper install per job, because the helper is process
734
+ * configuration and every later cargo fetch in that job resolves through it:
735
+ * the release candidate, both native platform legs, and the final publish job
736
+ * whose pending-release repair still builds historical versions from source.
737
+ */
738
+ function cargoCredentialsStepLines(options: PublishWorkflowDefinitionOptions): string[] {
739
+ const config = options.cargoCredentials;
740
+ if (config === undefined) {
741
+ return [];
742
+ }
743
+ return cargoCredentialStepLines(
744
+ { kind: CiWorkflowStepKind.CargoCredentials, name: CARGO_CREDENTIALS_STEP_NAME, number: 0 },
745
+ config,
746
+ );
747
+ }
748
+
749
+ /**
750
+ * Cargo credentials are job env, not step env: the helper reads its token at
751
+ * call time from whichever later step runs the fetch, and build, lint, test
752
+ * and platform-output builds all do. Narrowing it to the install step would
753
+ * leave those fetches unauthenticated. Only `${{ secrets.NAME }}` is ever
754
+ * rendered — no token value, URL, or argv. Malformed declarations throw here,
755
+ * on every render path, rather than in CI.
756
+ */
757
+ function cargoCredentialsJobEnv(options: PublishWorkflowDefinitionOptions): string {
758
+ const rendered = cargoCredentialJobEnvLines(options.cargoCredentials).trimEnd();
759
+ return rendered === '' ? '' : `\n${rendered}`;
760
+ }
761
+
762
+ /**
763
+ * The remote cache is job env for the same reason: every Nx target in the job
764
+ * reads it, and a release build that missed the cache would rebuild what CI
765
+ * already built for the identical hashes. Only `${{ secrets.NAME }}` is
766
+ * rendered for the token. Malformed declarations throw here, not in CI.
767
+ */
768
+ function remoteCacheJobEnv(options: PublishWorkflowDefinitionOptions): string {
769
+ const rendered = remoteCacheJobEnvLines(options.remoteCache).trimEnd();
770
+ return rendered === '' ? '' : `\n${rendered}`;
771
+ }
772
+
773
+ function renderSingleJobPublishWorkflowSteps(
774
+ steps: PublishWorkflowStep[],
775
+ options: PublishWorkflowDefinitionOptions,
776
+ ): string {
777
+ const lines: string[] = [];
778
+ const producer = options.platformProducer;
779
+ const crossOnThisRunner = skipsPublishHandoff(options) && hasMacosPlatformTargets(options);
780
+ for (const step of steps) {
781
+ lines.push(...sectionLinesBefore(step));
782
+ lines.push(...commentLinesForStep(step));
783
+ lines.push(...yamlLinesForStep(step, options));
784
+ lines.push('');
785
+ if (crossOnThisRunner && producer && step.kind === PublishWorkflowStepKind.Checkout) {
786
+ // Before any toolchain setup or build, exactly as the dedicated producer
787
+ // job ordered it: the SDK has to be on disk before devenv resolves it.
788
+ lines.push(
789
+ ' - name: Check cross-platform toolchain prerequisites',
790
+ ' working-directory: .',
791
+ ' run: |',
792
+ ' set -euo pipefail',
793
+ ...producer.preflight.split('\n').map((line) => ` ${line}`),
794
+ '',
795
+ );
796
+ }
797
+ if (step.kind === PublishWorkflowStepKind.Build) {
798
+ lines.push(
799
+ ' - name: 🐧 Build supplemental Linux targets',
800
+ " if: steps.version.outputs.mode != 'none'",
801
+ ` run: smoo github-ci nx-run-many --targets "${LINUX_PLATFORM_TARGET_GLOBS.join(',')}" --projects "${githubExpression(
802
+ 'steps.version.outputs.projects',
803
+ )}"`,
804
+ '',
805
+ );
806
+ if (crossOnThisRunner) {
807
+ lines.push(
808
+ ' - name: 🍎 Build selected macOS and iOS release outputs',
809
+ " if: steps.version.outputs.mode != 'none'",
810
+ ` run: smoo github-ci nx-run-many --targets "${macosPlatformFamilies(options).join(',')}" --projects "${githubExpression(
811
+ 'steps.version.outputs.projects',
812
+ )}"`,
813
+ '',
814
+ );
815
+ }
816
+ }
817
+ }
818
+ return `${lines.join('\n').trimEnd()}\n`;
819
+ }
820
+
821
+ function renderPlatformPublishWorkflowYaml(options: PublishWorkflowDefinitionOptions): string {
822
+ const deployInput =
823
+ options.deploy === true
824
+ ? `
825
+ deploy_stage:
826
+ type: choice
827
+ description: Deploy live systems after a successful publish.
828
+ options: [none, production]
829
+ default: none`
830
+ : '';
831
+ const steps = definePublishWorkflow(options).steps;
832
+ return `name: Publish
833
+
834
+ on:
835
+ workflow_dispatch:
836
+ inputs:
837
+ bump:
838
+ type: choice
839
+ description:
840
+ Use auto for conventional commits, or force a semver bump. Prerelease publishes to next; all others publish to
841
+ latest.
842
+ options: [auto, patch, minor, major, prerelease]
843
+ default: auto
844
+ projects:
845
+ type: string
846
+ description:
847
+ Comma-separated Nx projects to release, or all for every owned release package. Blank releases package-local
848
+ changes since the last release, whatever the bump mode is.
849
+ default: ''
850
+ dry_run:
851
+ type: boolean
852
+ description: Run release commands without writing versions, tags, publishes, or GitHub Releases.
853
+ default: false${deployInput}
854
+
855
+ permissions:
856
+ contents: read
857
+
858
+ concurrency:
859
+ group: release-${githubExpression('github.ref')}
860
+ cancel-in-progress: false
861
+
862
+ defaults:
863
+ run:
864
+ working-directory: tooling/direnv
865
+
866
+ jobs:
867
+ linux-release-candidate:
868
+ ${renderRunsOnLine(options.runsOn)}
869
+ permissions:
870
+ contents: write
871
+ id-token: none
872
+ outputs:
873
+ mode: ${githubExpression('steps.version.outputs.mode')}
874
+ release-sha: ${githubExpression('steps.release-state.outputs.sha')}
875
+ env:
876
+ GH_TOKEN: ${githubExpression('github.token')}${remoteCacheJobEnv(options)}${cargoCredentialsJobEnv(options)}${privateNpmInstallJobEnv(options)}
877
+ steps:
878
+ ${renderLinuxReleaseCandidateSteps(steps, options)}
879
+
880
+ ${options.platformProducer?.kind === 'linux-cross' ? 'cross-platform' : 'macos-platform'}:
881
+ ${renderMacosJobHeaderLines(options)}
882
+ permissions:
883
+ contents: read
884
+ id-token: none
885
+ env:
886
+ GH_TOKEN: ${githubExpression('github.token')}${remoteCacheJobEnv(options)}${cargoCredentialsJobEnv(options)}${privateNpmInstallJobEnv(options)}
887
+ ${Object.entries(options.platformProducer?.env ?? {})
888
+ .map(([name, value]) => ` ${name}: ${JSON.stringify(value)}`)
889
+ .join('\n')}
890
+ steps:
891
+ ${renderMacosPlatformSteps(options)}
892
+
893
+ publish-on-linux:
894
+ needs: [linux-release-candidate, ${options.platformProducer?.kind === 'linux-cross' ? 'cross-platform' : 'macos-platform'}]
895
+ ${publishJobRunsOnLine(options)}
896
+ permissions:
897
+ contents: write
898
+ id-token: write
899
+ env:
900
+ TTSC_TSGO_BINARY: ${githubExpression('github.workspace')}/node_modules/@typescript/native/bin/tsc
901
+ GH_TOKEN: ${githubExpression('github.token')}${remoteCacheJobEnv(options)}${cargoCredentialsJobEnv(options)}${privateNpmInstallJobEnv(options)}
902
+ steps:
903
+ ${renderFinalLinuxPublishSteps(options)}
904
+ `;
905
+ }
906
+
907
+ function renderLinuxReleaseCandidateSteps(
908
+ steps: PublishWorkflowStep[],
909
+ options: PublishWorkflowDefinitionOptions,
910
+ ): string {
911
+ const lines: string[] = [];
912
+ let stepNumber = 2;
913
+ for (const step of steps) {
914
+ if (
915
+ step.kind === PublishWorkflowStepKind.RepairPendingReleases ||
916
+ step.kind === PublishWorkflowStepKind.TagRelease ||
917
+ step.kind === PublishWorkflowStepKind.PublishRelease ||
918
+ step.kind === PublishWorkflowStepKind.DeployProduction ||
919
+ step.kind === PublishWorkflowStepKind.SaveNixDevenv
920
+ ) {
921
+ continue;
922
+ }
923
+ lines.push(...sectionLinesBefore(step));
924
+ if (step.kind === PublishWorkflowStepKind.Checkout) {
925
+ lines.push(' # Step 1: GitHub adds "Set up job" automatically', ` # Step ${stepNumber}`);
926
+ } else if (step.kind === PublishWorkflowStepKind.SetupDevenv) {
927
+ lines.push(
928
+ ` # Step ${stepNumber}. Composite action internals do not affect top-level job step`,
929
+ ' # anchors; update these comments if top-level steps move.',
930
+ );
931
+ } else {
932
+ lines.push(` # Step ${stepNumber}`);
933
+ }
934
+ if (step.kind === PublishWorkflowStepKind.Checkout) {
935
+ lines.push(
936
+ ` - name: ${step.name}`,
937
+ ' uses: actions/checkout@v6.0.2',
938
+ ' with:',
939
+ ` ref: ${githubExpression('github.sha')}`,
940
+ ' filter: blob:none',
941
+ ' fetch-depth: 0',
942
+ );
943
+ } else if (step.kind === PublishWorkflowStepKind.Build) {
944
+ lines.push(
945
+ ` - name: ${step.name}`,
946
+ " if: steps.version.outputs.mode != 'none'",
947
+ ' run:',
948
+ ` smoo github-ci nx-run-many --targets build --projects "${githubExpression(
949
+ 'steps.version.outputs.projects',
950
+ )}" --collect-outputs "${githubExpression('runner.temp')}/release-build-outputs"`,
951
+ );
952
+ } else {
953
+ lines.push(...yamlLinesForStep(step, options));
954
+ }
955
+ stepNumber += 1;
956
+ if (step.kind === PublishWorkflowStepKind.VersionRelease) {
957
+ lines.push(
958
+ '',
959
+ ` # Step ${stepNumber}`,
960
+ ' - name: 🔒 Capture candidate release SHA',
961
+ ' id: release-state',
962
+ ' run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"',
963
+ );
964
+ stepNumber += 1;
965
+ }
966
+ if (step.kind === PublishWorkflowStepKind.Build && hasLinuxPlatformTargets(options)) {
967
+ lines.push(
968
+ '',
969
+ ` # Step ${stepNumber}`,
970
+ ' - name: 🐧 Build supplemental Linux targets',
971
+ " if: steps.version.outputs.mode != 'none'",
972
+ ' run:',
973
+ ` smoo github-ci nx-run-many --targets "${LINUX_PLATFORM_TARGET_GLOBS.join(
974
+ ',',
975
+ )}" --projects "${githubExpression(
976
+ 'steps.version.outputs.projects',
977
+ )}" --collect-outputs "${githubExpression('runner.temp')}/linux-platform-outputs"`,
978
+ );
979
+ stepNumber += 1;
980
+ }
981
+ lines.push('');
982
+ }
983
+ lines.push(
984
+ ' # --- Candidate transfer --------------------------------------------------',
985
+ '',
986
+ ` # Step ${stepNumber++}`,
987
+ ' - name: 📦 Bundle validated release state',
988
+ ' run:',
989
+ ` mkdir -p "${githubExpression('runner.temp')}/publish-release-state" && git bundle create`,
990
+ ` "${githubExpression('runner.temp')}/publish-release-state/release-state.bundle" HEAD --tags && git rev-parse HEAD >`,
991
+ ` "${githubExpression('runner.temp')}/publish-release-state/release-head"`,
992
+ '',
993
+ ` # Step ${stepNumber++}`,
994
+ ...artifactStepLines(options.actionsProvider, '📤 Upload validated release state', 'upload', [
995
+ `name: publish-release-state-${githubExpression('github.run_id')}`,
996
+ `path: ${githubExpression('runner.temp')}/publish-release-state`,
997
+ 'if-no-files-found: error',
998
+ 'retention-days: 1',
999
+ ]),
1000
+ '',
1001
+ ` # Step ${stepNumber++}`,
1002
+ ...artifactStepLines(
1003
+ options.actionsProvider,
1004
+ '📤 Upload validated build outputs',
1005
+ 'upload',
1006
+ [
1007
+ `name: publish-release-outputs-${githubExpression('github.run_id')}`,
1008
+ `path: ${githubExpression('runner.temp')}/release-build-outputs`,
1009
+ 'if-no-files-found: error',
1010
+ 'retention-days: 1',
1011
+ 'include-hidden-files: true',
1012
+ ],
1013
+ "steps.version.outputs.mode != 'none'",
1014
+ ),
1015
+ );
1016
+ if (hasLinuxPlatformTargets(options)) {
1017
+ lines.push(
1018
+ '',
1019
+ ` # Step ${stepNumber++}`,
1020
+ ...artifactStepLines(
1021
+ options.actionsProvider,
1022
+ '📤 Upload supplemental Linux outputs',
1023
+ 'upload',
1024
+ [
1025
+ `name: publish-linux-outputs-${githubExpression('github.run_id')}`,
1026
+ `path: ${githubExpression('runner.temp')}/linux-platform-outputs`,
1027
+ 'if-no-files-found: error',
1028
+ 'retention-days: 1',
1029
+ 'include-hidden-files: true',
1030
+ ],
1031
+ "steps.version.outputs.mode != 'none'",
1032
+ ),
1033
+ );
1034
+ }
1035
+ lines.push(
1036
+ '',
1037
+ ' # --- Cleanup ------------------------------------------------------------',
1038
+ '',
1039
+ ` # Step ${stepNumber}`,
1040
+ ' - name: 🧹 Cleanup and cache Nix/devenv',
1041
+ ' # success() is default; always() still saves GH Nix cache after a red job.',
1042
+ ' if: always()',
1043
+ ' uses: ./.github/actions/save-nix-devenv',
1044
+ ' with:',
1045
+ ` devenv-cache-hit: ${githubExpression('steps.setup.outputs.devenv-cache-hit')}`,
1046
+ );
1047
+ return lines.join('\n').trimEnd();
1048
+ }
1049
+
1050
+ function renderMacosPlatformSteps(options: PublishWorkflowDefinitionOptions): string {
1051
+ let stepNumber = 3;
1052
+ const lines = [
1053
+ ' # --- Setup --------------------------------------------------------------',
1054
+ '',
1055
+ ' # Step 1: GitHub adds "Set up job" automatically',
1056
+ ' # Step 2',
1057
+ ' - name: 📥 Checkout dispatch commit',
1058
+ ' uses: actions/checkout@v6.0.2',
1059
+ ' with:',
1060
+ ` ref: ${githubExpression('github.sha')}`,
1061
+ ' filter: blob:none',
1062
+ ' fetch-depth: 0',
1063
+ ];
1064
+ if (options.platformProducer) {
1065
+ if (!options.platformProducer.preflight.trim()) {
1066
+ throw new Error('Linux cross-platform production requires a nonempty toolchain preflight command.');
1067
+ }
1068
+ lines.push(
1069
+ '',
1070
+ ` # Step ${stepNumber++}`,
1071
+ ' - name: Check cross-platform toolchain prerequisites',
1072
+ ' working-directory: .',
1073
+ ' run: |',
1074
+ ' set -euo pipefail',
1075
+ ...options.platformProducer.preflight.split('\n').map((line) => ` ${line}`),
1076
+ );
1077
+ }
1078
+ const macosCargoCredentials = cargoCredentialsStepLines(options);
1079
+ if (macosCargoCredentials.length > 0) {
1080
+ lines.push('', ` # Step ${stepNumber++}`, ...macosCargoCredentials);
1081
+ }
1082
+ const siblingSourceCheckouts = siblingSourceCheckoutStepLines(options);
1083
+ if (siblingSourceCheckouts.length > 0) {
1084
+ lines.push('', ` # Step ${stepNumber++}`, ...siblingSourceCheckouts);
1085
+ }
1086
+ lines.push(
1087
+ '',
1088
+ ` # Step ${stepNumber++}. Composite action internals do not affect top-level job step`,
1089
+ ' # anchors; update these comments if top-level steps move.',
1090
+ ' - name: 🧱 Setup Nix/devenv',
1091
+ ' id: setup',
1092
+ ' uses: ./.github/actions/setup-devenv',
1093
+ );
1094
+ if (isSmoothBricksCodebasePackageName(options.repoName)) {
1095
+ lines.push(
1096
+ '',
1097
+ ` # Step ${stepNumber++}`,
1098
+ ' - name: 🏗️ Build smoo Nx version actions',
1099
+ ' # Nx Release loads @smoothbricks/nx-plugin/version-actions through the',
1100
+ ' # export map in its own node process, and versioning runs before the',
1101
+ ' # build phase, so the hook must exist in dist first. Downstream',
1102
+ ' # consumers install the published package and skip this bootstrap.',
1103
+ ' #',
1104
+ ' # `nx` cannot do it: the project graph loads this very plugin, so',
1105
+ ' # `nx build nx-plugin` deadlocks on the executor it is building.',
1106
+ ' # ttsc needs only the package tsconfig -- same bootstrap the devenv',
1107
+ ' # shell runs (tooling/direnv/enter-shell.ts).',
1108
+ ' working-directory: packages/nx-plugin',
1109
+ ' run: ttsc -p tsconfig.lib.json --emit',
1110
+ );
1111
+ }
1112
+ lines.push(
1113
+ '',
1114
+ ` # Step ${stepNumber++}`,
1115
+ ' - name: 🤖 Configure release author',
1116
+ ' run:',
1117
+ ' git config user.name "github-actions[bot]" && git config user.email',
1118
+ ' "41898282+github-actions[bot]@users.noreply.github.com"',
1119
+ '',
1120
+ ` # Step ${stepNumber++}`,
1121
+ ' - name: 🔢 Version release',
1122
+ ' id: version',
1123
+ ' run:',
1124
+ ` smoo release version --bump "${githubExpression('inputs.bump')}" --projects "${githubExpression('inputs.projects')}" --dry-run "${githubExpression('inputs.dry_run')}" --github-output`,
1125
+ ' "$GITHUB_OUTPUT"',
1126
+ );
1127
+ const architectures = macosPlatformArchitectures(options);
1128
+ const isMatrix = architectures.length >= 2;
1129
+ const testArchitecture = macosTestArchitecture(architectures);
1130
+ const legLabel = isMatrix ? ` (${githubExpression('matrix.arch')})` : '';
1131
+ const testCondition =
1132
+ isMatrix && testArchitecture !== undefined
1133
+ ? `matrix.arch == '${testArchitecture}' && steps.platform-outputs.outputs.projects != ''`
1134
+ : `steps.platform-outputs.outputs.projects != ''`;
1135
+ lines.push(
1136
+ '',
1137
+ ` # Step ${stepNumber++}`,
1138
+ ` - name: 🍎 Build selected macOS and iOS release outputs${legLabel}`,
1139
+ ' id: platform-outputs',
1140
+ ' run:',
1141
+ ` smoo release build-platform-outputs --bump "${githubExpression(
1142
+ 'inputs.bump',
1143
+ )}" --projects "${githubExpression('inputs.projects')}" --ref "${githubExpression('github.sha')}" --targets "${macosPlatformTargetSelector(options)}" --output`,
1144
+ ` "${githubExpression('runner.temp')}/macos-platform-outputs" --github-output "$GITHUB_OUTPUT"`,
1145
+ );
1146
+ if (options.platformProducer?.kind !== 'linux-cross') {
1147
+ lines.push('', ` # Step ${stepNumber++}`, ' - name: 🧪 Unit test selected macOS and iOS packages');
1148
+ if (isMatrix) {
1149
+ lines.push(
1150
+ ' # Only the runner-native leg can execute what it built; the foreign',
1151
+ ' # architecture ships as an artifact without running here.',
1152
+ );
1153
+ }
1154
+ lines.push(
1155
+ ` if: ${testCondition}`,
1156
+ ' run:',
1157
+ ' smoo github-ci nx-run-many --targets test --projects',
1158
+ ` "${githubExpression('steps.platform-outputs.outputs.projects')}"`,
1159
+ );
1160
+ }
1161
+ lines.push(
1162
+ '',
1163
+ ` # Step ${stepNumber++}`,
1164
+ ...artifactStepLines(options.actionsProvider, `📤 Upload macOS platform outputs${legLabel}`, 'upload', [
1165
+ `name: ${
1166
+ isMatrix
1167
+ ? `publish-macos-${githubExpression('matrix.arch')}-outputs-${githubExpression('github.run_id')}`
1168
+ : `publish-macos-outputs-${githubExpression('github.run_id')}`
1169
+ }`,
1170
+ `path: ${githubExpression('runner.temp')}/macos-platform-outputs`,
1171
+ 'if-no-files-found: error',
1172
+ 'retention-days: 1',
1173
+ 'include-hidden-files: true',
1174
+ ]),
1175
+ '',
1176
+ ' # --- Cleanup ------------------------------------------------------------',
1177
+ '',
1178
+ ` # Step ${stepNumber}`,
1179
+ ' - name: 🧹 Cleanup and cache Nix/devenv',
1180
+ ' # success() is default; always() still saves GH Nix cache after a red job.',
1181
+ ' if: always()',
1182
+ ' uses: ./.github/actions/save-nix-devenv',
1183
+ ' with:',
1184
+ ` devenv-cache-hit: ${githubExpression('steps.setup.outputs.devenv-cache-hit')}`,
1185
+ );
1186
+ return lines.join('\n').trimEnd();
1187
+ }
1188
+
1189
+ function renderFinalLinuxPublishSteps(options: PublishWorkflowDefinitionOptions): string {
1190
+ const mode = 'needs.linux-release-candidate.outputs.mode';
1191
+ let stepNumber = 2;
1192
+ const lines = [
1193
+ ' # --- Setup --------------------------------------------------------------',
1194
+ '',
1195
+ ' # Step 1: GitHub adds "Set up job" automatically',
1196
+ ` # Step ${stepNumber++}`,
1197
+ ' - name: 📥 Checkout dispatch commit',
1198
+ ' uses: actions/checkout@v6.0.2',
1199
+ ' with:',
1200
+ ` ref: ${githubExpression('github.sha')}`,
1201
+ ' filter: blob:none',
1202
+ ' fetch-depth: 0',
1203
+ ];
1204
+ const publishCargoCredentials = cargoCredentialsStepLines(options);
1205
+ if (publishCargoCredentials.length > 0) {
1206
+ lines.push('', ` # Step ${stepNumber++}`, ...publishCargoCredentials);
1207
+ }
1208
+ const siblingSourceCheckouts = siblingSourceCheckoutStepLines(options);
1209
+ if (siblingSourceCheckouts.length > 0) {
1210
+ lines.push('', ` # Step ${stepNumber++}`, ...siblingSourceCheckouts);
1211
+ }
1212
+ lines.push(
1213
+ '',
1214
+ ` # Step ${stepNumber++}`,
1215
+ ' - name: 🧱 Setup Nix/devenv',
1216
+ ' # Pending release repair builds historical npm gaps before the current',
1217
+ ' # verified artifacts are restored, so this job still needs the full',
1218
+ ' # toolchain even though current release publishing is prebuilt-only.',
1219
+ ' id: setup',
1220
+ ' uses: ./.github/actions/setup-devenv',
1221
+ '',
1222
+ ` # Step ${stepNumber++}`,
1223
+ ...artifactStepLines(options.actionsProvider, '📥 Download candidate artifacts', 'download', [
1224
+ `pattern: publish-*-${githubExpression('github.run_id')}`,
1225
+ `path: ${githubExpression('runner.temp')}/publish-artifacts`,
1226
+ 'merge-multiple: false',
1227
+ ]),
1228
+ '',
1229
+ ` # Step ${stepNumber++}`,
1230
+ ' - name: 🤖 Configure release author',
1231
+ ' run:',
1232
+ ' git config user.name "github-actions[bot]" && git config user.email',
1233
+ ' "41898282+github-actions[bot]@users.noreply.github.com"',
1234
+ );
1235
+ if (isSmoothBricksCodebasePackageName(options.repoName)) {
1236
+ lines.push(
1237
+ '',
1238
+ ` # Step ${stepNumber++}`,
1239
+ ' - name: 🏗️ Build smoo Nx version actions',
1240
+ ' # Nx Release loads @smoothbricks/nx-plugin/version-actions through the',
1241
+ ' # export map in its own node process, and that export has no source',
1242
+ ' # condition, so the next-prerelease bump inside smoo release publish',
1243
+ ' # needs dist/version-actions.cjs on disk. Downstream consumers install',
1244
+ ' # the published package and skip this bootstrap.',
1245
+ ' #',
1246
+ ' # `nx` cannot do it: the project graph loads this very plugin, so',
1247
+ ' # `nx build nx-plugin` deadlocks on the executor it is building.',
1248
+ ' # ttsc needs only the package tsconfig -- same bootstrap the devenv',
1249
+ ' # shell runs (tooling/direnv/enter-shell.ts).',
1250
+ ' working-directory: packages/nx-plugin',
1251
+ ' run: ttsc -p tsconfig.lib.json --emit',
1252
+ );
1253
+ }
1254
+ lines.push(
1255
+ '',
1256
+ ' # --- Repair -------------------------------------------------------------',
1257
+ '',
1258
+ ` # Step ${stepNumber++}`,
1259
+ ' - name: 🧯 Repair pending releases',
1260
+ ' run:',
1261
+ ` smoo release repair-pending --ref "${githubExpression('github.sha')}" --platform-outputs`,
1262
+ ` "${macosPlatformArtifactNames(options)
1263
+ .map((name) => `${githubExpression('runner.temp')}/publish-artifacts/${name}/repairs`)
1264
+ .join(',')}" --dry-run "${githubExpression('inputs.dry_run')}"`,
1265
+ '',
1266
+ ` # Step ${stepNumber++}`,
1267
+ ' - name: ♻️ Restore validated release state',
1268
+ ' env:',
1269
+ ` EXPECTED_RELEASE_SHA: ${githubExpression('needs.linux-release-candidate.outputs.release-sha')}`,
1270
+ ' run: |',
1271
+ ' set -euo pipefail',
1272
+ ` state="${githubExpression('runner.temp')}/publish-artifacts/publish-release-state-${githubExpression('github.run_id')}"`,
1273
+ ' actual="$(cat "$state/release-head")"',
1274
+ ' if [ -z "$EXPECTED_RELEASE_SHA" ] || [ "$actual" != "$EXPECTED_RELEASE_SHA" ]; then',
1275
+ ' echo "Release state does not match the validated candidate SHA." >&2',
1276
+ ' exit 1',
1277
+ ' fi',
1278
+ ' git bundle verify "$state/release-state.bundle"',
1279
+ ' git fetch "$state/release-state.bundle" HEAD --tags',
1280
+ ' if [ "$(git rev-parse FETCH_HEAD)" != "$EXPECTED_RELEASE_SHA" ]; then',
1281
+ ' echo "Release bundle HEAD does not match the validated candidate SHA." >&2',
1282
+ ' exit 1',
1283
+ ' fi',
1284
+ ' git reset --hard "$EXPECTED_RELEASE_SHA"',
1285
+ );
1286
+ lines.push(
1287
+ '',
1288
+ ' # --- Validation ---------------------------------------------------------',
1289
+ '',
1290
+ ` # Step ${stepNumber++}`,
1291
+ ' - name: 📦 Apply verified Linux outputs',
1292
+ ` if: ${mode} != 'none'`,
1293
+ ' run:',
1294
+ ` smoo github-ci apply-outputs --source-sha "${githubExpression(
1295
+ 'needs.linux-release-candidate.outputs.release-sha',
1296
+ )}"`,
1297
+ ` "${githubExpression('runner.temp')}/publish-artifacts/publish-release-outputs-${githubExpression(
1298
+ 'github.run_id',
1299
+ )}"`,
1300
+ );
1301
+ if (hasLinuxPlatformTargets(options)) {
1302
+ lines.push(
1303
+ ` "${githubExpression('runner.temp')}/publish-artifacts/publish-linux-outputs-${githubExpression(
1304
+ 'github.run_id',
1305
+ )}"`,
1306
+ );
1307
+ }
1308
+ lines.push(
1309
+ '',
1310
+ ` # Step ${stepNumber++}`,
1311
+ ' - name: 🍎 Apply verified macOS outputs',
1312
+ ` if: ${mode} != 'none'`,
1313
+ ' run:',
1314
+ ` smoo github-ci apply-outputs --source-sha "${githubExpression('github.sha')}"`,
1315
+ ...macosPlatformArtifactNames(options).map(
1316
+ (name) => ` "${githubExpression('runner.temp')}/publish-artifacts/${name}/current"`,
1317
+ ),
1318
+ '',
1319
+ ' # --- Release ------------------------------------------------------------',
1320
+ '',
1321
+ ` # Step ${stepNumber++}`,
1322
+ ...tagReleaseStepLines('🏷️ Tag release'),
1323
+ '',
1324
+ ` # Step ${stepNumber++}`,
1325
+ ` - name: 📦 Publish release (${githubExpression(mode)})`,
1326
+ ...privateNpmPublisherStepEnv(options),
1327
+ ' # Pack verified outputs; --prebuilt refuses missing artifacts rather than rebuilding.',
1328
+ ...(options.privateNpm
1329
+ ? [' # Private publication uses the declared registry and step-scoped publisher credential.']
1330
+ : [' # Public npm packages use trusted publishing/OIDC after local bootstrap.']),
1331
+ ' run:',
1332
+ ' smoo release publish --prebuilt',
1333
+ ` "${githubExpression('runner.temp')}/publish-artifacts/publish-release-outputs-${githubExpression(
1334
+ 'github.run_id',
1335
+ )}"`,
1336
+ ...(hasLinuxPlatformTargets(options)
1337
+ ? [
1338
+ ` "${githubExpression('runner.temp')}/publish-artifacts/publish-linux-outputs-${githubExpression(
1339
+ 'github.run_id',
1340
+ )}"`,
1341
+ ]
1342
+ : []),
1343
+ ...macosPlatformArtifactNames(options).map(
1344
+ (name) => ` "${githubExpression('runner.temp')}/publish-artifacts/${name}/current"`,
1345
+ ),
1346
+ ` --bump "${githubExpression('inputs.bump')}" --dry-run "${githubExpression('inputs.dry_run')}"`,
1347
+ );
1348
+ if (options.deploy === true) {
1349
+ lines.push(
1350
+ '',
1351
+ ` # Step ${stepNumber++}`,
1352
+ ' - name: 🚀 Deploy production',
1353
+ ' if:',
1354
+ " ${{ needs.linux-release-candidate.outputs.mode != 'none' && inputs.deploy_stage == 'production' &&",
1355
+ " inputs.dry_run != 'true' }}",
1356
+ ...deployStepSecretEnvLines(options),
1357
+ ' run: smoo github-ci nx-deploy --stage production --mode run-many --verify --name "Deploy Production"',
1358
+ );
1359
+ }
1360
+ lines.push(
1361
+ '',
1362
+ ' # --- Cleanup ------------------------------------------------------------',
1363
+ '',
1364
+ ` # Step ${stepNumber}`,
1365
+ ' - name: 🧹 Cleanup and cache Nix/devenv',
1366
+ ' if: always()',
1367
+ ' uses: ./.github/actions/save-nix-devenv',
1368
+ ' with:',
1369
+ ` devenv-cache-hit: ${githubExpression('steps.setup.outputs.devenv-cache-hit')}`,
1370
+ );
1371
+ return lines.join('\n').trimEnd();
1372
+ }
1373
+
1374
+ function hasMacosPlatformTargets(options: PublishWorkflowDefinitionOptions): boolean {
1375
+ return MACOS_PLATFORM_TARGET_GLOBS.some((glob) => options.platformTargetGlobs?.includes(glob) === true);
1376
+ }
1377
+
1378
+ /**
1379
+ * The architecture `macos-latest` runs natively. Only that leg can execute the
1380
+ * binaries it just built, so it owns the unit-test step; keep this beside the
1381
+ * `runs-on` label it describes.
1382
+ */
1383
+ const MACOS_RUNNER_ARCHITECTURE = 'arm64';
1384
+
1385
+ function macosPlatformFamilies(options: PublishWorkflowDefinitionOptions): string[] {
1386
+ return MACOS_PLATFORM_TARGET_GLOBS.filter((glob) => options.platformTargetGlobs?.includes(glob) === true);
1387
+ }
1388
+
1389
+ /**
1390
+ * One matrix leg per architecture. A single runner cannot overlap two platform
1391
+ * builds of one package: cargo holds an exclusive lock on the package's whole
1392
+ * `target/` directory, so extra Nx workers only queue behind it. Separate
1393
+ * runners have separate target directories, so the architectures compile in
1394
+ * parallel for real.
1395
+ */
1396
+ function macosPlatformArchitectures(options: PublishWorkflowDefinitionOptions): string[] {
1397
+ if (options.platformProducer?.kind === 'linux-cross') return [];
1398
+ return hasMacosPlatformTargets(options) ? [...(options.macosPlatformArchitectures ?? [])] : [];
1399
+ }
1400
+
1401
+ function macosTestArchitecture(architectures: readonly string[]): string | undefined {
1402
+ return architectures.includes(MACOS_RUNNER_ARCHITECTURE) ? MACOS_RUNNER_ARCHITECTURE : architectures[0];
1403
+ }
1404
+
1405
+ function renderMacosJobHeaderLines(options: PublishWorkflowDefinitionOptions): string {
1406
+ if (options.platformProducer?.kind === 'linux-cross') return renderRunsOnLine(options.runsOn);
1407
+ const architectures = macosPlatformArchitectures(options);
1408
+ const lines = [
1409
+ options.macosRunsOn === undefined ? ' runs-on: macos-latest' : renderRunsOnLine(options.macosRunsOn),
1410
+ ];
1411
+ if (architectures.length >= 2) {
1412
+ lines.push(
1413
+ ' strategy:',
1414
+ ' # One architecture per runner: a leg that fails still leaves the other',
1415
+ ' # architecture uploaded for inspection.',
1416
+ ' fail-fast: false',
1417
+ ' matrix:',
1418
+ ` arch: [${architectures.join(', ')}]`,
1419
+ );
1420
+ }
1421
+ return lines.join('\n');
1422
+ }
1423
+
1424
+ /** Per-leg target selector, or every macOS family when there is no matrix. */
1425
+ function macosPlatformTargetSelector(options: PublishWorkflowDefinitionOptions): string {
1426
+ const families = macosPlatformFamilies(options);
1427
+ const selectors = families.length > 0 ? families : [...MACOS_PLATFORM_TARGET_GLOBS];
1428
+ if (macosPlatformArchitectures(options).length < 2) {
1429
+ return selectors.join(',');
1430
+ }
1431
+ return selectors.map((glob) => `*-${githubExpression('matrix.arch')}-${glob.slice(2)}`).join(',');
1432
+ }
1433
+
1434
+ /** Artifact names the final job downloads, one per rendered macOS leg. */
1435
+ function macosPlatformArtifactNames(options: PublishWorkflowDefinitionOptions): string[] {
1436
+ const architectures = macosPlatformArchitectures(options);
1437
+ const runId = githubExpression('github.run_id');
1438
+ if (architectures.length < 2) {
1439
+ return [`publish-macos-outputs-${runId}`];
1440
+ }
1441
+ return architectures.map((architecture) => `publish-macos-${architecture}-outputs-${runId}`);
1442
+ }
1443
+
1444
+ function hasLinuxPlatformTargets(options: PublishWorkflowDefinitionOptions): boolean {
1445
+ return LINUX_PLATFORM_TARGET_GLOBS.some((glob) => options.platformTargetGlobs?.includes(glob) === true);
1446
+ }
1447
+
1448
+ /**
1449
+ * Runner for the job that tags and publishes, on GitHub Actions always the
1450
+ * GitHub-hosted one.
1451
+ *
1452
+ * npmjs mints provenance from the job's OIDC token and then rejects the upload
1453
+ * with `422 Unsupported GitHub Actions runner environment "self-hosted", only
1454
+ * github-hosted supported for provenance`: the tarball is signed, the registry
1455
+ * refuses it, and the release is left tagged but unpublished. Publishing from
1456
+ * a GitHub-hosted runner is the fix; dropping `--provenance` is not.
1457
+ *
1458
+ * A `forgejo` actions provider keeps the configured labels: that workflow does
1459
+ * not run on GitHub Actions, so `ubuntu-latest` names no runner there and
1460
+ * there is no GitHub OIDC to mint provenance from in the first place.
1461
+ * Private-registry publishing is unaffected either way — its static publisher
1462
+ * token works from any runner, and its packages ride the same job.
1463
+ *
1464
+ * Build lanes keep `smoo.github.runsOn`: only the publishing job moves. Where
1465
+ * build and publish share one job (no macOS platform fan-out) that whole job
1466
+ * follows the publisher, because that job is the one npmjs sees.
1467
+ */
1468
+ function publishJobRunsOnLine(options: PublishWorkflowDefinitionOptions): string {
1469
+ return renderRunsOnLine(options.actionsProvider === 'forgejo' ? options.runsOn : GITHUB_HOSTED_LINUX_RUNNER);
1470
+ }
1471
+
1472
+ function githubExpression(expression: string): string {
1473
+ return ['$', '{{ ', expression, ' }}'].join('');
1474
+ }
1475
+
1476
+ /**
1477
+ * Whether the separate publishing job can be dropped, so the release runs as
1478
+ * one job that builds every artifact and publishes them.
1479
+ *
1480
+ * The hand-off exists for ONE reason: npmjs mints provenance from the
1481
+ * publishing job's OIDC token and refuses a self-hosted runner for it, so a
1482
+ * release with public packages must publish from the GitHub-hosted runner and
1483
+ * therefore has to receive its self-hosted artifacts through an artifact.
1484
+ * A release that publishes only to the declared private registry has no such
1485
+ * constraint; when its Apple targets are cross-built on the same runner (or it
1486
+ * has none), one job holds everything.
1487
+ */
1488
+ function skipsPublishHandoff(options: PublishWorkflowDefinitionOptions): boolean {
1489
+ if (options.actionsProvider !== 'forgejo' || options.privateNpm === undefined) {
1490
+ return false;
1491
+ }
1492
+ return !hasMacosPlatformTargets(options) || options.platformProducer?.kind === 'linux-cross';
1493
+ }
1494
+
1495
+ /**
1496
+ * Toolchain environment for a foreign-platform producer, rendered onto whichever
1497
+ * job runs its builds. In the flattened single-job shape that is the publish job
1498
+ * itself, so the SDK path and cross flags have to reach it the same way the
1499
+ * dedicated producer job received them.
1500
+ */
1501
+ function platformProducerJobEnv(options: PublishWorkflowDefinitionOptions): string {
1502
+ const producer = options.platformProducer;
1503
+ if (!producer || !skipsPublishHandoff(options)) {
1504
+ return '';
1505
+ }
1506
+ return Object.entries(producer.env ?? {})
1507
+ .map(([name, value]) => `\n ${name}: ${JSON.stringify(value)}`)
1508
+ .join('');
1509
+ }
1510
+
1511
+ function privateNpmInstallJobEnv(options: PublishWorkflowDefinitionOptions): string {
1512
+ const tokenEnv = options.privateNpm?.readTokenEnv;
1513
+ if (!tokenEnv) {
1514
+ return '';
1515
+ }
1516
+ return ['', ` ${tokenEnv}: ${githubExpression(`secrets.${tokenEnv}`)}`].join('\n');
1517
+ }
1518
+
1519
+ /** Both repair and publish can write packages; neither exposes the credential to setup/build. */
1520
+ function privateNpmPublisherStepEnv(options: PublishWorkflowDefinitionOptions): string[] {
1521
+ const name = options.privateNpm?.publishTokenEnv;
1522
+ return name ? [' env:', ` ${name}: ${githubExpression(`secrets.${name}`)}`] : [];
1523
+ }