@astryxdesign/cli 0.7.5-canary.a17ee0a → 0.7.5-canary.a2e2bcc

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 (51) hide show
  1. package/CHANGELOG.md +3 -3
  2. package/api/hook/detail/detail.test.mjs +11 -0
  3. package/api/swizzle/copy/copy.mjs +1 -1
  4. package/api/template/tokenizer-showcase.test.mjs +47 -0
  5. package/api/theme/build/build.adaptation-enrollment.test.mjs +4 -0
  6. package/api/theme/build/build.icon-entry-variants.test.mjs +134 -0
  7. package/api/theme/build/build.icon-function-entries.test.mjs +499 -0
  8. package/api/theme/build/build.icon-variants.test.mjs +105 -0
  9. package/api/theme/build/build.mjs +362 -109
  10. package/api/theme/build/build.project-core.test.mjs +63 -8
  11. package/api/theme/build/build.test.mjs +77 -0
  12. package/api/theme/build/icon-imports.d.mts +12 -2
  13. package/api/theme/build/icon-imports.mjs +36 -11
  14. package/assets/codemods/transforms/next/__tests__/migrate-codeblock-tokenizer-to-language.test.mjs +130 -0
  15. package/assets/codemods/transforms/next/index.mjs +11 -1
  16. package/assets/codemods/transforms/next/migrate-codeblock-tokenizer-to-language.mjs +315 -0
  17. package/assets/codemods/transforms/v0.1.2/rename-text-color-active-to-accent.mjs +1 -1
  18. package/assets/codemods/transforms/v0.1.5/rename-switch-label-spacing-default-to-hug.mjs +1 -1
  19. package/assets/codemods/transforms/v0.1.7/migrate-table-tableprops-to-direct-props.mjs +1 -1
  20. package/assets/codemods/transforms/v0.1.8/rename-avatar-size-scale.mjs +1 -1
  21. package/assets/codemods/transforms/v0.2.0/remove-tablist-orientation.mjs +1 -1
  22. package/assets/codemods/transforms/v0.2.1/migrate-dialog-position-to-logical.mjs +1 -1
  23. package/assets/docs/README.md +13 -13
  24. package/assets/docs/author-a-theme.doc.mjs +5 -1
  25. package/assets/docs/getting-started.doc.mjs +5 -5
  26. package/assets/docs/icons.doc.mjs +82 -1
  27. package/assets/docs/motion.doc.mjs +1 -1
  28. package/assets/docs/theme.doc.dense.mjs +8 -0
  29. package/assets/docs/theme.doc.mjs +16 -0
  30. package/assets/docs/theme.doc.zh.mjs +11 -0
  31. package/assets/docs/tree/i18n-library-integration.doc.mjs +1 -1
  32. package/assets/docs/tree/tokens-ease.doc.mjs +4 -0
  33. package/assets/docs/tree/tokens.doc.mjs +1 -1
  34. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.doc.mjs +6 -4
  35. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.tsx +61 -55
  36. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.doc.mjs +6 -4
  37. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.tsx +68 -37
  38. package/assets/templates/blocks/components/Thumbnail/ThumbnailDisabled.doc.mjs +1 -1
  39. package/assets/templates/blocks/components/Tokenizer/TokenizerShowcase.tsx +13 -6
  40. package/assets/theme.template.ts +19 -6
  41. package/authoring/config/config.doc.mjs +1 -1
  42. package/clients/cli/commands/build-theme.outside-project.test.mjs +140 -0
  43. package/clients/cli/commands/swizzle.routing.test.mjs +1 -1
  44. package/foundation/agent-docs/agent-docs.mjs +1 -0
  45. package/foundation/agent-docs/agent-docs.test.mjs +5 -0
  46. package/foundation/config/project.d.mts +1 -1
  47. package/foundation/config/project.mjs +1 -1
  48. package/foundation/debug/redact.test.mjs +1 -1
  49. package/foundation/doc-compiler/doc-loads.test.mjs +2 -6
  50. package/foundation/env/package-manager.test.mjs +14 -1
  51. package/package.json +12 -12
@@ -7,15 +7,26 @@
7
7
  * app's `<Theme>` runs on the app's Core either way, so the build loads the
8
8
  * project's installed `@astryxdesign/core` when it differs from the CLI's own.
9
9
  * When there is no Core to use, the error names the fix for where it ran:
10
- * install it in an app, build it in the Astryx repository.
10
+ * install it in an app, build it in the Astryx repository. An installed Core
11
+ * that does not load, or lacks the functions the build calls, fails the build,
12
+ * naming it, rather than leave the build to the CLI's own Core.
11
13
  */
12
14
 
13
- import {afterEach, beforeEach, describe, expect, it} from 'vitest';
15
+ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
14
16
  import * as fs from 'node:fs';
15
17
  import * as os from 'node:os';
16
18
  import * as path from 'node:path';
17
19
  import {fileURLToPath, pathToFileURL} from 'node:url';
18
20
  import {coreUnavailableMessage, themeBuild} from './build.mjs';
21
+ import {fetchCarriedThemeCoreDir} from '../_adapter.mjs';
22
+
23
+ vi.mock('../_adapter.mjs', async importOriginal => {
24
+ const actual = /** @type {Record<string, any>} */ (await importOriginal());
25
+ return {
26
+ ...actual,
27
+ fetchCarriedThemeCoreDir: vi.fn(actual.fetchCarriedThemeCoreDir),
28
+ };
29
+ });
19
30
 
20
31
  const HERE = path.dirname(fileURLToPath(import.meta.url));
21
32
  const REPO_ROOT = path.resolve(HERE, '../../../../..');
@@ -53,9 +64,10 @@ afterEach(() => {
53
64
  * entry as it is imported. Its `exports` map lists `source` first, as Core's
54
65
  * own does, so the build must skip that condition to find the runtime file.
55
66
  * @param {string} dir
56
- * @param {{broken?: boolean}} [options]
67
+ * @param {{broken?: boolean, themeModule?: string}} [options] `themeModule`
68
+ * replaces the theme entry's source
57
69
  */
58
- function installCore(dir, {broken = false} = {}) {
70
+ function installCore(dir, {broken = false, themeModule} = {}) {
59
71
  const core = path.join(dir, 'node_modules', '@astryxdesign', 'core');
60
72
  fs.mkdirSync(core, {recursive: true});
61
73
  fs.writeFileSync(
@@ -82,12 +94,29 @@ function installCore(dir, {broken = false} = {}) {
82
94
  `globalThis.__astryxProjectCoreLoads = [...(globalThis.__astryxProjectCoreLoads ?? []), '${entry}'];\n`;
83
95
  fs.writeFileSync(
84
96
  path.join(core, 'theme.mjs'),
85
- module('theme', 'theme/index.js'),
97
+ themeModule ?? module('theme', 'theme/index.js'),
86
98
  );
87
99
  fs.writeFileSync(path.join(core, 'root.mjs'), module('root', 'index.js'));
88
100
  return core;
89
101
  }
90
102
 
103
+ describe('theme build outside a project, with the Core this CLI release carries', () => {
104
+ it('fails naming a carried Core that does not load, rather than build with the CLI’s own', async () => {
105
+ const carried = installCore(makeDir(), {broken: true});
106
+ vi.mocked(fetchCarriedThemeCoreDir).mockReturnValueOnce(carried);
107
+ const bare = makeDir();
108
+ const build = themeBuild('ocean.mjs', {}, {cwd: bare});
109
+ await expect(build).rejects.toMatchObject({
110
+ code: 'ERR_CORE_NOT_FOUND',
111
+ message: expect.stringContaining(
112
+ `Could not load the @astryxdesign/core this CLI release carries, at ${carried}`,
113
+ ),
114
+ });
115
+ await expect(build).rejects.toThrow(/Import error: this Core is broken/);
116
+ expect(fs.existsSync(path.join(bare, 'ocean.css'))).toBe(false);
117
+ });
118
+ });
119
+
91
120
  describe('theme build generates with the Core the project installed', () => {
92
121
  it('loads the app’s installed Core when it differs from the CLI’s own', async () => {
93
122
  const app = makeDir();
@@ -114,11 +143,37 @@ describe('theme build generates with the Core the project installed', () => {
114
143
  expect(fs.existsSync(path.join(bare, 'ocean.css'))).toBe(true);
115
144
  });
116
145
 
117
- it('keeps the CLI’s own Core when the installed one does not load', async () => {
146
+ it('fails naming an installed Core that does not load, rather than build with the CLI’s own', async () => {
118
147
  const app = makeDir();
119
148
  installCore(app, {broken: true});
120
- await themeBuild('ocean.mjs', {}, {cwd: app});
121
- expect(fs.existsSync(path.join(app, 'ocean.css'))).toBe(true);
149
+ await expect(themeBuild('ocean.mjs', {}, {cwd: app})).rejects.toMatchObject(
150
+ {
151
+ code: 'ERR_CORE_NOT_FOUND',
152
+ message: expect.stringContaining(
153
+ `Could not load the @astryxdesign/core installed at ${path.join('node_modules', '@astryxdesign', 'core')}`,
154
+ ),
155
+ },
156
+ );
157
+ await expect(themeBuild('ocean.mjs', {}, {cwd: app})).rejects.toThrow(
158
+ /Import error: this Core is broken/,
159
+ );
160
+ expect(fs.existsSync(path.join(app, 'ocean.css'))).toBe(false);
161
+ });
162
+
163
+ it('fails naming an installed Core without the functions the build calls, rather than build with the CLI’s own', async () => {
164
+ const app = makeDir();
165
+ installCore(app, {
166
+ themeModule: 'export const defineTheme = theme => theme;\n',
167
+ });
168
+ await expect(themeBuild('ocean.mjs', {}, {cwd: app})).rejects.toMatchObject(
169
+ {
170
+ code: 'ERR_CORE_INCOMPATIBLE',
171
+ message: expect.stringContaining(
172
+ 'does not export generateThemeRulesSplit',
173
+ ),
174
+ },
175
+ );
176
+ expect(fs.existsSync(path.join(app, 'ocean.css'))).toBe(false);
122
177
  });
123
178
  });
124
179
 
@@ -27,6 +27,7 @@ import {
27
27
  import {
28
28
  themeBuild,
29
29
  validateComponentOverridesAgainstRegistry,
30
+ validateThemePrivateInputs,
30
31
  } from './build.mjs';
31
32
 
32
33
  // `themeBuild` captures core's generator once at module load. Wrap the two
@@ -212,6 +213,55 @@ describe('themeBuild() — receipt', () => {
212
213
  });
213
214
  });
214
215
 
216
+ describe.each(['mjs', 'ts'])('a .%s theme module with no theme export', ext => {
217
+ beforeEach(() => {
218
+ fs.writeFileSync(
219
+ path.join(tmpDir, `none.${ext}`),
220
+ 'export const notATheme = 42;\n',
221
+ );
222
+ });
223
+
224
+ it('fails the build as a module that does not load a theme', async () => {
225
+ const build = themeBuild(`none.${ext}`, {}, {cwd: tmpDir});
226
+ await expect(build).rejects.toThrow(
227
+ /Could not find a defineTheme\(\) result/,
228
+ );
229
+ await expect(build).rejects.toMatchObject({code: 'ERR_THEME_LOAD'});
230
+ });
231
+
232
+ it("fails doctor's private-input check the same way, rather than read its exports as a theme", async () => {
233
+ await expect(
234
+ validateThemePrivateInputs(`none.${ext}`, {cwd: tmpDir}),
235
+ ).rejects.toThrow(/Could not find a defineTheme\(\) result/);
236
+ });
237
+ });
238
+
239
+ describe('themeBuild() — a theme module that does not load', () => {
240
+ it('fails with the import error, rather than build the theme from the file text', async () => {
241
+ fs.writeFileSync(
242
+ path.join(tmpDir, 'unresolved.mjs'),
243
+ "import './missing-helper.mjs';\nexport default {name: 'unresolved', tokens: {'--color-bg': '#000'}};\n",
244
+ );
245
+ await expect(
246
+ themeBuild('unresolved.mjs', {}, {cwd: tmpDir}),
247
+ ).rejects.toThrow(
248
+ /Failed to load theme from .*unresolved\.mjs: .*missing-helper\.mjs/s,
249
+ );
250
+ expect(fs.existsSync(path.join(tmpDir, 'unresolved.css'))).toBe(false);
251
+ });
252
+
253
+ it('fails with the error the module throws, rather than build the theme from the file text', async () => {
254
+ fs.writeFileSync(
255
+ path.join(tmpDir, 'throws.mjs'),
256
+ "throw new Error('the theme module failed');\nexport default {name: 'throws', tokens: {'--color-bg': '#000'}};\n",
257
+ );
258
+ await expect(themeBuild('throws.mjs', {}, {cwd: tmpDir})).rejects.toThrow(
259
+ /the theme module failed/,
260
+ );
261
+ expect(fs.existsSync(path.join(tmpDir, 'throws.css'))).toBe(false);
262
+ });
263
+ });
264
+
215
265
  describe('themeBuild() — dropped declarations reach the receipt', () => {
216
266
  // Core's generator refuses a declaration whose value would end it early
217
267
  // (an unquoted `;` or brace, an unclosed string/comment/url). The runtime
@@ -599,6 +649,33 @@ describe('themeBuild() — component override validation', () => {
599
649
  });
600
650
  });
601
651
 
652
+ describe('themeBuild() — Icon size dimensions', () => {
653
+ it('writes width and height on an icon size into the vars the glyph reads, with no warnings', async () => {
654
+ // spec:AST-087 FR10: a built theme sets an Icon size's glyph dimension the
655
+ // way the runtime provider does, through the shared compiler's derived
656
+ // vars. Raw width/height would lose to a consumer's unlayered StyleX.
657
+ const themeFile = path.join(tmpDir, 'iconsizes.mjs');
658
+ fs.writeFileSync(
659
+ themeFile,
660
+ `export default {
661
+ name: 'iconsizes',
662
+ tokens: {'--color-bg': '#0a0a0a'},
663
+ components: {icon: {'size:sm': {width: '18px', height: '22px'}}},
664
+ };\n`,
665
+ );
666
+
667
+ const result = await themeBuild('iconsizes.mjs', {}, {cwd: tmpDir});
668
+
669
+ expect(result?.data.warnings).toEqual([]);
670
+ const css = fs.readFileSync(path.join(tmpDir, 'iconsizes.css'), 'utf8');
671
+ const rule =
672
+ css.match(/\.astryx-icon\[data-size="sm"\]\s*\{([^}]*)\}/)?.[1] ?? '';
673
+ expect(rule).toMatch(/--_icon-width:\s*18px/);
674
+ expect(rule).toMatch(/--_icon-height:\s*22px/);
675
+ expect(rule).not.toMatch(/(^|[\s;])(width|height)\s*:/);
676
+ });
677
+ });
678
+
602
679
  describe('themeBuild() — the shipped theme template', () => {
603
680
  // `assets/theme.template.ts` is what `astryx theme template` puts in a
604
681
  // consumer's project. It is the one theme file we hand out, so it has to
@@ -6,13 +6,18 @@
6
6
  * Local base themes are traced to their registry imports. Package bases remain
7
7
  * public theme imports, so their implementation and private files stay private.
8
8
  *
9
+ * A theme whose resolved icon entries include a function keeps them: a package
10
+ * base is read for its entries (`__icons`) as well as its node-valued `icons`,
11
+ * and a built base module's `__icons` field is followed instead of `icons`.
12
+ *
9
13
  * @param {string} filePath
10
14
  * @param {string | undefined} exportName
11
- * @param {{hasIcons: boolean, readSource: (filename: string) => string, resolveModule: (specifier: string, fromFile: string) => string | Promise<string>, reservedNames?: string[], rawInput?: boolean}} options
15
+ * @param {{hasIcons: boolean, functionEntries?: boolean, readSource: (filename: string) => string, resolveModule: (specifier: string, fromFile: string) => string | Promise<string>, reservedNames?: string[], rawInput?: boolean}} options
12
16
  * @returns {Promise<IconImports | null>}
13
17
  */
14
- export function resolveIconImports(filePath: string, exportName: string | undefined, { hasIcons, readSource, resolveModule, reservedNames, rawInput }: {
18
+ export function resolveIconImports(filePath: string, exportName: string | undefined, { hasIcons, functionEntries, readSource, resolveModule, reservedNames, rawInput, }: {
15
19
  hasIcons: boolean;
20
+ functionEntries?: boolean;
16
21
  readSource: (filename: string) => string;
17
22
  resolveModule: (specifier: string, fromFile: string) => string | Promise<string>;
18
23
  reservedNames?: string[];
@@ -35,11 +40,16 @@ export type RegistryReference = {
35
40
  binding: any;
36
41
  members: string[];
37
42
  };
43
+ /**
44
+ * `entries` marks a package theme read for its icon entries: its node-valued
45
+ * `icons` merged with the `__icons` that hold its function entries, if any.
46
+ */
38
47
  export type RegistryPlan = {
39
48
  kind: "registry";
40
49
  ref: RegistryReference;
41
50
  preferredName: string;
42
51
  override?: boolean;
52
+ entries?: boolean;
43
53
  } | {
44
54
  kind: "merge";
45
55
  base: RegistryPlan;
@@ -24,7 +24,11 @@ import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
24
24
  */
25
25
 
26
26
  /** @typedef {{kind: 'reference', module: any, binding: any, members: string[]}} RegistryReference */
27
- /** @typedef {{kind: 'registry', ref: RegistryReference, preferredName: string, override?: boolean} | {kind: 'merge', base: RegistryPlan, own: RegistryPlan}} RegistryPlan */
27
+ /**
28
+ * `entries` marks a package theme read for its icon entries: its node-valued
29
+ * `icons` merged with the `__icons` that hold its function entries, if any.
30
+ * @typedef {{kind: 'registry', ref: RegistryReference, preferredName: string, override?: boolean, entries?: boolean} | {kind: 'merge', base: RegistryPlan, own: RegistryPlan}} RegistryPlan
31
+ */
28
32
 
29
33
  /** @param {any} node */
30
34
  function unwrap(node) {
@@ -98,15 +102,26 @@ function invalidRegistry(name, reason = '') {
98
102
  * Local base themes are traced to their registry imports. Package bases remain
99
103
  * public theme imports, so their implementation and private files stay private.
100
104
  *
105
+ * A theme whose resolved icon entries include a function keeps them: a package
106
+ * base is read for its entries (`__icons`) as well as its node-valued `icons`,
107
+ * and a built base module's `__icons` field is followed instead of `icons`.
108
+ *
101
109
  * @param {string} filePath
102
110
  * @param {string | undefined} exportName
103
- * @param {{hasIcons: boolean, readSource: (filename: string) => string, resolveModule: (specifier: string, fromFile: string) => string | Promise<string>, reservedNames?: string[], rawInput?: boolean}} options
111
+ * @param {{hasIcons: boolean, functionEntries?: boolean, readSource: (filename: string) => string, resolveModule: (specifier: string, fromFile: string) => string | Promise<string>, reservedNames?: string[], rawInput?: boolean}} options
104
112
  * @returns {Promise<IconImports | null>}
105
113
  */
106
114
  export async function resolveIconImports(
107
115
  filePath,
108
116
  exportName,
109
- {hasIcons, readSource, resolveModule, reservedNames = [], rawInput = false},
117
+ {
118
+ hasIcons,
119
+ functionEntries = false,
120
+ readSource,
121
+ resolveModule,
122
+ reservedNames = [],
123
+ rawInput = false,
124
+ },
110
125
  ) {
111
126
  if (exportName === undefined) {
112
127
  if (!hasIcons) return null;
@@ -391,11 +406,16 @@ export async function resolveIconImports(
391
406
 
392
407
  /** @param {RegistryReference} ref @returns {RegistryPlan} */
393
408
  function packageTheme(ref) {
394
- return {
395
- kind: 'registry',
396
- ref: {...ref, members: [...ref.members, 'icons']},
397
- preferredName: 'themeIcons',
398
- };
409
+ // A theme's `icons` is node-valued; its function entries live in
410
+ // `__icons`. Read both only when the built theme needs its functions, so
411
+ // a theme without them keeps its existing output.
412
+ return functionEntries
413
+ ? {kind: 'registry', ref, preferredName: 'themeIcons', entries: true}
414
+ : {
415
+ kind: 'registry',
416
+ ref: {...ref, members: [...ref.members, 'icons']},
417
+ preferredName: 'themeIcons',
418
+ };
399
419
  }
400
420
 
401
421
  /** @param {any} module @param {string} name @param {boolean} [rejectOpaque] @returns {Promise<RegistryPlan | null>} */
@@ -513,7 +533,7 @@ export async function resolveIconImports(
513
533
  : propertyName(item.key);
514
534
  if (key === null)
515
535
  invalidRegistry(undefined, 'Computed theme keys cannot be resolved.');
516
- if (!['icons', 'extends'].includes(key)) continue;
536
+ if (!['icons', '__icons', 'extends'].includes(key)) continue;
517
537
  if (
518
538
  !['ObjectProperty', 'Property'].includes(item.type) ||
519
539
  item.method ||
@@ -566,7 +586,9 @@ export async function resolveIconImports(
566
586
  }
567
587
  const config = await fields(module, node);
568
588
  const baseField = config.get('extends');
569
- const iconField = config.get('icons');
589
+ // A built module keeps its function entries in `__icons` beside its
590
+ // node-valued `icons`; the entries are the registry to carry.
591
+ const iconField = config.get('__icons') ?? config.get('icons');
570
592
  const base = baseField
571
593
  ? await theme(baseField.module, baseField.node)
572
594
  : null;
@@ -655,10 +677,13 @@ export async function resolveIconImports(
655
677
  localName,
656
678
  });
657
679
  }
658
- const expression = ref.members.reduce(
680
+ const target = ref.members.reduce(
659
681
  (result, member) => `${result}[${JSON.stringify(member)}]`,
660
682
  localName,
661
683
  );
684
+ const expression = value.entries
685
+ ? `{...${target}["icons"], ...${target}["__icons"]}`
686
+ : target;
662
687
  return {
663
688
  expression,
664
689
  preferredName:
@@ -0,0 +1,130 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ import {describe, expect, it} from 'vitest';
4
+ import transform from '../migrate-codeblock-tokenizer-to-language.mjs';
5
+
6
+ async function applyTransform(source) {
7
+ const jscodeshift = (await import('jscodeshift')).default;
8
+ const j = jscodeshift.withParser('tsx');
9
+ const api = {jscodeshift: j, stats: () => {}, report: () => {}};
10
+ return transform({source, path: 'test.tsx'}, api) ?? source;
11
+ }
12
+
13
+ /** Collapse whitespace so assertions ignore the printer's line breaks. */
14
+ const flat = text => text.replace(/\s+/g, ' ');
15
+
16
+ describe('migrate-codeblock-tokenizer-to-language', () => {
17
+ it('rewrites tokenizer beside a static language to a custom language', async () => {
18
+ const output = flat(
19
+ await applyTransform(`import {CodeBlock} from '@astryxdesign/core/CodeBlock';
20
+ const a = <CodeBlock code={src} language="zig" tokenizer={zigTokens} />;
21
+ const b = <CodeBlock code={src} language={'nim'} tokenizer={(c) => tokens(c)} />;`),
22
+ );
23
+
24
+ expect(output).not.toContain('tokenizer=');
25
+ expect(output).toContain(
26
+ "import { CodeBlock, createCodeLanguage } from '@astryxdesign/core/CodeBlock';",
27
+ );
28
+ expect(output).toContain(
29
+ "language={zigTokens ? createCodeLanguage({ name: 'zig', identifiers: ['zig'], tokenize: zigTokens }) : 'zig'}",
30
+ );
31
+ expect(output).toContain(
32
+ "language={createCodeLanguage({ name: 'nim', identifiers: ['nim'], tokenize: (c) => tokens(c) })}",
33
+ );
34
+ });
35
+
36
+ it('adds the import beside a root-package import and follows aliases', async () => {
37
+ const output = flat(
38
+ await applyTransform(`import {CodeBlock as Code} from '@astryxdesign/core';
39
+ const a = <Code code={src} language="zig" tokenizer={zigTokens} />;`),
40
+ );
41
+
42
+ expect(output).toContain(
43
+ "import { createCodeLanguage } from '@astryxdesign/core/CodeBlock';",
44
+ );
45
+ expect(output).toContain("createCodeLanguage({ name: 'zig'");
46
+ });
47
+
48
+ it('adds a separate import beside a namespace import', async () => {
49
+ const output =
50
+ await applyTransform(`import * as CB from '@astryxdesign/core/CodeBlock';
51
+ const a = <CB.CodeBlock code={src} language="zig" tokenizer={zigTokens} />;`);
52
+ expect(output).toContain(
53
+ "import * as CB from '@astryxdesign/core/CodeBlock';",
54
+ );
55
+ expect(flat(output)).toContain(
56
+ "import { createCodeLanguage } from '@astryxdesign/core/CodeBlock';",
57
+ );
58
+ const jscodeshift = (await import('jscodeshift')).default;
59
+ expect(() => jscodeshift.withParser('tsx')(output)).not.toThrow();
60
+ });
61
+
62
+ it('guards a name or property that may be undefined', async () => {
63
+ const output = flat(
64
+ await applyTransform(`import {CodeBlock} from '@astryxdesign/core/CodeBlock';
65
+ const a = <CodeBlock code={src} language="zig" tokenizer={props.tokenizer} />;`),
66
+ );
67
+ expect(output).toContain(
68
+ "language={props.tokenizer ? createCodeLanguage({ name: 'zig', identifiers: ['zig'], tokenize: props.tokenizer }) : 'zig'}",
69
+ );
70
+ });
71
+
72
+ it('imports under a free alias when the file binds the name already', async () => {
73
+ const fromLocal = flat(
74
+ await applyTransform(`import {CodeBlock} from '@astryxdesign/core/CodeBlock';
75
+ import {createCodeLanguage} from './my-languages';
76
+ const a = <CodeBlock code={src} language="zig" tokenizer={(c) => t(c)} />;`),
77
+ );
78
+ expect(fromLocal).toContain(
79
+ "import { CodeBlock, createCodeLanguage as createCodeLanguage2 } from '@astryxdesign/core/CodeBlock';",
80
+ );
81
+ expect(fromLocal).toContain(
82
+ "import {createCodeLanguage} from './my-languages';",
83
+ );
84
+ expect(fromLocal).toContain("language={createCodeLanguage2({ name: 'zig'");
85
+
86
+ const fromFunction = flat(
87
+ await applyTransform(`import {CodeBlock} from '@astryxdesign/core/CodeBlock';
88
+ function createCodeLanguage() {}
89
+ const a = <CodeBlock code={src} language="zig" tokenizer={(c) => t(c)} />;`),
90
+ );
91
+ expect(fromFunction).toContain('createCodeLanguage as createCodeLanguage2');
92
+ const jscodeshift = (await import('jscodeshift')).default;
93
+ const parse = jscodeshift.withParser('tsx');
94
+ expect(() => parse(fromLocal)).not.toThrow();
95
+ });
96
+
97
+ it('reports a tokenizer value it cannot read twice, naming the tokenizer', async () => {
98
+ const output =
99
+ await applyTransform(`import {CodeBlock} from '@astryxdesign/core/CodeBlock';
100
+ const a = <CodeBlock code={src} language="zig" tokenizer={registry.get('zig').tokenize} />;
101
+ const b = <CodeBlock code={src} language="zig" tokenizer={enabled ? t : undefined} />;`);
102
+ expect(output.match(/this tokenizer value is computed/g)).toHaveLength(2);
103
+ expect(output).not.toContain('the language here is computed');
104
+ expect(output).toContain("tokenizer={registry.get('zig').tokenize}");
105
+ });
106
+
107
+ it('reports what it cannot prove and leaves it unchanged', async () => {
108
+ const source = `import {CodeBlock} from '@astryxdesign/core/CodeBlock';
109
+ const a = <CodeBlock code={src} language={lang} tokenizer={t} />;
110
+ const b = <CodeBlock code={src} tokenizer={t} />;
111
+ const c = <CodeBlock code={src} language="plaintext" tokenizer={t} />;
112
+ const d = <CodeBlock {...rest} code={src} language="zig" tokenizer={t} />;
113
+ const e = <CodeBlock code={src} language="zig" tokenizer={enabled ? t : undefined} />;
114
+ const f = <CodeBlock code={src} language="zig" tokenizer={enabled && t} />;`;
115
+ const output = await applyTransform(source);
116
+
117
+ expect(output.match(/TODO\(astryx upgrade\)/g)).toHaveLength(6);
118
+ expect(output.match(/tokenizer=\{t\}/g)).toHaveLength(4);
119
+ expect(output).toContain('tokenizer={enabled ? t : undefined}');
120
+ expect(output).toContain('tokenizer={enabled && t}');
121
+ expect(output).not.toMatch(/import \{[^}]*createCodeLanguage/);
122
+ expect(await applyTransform(output)).toBe(output);
123
+ });
124
+
125
+ it('leaves files without CodeBlock tokenizer alone', async () => {
126
+ const source = `import {CodeBlock} from '@astryxdesign/core/CodeBlock';
127
+ const a = <CodeBlock code={src} language="ts" />;`;
128
+ expect(await applyTransform(source)).toBe(source);
129
+ });
130
+ });
@@ -7,4 +7,14 @@
7
7
  * this file into the resolved version folder.
8
8
  */
9
9
 
10
- export default [];
10
+ import migrateCodeBlockTokenizerToLanguage, {
11
+ meta as migrateCodeBlockTokenizerToLanguageMeta,
12
+ } from './migrate-codeblock-tokenizer-to-language.mjs';
13
+
14
+ export default [
15
+ {
16
+ name: 'migrate-codeblock-tokenizer-to-language',
17
+ transform: migrateCodeBlockTokenizerToLanguage,
18
+ meta: migrateCodeBlockTokenizerToLanguageMeta,
19
+ },
20
+ ];