@astryxdesign/cli 0.7.5-canary.fccd771 → 0.7.5-canary.fd0aba8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/CHANGELOG.md +3 -3
  2. package/README.md +2 -2
  3. package/api/hook/detail/detail.test.mjs +11 -0
  4. package/api/integration/pack-check.lifecycle-output.test.mjs +24 -1
  5. package/api/integration/pack-check.mjs +10 -4
  6. package/api/integration/pack-check.test.mjs +5 -1
  7. package/api/swizzle/copy/copy.mjs +1 -1
  8. package/api/template/tokenizer-showcase.test.mjs +47 -0
  9. package/api/theme/build/build.adaptation-enrollment.test.mjs +4 -0
  10. package/api/theme/build/build.icon-entry-variants.test.mjs +134 -0
  11. package/api/theme/build/build.icon-function-entries.test.mjs +499 -0
  12. package/api/theme/build/build.icon-variants.test.mjs +105 -0
  13. package/api/theme/build/build.mjs +371 -113
  14. package/api/theme/build/build.project-core.test.mjs +63 -8
  15. package/api/theme/build/build.test.mjs +77 -0
  16. package/api/theme/build/icon-imports.d.mts +12 -2
  17. package/api/theme/build/icon-imports.mjs +36 -11
  18. package/api/upgrade/_adapter.d.mts +47 -2
  19. package/api/upgrade/_adapter.mjs +58 -2
  20. package/api/upgrade/run/failure-receipt.test.mjs +212 -0
  21. package/api/upgrade/run/outcomes.test.mjs +646 -0
  22. package/api/upgrade/run/run.d.mts +36 -0
  23. package/api/upgrade/run/run.mjs +670 -44
  24. package/api/upgrade/upgrade.doc.mjs +4 -4
  25. package/api/upgrade/upgrade.mjs +19 -4
  26. package/api/upgrade/upgrade.type.d.mts +36 -1
  27. package/api/upgrade/upgrade.type.mjs +29 -4
  28. package/assets/codemods/__tests__/runner.symlinks.test.mjs +205 -0
  29. package/assets/codemods/__tests__/runner.unparseable.test.mjs +457 -0
  30. package/assets/codemods/integration-runner.mjs +8 -2
  31. package/assets/codemods/integration-runner.protection.test.mjs +53 -0
  32. package/assets/codemods/outcome.mjs +79 -0
  33. package/assets/codemods/outcome.test.mjs +40 -0
  34. package/assets/codemods/parse.mjs +94 -0
  35. package/assets/codemods/run-codemod.mjs +109 -5
  36. package/assets/codemods/runner.mjs +119 -13
  37. package/assets/codemods/transform-prop.mjs +99 -49
  38. package/assets/codemods/transform-prop.test.mjs +36 -1
  39. package/assets/codemods/transforms/next/__tests__/migrate-codeblock-tokenizer-to-language.test.mjs +130 -0
  40. package/assets/codemods/transforms/next/index.mjs +11 -1
  41. package/assets/codemods/transforms/next/migrate-codeblock-tokenizer-to-language.mjs +315 -0
  42. package/assets/codemods/transforms/v0.1.2/rename-text-color-active-to-accent.mjs +1 -1
  43. package/assets/codemods/transforms/v0.1.3/__tests__/migrate-layout-components-to-experimental.test.mjs +216 -2
  44. package/assets/codemods/transforms/v0.1.3/migrate-layout-components-to-experimental.mjs +88 -6
  45. package/assets/codemods/transforms/v0.1.5/rename-switch-label-spacing-default-to-hug.mjs +1 -1
  46. package/assets/codemods/transforms/v0.1.7/migrate-table-tableprops-to-direct-props.mjs +1 -1
  47. package/assets/codemods/transforms/v0.1.8/rename-avatar-size-scale.mjs +1 -1
  48. package/assets/codemods/transforms/v0.2.0/remove-tablist-orientation.mjs +1 -1
  49. package/assets/codemods/transforms/v0.2.1/migrate-dialog-position-to-logical.mjs +1 -1
  50. package/assets/codemods/transforms/v0.6.0/migrate-astryx-theme-selectors-to-data-attrs.mjs +4 -3
  51. package/assets/codemods/transforms/v0.7.0/__tests__/migrate-deprecated-theme-surface.test.mjs +207 -6
  52. package/assets/codemods/transforms/v0.7.0/__tests__/validate-data-token-ownership.test.mjs +143 -70
  53. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface-v0.6-data.mjs +6 -1
  54. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs +244 -42
  55. package/assets/codemods/transforms/v0.7.0/validate-data-token-ownership.mjs +23 -78
  56. package/assets/docs/README.md +13 -13
  57. package/assets/docs/author-a-theme.doc.mjs +5 -1
  58. package/assets/docs/getting-started.doc.mjs +5 -5
  59. package/assets/docs/icons.doc.mjs +82 -1
  60. package/assets/docs/motion.doc.mjs +1 -1
  61. package/assets/docs/theme.doc.dense.mjs +8 -0
  62. package/assets/docs/theme.doc.mjs +16 -0
  63. package/assets/docs/theme.doc.zh.mjs +11 -0
  64. package/assets/docs/tree/i18n-library-integration.doc.mjs +1 -1
  65. package/assets/docs/tree/styling-advanced.doc.mjs +1 -1
  66. package/assets/docs/tree/template-styles.doc.mjs +1 -1
  67. package/assets/docs/tree/tokens-color.doc.mjs +145 -1
  68. package/assets/docs/tree/tokens-ease.doc.mjs +4 -0
  69. package/assets/docs/tree/tokens.doc.mjs +1 -1
  70. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.doc.mjs +6 -4
  71. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.tsx +61 -55
  72. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.doc.mjs +6 -4
  73. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.tsx +68 -37
  74. package/assets/templates/blocks/components/CodeBlock/CodeBlockBashCommand.doc.mjs +1 -1
  75. package/assets/templates/blocks/components/CodeBlock/CodeBlockBashCommand.tsx +10 -2
  76. package/assets/templates/blocks/components/Thumbnail/ThumbnailDisabled.doc.mjs +1 -1
  77. package/assets/templates/blocks/components/Tokenizer/TokenizerShowcase.tsx +13 -6
  78. package/assets/templates/pages/dashboard-alert-rail/page.tsx +3 -3
  79. package/assets/templates/pages/library/page.tsx +1 -2
  80. package/assets/templates/pages/table-comparison/page.tsx +12 -3
  81. package/assets/templates/themes/butter/butterPaletteRefs.generated.ts +3 -2
  82. package/assets/templates/themes/butter/butterTheme.ts +47 -44
  83. package/assets/templates/themes/chocolate/chocolateTheme.ts +15 -2
  84. package/assets/templates/themes/gothic/gothicTheme.ts +21 -16
  85. package/assets/templates/themes/matcha/matchaPaletteRefs.generated.ts +1 -1
  86. package/assets/templates/themes/matcha/matchaTheme.ts +15 -2
  87. package/assets/templates/themes/neutral/neutralPaletteRefs.generated.ts +4 -4
  88. package/assets/templates/themes/neutral/neutralTheme.ts +24 -119
  89. package/assets/templates/themes/stone/stoneTheme.ts +46 -21
  90. package/assets/templates/themes/y2k/y2kTheme.ts +20 -16
  91. package/assets/theme.template.ts +19 -6
  92. package/authoring/codemod/type.ts +10 -0
  93. package/authoring/config/config.doc.mjs +1 -1
  94. package/clients/cli/commands/build-theme.adaptations.test.mjs +110 -0
  95. package/clients/cli/commands/build-theme.outside-project.test.mjs +140 -0
  96. package/clients/cli/commands/swizzle.routing.test.mjs +1 -1
  97. package/clients/cli/commands/upgrade.doc.mjs +47 -2
  98. package/clients/cli/commands/upgrade.file-protection.test.mjs +175 -0
  99. package/clients/cli/commands/upgrade.flag-help.test.mjs +37 -0
  100. package/clients/cli/commands/upgrade.integration-policy.test.mjs +103 -0
  101. package/clients/cli/commands/upgrade.mjs +9 -2
  102. package/clients/cli/commands/upgrade.outcomes.test.mjs +350 -0
  103. package/foundation/agent-docs/agent-docs.mjs +1 -0
  104. package/foundation/agent-docs/agent-docs.test.mjs +5 -0
  105. package/foundation/config/project.d.mts +1 -1
  106. package/foundation/config/project.mjs +1 -1
  107. package/foundation/debug/redact.test.mjs +1 -1
  108. package/foundation/doc-compiler/doc-loads.test.mjs +2 -6
  109. package/foundation/response/base.d.ts +7 -0
  110. package/foundation/response/error-codes.doc.mjs +3 -2
  111. package/foundation/response/error-codes.mjs +1 -1
  112. package/foundation/response/json.d.mts +10 -3
  113. package/foundation/response/json.mjs +16 -4
  114. package/foundation/response/response-types.doc.mjs +1 -1
  115. package/package.json +13 -12
@@ -0,0 +1,140 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file `astryx theme build` outside any project, as a separate process.
5
+ *
6
+ * A theme in a folder with no Core installed (an empty folder, a fresh clone)
7
+ * imports `defineTheme` from Core all the same: the build hands its imports
8
+ * the Core the CLI answers with, as a new project with that Core would build
9
+ * it (spec AST-081 FR3). The CLI runs as its own process, without the
10
+ * `NODE_PATH` a pnpm script sets (it reaches the repository's packages): in
11
+ * the test runner, or with that path, the theme's import would find the
12
+ * repository's Core, which a real run outside a project cannot.
13
+ */
14
+
15
+ import {afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';
16
+ import * as fs from 'node:fs';
17
+ import * as os from 'node:os';
18
+ import * as path from 'node:path';
19
+ import {spawnSync} from 'node:child_process';
20
+ import {fileURLToPath} from 'node:url';
21
+ import {ensureCoreBuilt} from './ensure-core-built.mjs';
22
+
23
+ const CLI_BIN = fileURLToPath(new URL('../bin/astryx.mjs', import.meta.url));
24
+ const CORE_DIR = fileURLToPath(new URL('../../../../core', import.meta.url));
25
+
26
+ /** @param {string[]} args @param {string} cwd */
27
+ function runCliProcess(args, cwd) {
28
+ const {NODE_PATH: _repositoryPackages, ...env} = process.env;
29
+ const result = spawnSync(process.execPath, [CLI_BIN, ...args], {
30
+ cwd,
31
+ encoding: 'utf-8',
32
+ timeout: 60_000,
33
+ env,
34
+ });
35
+ if (result.error) throw result.error;
36
+ return result;
37
+ }
38
+
39
+ beforeAll(() => {
40
+ ensureCoreBuilt();
41
+ }, 200_000);
42
+
43
+ let tmpDir;
44
+ beforeEach(() => {
45
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-theme-outside-'));
46
+ });
47
+ afterEach(() => {
48
+ fs.rmSync(tmpDir, {recursive: true, force: true});
49
+ });
50
+
51
+ /**
52
+ * A project beside the empty folder: its own package.json and Core (this
53
+ * repository's, linked), so the same theme builds there through the
54
+ * project's own resolution.
55
+ * @param {string} dir
56
+ */
57
+ function makeProject(dir) {
58
+ fs.mkdirSync(path.join(dir, 'node_modules', '@astryxdesign'), {
59
+ recursive: true,
60
+ });
61
+ fs.writeFileSync(
62
+ path.join(dir, 'package.json'),
63
+ '{"name": "theme-project", "private": true, "dependencies": {"@astryxdesign/core": "*"}}\n',
64
+ );
65
+ fs.symlinkSync(
66
+ CORE_DIR,
67
+ path.join(dir, 'node_modules', '@astryxdesign', 'core'),
68
+ 'junction',
69
+ );
70
+ }
71
+
72
+ describe('theme build outside any project builds a plain-object theme as a project does', () => {
73
+ const themes = {
74
+ typography: `export default {
75
+ name: 'plain-type',
76
+ tokens: {'--color-background': '#123456'},
77
+ typography: {body: {family: 'Helvetica', fallbacks: 'Arial, sans-serif'}},
78
+ };\n`,
79
+ 'local tokens and media surfaces': `export default {
80
+ name: 'plain-local',
81
+ tokens: {'--color-background': '#123456'},
82
+ localTokens: {'--ac-selection-ink': ['#0077b6', '#48cae4']},
83
+ components: {badge: {'variant:info': {backgroundColor: 'var(--ac-selection-ink)'}}},
84
+ onDark: {components: {badge: {'variant:info': {color: 'var(--ac-selection-ink)'}}}},
85
+ };\n`,
86
+ };
87
+ for (const [what, source] of Object.entries(themes)) {
88
+ for (const ext of ['mjs', 'ts']) {
89
+ it(`with ${what}, in a .${ext} file`, () => {
90
+ const name = /name: '([^']+)'/.exec(source)[1];
91
+ const project = path.join(tmpDir, 'project');
92
+ makeProject(project);
93
+ const outside = path.join(tmpDir, 'outside');
94
+ fs.mkdirSync(outside);
95
+ for (const dir of [project, outside]) {
96
+ fs.writeFileSync(path.join(dir, `theme.${ext}`), source);
97
+ const result = runCliProcess(['theme', 'build', `theme.${ext}`], dir);
98
+ expect(result.status, result.stderr + result.stdout).toBe(0);
99
+ }
100
+ expect(fs.readFileSync(path.join(outside, `${name}.css`), 'utf8')).toBe(
101
+ fs.readFileSync(path.join(project, `${name}.css`), 'utf8'),
102
+ );
103
+ });
104
+ }
105
+ }
106
+ });
107
+
108
+ describe('theme build outside any project', () => {
109
+ for (const ext of ['mjs', 'ts']) {
110
+ it(`builds a .${ext} theme that imports defineTheme from Core, with the Core the CLI answers with`, () => {
111
+ fs.writeFileSync(
112
+ path.join(tmpDir, `outside.${ext}`),
113
+ "import {defineTheme} from '@astryxdesign/core/theme';\n" +
114
+ "export default defineTheme({name: 'outside', tokens: {'--color-background': '#123456'}});\n",
115
+ );
116
+ const result = runCliProcess(
117
+ ['theme', 'build', `outside.${ext}`],
118
+ tmpDir,
119
+ );
120
+ expect(result.status, result.stderr + result.stdout).toBe(0);
121
+ expect(
122
+ fs.readFileSync(path.join(tmpDir, 'outside.css'), 'utf8'),
123
+ ).toContain('#123456');
124
+ });
125
+ }
126
+
127
+ for (const ext of ['mjs', 'ts']) {
128
+ it(`still fails a .${ext} module that defines no theme`, () => {
129
+ fs.writeFileSync(
130
+ path.join(tmpDir, `none.${ext}`),
131
+ 'export const notATheme = 42;\n',
132
+ );
133
+ const result = runCliProcess(['theme', 'build', `none.${ext}`], tmpDir);
134
+ expect(result.status).toBe(1);
135
+ expect(result.stderr + result.stdout).toMatch(
136
+ /Could not find a defineTheme\(\) result/,
137
+ );
138
+ });
139
+ }
140
+ });
@@ -155,7 +155,7 @@ describe('swizzle — core feedback routing via config', () => {
155
155
  expect(result.code).toBe(0);
156
156
  const env = JSON.parse(result.stdout);
157
157
  expect(env.data.feedback.issuesUrl).toBe(
158
- 'https://github.com/facebook/astryx/issues/new',
158
+ 'https://github.com/meta/astryx/issues/new',
159
159
  );
160
160
  });
161
161
  });
@@ -108,14 +108,17 @@ export const doc = {
108
108
  ],
109
109
  outsideProject: 'own',
110
110
  exitCodes: [
111
- {code: 0, when: 'success, including complete dry-run previews'},
111
+ {
112
+ code: 0,
113
+ when: 'success, including complete dry-run previews and runs whose only findings are manual migrations',
114
+ },
112
115
  {
113
116
  code: 1,
114
117
  when:
115
118
  'missing or invalid --from, --registry with --list or a migration flag, a --path escape, ' +
116
119
  'no installed @astryxdesign/core (or legacy @xds/core), jscodeshift missing and not installed by --install-deps, ' +
117
120
  'an astryx.config that fails validation and that no pending config codemod repairs, ' +
118
- 'an unreadable or invalid protection declaration, a protected file that still requires a codemod change, ' +
121
+ 'an unreadable or invalid protection declaration, a protected file that still requires a codemod change, a generated file that must be regenerated, ' +
119
122
  'an unknown codemod, a codemod or post-codemod hook failure, or unresolved registry items',
120
123
  },
121
124
  ],
@@ -157,6 +160,13 @@ export const doc = {
157
160
  'it is an installed dependency (such as anything in `node_modules`), is inside `.git`, `.hg`, or `.sl`, is a symbolic link, or is outside the project',
158
161
  ],
159
162
  },
163
+ {
164
+ type: 'prose',
165
+ text:
166
+ 'upgrade does not scan installed dependencies or version-control folders at all, including through a symbolic link: ' +
167
+ 'a symlinked `node_modules`, or a link whose target is inside one or inside a package store such as `.yarn/cache`, is skipped. ' +
168
+ 'Other symbolically linked folders are scanned so a change they need is reported, but nothing is written through them.',
169
+ },
160
170
  {
161
171
  type: 'prose',
162
172
  text:
@@ -194,5 +204,40 @@ export const doc = {
194
204
  '`Command:` line in its header, such as `// Command: pnpm run gen:panel`; upgrade prints it as ' +
195
205
  '`Regenerate with: <command>` and lists it in `commands`.',
196
206
  },
207
+ {
208
+ type: 'prose',
209
+ text:
210
+ 'A protected file a codemod cannot parse, such as a vendored bundle written for another toolchain, cannot need a ' +
211
+ 'change the codemod can prove, and upgrade never writes it. upgrade skips it, lists it under ' +
212
+ '`declinedCandidates` with the parse error and where it occurred, and carries on; on its own it does not fail the run. ' +
213
+ 'If another codemod in the same upgrade still requires a change to that file (the 0.6.0 theme selector migration, for one, ' +
214
+ 'adds a TODO comment above a selector it cannot parse), the file is listed once, under `protectedFiles`, and the run is ' +
215
+ 'incomplete as for any protected file. A file upgrade owns that does not parse still fails the run with ERR_CODEMOD_FAILED.',
216
+ },
217
+ {type: 'heading', level: 3, text: 'Manual migrations and regeneration'},
218
+ {
219
+ type: 'prose',
220
+ text:
221
+ 'Some changes a codemod can find but not make. upgrade lists them in the result, so a script can keep the rest of the run and act on each. ' +
222
+ 'Code a codemod can identify but cannot migrate safely is a manual migration: upgrade lists each file with its line, ' +
223
+ 'the codemod and what to change, finishes the run, and exits 0. With --json they are in `declinedCandidates`, one row per file (each finding in `reason` starts with `manual migration needed (<codemod>):`, and a file with several findings lists them all, joined by `; `), and `complete` stays true. ' +
224
+ 'A generated file that must be rebuilt is listed in `regenerate` with the command that rebuilds it, such as `astryx theme build`: a protected generated file a codemod still needs to change ' +
225
+ '(also in `protectedFiles`), or a generated output a codemod found out of date (also in `protectedFiles`, with the rule that protects it, when the project marks it generated). With --apply, upgrade runs your `hooks.postCodemod` commands and checks again. ' +
226
+ 'If a protected file still needs rebuilding, the run is incomplete exactly as for any protected file: it exits 1 and the result says `complete: false` and `errorCode: "ERR_CODEMOD_PROTECTED"`. ' +
227
+ 'If a file nothing protects still needs rebuilding, no protected file is in the way: the codemod could not make a required change, so it is also in `errors` and the run fails with `ERR_CODEMOD_FAILED`, as described below. ' +
228
+ 'Either way, rebuild it, then run the same upgrade again. ' +
229
+ 'When a codemod also failed, the failure is reported as below, and the receipt it carries still lists `declinedCandidates` and `regenerate`, ' +
230
+ 'unless a protected file to regenerate also remains, in which case the run returns `ERR_CODEMOD_PROTECTED` with the failure in `errors`.',
231
+ },
232
+ {type: 'heading', level: 3, text: 'A failed codemod'},
233
+ {
234
+ type: 'prose',
235
+ text:
236
+ 'When a codemod or a `hooks.postCodemod` command fails, upgrade still makes every other change, exits 1 with ERR_CODEMOD_FAILED, and does not refresh the agent docs. ' +
237
+ 'With --json, the result is the usual error, `{"error": ..., "code": "ERR_CODEMOD_FAILED"}`, plus a `receipt`: the same fields a finished run returns, with `complete: false`, ' +
238
+ 'each failure in `errors`, and every file upgrade changed (or would change) in `modifiedFiles`, so a script can review, keep, or revert them. ' +
239
+ 'An error that stops the run after codemods have written files, such as an astryx.config that fails validation, carries a `receipt` too. ' +
240
+ 'Rerun past a failed codemod with --skip-codemod.',
241
+ },
197
242
  ],
198
243
  };
@@ -199,6 +199,35 @@ describe('upgrade protected-file contract', () => {
199
199
  });
200
200
  });
201
201
 
202
+ it('keeps the error and adds the receipt when a hook leaves a protection declaration unreadable', () => {
203
+ seed();
204
+ write(
205
+ 'astryx.config.mjs',
206
+ `export default {hooks: {postCodemod: [{name: 'regenerate', buildCommand: () => ({command: process.execPath, args: ['-e', ${JSON.stringify("require('node:fs').writeFileSync('.hgignore', 'syntax: regexp\\n[bad\\n')")}]})}]}};\n`,
207
+ );
208
+
209
+ const applied = run([...ARGS, '--apply']);
210
+
211
+ expect(applied.status).toBe(1);
212
+ expect(applied.envelope).not.toHaveProperty('type');
213
+ expect(applied.envelope).toMatchObject({
214
+ code: 'ERR_CODEMOD_PROTECTION_SOURCE',
215
+ error: expect.stringContaining('.hgignore'),
216
+ receipt: {
217
+ complete: false,
218
+ errorCode: 'ERR_CODEMOD_PROTECTION_SOURCE',
219
+ modifiedFiles: ['src/owned.tsx'],
220
+ protectedFiles: [
221
+ expect.objectContaining({file: 'generated/panel.tsx'}),
222
+ ],
223
+ errors: [expect.objectContaining({codemod: 'file-protection'})],
224
+ },
225
+ });
226
+ expect(fs.readFileSync(path.join(root, 'src/owned.tsx'), 'utf8')).toContain(
227
+ 'minSize: 200',
228
+ );
229
+ });
230
+
202
231
  it('runs declared regeneration and clears a generated-file block after reevaluation', () => {
203
232
  seed({hook: true});
204
233
 
@@ -226,4 +255,150 @@ describe('upgrade protected-file contract', () => {
226
255
  expect(second.envelope.data.complete).toBe(true);
227
256
  expect(second.envelope.data.filesChanged).toBe(0);
228
257
  });
258
+
259
+ it('skips a vendored file that does not parse and completes the upgrade', () => {
260
+ seed();
261
+ write('.gitattributes', 'vendor/** linguist-vendored\n');
262
+ const bundle =
263
+ "/* minified */ import {useResizable} from '@astryxdesign/core';\n" +
264
+ 'export const x = useResizable({minSizePx: 200;\n';
265
+ write('vendor/bundle.js', bundle);
266
+ rmGenerated();
267
+
268
+ const applied = run([...ARGS, '--apply']);
269
+
270
+ expect(applied.status, applied.stderr).toBe(0);
271
+ expect(applied.envelope).toMatchObject({
272
+ type: 'upgrade.run',
273
+ data: {
274
+ complete: true,
275
+ modifiedFiles: ['src/owned.tsx'],
276
+ protectedFiles: [],
277
+ declinedCandidates: [
278
+ {
279
+ file: 'vendor/bundle.js',
280
+ location: '2:46',
281
+ reason:
282
+ 'unparseable protected file (vendored): Unexpected token, expected ","',
283
+ },
284
+ ],
285
+ },
286
+ });
287
+ expect(applied.envelope.data.errors ?? []).toEqual([]);
288
+ expect(fs.readFileSync(path.join(root, 'src/owned.tsx'), 'utf8')).toContain(
289
+ 'minSize: 200',
290
+ );
291
+ expect(fs.readFileSync(path.join(root, 'vendor/bundle.js'), 'utf8')).toBe(
292
+ bundle,
293
+ );
294
+
295
+ const text = spawnSync(process.execPath, [CLI, 'upgrade', ...ARGS], {
296
+ cwd: root,
297
+ encoding: 'utf8',
298
+ timeout: 60_000,
299
+ env: {...process.env, FORCE_COLOR: '0', CI: ''},
300
+ });
301
+ expect(text.status, text.stderr).toBe(0);
302
+ expect(`${text.stdout}${text.stderr}`).toContain(
303
+ '1 protected file was skipped because it does not parse',
304
+ );
305
+ const declinedLine = `${text.stdout}${text.stderr}`
306
+ .split('\n')
307
+ .find(line => line.includes('vendor/bundle.js:2:46'));
308
+ expect(declinedLine).toMatch(/^ {2}vendor\/bundle\.js:2:46 - /);
309
+ // cli-surface output is plain ASCII.
310
+ expect(declinedLine).toMatch(/^[\x20-\x7e]*$/);
311
+ });
312
+
313
+ it('still fails when an owned file does not parse', () => {
314
+ seed();
315
+ write(
316
+ 'lib/broken.js',
317
+ "import {useResizable} from '@astryxdesign/core';\n" +
318
+ 'export const x = useResizable({minSizePx: 200;\n',
319
+ );
320
+ rmGenerated();
321
+
322
+ const applied = run([...ARGS, '--apply']);
323
+
324
+ expect(applied.status).toBe(1);
325
+ expect(applied.envelope).toMatchObject({code: 'ERR_CODEMOD_FAILED'});
326
+ });
327
+
328
+ it('reports a stylesheet the 0.6 and 0.7 theme codemods both need once, as protected', () => {
329
+ write('package.json', JSON.stringify({name: 'consumer', private: true}));
330
+ write(
331
+ 'node_modules/@astryxdesign/core/package.json',
332
+ JSON.stringify({name: '@astryxdesign/core', version: CLI_VERSION}),
333
+ );
334
+ write('.gitattributes', 'vendor/** linguist-vendored\n');
335
+ write('vendor/bundle.css', 'a:: { color: red; }\n');
336
+
337
+ const result = run(['--from', '0.5.4', '--path', '.']);
338
+ const text = spawnSync(
339
+ process.execPath,
340
+ [CLI, 'upgrade', '--from', '0.5.4', '--path', '.'],
341
+ {
342
+ cwd: root,
343
+ encoding: 'utf8',
344
+ timeout: 60_000,
345
+ env: {...process.env, FORCE_COLOR: '0', CI: ''},
346
+ },
347
+ );
348
+ const output = `${text.stdout}${text.stderr}`;
349
+ expect(text.status).toBe(1);
350
+ expect(output).toContain('ERR_CODEMOD_PROTECTED');
351
+ expect(output).toMatch(/^ {2}vendor\/bundle\.css — /m);
352
+ expect(output).not.toContain('skipped because');
353
+ expect(output).not.toContain('unparseable protected file');
354
+
355
+ expect(result.status).toBe(1);
356
+ expect(result.envelope).toMatchObject({
357
+ type: 'upgrade.run',
358
+ data: {
359
+ complete: false,
360
+ errorCode: 'ERR_CODEMOD_PROTECTED',
361
+ protectedFiles: [expect.objectContaining({file: 'vendor/bundle.css'})],
362
+ declinedCandidates: [],
363
+ },
364
+ });
365
+ });
366
+
367
+ it('lists a generated file the hook regenerates into bytes that do not parse', () => {
368
+ seed();
369
+ const broken =
370
+ "// @generated\nimport {useResizable} from '@astryxdesign/core';\n" +
371
+ 'export const usePanel = () => useResizable({minSizePx: 200;\n';
372
+ write(
373
+ 'astryx.config.mjs',
374
+ `export default {hooks: {postCodemod: [{name: 'regenerate', buildCommand: () => ({command: process.execPath, args: ['-e', ${JSON.stringify(`require('node:fs').writeFileSync('generated/panel.tsx', ${JSON.stringify(broken)})`)}]})}]}};\n`,
375
+ );
376
+
377
+ const applied = run([...ARGS, '--apply']);
378
+
379
+ expect(applied.status, applied.stderr).toBe(0);
380
+ expect(applied.envelope).toMatchObject({
381
+ type: 'upgrade.run',
382
+ data: {
383
+ complete: true,
384
+ protectedFiles: [],
385
+ declinedCandidates: [
386
+ {
387
+ file: 'generated/panel.tsx',
388
+ location: expect.stringMatching(/^3:\d+$/),
389
+ reason: expect.stringMatching(
390
+ /^unparseable protected file \(generated\): /,
391
+ ),
392
+ },
393
+ ],
394
+ },
395
+ });
396
+ expect(
397
+ fs.readFileSync(path.join(root, 'generated/panel.tsx'), 'utf8'),
398
+ ).toBe(broken);
399
+ });
229
400
  });
401
+
402
+ function rmGenerated() {
403
+ fs.rmSync(path.join(root, 'generated'), {recursive: true, force: true});
404
+ }
@@ -175,6 +175,43 @@ describe('astryx upgrade exit codes', () => {
175
175
  expect(status).toBe(1);
176
176
  expect(envelope.code).toBe('ERR_CODEMOD_FAILED');
177
177
  expect(envelope.error).toMatch(/Post-codemod hook failed/);
178
+ // Additive: the receipt names what the run had already changed.
179
+ expect(envelope).toMatchObject({
180
+ receipt: {
181
+ complete: false,
182
+ errorCode: 'ERR_CODEMOD_FAILED',
183
+ modifiedFiles: ['src/panel.tsx'],
184
+ errors: [
185
+ expect.objectContaining({
186
+ codemod: 'post-codemod-hook',
187
+ error: expect.stringMatching(/Post-codemod hook failed/),
188
+ }),
189
+ ],
190
+ },
191
+ });
192
+ }, SLOW);
193
+
194
+ it('reports what core codemods wrote when astryx.config then fails validation', async () => {
195
+ installPackage('@astryxdesign/core', '0.6.0');
196
+ write(
197
+ 'src/panel.tsx',
198
+ "import {useResizable} from '@astryxdesign/core';\nexport const r = () => useResizable({minSizePx: 200});\n",
199
+ );
200
+ write('astryx.config.mjs', "export default {theme: 'neutral'};\n");
201
+ const {status, envelope} = await upgradeJson(['--from', '0.5.0', '--apply']);
202
+ expect(status).toBe(1);
203
+ expect(envelope).toMatchObject({
204
+ code: 'ERR_INVALID_ARGUMENT',
205
+ receipt: {
206
+ complete: false,
207
+ errorCode: 'ERR_INVALID_ARGUMENT',
208
+ modifiedFiles: ['src/panel.tsx'],
209
+ errors: [expect.objectContaining({codemod: 'config'})],
210
+ },
211
+ });
212
+ expect(fs.readFileSync(path.join(tmpDir, 'src/panel.tsx'), 'utf8')).toContain(
213
+ 'minSize: 200',
214
+ );
178
215
  }, SLOW);
179
216
 
180
217
  it('lists a missing jscodeshift and the refused flag combinations', () => {
@@ -17,6 +17,7 @@ import * as fs from 'node:fs';
17
17
  import * as path from 'node:path';
18
18
  import {Command} from 'commander';
19
19
  import {registerUpgrade} from './upgrade.mjs';
20
+ import {isError} from '../../../api/json/parse.mjs';
20
21
  import {Project} from '../../../foundation/config/project.mjs';
21
22
  import {
22
23
  generateCompressedIndex,
@@ -47,6 +48,7 @@ beforeEach(() => {
47
48
  });
48
49
 
49
50
  afterEach(() => {
51
+ process.exitCode = undefined;
50
52
  process.chdir(originalCwd);
51
53
  fs.rmSync(tmpDir, {recursive: true, force: true});
52
54
  vi.restoreAllMocks();
@@ -298,6 +300,13 @@ describe('upgrade integration error policy (skip + warn)', () => {
298
300
  ]);
299
301
 
300
302
  expect(result.code).toBe('ERR_CODEMOD_FAILED');
303
+ expect(result.receipt).toMatchObject({
304
+ complete: false,
305
+ errorCode: 'ERR_CODEMOD_FAILED',
306
+ agentDocsRefreshed: false,
307
+ modifiedFiles: ['src/index.ts'],
308
+ errors: [expect.objectContaining({codemod: 'post-codemod-hook'})],
309
+ });
301
310
  expect(fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8')).toBe(
302
311
  before,
303
312
  );
@@ -476,3 +485,97 @@ describe('upgrade integration error policy (skip + warn)', () => {
476
485
  expect(out).not.toContain('bar');
477
486
  });
478
487
  });
488
+
489
+ describe('upgrade failure receipt when a codemod fails', () => {
490
+ const codemods = {
491
+ '0.2.0/drop-foo.mjs': `export default {type: 'code', title: 'Drop foo', transform: file => file.source.replace(/foo/g, 'bar')};\n`,
492
+ '0.2.0/fail.mjs': `export default {type: 'code', title: 'Fail on boom', transform: file => { if (file.source.includes('boom')) throw new Error('codemod boom'); return undefined; }};\n`,
493
+ };
494
+
495
+ function scaffold() {
496
+ scaffoldIntegration(codemods);
497
+ writeInstalledCore('0.2.0');
498
+ writeSource();
499
+ fs.writeFileSync(path.join(tmpDir, 'src', 'broken.ts'), 'const boom = 1;\n');
500
+ }
501
+
502
+ const ARGS = ['upgrade', '--from', '0.1.0', '--path', 'src'];
503
+
504
+ it('keeps the error envelope and adds the receipt of what was written', async () => {
505
+ scaffold();
506
+
507
+ const result = await runJson(['--json', ...ARGS, '--apply']);
508
+
509
+ expect(exitCode).toBe(1);
510
+ expect(isError(result)).toBe(true);
511
+ expect(result).not.toHaveProperty('type');
512
+ expect(result).toMatchObject({
513
+ apiVersion: 1,
514
+ code: 'ERR_CODEMOD_FAILED',
515
+ error: 'Upgrade completed with 1 codemod error.',
516
+ receipt: {
517
+ complete: false,
518
+ errorCode: 'ERR_CODEMOD_FAILED',
519
+ filesChanged: 1,
520
+ modifiedFiles: ['src/index.ts'],
521
+ protectedFiles: [],
522
+ errors: [
523
+ {
524
+ file: 'src/broken.ts',
525
+ codemod: '@acme/widgets:fail',
526
+ error: 'codemod boom',
527
+ },
528
+ ],
529
+ },
530
+ });
531
+ expect(fs.readFileSync(path.join(tmpDir, 'src', 'index.ts'), 'utf-8')).toBe(
532
+ 'const bar = 1;\n',
533
+ );
534
+ });
535
+
536
+ it('previews the same receipt in a dry run without writing', async () => {
537
+ scaffold();
538
+
539
+ const result = await runJson(['--json', ...ARGS]);
540
+
541
+ expect(result.code).toBe('ERR_CODEMOD_FAILED');
542
+ expect(result.receipt).toMatchObject({
543
+ complete: false,
544
+ modifiedFiles: ['src/index.ts'],
545
+ errors: [expect.objectContaining({file: 'src/broken.ts'})],
546
+ });
547
+ expect(fs.readFileSync(path.join(tmpDir, 'src', 'index.ts'), 'utf-8')).toBe(
548
+ 'const foo = 1;\n',
549
+ );
550
+ });
551
+
552
+ it('still returns the protected-file receipt when a protected file remains', async () => {
553
+ scaffold();
554
+ fs.writeFileSync(
555
+ path.join(tmpDir, 'src', 'gen.ts'),
556
+ '// @generated\nconst foo = 2;\n',
557
+ );
558
+
559
+ const result = await runJson(['--json', ...ARGS, '--apply']);
560
+
561
+ expect(result).toMatchObject({
562
+ type: 'upgrade.run',
563
+ data: {
564
+ complete: false,
565
+ errorCode: 'ERR_CODEMOD_PROTECTED',
566
+ protectedFiles: [expect.objectContaining({file: 'src/gen.ts'})],
567
+ errors: [expect.objectContaining({file: 'src/broken.ts'})],
568
+ },
569
+ });
570
+ });
571
+
572
+ it('keeps the human output and exit status in text mode', async () => {
573
+ scaffold();
574
+
575
+ await runJson([...ARGS, '--apply']);
576
+
577
+ expect(process.exitCode).toBe(1);
578
+ expect(logCalls.join('\n')).toMatch(/Upgrade failed/);
579
+ expect(logCalls.join('\n')).not.toMatch(/"receipt"/);
580
+ });
581
+ });
@@ -57,8 +57,15 @@ export function registerUpgrade(program) {
57
57
  // already printed the error before throwing.
58
58
  logger.setSilent(json);
59
59
  if (e instanceof AstryxError) {
60
- if (json) jsonError(e.message, undefined, e.code);
61
- else {
60
+ if (json) {
61
+ // A failed migration still names the files it already changed.
62
+ jsonError(
63
+ e.message,
64
+ undefined,
65
+ e.code,
66
+ /** @type {any} */ (e).receipt,
67
+ );
68
+ } else {
62
69
  // The logger was silent only for --list; replay the error there.
63
70
  // Non-list failures were already printed by the API.
64
71
  if (isList) logger.error(e.message);