@astryxdesign/cli 0.7.5-canary.21631be → 0.7.5-canary.2d78c4b

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 (29) hide show
  1. package/README.md +1 -1
  2. package/api/upgrade/run/failure-receipt.test.mjs +155 -0
  3. package/api/upgrade/run/run.mjs +170 -8
  4. package/api/upgrade/upgrade.doc.mjs +4 -4
  5. package/api/upgrade/upgrade.mjs +19 -4
  6. package/api/upgrade/upgrade.type.d.mts +12 -1
  7. package/api/upgrade/upgrade.type.mjs +16 -3
  8. package/assets/codemods/__tests__/runner.symlinks.test.mjs +205 -0
  9. package/assets/codemods/integration-runner.mjs +1 -1
  10. package/assets/codemods/run-codemod.mjs +17 -3
  11. package/assets/codemods/runner.mjs +81 -8
  12. package/assets/codemods/transform-prop.mjs +99 -49
  13. package/assets/codemods/transform-prop.test.mjs +36 -1
  14. package/assets/codemods/transforms/v0.7.0/__tests__/migrate-deprecated-theme-surface.test.mjs +207 -6
  15. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface-v0.6-data.mjs +6 -1
  16. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs +200 -32
  17. package/assets/docs/tree/styling-advanced.doc.mjs +1 -1
  18. package/assets/templates/pages/library/page.tsx +1 -2
  19. package/clients/cli/commands/upgrade.doc.mjs +17 -0
  20. package/clients/cli/commands/upgrade.file-protection.test.mjs +29 -0
  21. package/clients/cli/commands/upgrade.flag-help.test.mjs +37 -0
  22. package/clients/cli/commands/upgrade.integration-policy.test.mjs +103 -0
  23. package/clients/cli/commands/upgrade.mjs +9 -2
  24. package/foundation/response/base.d.ts +7 -0
  25. package/foundation/response/error-codes.doc.mjs +3 -2
  26. package/foundation/response/error-codes.mjs +1 -1
  27. package/foundation/response/json.d.mts +10 -3
  28. package/foundation/response/json.mjs +16 -4
  29. package/package.json +9 -9
package/README.md CHANGED
@@ -209,7 +209,7 @@ if (isError(result)) {
209
209
  | `ERR_UNKNOWN_AGENT` | An unrecognized `--agent` value was passed to init. |
210
210
  | `ERR_UNKNOWN_FEATURE` | An unrecognized `--features` value was passed to init. |
211
211
  | `ERR_UNKNOWN_CODEMOD` | A `--codemod` value did not match any registered codemod (upgrade). |
212
- | `ERR_CODEMOD_FAILED` | One or more codemods failed during an upgrade run. |
212
+ | `ERR_CODEMOD_FAILED` | A codemod or post-codemod hook failed during an upgrade run; the error carries a `receipt` that lists the files the run already changed. |
213
213
  | `ERR_CODEMOD_PROTECTED` | A required codemod change remains blocked by a protected consumer file. |
214
214
  | `ERR_CODEMOD_PROTECTION_SOURCE` | A working-tree protection declaration could not be read or parsed. |
215
215
  | `ERR_NOT_FOUND` | A generic discover/lookup query matched nothing in any package. |
@@ -0,0 +1,155 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file A failed upgrade keeps its error contract and adds the receipt: the
5
+ * thrown AstryxError still carries ERR_CODEMOD_FAILED, and its `receipt`
6
+ * names the files the run already changed, from the folder the command ran
7
+ * in. Core codemods come from a stubbed registry so the contract is tested
8
+ * apart from any one shipped codemod.
9
+ */
10
+
11
+ import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
12
+ import * as fs from 'node:fs';
13
+ import * as os from 'node:os';
14
+ import * as path from 'node:path';
15
+
16
+ vi.mock('../../../assets/codemods/registry.mjs', async importOriginal => {
17
+ const actual = /** @type {Record<string, unknown>} */ (
18
+ await importOriginal()
19
+ );
20
+ return {
21
+ ...actual,
22
+ getTransformsBetween: async () => [
23
+ {
24
+ version: '0.2.0',
25
+ transforms: [
26
+ {
27
+ name: 'rename-foo',
28
+ meta: {title: 'Rename foo', fileExtensions: ['.ts']},
29
+ /** @param {{source: string}} file */
30
+ transform: file => file.source.replace(/foo/g, 'bar'),
31
+ },
32
+ {
33
+ name: 'fail-on-boom',
34
+ meta: {title: 'Fail on boom', fileExtensions: ['.ts']},
35
+ /** @param {{source: string}} file */
36
+ transform(file) {
37
+ if (file.source.includes('boom')) throw new Error('codemod boom');
38
+ return undefined;
39
+ },
40
+ },
41
+ ],
42
+ },
43
+ ],
44
+ };
45
+ });
46
+
47
+ const {upgrade} = await import('../upgrade.mjs');
48
+ const {AstryxError} = await import('../../error.mjs');
49
+ const {toErrorEnvelope} = await import('../../../foundation/response/json.mjs');
50
+ const {isError} = await import('../../json/parse.mjs');
51
+
52
+ let dir;
53
+
54
+ /** @param {string} rel @param {string} body */
55
+ function write(rel, body) {
56
+ fs.mkdirSync(path.dirname(path.join(dir, rel)), {recursive: true});
57
+ fs.writeFileSync(path.join(dir, rel), body);
58
+ }
59
+
60
+ beforeEach(() => {
61
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'upg-failure-receipt-'));
62
+ write(
63
+ 'package.json',
64
+ JSON.stringify({name: 'x', dependencies: {'@astryxdesign/core': '0.2.0'}}),
65
+ );
66
+ write(
67
+ 'node_modules/@astryxdesign/core/package.json',
68
+ JSON.stringify({name: '@astryxdesign/core', version: '0.2.0'}),
69
+ );
70
+ write('src/index.ts', 'const foo = 1;\n');
71
+ write('src/broken.ts', 'const boom = 1;\n');
72
+ });
73
+
74
+ afterEach(() => fs.rmSync(dir, {recursive: true, force: true}));
75
+
76
+ /** @param {Promise<unknown>} promise */
77
+ async function rejection(promise) {
78
+ try {
79
+ await promise;
80
+ } catch (err) {
81
+ return /** @type {any} */ (err);
82
+ }
83
+ throw new Error('expected upgrade() to reject');
84
+ }
85
+
86
+ describe('a failed upgrade', () => {
87
+ it('still rejects with ERR_CODEMOD_FAILED, and the error carries the receipt', async () => {
88
+ const err = await rejection(
89
+ upgrade({from: '0.1.0', apply: true, path: 'src'}, {cwd: dir}),
90
+ );
91
+
92
+ expect(err).toBeInstanceOf(AstryxError);
93
+ expect(err.code).toBe('ERR_CODEMOD_FAILED');
94
+ expect(err.message).toBe('Upgrade completed with 1 codemod error.');
95
+ expect(err.receipt).toMatchObject({
96
+ complete: false,
97
+ errorCode: 'ERR_CODEMOD_FAILED',
98
+ filesChanged: 1,
99
+ modifiedFiles: ['src/index.ts'],
100
+ errors: [
101
+ {
102
+ file: 'src/broken.ts',
103
+ codemod: 'core:fail-on-boom',
104
+ error: 'codemod boom',
105
+ },
106
+ ],
107
+ });
108
+ expect(fs.readFileSync(path.join(dir, 'src/index.ts'), 'utf8')).toBe(
109
+ 'const bar = 1;\n',
110
+ );
111
+ });
112
+
113
+ it('names receipt files from the folder the command ran in', async () => {
114
+ const err = await rejection(
115
+ upgrade(
116
+ {from: '0.1.0', apply: true, path: '.'},
117
+ {cwd: path.join(dir, 'src')},
118
+ ),
119
+ );
120
+
121
+ expect(err.code).toBe('ERR_CODEMOD_FAILED');
122
+ expect(err.receipt.modifiedFiles).toEqual(['index.ts']);
123
+ expect(err.receipt.errors).toEqual([
124
+ expect.objectContaining({file: 'broken.ts'}),
125
+ ]);
126
+ });
127
+
128
+ it('becomes an error envelope that keeps its code and adds the receipt', async () => {
129
+ const err = await rejection(
130
+ upgrade({from: '0.1.0', path: 'src'}, {cwd: dir}),
131
+ );
132
+
133
+ const envelope = toErrorEnvelope(err);
134
+ expect(isError(envelope)).toBe(true);
135
+ expect(envelope).toMatchObject({
136
+ apiVersion: 1,
137
+ code: 'ERR_CODEMOD_FAILED',
138
+ error: 'Upgrade completed with 1 codemod error.',
139
+ receipt: {modifiedFiles: ['src/index.ts'], complete: false},
140
+ });
141
+ expect(fs.readFileSync(path.join(dir, 'src/index.ts'), 'utf8')).toBe(
142
+ 'const foo = 1;\n',
143
+ );
144
+ });
145
+ });
146
+
147
+ describe('the error envelope', () => {
148
+ it('has no receipt for an error that carries none', () => {
149
+ expect(
150
+ toErrorEnvelope(
151
+ new AstryxError('nope', undefined, 'ERR_INVALID_ARGUMENT'),
152
+ ),
153
+ ).toEqual({apiVersion: 1, error: 'nope', code: 'ERR_INVALID_ARGUMENT'});
154
+ });
155
+ });
@@ -109,6 +109,80 @@ function loadFileProtection(cwd) {
109
109
  }
110
110
  }
111
111
 
112
+ /**
113
+ * The receipt of a run that stopped after codemods ran. Whatever the codemods
114
+ * already wrote stays on disk, so the error the run throws carries this
115
+ * receipt (`failWithReceipt`): a caller that reads only the error would
116
+ * report nothing changed while the files it lists remain modified
117
+ * (spec:AST-040 FR7).
118
+ *
119
+ * @param {{from: string, to: string, codemods: number, integrations: string[], sourcePathFound: boolean, cwd: string, changedFiles: string[], transformsApplied: number, protectedRows: Array<{file: string, codemod: string, reason: string, declaration: string, generated: boolean, command?: string}>, errors: Array<{file: string, codemod: string, error: string}>, errorCode: string, cliBehindCore?: import('../upgrade.type.mjs').CliBehindCore | null, registryCompositions?: import('../upgrade.type.mjs').RegistryCompositionSummary}} facts
120
+ * @returns {import('../upgrade.type.mjs').UpgradeRunResponse['data']}
121
+ */
122
+ function stoppedReceipt({
123
+ from,
124
+ to,
125
+ codemods,
126
+ integrations,
127
+ sourcePathFound,
128
+ cwd,
129
+ changedFiles,
130
+ transformsApplied,
131
+ protectedRows,
132
+ errors,
133
+ errorCode,
134
+ cliBehindCore,
135
+ registryCompositions,
136
+ }) {
137
+ const modifiedFiles = uniqueFiles(changedFiles).map(file =>
138
+ path.relative(cwd, file).split(path.sep).join('/'),
139
+ );
140
+ return /** @type {import('../upgrade.type.mjs').UpgradeRunResponse['data']} */ ({
141
+ from,
142
+ to,
143
+ codemods,
144
+ integrations,
145
+ agentDocsRefreshed: false,
146
+ agentDocs: {
147
+ status: 'current',
148
+ installedVersion: to,
149
+ fromVersions: [],
150
+ files: [],
151
+ refreshed: false,
152
+ action: 'none',
153
+ },
154
+ sourcePathFound,
155
+ filesChanged: modifiedFiles.length,
156
+ transformsApplied,
157
+ modifiedFiles,
158
+ protectedFiles: summarizeProtectedFiles(protectedRows),
159
+ declinedCandidates: [],
160
+ complete: false,
161
+ errorCode,
162
+ errors,
163
+ ...(registryCompositions ? {registryCompositions} : {}),
164
+ ...(cliBehindCore ? {cliBehindCore} : {}),
165
+ });
166
+ }
167
+
168
+ /**
169
+ * The error a run throws once codemods have run: the same message and stable
170
+ * code as always, plus the run's receipt on `receipt`, so the JSON error
171
+ * envelope and a programmatic caller can still see what was written.
172
+ * @param {string} message
173
+ * @param {string} code
174
+ * @param {import('../upgrade.type.mjs').UpgradeRunResponse['data']} receipt
175
+ * @returns {AstryxError & {receipt: import('../upgrade.type.mjs').UpgradeRunResponse['data']}}
176
+ */
177
+ function failWithReceipt(message, code, receipt) {
178
+ const err =
179
+ /** @type {AstryxError & {receipt: import('../upgrade.type.mjs').UpgradeRunResponse['data']}} */ (
180
+ new AstryxError(message, undefined, code)
181
+ );
182
+ err.receipt = receipt;
183
+ return err;
184
+ }
185
+
112
186
  /**
113
187
  * Run the upgrade pipeline for a validated, non-list invocation. Returns the
114
188
  * terminal run receipt, or one of the status short-circuits; throws AstryxError
@@ -368,6 +442,32 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
368
442
  // Genuine config error: abort.
369
443
  logger.error(configErr.message);
370
444
  logger.log('Aborted\n');
445
+ if ((coreResult?.writtenFiles.length ?? 0) > 0) {
446
+ // Core codemods already wrote: the error carries what they changed.
447
+ if (cliBehindCore) logCliBehindCore(cliBehindCore, targetVersion);
448
+ const stopped = stoppedReceipt({
449
+ from: currentVersion,
450
+ to: targetVersion,
451
+ codemods: totalTransforms,
452
+ integrations: [],
453
+ sourcePathFound,
454
+ cwd,
455
+ changedFiles: coreResult?.changedFiles ?? [],
456
+ transformsApplied: coreResult?.totalTransformsApplied ?? 0,
457
+ protectedRows: [],
458
+ errors: [
459
+ ...(coreResult?.errors ?? []),
460
+ {file: '.', codemod: 'config', error: configErr.message},
461
+ ],
462
+ errorCode: ERROR_CODES.ERR_INVALID_ARGUMENT,
463
+ cliBehindCore,
464
+ });
465
+ throw failWithReceipt(
466
+ configErr.message,
467
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
468
+ stopped,
469
+ );
470
+ }
371
471
  throw new AstryxError(
372
472
  configErr.message,
373
473
  undefined,
@@ -561,7 +661,30 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
561
661
  logger.error(msg);
562
662
  if (initialProtected.length === 0) {
563
663
  logger.log('Upgrade failed\n');
564
- throw new AstryxError(msg, undefined, ERROR_CODES.ERR_CODEMOD_FAILED);
664
+ throw failWithReceipt(
665
+ msg,
666
+ ERROR_CODES.ERR_CODEMOD_FAILED,
667
+ stoppedReceipt({
668
+ from: currentVersion,
669
+ to: targetVersion,
670
+ codemods: totalTransforms,
671
+ integrations: receipt.integrations,
672
+ sourcePathFound,
673
+ cwd,
674
+ changedFiles: mergedChangedFiles,
675
+ transformsApplied: mergedTransformsApplied,
676
+ protectedRows: [],
677
+ errors: [
678
+ ...mergedErrors,
679
+ {file: '.', codemod: 'post-codemod-hook', error: msg},
680
+ ],
681
+ errorCode: ERROR_CODES.ERR_CODEMOD_FAILED,
682
+ cliBehindCore,
683
+ ...(registryResult
684
+ ? {registryCompositions: registryResult.summary}
685
+ : {}),
686
+ }),
687
+ );
565
688
  }
566
689
  hookFailure = msg;
567
690
  finalErrors = [
@@ -587,7 +710,35 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
587
710
  // to distinguish resolved outputs from changes that remain blocked.
588
711
  let remainingProtected = initialProtected;
589
712
  if (apply && shouldRunHooks && !hookFailure) {
590
- const refreshedProtection = loadFileProtection(cwd);
713
+ let refreshedProtection;
714
+ try {
715
+ refreshedProtection = loadFileProtection(cwd);
716
+ } catch (err) {
717
+ if (!(err instanceof AstryxError)) throw err;
718
+ // The hooks ran after the codemods wrote; the error carries their receipt.
719
+ if (cliBehindCore) logCliBehindCore(cliBehindCore, targetVersion);
720
+ const stopped = stoppedReceipt({
721
+ from: currentVersion,
722
+ to: targetVersion,
723
+ codemods: totalTransforms,
724
+ integrations: receipt.integrations,
725
+ sourcePathFound,
726
+ cwd,
727
+ changedFiles: [...mergedChangedFiles, ...hookModifiedFiles],
728
+ transformsApplied: mergedTransformsApplied,
729
+ protectedRows: initialProtected,
730
+ errors: [
731
+ ...mergedErrors,
732
+ {file: '.', codemod: 'file-protection', error: err.message},
733
+ ],
734
+ errorCode: err.code,
735
+ cliBehindCore,
736
+ ...(registryResult
737
+ ? {registryCompositions: registryResult.summary}
738
+ : {}),
739
+ });
740
+ throw failWithReceipt(err.message, err.code, stopped);
741
+ }
591
742
  const coreCheck = await runCoreCodemods(versionManifests, {
592
743
  apply: false,
593
744
  path: path_,
@@ -654,9 +805,12 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
654
805
  ]).map(file => path.relative(cwd, file).split(path.sep).join('/'));
655
806
  receipt.protectedFiles = protectedFiles;
656
807
  receipt.declinedCandidates = [];
657
- receipt.complete = protectedFiles.length === 0;
658
- if (!receipt.complete) {
808
+ receipt.complete = protectedFiles.length === 0 && finalErrors.length === 0;
809
+ if (protectedFiles.length > 0) {
659
810
  receipt.errorCode = 'ERR_CODEMOD_PROTECTED';
811
+ } else if (finalErrors.length > 0) {
812
+ // Only on the receipt the thrown error carries (below).
813
+ receipt.errorCode = 'ERR_CODEMOD_FAILED';
660
814
  }
661
815
  receipt.errors = finalErrors;
662
816
  if (registryResult) receipt.registryCompositions = registryResult.summary;
@@ -674,14 +828,22 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
674
828
  }
675
829
  }
676
830
 
677
- if (receipt.errors?.length > 0 && protectedFiles.length === 0) {
678
- const msg = `Upgrade completed with ${receipt.errors.length} codemod error${receipt.errors.length === 1 ? '' : 's'}.`;
831
+ if (finalErrors.length > 0 && protectedFiles.length === 0) {
832
+ const msg = `Upgrade completed with ${finalErrors.length} codemod error${finalErrors.length === 1 ? '' : 's'}.`;
679
833
  logger.log('Upgrade failed\n');
680
- throw new AstryxError(msg, undefined, ERROR_CODES.ERR_CODEMOD_FAILED);
834
+ // The error carries the receipt: every file the codemods wrote before the
835
+ // failure stays changed, and the caller keeps or reverts them knowingly.
836
+ throw failWithReceipt(
837
+ msg,
838
+ ERROR_CODES.ERR_CODEMOD_FAILED,
839
+ /** @type {import('../upgrade.type.mjs').UpgradeRunResponse['data']} */ (
840
+ /** @type {unknown} */ (receipt)
841
+ ),
842
+ );
681
843
  }
682
844
 
683
845
  // Only refresh managed docs after all required codemod changes are complete.
684
- if (protectedFiles.length === 0) {
846
+ if (receipt.complete) {
685
847
  const agentDocsPlan = await prepareAgentDocsRefresh({
686
848
  cwd,
687
849
  origin,
@@ -128,13 +128,13 @@ export const doc = {
128
128
  {
129
129
  type: 'upgrade.run',
130
130
  description:
131
- 'The terminal run receipt: from, to, codemods (count), integrations, agentDocs, agentDocsRefreshed, registryCompositions (when receipts are found), sourcePathFound (false when the resolved `path` does not exist, so nothing was scanned), filesChanged, transformsApplied, modifiedFiles, protectedFiles, declinedCandidates, errors, and complete. When a protected file still requires a change, complete is false and errorCode is ERR_CODEMOD_PROTECTED; the CLI exits nonzero while preserving the structured receipt. When the installed Core is newer than the CLI, it also carries cliBehindCore ({cliVersion, command}): codemods for the releases after cliVersion did not run, and command runs the same upgrade with the matching CLI.',
131
+ 'The terminal run receipt: from, to, codemods (count), integrations, agentDocs, agentDocsRefreshed, registryCompositions (when receipts are found), sourcePathFound (false when the resolved `path` does not exist, so nothing was scanned), filesChanged, transformsApplied, modifiedFiles, protectedFiles, declinedCandidates, errors, and complete. When a protected file still requires a change, complete is false and errorCode is ERR_CODEMOD_PROTECTED; the CLI exits nonzero while preserving the structured receipt. A run that fails after its codemods ran throws instead (see throws), and the thrown AstryxError carries the same receipt on `receipt`, with complete false and errorCode set to its code. When the installed Core is newer than the CLI, it also carries cliBehindCore ({cliVersion, command}): codemods for the releases after cliVersion did not run, and command runs the same upgrade with the matching CLI.',
132
132
  },
133
133
  ],
134
134
  throws: [
135
135
  {
136
136
  code: 'ERR_INVALID_ARGUMENT',
137
- when: '`from` is missing (and neither `list` nor `registry` is set); `list` and `registry` are both set; `list` is combined with `from`, `force`, `apply`, `path` (non-default), `codemod`, `skipCodemod`, `integration` or `installDeps`; `registry` is combined with `from`, `force`, `codemod`, `skipCodemod`, `integration` or `installDeps`; an `integration` specifier is invalid or not installed; or astryx.config fails to load or validate and no pending config codemod repairs it',
137
+ when: '`from` is missing (and neither `list` nor `registry` is set); `list` and `registry` are both set; `list` is combined with `from`, `force`, `apply`, `path` (non-default), `codemod`, `skipCodemod`, `integration` or `installDeps`; `registry` is combined with `from`, `force`, `codemod`, `skipCodemod`, `integration` or `installDeps`; an `integration` specifier is invalid or not installed; or astryx.config fails to load or validate and no pending config codemod repairs it (when core codemods already wrote files, the error carries their receipt on `receipt`)',
138
138
  },
139
139
  {code: 'ERR_INVALID_VERSION', when: '`from` is not a valid semver string'},
140
140
  {
@@ -155,11 +155,11 @@ export const doc = {
155
155
  },
156
156
  {
157
157
  code: 'ERR_CODEMOD_FAILED',
158
- when: 'one or more codemods failed, or a post-codemod hook failed, and no protected file still needs a change (otherwise an upgrade.run receipt with complete: false is returned)',
158
+ when: "one or more codemods failed, or a post-codemod hook failed, and no protected file still needs a change (otherwise an upgrade.run receipt with complete: false is returned). The error carries the run's receipt on `receipt`: the files already changed, each failure in errors, complete: false",
159
159
  },
160
160
  {
161
161
  code: 'ERR_CODEMOD_PROTECTION_SOURCE',
162
- when: 'a working-tree protection declaration cannot be read or parsed before writes begin',
162
+ when: 'a working-tree protection declaration cannot be read or parsed before writes begin, or after post-codemod hooks rewrite it (the error then carries the receipt on `receipt`)',
163
163
  },
164
164
  ],
165
165
  examples: [
@@ -120,8 +120,23 @@ export async function upgrade(options = {}, {cwd = process.cwd()} = {}) {
120
120
  // A run from a subfolder upgrades the project the folder belongs to, and
121
121
  // names files relative to the folder it ran in.
122
122
  const scoped = scopeToProject(options, cwd);
123
- return relativeToOrigin(
124
- await run(scoped.options, {cwd: scoped.cwd, origin: scoped.origin}),
125
- scoped,
126
- );
123
+ let result;
124
+ try {
125
+ result = await run(scoped.options, {
126
+ cwd: scoped.cwd,
127
+ origin: scoped.origin,
128
+ });
129
+ } catch (err) {
130
+ // A failure after codemods wrote carries their receipt; name its files
131
+ // from the folder the command ran in, as a returned receipt does.
132
+ const receipt = /** @type {any} */ (err)?.receipt;
133
+ if (err instanceof AstryxError && receipt) {
134
+ /** @type {any} */ (err).receipt = relativeToOrigin(
135
+ {type: 'upgrade.run', data: receipt},
136
+ scoped,
137
+ ).data;
138
+ }
139
+ throw err;
140
+ }
141
+ return relativeToOrigin(result, scoped);
127
142
  }
@@ -193,7 +193,7 @@ export type UpgradeRunResponse = {
193
193
  sourcePathFound: boolean;
194
194
  registryCompositions?: RegistryCompositionSummary | undefined;
195
195
  complete?: boolean | undefined;
196
- errorCode?: "ERR_CODEMOD_PROTECTED" | undefined;
196
+ errorCode?: string | undefined;
197
197
  filesChanged?: number | undefined;
198
198
  modifiedFiles?: string[] | undefined;
199
199
  protectedFiles?: ProtectedCodemodFile[] | undefined;
@@ -211,6 +211,17 @@ export type UpgradeRunResponse = {
211
211
  cliBehindCore?: CliBehindCore | undefined;
212
212
  };
213
213
  };
214
+ /**
215
+ * What a failed upgrade had already done. When a run fails after its codemods
216
+ * ran (a codemod or post-codemod hook failed, or an error stopped it after
217
+ * codemods wrote files), the failure keeps its usual shape: the --json error
218
+ * envelope `{apiVersion, error, code}` and a rejected `upgrade()` with that
219
+ * `code`. The envelope adds `receipt`, and the thrown AstryxError a `receipt`
220
+ * property: the same `upgrade.run` data a completed run returns, with
221
+ * `complete: false` and `errorCode` equal to the error's `code`. Files in
222
+ * `modifiedFiles` stay changed.
223
+ */
224
+ export type UpgradeFailureReceipt = UpgradeRunResponse["data"];
214
225
  /**
215
226
  * astryx --json upgrade — short-circuit status results.
216
227
  *
@@ -131,17 +131,30 @@
131
131
  * @property {AgentDocsSummary} data.agentDocs
132
132
  * @property {boolean} data.sourcePathFound Whether the resolved source directory (`path`, default `./src`) exists. False means no source file was read, so a zero `filesChanged` says nothing about the project being migrated.
133
133
  * @property {RegistryCompositionSummary} [data.registryCompositions]
134
- * @property {boolean} [data.complete] False when protected required changes remain.
135
- * @property {'ERR_CODEMOD_PROTECTED'} [data.errorCode] Stable incomplete-result code when complete is false.
134
+ * @property {boolean} [data.complete] False when protected required changes remain. Also false on the receipt a failed run's error carries (`UpgradeFailureReceipt`).
135
+ * @property {string} [data.errorCode] Stable incomplete-result code when complete is false: `ERR_CODEMOD_PROTECTED` on a returned receipt; on the receipt a failed run's error carries, the error's own code.
136
136
  * @property {number} [data.filesChanged] Distinct files changed across core + integration codemods (apply mode). One file that four codemods each changed counts once.
137
137
  * @property {string[]} [data.modifiedFiles] Files changed or previewed, relative to the folder the command ran in.
138
138
  * @property {ProtectedCodemodFile[]} [data.protectedFiles] Protected files that still require a codemod change after regeneration.
139
139
  * @property {Array<{file: string, location?: string, reason: string}>} [data.declinedCandidates] Candidates left unchanged because proof was insufficient. Each `file` is relative to the folder the command ran in.
140
140
  * @property {number} [data.transformsApplied] Total codemod changes. A code or config codemod counts once for each file it changed, so one file changed by four of them counts four times; a project codemod counts once, however many files it writes.
141
- * @property {Array<{file: string, codemod: string, error: string}>} [data.errors] Per-codemod errors, when any codemod failed. Each `file` is relative to the folder the command ran in.
141
+ * @property {Array<{file: string, codemod: string, error: string}>} [data.errors] Per-codemod errors, when any codemod failed. On the receipt a failed run's error carries, also a post-codemod hook failure (`codemod: 'post-codemod-hook'`) or the error that stopped the run after codemods wrote files. Each `file` is relative to the folder the command ran in.
142
142
  * @property {CliBehindCore} [data.cliBehindCore] Present only when the installed Core is newer than this CLI: codemods for the releases after `cliBehindCore.cliVersion` did not run.
143
143
  */
144
144
 
145
+ /**
146
+ * What a failed upgrade had already done. When a run fails after its codemods
147
+ * ran (a codemod or post-codemod hook failed, or an error stopped it after
148
+ * codemods wrote files), the failure keeps its usual shape: the --json error
149
+ * envelope `{apiVersion, error, code}` and a rejected `upgrade()` with that
150
+ * `code`. The envelope adds `receipt`, and the thrown AstryxError a `receipt`
151
+ * property: the same `upgrade.run` data a completed run returns, with
152
+ * `complete: false` and `errorCode` equal to the error's `code`. Files in
153
+ * `modifiedFiles` stay changed.
154
+ *
155
+ * @typedef {UpgradeRunResponse['data']} UpgradeFailureReceipt
156
+ */
157
+
145
158
  /**
146
159
  * astryx --json upgrade — short-circuit status results.
147
160
  *