An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): exclude template-local helpers from extractComponents (#7641)
Cindy Zhang52c42390c742
diff --git a/.changeset/cli-fix-timeline-phantom-component.md b/.changeset/cli-fix-timeline-phantom-component.mdnew file mode 100644index 0000000000..f42df56893--- /dev/null+++ b/.changeset/cli-fix-timeline-phantom-component.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] `extractComponents` reported phantom components from locally-declared helper functions in template files — e.g. "Timeline", derived from a `function TimelineSection() {...}` helper declared directly in the detail-page template, which isn't a real component. It now excludes any name bound by a top-level `function`, `class`, `const`, `let` or `var` declaration in the same file (read from the parsed source, so comments, strings and type annotations don't count), before suffix-stripping runs, so a locally-declared helper is never mistaken for an imported component. A component whose whole name is a stripped suffix, such as a bare `Section`, now stays in the list instead of emptying out.++@abu-abdullah22diff --git a/packages/cli/api/template/template.test.mjs b/packages/cli/api/template/template.test.mjsindex 472a419a5e..9d785a3afd 100644--- a/packages/cli/api/template/template.test.mjs+++ b/packages/cli/api/template/template.test.mjs@@ -1,7 +1,14 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';import {describe, it, expect} from 'vitest';-import {stripTemplateAssetRefs, template} from './template.mjs';+import {+ stripTemplateAssetRefs,+ template,+ extractComponents,+} from './template.mjs';describe('stripTemplateAssetRefs', () => {it('replaces a /template-assets image path with an inline data URI', () => {@@ -31,8 +38,7 @@ describe('stripTemplateAssetRefs', () => {});it('preserves surrounding source structure', () => {- const src =- "const data = [{src: '/template-assets/x.png', alt: 'X'}];";+ const src = "const data = [{src: '/template-assets/x.png', alt: 'X'}];";const out = stripTemplateAssetRefs(src);expect(out).toContain("alt: 'X'");expect(out).toContain('const data = [{src:');@@ -102,4 +108,115 @@ describe('template --skeleton component extraction (prefix-agnostic)', () => {expect(result.data.skeleton).toContain('columns={{minWidth: 200}}');});++ it('filters out local helper components declared in the same file', () => {+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-test-'));+ const pagePath = path.join(tmpDir, 'page.tsx');+ fs.writeFileSync(+ pagePath,+ `+import {Card} from '@astryxdesign/core/Layout';++function TimelineSection() {+ return <div />;+}++export default function Page() {+ return (+ <Card>+ <TimelineSection />+ </Card>+ );+}+ `,+ );++ try {+ const components = extractComponents(pagePath);+ expect(components).toContain('Card');+ expect(components).not.toContain('Timeline');+ } finally {+ fs.rmSync(tmpDir, {recursive: true, force: true});+ }+ });++ it('filters out a type-annotated local helper', () => {+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-test-'));+ const pagePath = path.join(tmpDir, 'page.tsx');+ fs.writeFileSync(+ pagePath,+ `+import type {FC} from 'react';+import {Card} from '@astryxdesign/core/Layout';++const TimelineSection: FC = () => <div />;++export default function Page() {+ return (+ <Card>+ <TimelineSection />+ </Card>+ );+}+`,+ );+ try {+ const components = extractComponents(pagePath);+ expect(components).toContain('Card');+ expect(components).not.toContain('Timeline');+ } finally {+ fs.rmSync(tmpDir, {recursive: true, force: true});+ }+ });++ it('keeps an imported component when declaration-like text appears in a comment or string', () => {+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-test-'));+ const pagePath = path.join(tmpDir, 'page.tsx');+ fs.writeFileSync(+ pagePath,+ `+import {Card} from '@astryxdesign/core/Layout';++// const Card = () => null;+const note = 'function Card() {}';++export default function Page() {+ return <Card>{note}</Card>;+}+`,+ );+ try {+ expect(extractComponents(pagePath)).toContain('Card');+ } finally {+ fs.rmSync(tmpDir, {recursive: true, force: true});+ }+ });++ it('keeps a bare imported component whose name is itself a stripped suffix', () => {+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-test-'));+ const pagePath = path.join(tmpDir, 'page.tsx');+ fs.writeFileSync(+ pagePath,+ `+import {Section} from '@astryxdesign/core/Section';++function SectionHeading() {+ return <div />;+}++export default function Page() {+ return (+ <Section>+ <SectionHeading />+ </Section>+ );+}+`,+ );+ try {+ expect(extractComponents(pagePath)).toContain('Section');+ } finally {+ fs.rmSync(tmpDir, {recursive: true, force: true});+ }+ });});diff --git a/packages/cli/foundation/discovery/template-adapter.mjs b/packages/cli/foundation/discovery/template-adapter.mjsindex 23b471a9d5..72b1899b3f 100644--- a/packages/cli/foundation/discovery/template-adapter.mjs+++ b/packages/cli/foundation/discovery/template-adapter.mjs@@ -15,7 +15,8 @@* needs it: `Project` assembles templates from it. While this sat in api/, that* made a cycle across the layer boundary — Project reached up for discovery and* this module imported Project back. Nothing here depends on api/; every import- * is node:*, jiti, foundation/*, or authoring/*.+ * is node:*, jiti, foundation/*, or authoring/*, plus a lazily required+ * @babel/parser for extractComponents' local-declaration scan.** @position packages/cli/foundation/discovery — shared template discovery/IO;* consumed by Project and by the api/template leaves.@@ -512,6 +513,19 @@ function expressionUse(source, open, close) {return null;}+/** @type {typeof import('@babel/parser') | undefined} */+let babelParser;++/**+ * The template source parser, loaded on first use so listing templates+ * never pays for it.+ * @returns {typeof import('@babel/parser')}+ */+function templateSourceParser() {+ babelParser ??= require('@babel/parser');+ return /** @type {typeof import('@babel/parser')} */ (babelParser);+}+/*** The [start, end) range of every comment in `source`, or none when it does* not parse as TSX.@@ -520,8 +534,7 @@ function expressionUse(source, open, close) {*/function commentRanges(source) {try {- const {parse} = require('@babel/parser');- const {comments} = parse(source, {+ const {comments} = templateSourceParser().parse(source, {sourceType: 'module',plugins: ['jsx', 'typescript'],});@@ -1267,7 +1280,8 @@ export async function discoverIntegrationTemplatesForOne(integration) {template: id,message: `Template "${id}" is missing a "type" of "page" or "block". Stamp the default export with type: 'page' or type: 'block'.`,});- const declared = doc?.replaces ?? (await declaredReplacement(docPath, id));+ const declared =+ doc?.replaces ?? (await declaredReplacement(docPath, id));if (declared != null) {errors.push({code: 'invalid_template_replacement',@@ -1423,6 +1437,51 @@ const UBIQUITOUS = new Set(['Icon',]);+/**+ * Names bound by top-level `function`, `class`, `const`, `let` or `var`+ * declarations (exported or not). Returns an empty set when the source does+ * not parse, so a parse failure never drops a real component.+ *+ * @param {string} src+ * @returns {Set<string>}+ */+function topLevelBindingNames(src) {+ /** @type {Set<string>} */+ const names = new Set();+ let program;+ try {+ program = templateSourceParser().parse(src, {+ sourceType: 'module',+ plugins: ['jsx', 'typescript'],+ errorRecovery: true,+ }).program;+ } catch {+ return names;+ }+ for (const statement of program.body) {+ const node =+ statement.type === 'ExportNamedDeclaration' ||+ statement.type === 'ExportDefaultDeclaration'+ ? statement.declaration+ : statement;+ if (node == null) continue;+ if (+ (node.type === 'FunctionDeclaration' ||+ node.type === 'ClassDeclaration') &&+ node.id+ ) {+ names.add(node.id.name);+ } else if (node.type === 'VariableDeclaration') {+ for (const declarator of node.declarations) {+ if (declarator.id.type === 'Identifier') {+ names.add(declarator.id.name);+ }+ }+ }+ }+ return names;+}+/*** @param {string} pagePath* @returns {string[]}@@ -1449,14 +1508,24 @@ export function extractComponents(pagePath) {while ((m = tagRegex.exec(src)) !== null) {matches.push(m[2]);}++ // Exclude names bound by a top-level declaration in the same file: those are+ // page-local helpers (e.g. `function TimelineSection()`), not components a+ // builder can import. Read real bindings from the syntax tree so comments,+ // strings and type annotations cannot add or hide a name.+ const localDeclNames = topLevelBindingNames(src);+return [...new Set(matches+ .filter(n => !localDeclNames.has(n)).filter(n => !['Theme', 'ThemeProvider'].includes(n)).filter(n => !UBIQUITOUS.has(n)).map(n =>n.replace(- /(Item|Section|Header|Content|Footer|Panel|Heading|CollapseButton|Column|Sortable|Selection|Group|Source)$/,+ // Strip only when a stem remains, so a bare `<Section>` keeps its+ // own name instead of emptying out.+ /(?<=.)(Item|Section|Header|Content|Footer|Panel|Heading|CollapseButton|Column|Sortable|Selection|Group|Source)$/,'',),)diff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjsindex ff61a1698c..d6fdbdb40d 100644--- a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs@@ -251,7 +251,7 @@ const RUNNERS = {sites: ['importDocModule'],},'foundation/discovery/template-adapter.mjs': {- runs: '@babel/parser, to find the fixture references in template source; and a template doc that does not validate, to read the replacement it declares',+ runs: '@babel/parser, to find the fixture references and page-local bindings in template source; and a template doc that does not validate, to read the replacement it declares',sites: ['importDocModule', 'require(@babel/parser)'],},'foundation/discovery/theme-discovery.mjs': {