@astryxdesign/cli 0.7.5-canary.21631be → 0.7.5-canary.3dd95a0

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.
@@ -1,27 +1,47 @@
1
1
  // Copyright (c) Meta Platforms, Inc. and affiliates.
2
2
 
3
3
  /**
4
- * Find imported components, resolve their local JSX names (including aliases),
5
- * and yield matching JSX prop paths to a visitor.
4
+ * Find imported components, resolve their local names (including aliases and
5
+ * namespace members) at a use site, and yield matching JSX prop paths to a
6
+ * visitor.
6
7
  *
7
- * This helper intentionally stops at the JSX boundary. It does not follow
8
- * variables, helper calls, object spreads, wrapper components, or types.
9
- *
10
- * @param {any} root jscodeshift collection for one source file
11
- * @param {any} j configured jscodeshift instance
12
- * @param {{
8
+ * `transformProp` intentionally stops at the JSX boundary. It does not follow
9
+ * variables, helper calls, object spreads, wrapper components, or types. The
10
+ * resolver it is built on (`importedComponents`, `resolveImportedComponent`,
11
+ * `isModuleBinding`) is exported for transforms that prove other use sites.
12
+ */
13
+
14
+ /**
15
+ * @typedef {{
13
16
  * matchesImport: (source: string) => boolean,
14
17
  * components: ReadonlyMap<string, ReadonlySet<string>>,
15
18
  * normalizeComponentName?: (name: string) => string,
16
- * }} options
17
- * @param {(propPath: any, context: {component: string, localName: string}) => void} visit
19
+ * }} ImportOptions
18
20
  */
19
- export function transformProp(root, j, options, visit) {
21
+
22
+ /**
23
+ * @typedef {{
24
+ * direct: Map<string, {component: string, props: ReadonlySet<string>}>,
25
+ * namespaces: Set<string>,
26
+ * normalize: (name: string) => string,
27
+ * components: ReadonlyMap<string, ReadonlySet<string>>,
28
+ * }} ImportedComponents
29
+ */
30
+
31
+ /**
32
+ * Local names bound by accepted runtime imports: named, aliased and default
33
+ * component imports, and namespace imports.
34
+ * @param {any} root jscodeshift collection for one source file
35
+ * @param {any} j configured jscodeshift instance
36
+ * @param {ImportOptions} options
37
+ * @returns {ImportedComponents}
38
+ */
39
+ export function importedComponents(root, j, options) {
20
40
  const normalize = options.normalizeComponentName ?? (name => name);
21
- /** @type {Map<string, {component: string, props: ReadonlySet<string>}>} */
22
- const directBindings = new Map();
41
+ /** @type {ImportedComponents['direct']} */
42
+ const direct = new Map();
23
43
  /** @type {Set<string>} */
24
- const namespaceBindings = new Set();
44
+ const namespaces = new Set();
25
45
 
26
46
  root.find(j.ImportDeclaration).forEach((/** @type {any} */ importPath) => {
27
47
  const source = importPath.node.source.value;
@@ -46,53 +66,83 @@ export function transformProp(root, j, options, visit) {
46
66
  const component = normalize(importedName);
47
67
  const props = options.components.get(component);
48
68
  if (!props) continue;
49
- directBindings.set(specifier.local?.name ?? importedName, {
50
- component,
51
- props,
52
- });
69
+ direct.set(specifier.local?.name ?? importedName, {component, props});
53
70
  } else if (specifier.type === 'ImportDefaultSpecifier' && subpathProps) {
54
- directBindings.set(specifier.local.name, {
71
+ direct.set(specifier.local.name, {
55
72
  component: subpathName,
56
73
  props: subpathProps,
57
74
  });
58
75
  } else if (specifier.type === 'ImportNamespaceSpecifier') {
59
- namespaceBindings.add(specifier.local.name);
76
+ namespaces.add(specifier.local.name);
60
77
  }
61
78
  }
62
79
  });
63
80
 
64
- if (directBindings.size === 0 && namespaceBindings.size === 0) return;
81
+ return {direct, namespaces, normalize, components: options.components};
82
+ }
65
83
 
66
- root.find(j.JSXOpeningElement).forEach((/** @type {any} */ jsxPath) => {
67
- const name = jsxPath.node.name;
68
- let localName;
69
- let component;
70
- let props;
84
+ /**
85
+ * True when `localName` at `path` resolves to a module-scope binding. A
86
+ * parameter or local declaration with the same name shadows the import.
87
+ * @param {any} path any node path inside the file
88
+ * @param {string} localName
89
+ */
90
+ export function isModuleBinding(path, localName) {
91
+ return path.scope?.lookup(localName)?.path.node.type === 'Program';
92
+ }
71
93
 
72
- if (name.type === 'JSXIdentifier') {
73
- localName = name.name;
74
- const binding = directBindings.get(localName);
75
- if (!binding) return;
76
- ({component, props} = binding);
77
- } else if (
78
- name.type === 'JSXMemberExpression' &&
79
- name.object?.type === 'JSXIdentifier' &&
80
- name.property?.type === 'JSXIdentifier' &&
81
- namespaceBindings.has(name.object.name)
82
- ) {
83
- localName = name.object.name;
84
- component = normalize(name.property.name);
85
- props = options.components.get(component);
86
- if (!props) return;
87
- } else {
88
- return;
89
- }
94
+ /**
95
+ * Resolve a component reference (`Card`, `Lib.Card`, or their JSX forms) to
96
+ * the imported component it names at `scopePath`, or null.
97
+ * @param {any} nameNode Identifier, JSXIdentifier, MemberExpression, or JSXMemberExpression
98
+ * @param {any} scopePath the path whose scope the reference is evaluated in
99
+ * @param {ImportedComponents} imports
100
+ * @returns {{component: string, props: ReadonlySet<string>, localName: string} | null}
101
+ */
102
+ export function resolveImportedComponent(nameNode, scopePath, imports) {
103
+ let localName;
104
+ let binding;
105
+ if (nameNode?.type === 'JSXIdentifier' || nameNode?.type === 'Identifier') {
106
+ localName = nameNode.name;
107
+ binding = imports.direct.get(localName);
108
+ } else if (
109
+ (nameNode?.type === 'JSXMemberExpression' ||
110
+ (nameNode?.type === 'MemberExpression' && !nameNode.computed)) &&
111
+ (nameNode.object?.type === 'JSXIdentifier' ||
112
+ nameNode.object?.type === 'Identifier') &&
113
+ (nameNode.property?.type === 'JSXIdentifier' ||
114
+ nameNode.property?.type === 'Identifier') &&
115
+ imports.namespaces.has(nameNode.object.name)
116
+ ) {
117
+ localName = nameNode.object.name;
118
+ const component = imports.normalize(nameNode.property.name);
119
+ const props = imports.components.get(component);
120
+ if (props) binding = {component, props};
121
+ }
122
+ if (!binding || !isModuleBinding(scopePath, localName)) return null;
123
+ return {...binding, localName};
124
+ }
90
125
 
91
- // A parameter or local declaration with the imported name shadows the
92
- // module binding. Only JSX tags whose root binding resolves to Program are
93
- // considered usages of the import discovered above.
94
- const bindingScope = jsxPath.scope.lookup(localName);
95
- if (!bindingScope || bindingScope.path.node.type !== 'Program') return;
126
+ /**
127
+ * @param {any} root jscodeshift collection for one source file
128
+ * @param {any} j configured jscodeshift instance
129
+ * @param {ImportOptions} options
130
+ * @param {(propPath: any, context: {component: string, localName: string}) => void} visit
131
+ */
132
+ export function transformProp(root, j, options, visit) {
133
+ const imports = importedComponents(root, j, options);
134
+ if (imports.direct.size === 0 && imports.namespaces.size === 0) return;
135
+
136
+ root.find(j.JSXOpeningElement).forEach((/** @type {any} */ jsxPath) => {
137
+ // Only JSX tags whose root binding resolves to Program are usages of the
138
+ // import discovered above.
139
+ const resolved = resolveImportedComponent(
140
+ jsxPath.node.name,
141
+ jsxPath,
142
+ imports,
143
+ );
144
+ if (!resolved) return;
145
+ const {component, props, localName} = resolved;
96
146
 
97
147
  for (let index = 0; index < jsxPath.node.attributes.length; index++) {
98
148
  const attribute = jsxPath.node.attributes[index];
@@ -2,7 +2,11 @@
2
2
 
3
3
  import {describe, expect, it} from 'vitest';
4
4
  import jscodeshift from 'jscodeshift';
5
- import {transformProp} from './transform-prop.mjs';
5
+ import {
6
+ importedComponents,
7
+ resolveImportedComponent,
8
+ transformProp,
9
+ } from './transform-prop.mjs';
6
10
 
7
11
  const j = jscodeshift.withParser('tsx');
8
12
  const components = new Map([
@@ -92,4 +96,35 @@ const b = <Group tone="old" size="old" />;`);
92
96
  expect(output).toContain('<Widget size="old" migratedtone="old"');
93
97
  expect(output).toContain('<Group tone="old" migratedsize="old"');
94
98
  });
99
+
100
+ it('resolves non-JSX references through the same import and shadow rules', () => {
101
+ const root = j(`import {Widget as Card} from '@example/core';
102
+ import * as Lib from '@example/core';
103
+ const a = Card;
104
+ const b = Lib.Group;
105
+ function shadow(Card, Lib) {
106
+ return [Card, Lib.Group];
107
+ }`);
108
+ const imports = importedComponents(root, j, {
109
+ matchesImport: value => /^@example\/core(?:\/|$)/.test(value),
110
+ components,
111
+ });
112
+ const resolved = root
113
+ .find(j.VariableDeclarator)
114
+ .paths()
115
+ .map(
116
+ path =>
117
+ resolveImportedComponent(path.node.init, path, imports)?.component,
118
+ );
119
+ expect(resolved).toEqual(['Widget', 'Group']);
120
+ const shadowed = root
121
+ .find(j.ArrayExpression)
122
+ .paths()
123
+ .flatMap(path =>
124
+ path.node.elements.map(element =>
125
+ resolveImportedComponent(element, path, imports),
126
+ ),
127
+ );
128
+ expect(shadowed).toEqual([null, null]);
129
+ });
95
130
  });
@@ -1,6 +1,9 @@
1
1
  // Copyright (c) Meta Platforms, Inc. and affiliates.
2
2
 
3
- import {describe, expect, it} from 'vitest';
3
+ import * as fs from 'node:fs';
4
+ import * as os from 'node:os';
5
+ import * as path from 'node:path';
6
+ import {afterEach, describe, expect, it} from 'vitest';
4
7
  import jscodeshift from 'jscodeshift';
5
8
  import manifest from '../index.mjs';
6
9
  import transform, {
@@ -16,6 +19,38 @@ function apply(source, filePath = 'theme.ts') {
16
19
  return transform({source, path: filePath}, api) ?? source;
17
20
  }
18
21
 
22
+ /** A proven theme: an object passed to Astryx's imported defineTheme(). */
23
+ function defined(components) {
24
+ return `${IMPORT}export default defineTheme({name: 'brand', components: ${components}});`;
25
+ }
26
+
27
+ const THEME_DOC = `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */
28
+ export default {
29
+ type: 'theme',
30
+ name: 'brand',
31
+ displayName: 'Brand',
32
+ description: 'A brand theme.',
33
+ maintained: false,
34
+ };
35
+ `;
36
+
37
+ const tempDirs = [];
38
+ afterEach(() => {
39
+ for (const dir of tempDirs.splice(0)) {
40
+ fs.rmSync(dir, {recursive: true, force: true});
41
+ }
42
+ });
43
+
44
+ /** Write `files` into a fresh directory and return its path. */
45
+ function folder(files) {
46
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-theme-surface-'));
47
+ tempDirs.push(dir);
48
+ for (const [name, content] of Object.entries(files)) {
49
+ fs.writeFileSync(path.join(dir, name), content);
50
+ }
51
+ return dir;
52
+ }
53
+
19
54
  const EXPECTED_TARGETS = {
20
55
  'base-table': 'table',
21
56
  checkbox: 'checkbox-indicator',
@@ -60,7 +95,7 @@ describe('migrate-deprecated-theme-surface', () => {
60
95
  'renames static target key %s to %s inside a components map',
61
96
  (oldKey, newKey) => {
62
97
  const output = apply(
63
- `export default {name: 'brand', components: {${JSON.stringify(oldKey)}: {base: {color: 'red'}}}};`,
98
+ defined(`{${JSON.stringify(oldKey)}: {base: {color: 'red'}}}`),
64
99
  );
65
100
 
66
101
  expect(output).not.toContain(`${JSON.stringify(oldKey)}:`);
@@ -103,12 +138,114 @@ export const theme = defineTheme({name: 'brand', components});`);
103
138
  }
104
139
  });
105
140
 
141
+ it('does not rewrite a look-alike theme object from another library', () => {
142
+ const input = `export const muiTheme = {
143
+ name: 'brand',
144
+ components: {checkbox: {root: {color: 'red'}}, radio: {root: {}}, textarea: {root: {}}},
145
+ };`;
146
+ expect(apply(input, 'src/muiTheme.ts')).toBe(input);
147
+ });
148
+
149
+ it('does not take a file-level Astryx import as proof for a look-alike object', () => {
150
+ const input = `import {Button} from '@astryxdesign/core';
151
+ export const editorTheme = {name: 'editor', components: {textarea: {root: {}}}};`;
152
+ expect(apply(input, 'src/editorTheme.ts')).toBe(input);
153
+ });
154
+
155
+ it('renames a direct theme object in a source its theme descriptor declares', () => {
156
+ const dir = folder({'brandTheme.doc.mjs': THEME_DOC});
157
+ const output = apply(
158
+ `export const brandTheme = {name: 'brand', components: {navicon: {base: {}}}};`,
159
+ path.join(dir, 'brandTheme.ts'),
160
+ );
161
+ expect(output).toContain("'nav-icon':");
162
+ expect(output).not.toMatch(/navicon\s*:/);
163
+ });
164
+
165
+ it('renames only the declared theme binding in a described theme source', () => {
166
+ const dir = folder({'brandTheme.doc.mjs': THEME_DOC});
167
+ const output = apply(
168
+ `export const brandTheme = {name: 'brand', components: {navicon: {base: {}}}};
169
+ export const otherLibraryTheme = {
170
+ name: 'other',
171
+ components: {checkbox: {root: {}}, textarea: {root: {}}},
172
+ };`,
173
+ path.join(dir, 'brandTheme.ts'),
174
+ );
175
+ expect(output).toContain("'nav-icon':");
176
+ expect(output).toContain(
177
+ 'components: {checkbox: {root: {}}, textarea: {root: {}}}',
178
+ );
179
+ expect(output).not.toContain('checkbox-indicator');
180
+ expect(output).not.toContain('text-area');
181
+ });
182
+
183
+ it('follows a local binding exported under the descriptor name', () => {
184
+ const dir = folder({'brandTheme.doc.mjs': THEME_DOC});
185
+ const output = apply(
186
+ `const theme = {name: 'brand', components: {navicon: {base: {}}}} as const;
187
+ export {theme as brandTheme};`,
188
+ path.join(dir, 'brandTheme.ts'),
189
+ );
190
+ expect(output).toContain("'nav-icon':");
191
+ });
192
+
193
+ it('does not treat an unexported or nested same-named object as the declared theme', () => {
194
+ const dir = folder({'brandTheme.doc.mjs': THEME_DOC});
195
+ for (const input of [
196
+ `const brandTheme = {name: 'brand', components: {navicon: {base: {}}}};`,
197
+ `export function make() {
198
+ const brandTheme = {name: 'brand', components: {navicon: {base: {}}}};
199
+ return brandTheme;
200
+ }`,
201
+ ]) {
202
+ expect(apply(input, path.join(dir, 'brandTheme.ts'))).toBe(input);
203
+ }
204
+ });
205
+
206
+ it('does not treat a descriptor for another stem or kind as theme proof', () => {
207
+ const input = `export const brandTheme = {name: 'brand', components: {navicon: {base: {}}}};`;
208
+ const otherStem = folder({'otherTheme.doc.mjs': THEME_DOC});
209
+ expect(apply(input, path.join(otherStem, 'brandTheme.ts'))).toBe(input);
210
+ const otherKind = folder({
211
+ 'brandTheme.doc.mjs': 'export default {name: "brand", props: []};\n',
212
+ });
213
+ expect(apply(input, path.join(otherKind, 'brandTheme.ts'))).toBe(input);
214
+ });
215
+
106
216
  it('does not treat a defineTheme from another library as an Astryx theme', () => {
107
217
  const input = `import {defineTheme} from 'other-ui';
108
218
  export default defineTheme({components: {checkbox: {base: {color: 'red'}}}});`;
109
219
  expect(apply(input)).toBe(input);
110
220
  });
111
221
 
222
+ it.each([
223
+ [
224
+ 'named defineTheme',
225
+ `import {defineTheme} from '@astryxdesign/core';
226
+ function unrelated(defineTheme) {
227
+ return defineTheme({name: 'fake', components: {checkbox: {root: {}}}});
228
+ }`,
229
+ ],
230
+ [
231
+ 'aliased defineTheme',
232
+ `import {defineTheme as makeTheme} from '@astryxdesign/core';
233
+ function unrelated() {
234
+ const makeTheme = otherLibrary.createTheme;
235
+ return makeTheme({name: 'fake', components: {checkbox: {root: {}}}});
236
+ }`,
237
+ ],
238
+ [
239
+ 'namespace defineTheme',
240
+ `import * as Astryx from '@astryxdesign/core';
241
+ function unrelated(Astryx) {
242
+ return Astryx.defineTheme({name: 'fake', components: {checkbox: {root: {}}}});
243
+ }`,
244
+ ],
245
+ ])('does not treat a shadowed %s as an Astryx call', (_name, input) => {
246
+ expect(apply(input)).toBe(input);
247
+ });
248
+
112
249
  it.each([
113
250
  [
114
251
  'an aliased defineTheme import',
@@ -141,9 +278,54 @@ const brand: DefineThemeInput = {name: 'brand', components: {navicon: {base: {}}
141
278
  expect(output).not.toMatch(/navicon\s*:/);
142
279
  });
143
280
 
281
+ it.each([
282
+ [
283
+ 'a locally redeclared named type',
284
+ `import type {DefineThemeInput} from '@astryxdesign/core';
285
+ function unrelated() {
286
+ type DefineThemeInput = OtherTheme;
287
+ return {name: 'fake', components: {checkbox: {root: {}}}} satisfies DefineThemeInput;
288
+ }`,
289
+ ],
290
+ [
291
+ 'an aliased type shadowed by a type parameter',
292
+ `import type {DefineThemeInput as Theme} from '@astryxdesign/core';
293
+ function unrelated<Theme>(value: unknown) {
294
+ const theme: Theme = {name: 'fake', components: {checkbox: {root: {}}}};
295
+ return theme;
296
+ }`,
297
+ ],
298
+ [
299
+ 'a namespace shadowed by a type parameter',
300
+ `import type * as Astryx from '@astryxdesign/core';
301
+ function unrelated<Astryx>() {
302
+ return {name: 'fake', components: {checkbox: {root: {}}}} satisfies Astryx.DefineThemeInput;
303
+ }`,
304
+ ],
305
+ [
306
+ 'a namespace shadowed by a local namespace',
307
+ `import * as Astryx from '@astryxdesign/core';
308
+ function unrelated() {
309
+ namespace Astryx { export type DefineThemeInput = OtherTheme; }
310
+ return ({name: 'fake', components: {checkbox: {root: {}}}}) as Astryx.DefineThemeInput;
311
+ }`,
312
+ ],
313
+ ])('does not treat %s as an Astryx theme type', (_name, input) => {
314
+ expect(apply(input)).toBe(input);
315
+ });
316
+
317
+ it('still recognizes an unshadowed theme type inside a function', () => {
318
+ const output =
319
+ apply(`import type {DefineThemeInput} from '@astryxdesign/core';
320
+ function makeTheme<T>() {
321
+ return {components: {navicon: {base: {}}}} satisfies DefineThemeInput;
322
+ }`);
323
+ expect(output).toContain("'nav-icon':");
324
+ });
325
+
144
326
  it('renames a clear-icon alias with a TODO naming the owner scope it loses', () => {
145
327
  const output = apply(
146
- `export default {name: 'brand', components: {'selector-clear-icon': {base: {color: 'red'}}}};`,
328
+ defined(`{'selector-clear-icon': {base: {color: 'red'}}}`),
147
329
  );
148
330
  expect(output).toContain("'input-clear-icon':");
149
331
  expect(output).toContain(
@@ -155,10 +337,12 @@ const brand: DefineThemeInput = {name: 'brand', components: {navicon: {base: {}}
155
337
  });
156
338
 
157
339
  it('flags two clear-icon aliases that collapse onto the shared target', () => {
158
- const output = apply(`export default {name: 'brand', components: {
340
+ const output = apply(
341
+ defined(`{
159
342
  'selector-clear-icon': {base: {color: 'red'}},
160
343
  'date-input-clear-icon': {base: {color: 'blue'}},
161
- }};`);
344
+ }`),
345
+ );
162
346
  expect(output).toContain("'input-clear-icon':");
163
347
  expect(output).toContain(
164
348
  'merge deprecated theme target `date-input-clear-icon` into `input-clear-icon`',
@@ -312,7 +496,9 @@ const theme = {name: 'brand', components: {[oldTarget]: {base: {color: 'red'}}}}
312
496
  });
313
497
 
314
498
  it('is byte-idempotent after JavaScript and CSS migration', () => {
315
- const js = `export default {name: 'brand', components: {statusdot: {base: {color: 'red'}}, 'selector-clear-icon': {base: {color: 'red'}}}};`;
499
+ const js = defined(
500
+ `{statusdot: {base: {color: 'red'}}, 'selector-clear-icon': {base: {color: 'red'}}}`,
501
+ );
316
502
  const css = '.astryx-textarea.sm {}';
317
503
  const jsOnce = apply(js);
318
504
  const cssOnce = apply(css, 'theme.css');
@@ -5,19 +5,28 @@
5
5
  *
6
6
  * Static keys directly inside a theme's `components` object move to their
7
7
  * canonical target. A theme is a `defineTheme()` call imported from Astryx, an
8
- * object typed as an Astryx theme (annotation, `as`, or `satisfies`), or a
9
- * direct theme object with a static `name` whose component entries are style
10
- * objects. CSS selectors move the same target classes, keep the owner scope of
11
- * the per-component clear-icon aliases, and replace target-qualified bare
12
- * prop/state classes with reflected `data-*` selectors using the final 0.6
13
- * runtime contract. A known bare class that cannot be classified for its target
14
- * gets a TODO. Dynamic theme keys, unqualified classes, declarations, comments,
8
+ * object typed as an Astryx theme (annotation, `as`, or `satisfies`), or the
9
+ * direct theme object a same-stem theme descriptor (`<stem>.doc.mjs`) declares:
10
+ * the top-level binding exported as `<stem>`, with a static `name` and
11
+ * component entries that are style objects. Shape alone is not proof: a
12
+ * look-alike object anywhere else, including another object in the same theme
13
+ * source, is left unchanged. CSS selectors move the same target classes, keep
14
+ * the owner scope of the per-component clear-icon aliases, and replace
15
+ * target-qualified bare prop/state classes with reflected `data-*` selectors
16
+ * using the final 0.6 runtime contract. A known bare class that cannot be
17
+ * classified for its target gets a TODO. Dynamic theme keys, unqualified classes, declarations, comments,
15
18
  * and strings containing CSS are left for manual review.
16
19
  */
17
20
 
21
+ import * as fs from 'node:fs';
18
22
  import path from 'node:path';
19
23
  import postcss from 'postcss';
20
24
  import selectorParser from 'postcss-selector-parser';
25
+ import {readThemeDescriptorValue} from '../../../../foundation/discovery/theme-discovery.mjs';
26
+ import {
27
+ importedComponents,
28
+ resolveImportedComponent,
29
+ } from '../../transform-prop.mjs';
21
30
  import {migrateAstryxThemeSelectors} from '../v0.6.0/migrate-astryx-theme-selectors-to-data-attrs.mjs';
22
31
  import {
23
32
  V06_THEME_SELECTOR_DYNAMIC_AXES,
@@ -338,15 +347,88 @@ const TS_WRAPPERS = new Set([
338
347
  ]);
339
348
 
340
349
  /**
341
- * Local names that refer to Astryx's `defineTheme`, its theme types, or an
342
- * Astryx namespace import.
343
- * @param {any} root @param {any} j
350
+ * The export name a same-stem theme descriptor beside this file declares
351
+ * (`brandTheme` for `brandTheme.ts` beside `brandTheme.doc.mjs`), or null. The
352
+ * descriptor is read statically, never executed; an unreadable or non-theme
353
+ * descriptor is not proof.
354
+ * @param {string} filePath
355
+ * @returns {string | null}
356
+ */
357
+ function describedThemeExportName(filePath) {
358
+ const stem = path.basename(filePath, path.extname(filePath));
359
+ const docPath = path.join(path.dirname(filePath), `${stem}.doc.mjs`);
360
+ if (!fs.existsSync(docPath)) return null;
361
+ try {
362
+ return readThemeDescriptorValue(docPath, `Theme descriptor ${docPath}`)
363
+ .type === 'theme'
364
+ ? stem
365
+ : null;
366
+ } catch {
367
+ return null;
368
+ }
369
+ }
370
+
371
+ /**
372
+ * Top-level local names this module exports under `exportName`: an exported
373
+ * declaration of that name, or a source-less `export {local as exportName}`.
374
+ * @param {any} root @param {any} j @param {string} exportName
375
+ */
376
+ function localNamesExportedAs(root, j, exportName) {
377
+ /** @type {Set<string>} */
378
+ const locals = new Set();
379
+ root
380
+ .find(j.ExportNamedDeclaration)
381
+ .forEach((/** @type {any} */ exportPath) => {
382
+ const node = exportPath.node;
383
+ if (node.exportKind === 'type' || node.source) return;
384
+ for (const declarator of node.declaration?.declarations ?? []) {
385
+ if (declarator.id?.name === exportName) locals.add(exportName);
386
+ }
387
+ for (const specifier of node.specifiers ?? []) {
388
+ const exported = specifier.exported?.name ?? specifier.exported?.value;
389
+ const local = specifier.local?.name ?? specifier.local?.value;
390
+ if (
391
+ specifier.exportKind !== 'type' &&
392
+ exported === exportName &&
393
+ typeof local === 'string'
394
+ ) {
395
+ locals.add(local);
396
+ }
397
+ }
398
+ });
399
+ return locals;
400
+ }
401
+
402
+ /**
403
+ * Astryx's `defineTheme` imports (resolved at each call site, so a shadowing
404
+ * parameter or local never counts), its theme types, an Astryx namespace
405
+ * import, and the binding a theme descriptor declares.
406
+ * @param {any} root @param {any} j @param {string} filePath
344
407
  */
345
- function astryxThemeBindings(root, j) {
408
+ function astryxThemeBindings(root, j, filePath) {
409
+ /** @type {Set<string> | undefined} */
410
+ let describedLocals;
346
411
  const bindings = {
347
- defineTheme: new Set(),
412
+ defineTheme: importedComponents(root, j, {
413
+ matchesImport: source => ASTRYX_MODULE.test(source),
414
+ components: new Map([['defineTheme', new Set()]]),
415
+ }),
348
416
  themeTypes: new Set(),
349
417
  namespaces: new Set(),
418
+ /**
419
+ * Top-level locals exported under the descriptor's name. Read lazily:
420
+ * only a direct theme-shaped object needs the descriptor.
421
+ * @returns {Set<string>}
422
+ */
423
+ describedThemeLocals() {
424
+ if (describedLocals == null) {
425
+ const exportName = describedThemeExportName(filePath);
426
+ describedLocals = exportName
427
+ ? localNamesExportedAs(root, j, exportName)
428
+ : new Set();
429
+ }
430
+ return describedLocals;
431
+ },
350
432
  };
351
433
  root.find(j.ImportDeclaration).forEach((/** @type {any} */ importPath) => {
352
434
  const source = importPath.node.source?.value;
@@ -358,7 +440,6 @@ function astryxThemeBindings(root, j) {
358
440
  bindings.namespaces.add(local);
359
441
  } else if (specifier.type === 'ImportSpecifier') {
360
442
  const imported = specifier.imported?.name ?? specifier.imported?.value;
361
- if (imported === 'defineTheme') bindings.defineTheme.add(local);
362
443
  if (THEME_TYPE_NAMES.has(imported)) bindings.themeTypes.add(local);
363
444
  }
364
445
  }
@@ -379,20 +460,80 @@ function namesBinding(name, locals, namespaces, members) {
379
460
  );
380
461
  }
381
462
 
382
- /** @param {any} typeNode @param {ReturnType<typeof astryxThemeBindings>} bindings */
383
- function isAstryxThemeType(typeNode, bindings) {
463
+ /** @param {any} typeNode @param {any} usePath @param {ReturnType<typeof astryxThemeBindings>} bindings */
464
+ function isAstryxThemeType(typeNode, usePath, bindings) {
384
465
  const node = typeNode?.typeAnnotation ?? typeNode;
385
- return (
386
- node?.type === 'TSTypeReference' &&
387
- namesBinding(
466
+ if (
467
+ node?.type !== 'TSTypeReference' ||
468
+ !namesBinding(
388
469
  node.typeName,
389
470
  bindings.themeTypes,
390
471
  bindings.namespaces,
391
472
  THEME_TYPE_NAMES,
392
473
  )
474
+ ) {
475
+ return false;
476
+ }
477
+ const root =
478
+ node.typeName.type === 'Identifier' ? node.typeName : node.typeName.left;
479
+ return isModuleTypeBinding(usePath, root.name);
480
+ }
481
+
482
+ /** @param {any} statement @param {string} name */
483
+ function statementDeclares(statement, name) {
484
+ const node =
485
+ statement?.type === 'ExportNamedDeclaration' ||
486
+ statement?.type === 'ExportDefaultDeclaration'
487
+ ? statement.declaration
488
+ : statement;
489
+ if (node?.id?.type === 'Identifier' && node.id.name === name) return true;
490
+ return (node?.declarations ?? []).some(
491
+ (/** @type {any} */ declarator) =>
492
+ declarator.id?.type === 'Identifier' && declarator.id.name === name,
393
493
  );
394
494
  }
395
495
 
496
+ /**
497
+ * True when a type-position `name` at `path` can only mean the module-scope
498
+ * import: no enclosing type parameter, parameter, or block-level declaration
499
+ * (type alias, interface, enum, class, namespace, function, or variable)
500
+ * reuses the name. Anything this cannot rule out counts as shadowed.
501
+ * @param {any} path @param {string} name
502
+ */
503
+ function isModuleTypeBinding(path, name) {
504
+ const valueScope = path.scope?.lookup(name);
505
+ if (valueScope != null && valueScope.path.node.type !== 'Program') {
506
+ return false;
507
+ }
508
+ for (let current = path; current != null; current = current.parent) {
509
+ const node = current.node;
510
+ if (node.type === 'Program') return true;
511
+ const typeParameters = node.typeParameters?.params ?? [];
512
+ if (
513
+ typeParameters.some(
514
+ (/** @type {any} */ parameter) =>
515
+ (parameter.name?.name ?? parameter.name) === name,
516
+ )
517
+ ) {
518
+ return false;
519
+ }
520
+ const statements =
521
+ node.type === 'SwitchCase'
522
+ ? node.consequent
523
+ : node.type !== 'ClassBody' && Array.isArray(node.body)
524
+ ? node.body
525
+ : [];
526
+ if (
527
+ statements.some((/** @type {any} */ statement) =>
528
+ statementDeclares(statement, name),
529
+ )
530
+ ) {
531
+ return false;
532
+ }
533
+ }
534
+ return false;
535
+ }
536
+
396
537
  /**
397
538
  * True for a theme object whose shape alone identifies it: a static string
398
539
  * `name` beside a `components` map whose entries are all style objects.
@@ -426,16 +567,45 @@ function isDirectThemeObject(node) {
426
567
  );
427
568
  }
428
569
 
570
+ /**
571
+ * True when this object literal initializes the top-level binding that the
572
+ * file's theme descriptor declares, directly or through TypeScript wrappers.
573
+ * @param {any} objectPath @param {ReturnType<typeof astryxThemeBindings>} bindings
574
+ */
575
+ function isDescribedThemeBinding(objectPath, bindings) {
576
+ let parent = objectPath.parent;
577
+ while (parent != null && TS_WRAPPERS.has(parent.node.type)) {
578
+ parent = parent.parent;
579
+ }
580
+ const declarator = parent?.node;
581
+ if (
582
+ declarator?.type !== 'VariableDeclarator' ||
583
+ declarator.id?.type !== 'Identifier'
584
+ ) {
585
+ return false;
586
+ }
587
+ const declaration = parent.parent;
588
+ const container = declaration?.parent?.node;
589
+ const topLevel =
590
+ container?.type === 'Program' ||
591
+ (container?.type === 'ExportNamedDeclaration' &&
592
+ declaration.parent.parent?.node.type === 'Program');
593
+ return topLevel && bindings.describedThemeLocals().has(declarator.id.name);
594
+ }
595
+
429
596
  /**
430
597
  * True when this object literal is an Astryx theme: the argument of an
431
- * imported `defineTheme()`, typed as an Astryx theme, or a direct theme object.
598
+ * imported `defineTheme()`, typed as an Astryx theme, or the direct theme
599
+ * object a theme descriptor declares.
432
600
  * @param {any} objectPath @param {ReturnType<typeof astryxThemeBindings>} bindings
433
601
  */
434
602
  function isThemeRoot(objectPath, bindings) {
435
603
  let child = objectPath;
436
604
  let parent = objectPath.parent;
437
605
  while (parent != null && TS_WRAPPERS.has(parent.node.type)) {
438
- if (isAstryxThemeType(parent.node.typeAnnotation, bindings)) return true;
606
+ if (isAstryxThemeType(parent.node.typeAnnotation, parent, bindings)) {
607
+ return true;
608
+ }
439
609
  child = parent;
440
610
  parent = parent.parent;
441
611
  }
@@ -443,22 +613,20 @@ function isThemeRoot(objectPath, bindings) {
443
613
  if (
444
614
  node?.type === 'CallExpression' &&
445
615
  node.arguments?.[0] === child.node &&
446
- namesBinding(
447
- node.callee,
448
- bindings.defineTheme,
449
- bindings.namespaces,
450
- new Set(['defineTheme']),
451
- )
616
+ resolveImportedComponent(node.callee, parent, bindings.defineTheme)
452
617
  ) {
453
618
  return true;
454
619
  }
455
620
  if (
456
621
  node?.type === 'VariableDeclarator' &&
457
- isAstryxThemeType(node.id?.typeAnnotation, bindings)
622
+ isAstryxThemeType(node.id?.typeAnnotation, parent, bindings)
458
623
  ) {
459
624
  return true;
460
625
  }
461
- return isDirectThemeObject(objectPath.node);
626
+ return (
627
+ isDirectThemeObject(objectPath.node) &&
628
+ isDescribedThemeBinding(objectPath, bindings)
629
+ );
462
630
  }
463
631
 
464
632
  /**
@@ -567,10 +735,10 @@ function addScopeTodo(property, oldKey, owner, j) {
567
735
  ];
568
736
  }
569
737
 
570
- /** @param {string} source @param {any} j */
571
- function migrateStaticThemeKeys(source, j) {
738
+ /** @param {string} source @param {string} filePath @param {any} j */
739
+ function migrateStaticThemeKeys(source, filePath, j) {
572
740
  const root = j(source);
573
- const bindings = astryxThemeBindings(root, j);
741
+ const bindings = astryxThemeBindings(root, j, filePath);
574
742
  let changed = false;
575
743
 
576
744
  root.find(j.ObjectExpression).forEach((/** @type {any} */ objectPath) => {
@@ -620,5 +788,5 @@ export default function migrateDeprecatedThemeSurface(file, api) {
620
788
  const result = migrateCss(file.source, file.path);
621
789
  return result === file.source ? undefined : result;
622
790
  }
623
- return migrateStaticThemeKeys(file.source, api.jscodeshift);
791
+ return migrateStaticThemeKeys(file.source, file.path, api.jscodeshift);
624
792
  }
@@ -142,7 +142,7 @@ const overrides = stylex.create({
142
142
  },
143
143
  {
144
144
  type: 'prose',
145
- text: 'The upgrade treats a `components` map as a theme when it belongs to a `defineTheme()` call imported from Astryx, an object typed as an Astryx theme, or a theme object with a static `name` whose component entries are style objects. It leaves computed theme keys, unqualified classes, unknown consumer classes, declarations, comments, and CSS inside JavaScript or TypeScript strings unchanged. It adds `TODO(astryx upgrade)` when a map has both an old and a canonical key, and when a bare class Astryx once emitted has no known meaning on the target it qualifies. Review each TODO by hand.',
145
+ text: 'The upgrade treats a `components` map as a theme when it belongs to a `defineTheme()` call imported from Astryx, an object typed as an Astryx theme, or the theme object a same-stem theme descriptor (`<stem>.doc.mjs`) declares: the top-level binding exported as `<stem>`, with a static `name` and component entries that are style objects. A look-alike object anywhere else, such as a theme object from another library in the same file, is not an Astryx theme. It leaves computed theme keys, unqualified classes, unknown consumer classes, declarations, comments, and CSS inside JavaScript or TypeScript strings unchanged. It adds `TODO(astryx upgrade)` when a map has both an old and a canonical key, and when a bare class Astryx once emitted has no known meaning on the target it qualifies. Review each TODO by hand.',
146
146
  },
147
147
  ],
148
148
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astryxdesign/cli",
3
- "version": "0.7.5-canary.21631be",
3
+ "version": "0.7.5-canary.3dd95a0",
4
4
  "displayName": "CLI",
5
5
  "description": "Scaffold projects, browse templates, generate themes, and get agent-ready docs from the command line.",
6
6
  "author": "Meta Open Source",
@@ -111,10 +111,10 @@
111
111
  "zod": "^4.4.3"
112
112
  },
113
113
  "peerDependencies": {
114
- "@astryxdesign/charts": "0.7.5-canary.21631be",
115
- "@astryxdesign/core": "0.7.5-canary.21631be",
116
- "@astryxdesign/lab": "0.7.5-canary.21631be",
117
- "@astryxdesign/theme-neutral": "0.7.5-canary.21631be"
114
+ "@astryxdesign/charts": "0.7.5-canary.3dd95a0",
115
+ "@astryxdesign/core": "0.7.5-canary.3dd95a0",
116
+ "@astryxdesign/lab": "0.7.5-canary.3dd95a0",
117
+ "@astryxdesign/theme-neutral": "0.7.5-canary.3dd95a0"
118
118
  },
119
119
  "peerDependenciesMeta": {
120
120
  "@astryxdesign/charts": {
@@ -131,10 +131,10 @@
131
131
  }
132
132
  },
133
133
  "devDependencies": {
134
- "@astryxdesign/charts": "0.7.5-canary.21631be",
135
- "@astryxdesign/core": "0.7.5-canary.21631be",
136
- "@astryxdesign/lab": "0.7.5-canary.21631be",
137
- "@astryxdesign/theme-neutral": "0.7.5-canary.21631be",
134
+ "@astryxdesign/charts": "0.7.5-canary.3dd95a0",
135
+ "@astryxdesign/core": "0.7.5-canary.3dd95a0",
136
+ "@astryxdesign/lab": "0.7.5-canary.3dd95a0",
137
+ "@astryxdesign/theme-neutral": "0.7.5-canary.3dd95a0",
138
138
  "@heroicons/react": "^2.2.0",
139
139
  "@stylexjs/stylex": "^0.19.0",
140
140
  "@types/babel__core": "^7.20.5",