@astryxdesign/cli 0.7.6-canary.fdabeba → 0.7.6

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 (37) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +2 -2
  3. package/api/component/detail/showcase/showcase.mjs +9 -3
  4. package/api/search/_adapter.d.mts +3 -1
  5. package/api/search/_adapter.mjs +19 -19
  6. package/api/template/copy/copy.mjs +13 -7
  7. package/api/template/show/show.mjs +12 -8
  8. package/api/template/skeleton/skeleton.mjs +14 -5
  9. package/api/template/template.d.mts +1 -1
  10. package/api/template/template.doc.mjs +2 -2
  11. package/api/template/template.mjs +1 -0
  12. package/api/template/template.type.d.mts +2 -0
  13. package/api/template/template.type.mjs +2 -0
  14. package/assets/docs/motion.doc.mjs +1 -1
  15. package/assets/templates/blocks/components/BottomSheet/BottomSheetShowcase.doc.mjs +1 -1
  16. package/assets/templates/blocks/components/BottomSheet/BottomSheetShowcase.tsx +12 -12
  17. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.doc.mjs +1 -1
  18. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.tsx +14 -10
  19. package/assets/templates/blocks/components/Hooks/useCollatorHookUsage.doc.mjs +20 -0
  20. package/assets/templates/blocks/components/Hooks/useCollatorHookUsage.tsx +55 -0
  21. package/assets/templates/blocks/components/Hooks/usePressFeedbackHookUsage.doc.mjs +14 -0
  22. package/assets/templates/blocks/components/Hooks/usePressFeedbackHookUsage.tsx +41 -0
  23. package/assets/templates/blocks/components/Hooks/useTranslatorHookUsage.doc.mjs +22 -0
  24. package/assets/templates/blocks/components/Hooks/useTranslatorHookUsage.tsx +88 -0
  25. package/assets/templates/blocks/components/Toast/useToastHookUsage.doc.mjs +14 -0
  26. package/assets/templates/blocks/components/Toast/useToastHookUsage.tsx +65 -0
  27. package/clients/cli/commands/template.mjs +29 -3
  28. package/foundation/discovery/package-tsconfig.mjs +34 -0
  29. package/foundation/discovery/template-adapter.d.mts +76 -1
  30. package/foundation/discovery/template-adapter.mjs +418 -13
  31. package/foundation/discovery/template-icons.mjs +7 -89
  32. package/foundation/discovery/template-source-tree.d.mts +48 -0
  33. package/foundation/discovery/template-source-tree.mjs +159 -0
  34. package/foundation/fs/read-record.d.mts +4 -1
  35. package/foundation/fs/read-record.mjs +9 -5
  36. package/foundation/response/response-types.doc.mjs +2 -2
  37. package/package.json +10 -9
@@ -30,6 +30,13 @@ import {importDocModule} from '../doc-compiler/import.mjs';
30
30
  import {CLI_ROOT, discoverExternalPackages} from '../fs/paths.mjs';
31
31
  import {CORE_PROVIDER_ID} from '../identity/providers.mjs';
32
32
  import {Project} from '../config/project.mjs';
33
+ import {
34
+ isReference,
35
+ parseTemplateSource,
36
+ programPath,
37
+ traverseTemplateSource,
38
+ writtenNames,
39
+ } from './template-source-tree.mjs';
33
40
 
34
41
  const require = createRequire(import.meta.url);
35
42
 
@@ -233,6 +240,14 @@ const PLACEHOLDER_IMAGE =
233
240
  */
234
241
  const VIDEO_EXTENSIONS = new Set(['mp4', 'webm', 'mov', 'ogv', 'm4v']);
235
242
 
243
+ /**
244
+ * A video placeholder that names itself in the source, for a copy that has no
245
+ * response to disclose the replacement in, such as the shadcn install. It is a
246
+ * text data URL: it makes no request, it does not play, and it is not image
247
+ * data, so a video element never receives image bytes.
248
+ */
249
+ export const MARKED_VIDEO_PLACEHOLDER = 'data:,placeholder-video-add-your-own';
250
+
236
251
  const IMAGE_EXTENSIONS = new Set([
237
252
  'svg',
238
253
  'png',
@@ -334,9 +349,11 @@ export function stripTemplateAssetRefs(source) {
334
349
  * third-party URL left as written. That count is what a receipt discloses.
335
350
  *
336
351
  * @param {string} source - Template source code.
352
+ * @param {{videoPlaceholder?: string}} [options] - `videoPlaceholder` replaces
353
+ * each video reference; the default is an empty source.
337
354
  * @returns {{source: string, demoMediaReplaced: number}}
338
355
  */
339
- export function replaceDemoMedia(source) {
356
+ export function replaceDemoMedia(source, {videoPlaceholder = ''} = {}) {
340
357
  const needle = `/${FIXTURE_SEGMENT}`;
341
358
  let output = '';
342
359
  let copied = 0;
@@ -352,7 +369,7 @@ export function replaceDemoMedia(source) {
352
369
  /** @type {{text: string, end: number} | null} */
353
370
  let edit;
354
371
  try {
355
- edit = fixtureEdit(source, start, at, end);
372
+ edit = fixtureEdit(source, start, at, end, videoPlaceholder);
356
373
  } catch (err) {
357
374
  comments ??= commentRanges(source);
358
375
  if (!comments.some(([from, to]) => from <= at && at < to)) throw err;
@@ -368,6 +385,359 @@ export function replaceDemoMedia(source) {
368
385
  return {source: output + source.slice(copied), demoMediaReplaced};
369
386
  }
370
387
 
388
+ /**
389
+ * The one module docs-only demo content is imported from. A template imports
390
+ * an element such as a playing card's face from here so its live preview shows
391
+ * real-looking content; the module exists only where Astryx's own previews
392
+ * build templates, so a copy replaces every element imported from it (see
393
+ * {@link replaceDemoContent}).
394
+ */
395
+ export const DEMO_CONTENT_MODULE = '@astryx-docs/demo-content';
396
+
397
+ /** What a demo-content element becomes in emitted source. */
398
+ const DEMO_CONTENT_PLACEHOLDER_TEXT = 'Card content';
399
+
400
+ /** Where emitted placeholders import Text from, as catalog templates do. */
401
+ const TEXT_MODULE = '@astryxdesign/core/Text';
402
+
403
+ /** The modules an existing Astryx Text import can come from. */
404
+ const TEXT_MODULES = new Set([TEXT_MODULE, '@astryxdesign/core']);
405
+
406
+ /** The local name a new Text import takes when the file already writes `Text`. */
407
+ const TEXT_ALIAS = 'AstryxText';
408
+
409
+ /**
410
+ * Replace each JSX element imported from {@link DEMO_CONTENT_MODULE} with a
411
+ * generic `<Text>` placeholder and remove that import, so emitted source never
412
+ * depends on content only Astryx's previews provide.
413
+ *
414
+ * Every check resolves a name to its binding through the module's scope, so a
415
+ * local declaration or parameter with the same name never counts as the same
416
+ * variable. The placeholder uses an existing Text import from Astryx when that
417
+ * import is the binding its name resolves to at every replaced element. Else
418
+ * the placeholder imports Text, under a unique alias when the file already
419
+ * writes the name `Text`.
420
+ *
421
+ * Only a plain static use is replaced: a named import used only as a JSX tag
422
+ * whose children, if any, are whitespace, and whose props are literal values or
423
+ * read only bindings that code outside the replaced elements still reads. So
424
+ * `faceDown={!isOpen}` is safe when the same `isOpen` is also read elsewhere.
425
+ * Anything else (a namespace or type import, a re-export, a dynamic import, the
426
+ * element used as a value or a type, a spread or computed prop, a prop whose
427
+ * binding nothing else reads, children) throws, naming the element, rather than
428
+ * leaving a reference behind, leaving a binding unused, or dropping code the
429
+ * rest of the file relies on. Source that never names the module is returned
430
+ * as is.
431
+ *
432
+ * @param {string} source - Template source code.
433
+ * @returns {{source: string, demoContentReplaced: number}}
434
+ */
435
+ export function replaceDemoContent(source) {
436
+ if (!source.includes(DEMO_CONTENT_MODULE)) {
437
+ return {source, demoContentReplaced: 0};
438
+ }
439
+ /** @type {any} */
440
+ let file;
441
+ try {
442
+ file = parseTemplateSource(source);
443
+ } catch (err) {
444
+ throw unsafeDemoContent(
445
+ `the source does not parse (${/** @type {Error} */ (err).message})`,
446
+ );
447
+ }
448
+
449
+ /** @type {any[]} */
450
+ const demoImports = [];
451
+ for (const statement of file.program.body) {
452
+ if (
453
+ statement.type !== 'ImportDeclaration' ||
454
+ statement.source.value !== DEMO_CONTENT_MODULE
455
+ ) {
456
+ continue;
457
+ }
458
+ if (statement.importKind === 'type') {
459
+ throw unsafeDemoContent('it is imported as a type');
460
+ }
461
+ for (const specifier of statement.specifiers) {
462
+ if (
463
+ specifier.type !== 'ImportSpecifier' ||
464
+ specifier.importKind === 'type'
465
+ ) {
466
+ throw unsafeDemoContent(
467
+ 'only named value imports can be replaced; import each element by name',
468
+ );
469
+ }
470
+ }
471
+ demoImports.push(statement);
472
+ }
473
+
474
+ const program = programPath(file);
475
+ const demoBindings = new Set(
476
+ demoImports.flatMap(statement =>
477
+ statement.specifiers.map((/** @type {any} */ specifier) =>
478
+ program.scope.getBinding(specifier.local.name),
479
+ ),
480
+ ),
481
+ );
482
+ /** The paths of the JSX elements to replace. */
483
+ /** @type {any[]} */
484
+ const elements = [];
485
+ traverseTemplateSource(file, {
486
+ StringLiteral(/** @type {any} */ path) {
487
+ if (
488
+ path.node.value === DEMO_CONTENT_MODULE &&
489
+ !(path.parentPath.isImportDeclaration() && path.key === 'source')
490
+ ) {
491
+ throw unsafeDemoContent(
492
+ 'it is used outside a static import (a re-export, dynamic import, require, or string value)',
493
+ );
494
+ }
495
+ },
496
+ TemplateLiteral(/** @type {any} */ path) {
497
+ if (
498
+ path.node.quasis.some((/** @type {any} */ quasi) =>
499
+ quasi.value.cooked?.includes(DEMO_CONTENT_MODULE),
500
+ )
501
+ ) {
502
+ throw unsafeDemoContent('it is used outside a static import');
503
+ }
504
+ },
505
+ 'Identifier|JSXIdentifier'(/** @type {any} */ path) {
506
+ const {node, parentPath} = path;
507
+ if (!demoBindings.has(path.scope.getBinding(node.name))) return;
508
+ if (!isReference(node, path.parent, path.listKey ?? path.key)) return;
509
+ if (path.key === 'name' && parentPath.isJSXOpeningElement()) {
510
+ elements.push(parentPath.parentPath);
511
+ return;
512
+ }
513
+ if (path.key === 'name' && parentPath.isJSXClosingElement()) return;
514
+ if (parentPath.isJSXMemberExpression()) {
515
+ throw unsafeDemoContent(`${node.name} is used as a namespace`);
516
+ }
517
+ throw unsafeDemoContent(
518
+ `${node.name} is used as a value, not only as a JSX element`,
519
+ );
520
+ },
521
+ });
522
+
523
+ /** @param {any} node */
524
+ const isReplaced = node =>
525
+ elements.some(
526
+ element =>
527
+ element.node.start <= node.start && node.end <= element.node.end,
528
+ );
529
+ for (const element of elements) {
530
+ for (const variable of assertStaticDemoElement(element.node)) {
531
+ const binding = element.scope.getBinding(variable);
532
+ // An unbound name is a global: removing its read leaves nothing unused.
533
+ if (!binding || isExportedDeclaration(binding)) continue;
534
+ if (
535
+ binding.referencePaths.every((/** @type {any} */ ref) =>
536
+ isReplaced(ref.node),
537
+ )
538
+ ) {
539
+ throw unsafeDemoContent(
540
+ `<${element.node.openingElement.name.name}> reads ${variable}, and nothing else in the file reads it, so the copy would leave it unused`,
541
+ );
542
+ }
543
+ }
544
+ }
545
+
546
+ const reused =
547
+ elements.length === 0 ? null : astryxTextAtEvery(file, program, elements);
548
+ const written = writtenNames(file);
549
+ const textName =
550
+ reused ?? (written.has('Text') ? uniqueName(TEXT_ALIAS, written) : 'Text');
551
+ const textImport =
552
+ elements.length > 0 && reused === null
553
+ ? `import {${textName === 'Text' ? 'Text' : `Text as ${textName}`}} from '${TEXT_MODULE}';\n`
554
+ : '';
555
+ const placeholder = `<${textName}>${DEMO_CONTENT_PLACEHOLDER_TEXT}</${textName}>`;
556
+
557
+ /** @type {Array<{start: number, end: number, text: string}>} */
558
+ const edits = elements.map(element => ({
559
+ start: element.node.start,
560
+ end: element.node.end,
561
+ text: placeholder,
562
+ }));
563
+ demoImports.forEach((statement, index) => {
564
+ let end = statement.end;
565
+ if (source[end] === '\n') end += 1;
566
+ edits.push({
567
+ start: statement.start,
568
+ end,
569
+ text: index === 0 ? textImport : '',
570
+ });
571
+ });
572
+ edits.sort((a, b) => b.start - a.start);
573
+ let output = source;
574
+ for (const edit of edits) {
575
+ output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);
576
+ }
577
+ return {source: output, demoContentReplaced: elements.length};
578
+ }
579
+
580
+ /**
581
+ * The local name of an Astryx Text import that is the binding its name
582
+ * resolves to at every element, or null when no such import exists.
583
+ * @param {any} file
584
+ * @param {any} program - The program path, from {@link programPath}.
585
+ * @param {any[]} elements - Element paths.
586
+ * @returns {string | null}
587
+ */
588
+ function astryxTextAtEvery(file, program, elements) {
589
+ for (const statement of file.program.body) {
590
+ if (
591
+ statement.type !== 'ImportDeclaration' ||
592
+ statement.importKind === 'type' ||
593
+ !TEXT_MODULES.has(statement.source.value)
594
+ ) {
595
+ continue;
596
+ }
597
+ for (const specifier of statement.specifiers) {
598
+ if (
599
+ specifier.type !== 'ImportSpecifier' ||
600
+ specifier.importKind === 'type' ||
601
+ (specifier.imported.name ?? specifier.imported.value) !== 'Text'
602
+ ) {
603
+ continue;
604
+ }
605
+ const name = specifier.local.name;
606
+ const imported = program.scope.getBinding(name);
607
+ if (
608
+ elements.every(element => element.scope.getBinding(name) === imported)
609
+ ) {
610
+ return name;
611
+ }
612
+ }
613
+ }
614
+ return null;
615
+ }
616
+
617
+ /**
618
+ * Whether a binding is declared in an export, so code outside the file can
619
+ * still read it.
620
+ * @param {any} binding
621
+ */
622
+ function isExportedDeclaration(binding) {
623
+ const declaration = binding.path.isVariableDeclarator()
624
+ ? binding.path.parentPath
625
+ : binding.path;
626
+ return Boolean(declaration.parentPath?.isExportDeclaration());
627
+ }
628
+
629
+ /**
630
+ * `base`, or `base` with the first number from 2 that makes it a name the
631
+ * file does not write.
632
+ * @param {string} base
633
+ * @param {Set<string>} written
634
+ */
635
+ function uniqueName(base, written) {
636
+ let name = base;
637
+ for (let n = 2; written.has(name); n++) name = `${base}${n}`;
638
+ return name;
639
+ }
640
+
641
+ /**
642
+ * Throw unless a demo-content element can be replaced without dropping code:
643
+ * each prop a literal or a read of variables (see {@link isVariableRead}), and
644
+ * no children but whitespace.
645
+ * @param {any} element
646
+ * @returns {string[]} The variables its props read.
647
+ */
648
+ function assertStaticDemoElement(element) {
649
+ const name = element.openingElement.name.name;
650
+ /** @type {string[]} */
651
+ const variables = [];
652
+ for (const attribute of element.openingElement.attributes) {
653
+ if (attribute.type === 'JSXSpreadAttribute') {
654
+ throw unsafeDemoContent(`<${name}> spreads props`);
655
+ }
656
+ const value = attribute.value;
657
+ if (value === null || value.type === 'StringLiteral') continue;
658
+ if (
659
+ value.type === 'JSXExpressionContainer' &&
660
+ (isLiteralExpression(value.expression) ||
661
+ isVariableRead(value.expression, variables))
662
+ ) {
663
+ continue;
664
+ }
665
+ throw unsafeDemoContent(
666
+ `<${name}> prop ${attribute.name.name ?? ''} is not a literal value or a variable read`,
667
+ );
668
+ }
669
+ for (const child of element.children) {
670
+ if (child.type === 'JSXText' && child.value.trim() === '') continue;
671
+ throw unsafeDemoContent(`<${name}> has children`);
672
+ }
673
+ return variables;
674
+ }
675
+
676
+ /**
677
+ * Whether an expression only reads variables: a variable, a non-computed
678
+ * property of one, or its negation. Removing such a read runs no code. Adds
679
+ * each variable it reads to `variables`.
680
+ * @param {any} node
681
+ * @param {string[]} variables
682
+ * @returns {boolean}
683
+ */
684
+ function isVariableRead(node, variables) {
685
+ switch (node.type) {
686
+ case 'Identifier':
687
+ variables.push(node.name);
688
+ return true;
689
+ case 'MemberExpression':
690
+ return !node.computed && isVariableRead(node.object, variables);
691
+ case 'UnaryExpression':
692
+ return node.operator === '!' && isVariableRead(node.argument, variables);
693
+ default:
694
+ return false;
695
+ }
696
+ }
697
+
698
+ /** @param {any} node */
699
+ function isLiteralExpression(node) {
700
+ switch (node.type) {
701
+ case 'StringLiteral':
702
+ case 'NumericLiteral':
703
+ case 'BooleanLiteral':
704
+ case 'NullLiteral':
705
+ return true;
706
+ case 'TemplateLiteral':
707
+ return node.expressions.length === 0;
708
+ case 'UnaryExpression':
709
+ return node.operator === '-' && node.argument.type === 'NumericLiteral';
710
+ default:
711
+ return false;
712
+ }
713
+ }
714
+
715
+ /** @param {string} reason */
716
+ function unsafeDemoContent(reason) {
717
+ return new Error(
718
+ `Demo content from ${DEMO_CONTENT_MODULE} cannot be replaced safely: ${reason}. Use each element as a JSX tag with no children, and give each prop a literal or a variable the file also reads elsewhere.`,
719
+ );
720
+ }
721
+
722
+ /**
723
+ * Replace everything in a template that only Astryx's previews provide, in
724
+ * the order a copy applies it: demo-content elements
725
+ * ({@link replaceDemoContent}), then demo media ({@link replaceDemoMedia}).
726
+ * Both counts are what a receipt discloses.
727
+ *
728
+ * @param {string} source - Template source code.
729
+ * @param {{videoPlaceholder?: string}} [options] - As {@link replaceDemoMedia}.
730
+ * @returns {{source: string, demoContentReplaced: number, demoMediaReplaced: number}}
731
+ */
732
+ export function replaceTemplateDemos(source, options) {
733
+ const {source: withContent, demoContentReplaced} = replaceDemoContent(source);
734
+ const {source: output, demoMediaReplaced} = replaceDemoMedia(
735
+ withContent,
736
+ options,
737
+ );
738
+ return {source: output, demoContentReplaced, demoMediaReplaced};
739
+ }
740
+
371
741
  /** @param {string | undefined} char */
372
742
  function isTokenDelimiter(char) {
373
743
  return char === undefined || /\s/u.test(char) || TOKEN_DELIMITERS.has(char);
@@ -402,9 +772,10 @@ function fixtureSegments(reference) {
402
772
  * @param {number} start
403
773
  * @param {number} at
404
774
  * @param {number} end
775
+ * @param {string} videoPlaceholder
405
776
  * @returns {{text: string, end: number} | null}
406
777
  */
407
- function fixtureEdit(source, start, at, end) {
778
+ function fixtureEdit(source, start, at, end, videoPlaceholder) {
408
779
  const token = source.slice(start, end);
409
780
  if (ABSOLUTE_URL.test(token)) return null;
410
781
  if (!token.startsWith('/')) {
@@ -472,7 +843,9 @@ function fixtureEdit(source, start, at, end) {
472
843
  .extname(segments[segments.length - 1])
473
844
  .slice(1)
474
845
  .toLowerCase();
475
- if (VIDEO_EXTENSIONS.has(ext)) return {text: '', end: referenceEnd};
846
+ if (VIDEO_EXTENSIONS.has(ext)) {
847
+ return {text: videoPlaceholder, end: referenceEnd};
848
+ }
476
849
  if (IMAGE_EXTENSIONS.has(ext)) {
477
850
  return {text: PLACEHOLDER_IMAGE, end: referenceEnd};
478
851
  }
@@ -1460,6 +1833,9 @@ export async function findShowcase(componentName, cwd, options) {
1460
1833
  return null;
1461
1834
  }
1462
1835
 
1836
+ /** The npm scope of every Astryx package. */
1837
+ const ASTRYX_PACKAGE_SCOPE = '@astryxdesign/';
1838
+
1463
1839
  const UBIQUITOUS = new Set([
1464
1840
  'Text',
1465
1841
  'Heading',
@@ -1472,16 +1848,21 @@ const UBIQUITOUS = new Set([
1472
1848
  ]);
1473
1849
 
1474
1850
  /**
1475
- * Names bound by top-level `function`, `class`, `const`, `let` or `var`
1476
- * declarations (exported or not). Returns an empty set when the source does
1477
- * not parse, so a parse failure never drops a real component.
1851
+ * The top-level bindings of a source. `declared` holds names bound by
1852
+ * `function`, `class`, `const`, `let` or `var` declarations (exported or not).
1853
+ * `astryxImports` maps each local name of a named Astryx import to the name the
1854
+ * package exports, so `Text as AstryxText` maps `AstryxText` to `Text`. Both
1855
+ * are empty when the source does not parse, so a parse failure never drops a
1856
+ * real component.
1478
1857
  *
1479
1858
  * @param {string} src
1480
- * @returns {Set<string>}
1859
+ * @returns {{declared: Set<string>, astryxImports: Map<string, string>}}
1481
1860
  */
1482
- function topLevelBindingNames(src) {
1861
+ function topLevelBindings(src) {
1483
1862
  /** @type {Set<string>} */
1484
1863
  const names = new Set();
1864
+ /** @type {Map<string, string>} */
1865
+ const astryxImports = new Map();
1485
1866
  let program;
1486
1867
  try {
1487
1868
  program = templateSourceParser().parse(src, {
@@ -1490,9 +1871,21 @@ function topLevelBindingNames(src) {
1490
1871
  errorRecovery: true,
1491
1872
  }).program;
1492
1873
  } catch {
1493
- return names;
1874
+ return {declared: names, astryxImports};
1494
1875
  }
1495
1876
  for (const statement of program.body) {
1877
+ if (statement.type === 'ImportDeclaration') {
1878
+ if (!statement.source.value.startsWith(ASTRYX_PACKAGE_SCOPE)) continue;
1879
+ for (const specifier of statement.specifiers) {
1880
+ if (specifier.type !== 'ImportSpecifier') continue;
1881
+ const {imported} = specifier;
1882
+ astryxImports.set(
1883
+ specifier.local.name,
1884
+ imported.type === 'Identifier' ? imported.name : imported.value,
1885
+ );
1886
+ }
1887
+ continue;
1888
+ }
1496
1889
  const node =
1497
1890
  statement.type === 'ExportNamedDeclaration' ||
1498
1891
  statement.type === 'ExportDefaultDeclaration'
@@ -1513,15 +1906,26 @@ function topLevelBindingNames(src) {
1513
1906
  }
1514
1907
  }
1515
1908
  }
1516
- return names;
1909
+ return {declared: names, astryxImports};
1517
1910
  }
1518
1911
 
1519
1912
  /**
1913
+ * The components a template file composes, as written in the catalog.
1520
1914
  * @param {string} pagePath
1521
1915
  * @returns {string[]}
1522
1916
  */
1523
1917
  export function extractComponents(pagePath) {
1524
- const src = fs.readFileSync(pagePath, 'utf-8');
1918
+ return componentsInSource(fs.readFileSync(pagePath, 'utf-8'));
1919
+ }
1920
+
1921
+ /**
1922
+ * The components a template source composes. A surface that returns rewritten
1923
+ * source lists the components of that source, so a component the rewrite
1924
+ * removed is not listed.
1925
+ * @param {string} src
1926
+ * @returns {string[]}
1927
+ */
1928
+ export function componentsInSource(src) {
1525
1929
  // Match JSX opening tags, e.g. `<Section` or the legacy `<XDSSection`.
1526
1930
  // Templates author bare component names post un-prefix migration
1527
1931
  // (P2380608025), so the `XDS` prefix is optional. Anchoring on the `<`
@@ -1547,12 +1951,13 @@ export function extractComponents(pagePath) {
1547
1951
  // page-local helpers (e.g. `function TimelineSection()`), not components a
1548
1952
  // builder can import. Read real bindings from the syntax tree so comments,
1549
1953
  // strings and type annotations cannot add or hide a name.
1550
- const localDeclNames = topLevelBindingNames(src);
1954
+ const {declared: localDeclNames, astryxImports} = topLevelBindings(src);
1551
1955
 
1552
1956
  return [
1553
1957
  ...new Set(
1554
1958
  matches
1555
1959
  .filter(n => !localDeclNames.has(n))
1960
+ .map(n => astryxImports.get(n) ?? n)
1556
1961
  .filter(n => !['Theme', 'ThemeProvider'].includes(n))
1557
1962
  .filter(n => !UBIQUITOUS.has(n))
1558
1963
  .map(n =>
@@ -37,7 +37,12 @@
37
37
  * @position packages/cli/foundation/discovery — read by template show/copy
38
38
  */
39
39
 
40
- import {parse} from '@babel/parser';
40
+ import {
41
+ isReference,
42
+ parseTemplateSource as parseSource,
43
+ walk,
44
+ writtenNames,
45
+ } from './template-source-tree.mjs';
41
46
  import {definitionsByIcon} from './icon-set-discovery.mjs';
42
47
  import {astryxDefinitionsByName} from './icon-definition-discovery.mjs';
43
48
 
@@ -219,86 +224,6 @@ function targetExport(icon, set, variant) {
219
224
  return {module, export: icon.export};
220
225
  }
221
226
 
222
- /** @param {string} source */
223
- function parseSource(source) {
224
- return parse(source, {
225
- sourceType: 'module',
226
- plugins: ['jsx', 'typescript'],
227
- errorRecovery: false,
228
- });
229
- }
230
-
231
- /**
232
- * Every node in the tree, with its parent and the key it sits under.
233
- * @param {any} node
234
- * @param {(node: any, parent: any, key: string) => void} visit
235
- * @param {any} [parent]
236
- * @param {string} [key]
237
- */
238
- function walk(node, visit, parent = null, key = '') {
239
- if (Array.isArray(node)) {
240
- for (const child of node) walk(child, visit, parent, key);
241
- return;
242
- }
243
- if (
244
- node == null ||
245
- typeof node !== 'object' ||
246
- typeof node.type !== 'string'
247
- ) {
248
- return;
249
- }
250
- visit(node, parent, key);
251
- for (const childKey of Object.keys(node)) {
252
- if (
253
- childKey === 'loc' ||
254
- childKey === 'extra' ||
255
- childKey.endsWith('Comments') ||
256
- childKey === 'comments' ||
257
- childKey === 'tokens'
258
- ) {
259
- continue;
260
- }
261
- const child = node[childKey];
262
- if (child != null && typeof child === 'object') {
263
- walk(child, visit, node, childKey);
264
- }
265
- }
266
- }
267
-
268
- /**
269
- * Whether an identifier node is a reference to a binding, not a property
270
- * name or a JSX attribute name.
271
- * @param {any} node
272
- * @param {any} parent
273
- * @param {string} key
274
- */
275
- function isReference(node, parent, key) {
276
- if (!parent) return true;
277
- switch (parent.type) {
278
- case 'ImportSpecifier':
279
- case 'ImportDefaultSpecifier':
280
- case 'ImportNamespaceSpecifier':
281
- return false;
282
- case 'MemberExpression':
283
- case 'OptionalMemberExpression':
284
- return key !== 'property' || parent.computed;
285
- case 'ObjectProperty':
286
- return key === 'value' || parent.computed;
287
- case 'ObjectMethod':
288
- case 'ClassMethod':
289
- case 'ClassProperty':
290
- return key !== 'key' || parent.computed;
291
- case 'JSXAttribute':
292
- return false;
293
- case 'JSXMemberExpression':
294
- return key === 'object';
295
- case 'TSPropertySignature':
296
- return key !== 'key';
297
- default:
298
- return true;
299
- }
300
- }
301
-
302
227
  /**
303
228
  * Whether a module is one of Astryx's own packages (`@astryxdesign/core`,
304
229
  * its subpaths, and every other `@astryxdesign/` package).
@@ -453,14 +378,7 @@ export function mapTemplateIcons(source, {sets, choice}, declared = {}) {
453
378
  );
454
379
 
455
380
  /** Every name the file writes, to keep aliases collision-free. */
456
- const written = new Set();
457
- walk(ast.program, (node, parent, key) => {
458
- // The name an import specifier reads from its module binds nothing here.
459
- if (parent?.type === 'ImportSpecifier' && key === 'imported') return;
460
- if (node.type === 'Identifier' || node.type === 'JSXIdentifier') {
461
- written.add(node.name);
462
- }
463
- });
381
+ const written = writtenNames(ast);
464
382
 
465
383
  /** @type {Array<{start: number, end: number, text: string}>} */
466
384
  const edits = [];
@@ -0,0 +1,48 @@
1
+ // @generated by scripts/sync-api-types.mjs from the JSDoc in foundation/**/*.mjs.
2
+ // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
+
4
+ /**
5
+ * Parse template source as TSX. Babel loads on first use, so a command that
6
+ * only lists templates never pays for it.
7
+ * @param {string} source
8
+ * @returns {any} The file node.
9
+ */
10
+ export function parseTemplateSource(source: string): any;
11
+ /**
12
+ * The module scope of a parsed file. Its bindings, and the scope of each path
13
+ * a traversal visits, resolve a name to the declaration it reads, so a rewrite
14
+ * acts on bindings and not on names.
15
+ * @param {any} file - A file node from {@link parseTemplateSource}.
16
+ * @returns {any} The program path; its `scope` is the module scope.
17
+ */
18
+ export function programPath(file: any): any;
19
+ /**
20
+ * Traverse a parsed file with scope tracking.
21
+ * @param {any} file - A file node from {@link parseTemplateSource}.
22
+ * @param {import('@babel/core').Visitor} visitor
23
+ */
24
+ export function traverseTemplateSource(file: any, visitor: import("@babel/core").Visitor): void;
25
+ /**
26
+ * Every node in the tree, with its parent and the key it sits under.
27
+ * @param {any} node
28
+ * @param {(node: any, parent: any, key: string) => void} visit
29
+ * @param {any} [parent]
30
+ * @param {string} [key]
31
+ */
32
+ export function walk(node: any, visit: (node: any, parent: any, key: string) => void, parent?: any, key?: string): void;
33
+ /**
34
+ * Whether an identifier node is a reference to a binding, not a property
35
+ * name or a JSX attribute name.
36
+ * @param {any} node
37
+ * @param {any} parent
38
+ * @param {string} key
39
+ */
40
+ export function isReference(node: any, parent: any, key: string): any;
41
+ /**
42
+ * Every name a file writes, so a name a rewrite adds collides with nothing
43
+ * and shadows nothing. The name an import specifier reads from its module
44
+ * binds nothing in the file, so it is not included.
45
+ * @param {any} file - A file node from {@link parseTemplateSource}.
46
+ * @returns {Set<string>}
47
+ */
48
+ export function writtenNames(file: any): Set<string>;