Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat: replace demo-content elements on every copy and every surface that hands out example source (#9430)

Cindy Zhang61e061cb5337
diff --git a/.changeset/template-demo-content-placeholder.md b/.changeset/template-demo-content-placeholder.md
new file mode 100644
index 0000000000..baa0386343
--- /dev/null
+++ b/.changeset/template-demo-content-placeholder.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] When a template imports Astryx's docs-only demo content, `astryx template <name> <path>`, `astryx template <name>`, `astryx template <name> --skeleton`, and `astryx component <Name> --showcase` replace each demo-content element with a marked `<Text>Card content</Text>` placeholder and remove the demo-content import, so the code they hand out never imports a module that only Astryx's own previews have. The placeholder uses the file's own Astryx `Text` import when that import is in scope, and otherwise imports `Text`, under an alias when the file already uses that name. `template.copy` and `template.show` gain `demoContentReplaced` (0 when the template carried none), their text output says how many elements became placeholders, and the `components` that `template.show` and `template.skeleton` list are the components of the returned source. No shipped template uses demo content yet, so every current template is copied, shown, and outlined exactly as before. The docsite's shadcn install of a block or page applies the same replacement and also replaces demo media, each with a marked placeholder: a placeholder image for an image and a `data:,placeholder-video-add-your-own` source for a video. The item's description says how many references and elements were replaced. The adjacent `.astryx/<item>.json` receipt keeps its current shape, so every released `astryx upgrade` still reads it.
+
+@cixzhang
diff --git a/apps/docsite/scripts/generate-data.mjs b/apps/docsite/scripts/generate-data.mjs
index 1d51adfd87..3945aef51a 100644
--- a/apps/docsite/scripts/generate-data.mjs
+++ b/apps/docsite/scripts/generate-data.mjs
@@ -57,6 +57,11 @@ import {
docs as readDocs,
template as queryTemplates,
} from '@astryxdesign/cli/api';
+import {
+ discoverAll,
+ pkgOf,
+ replaceDemoContent,
+} from '../../../packages/cli/foundation/discovery/template-adapter.mjs';
import docsiteConfig from '../astryx.config.mjs';
import {
integrationContentEnabled,
@@ -1462,6 +1467,9 @@ export const groupedComponents: Record<string, GroupedComponents> = ${JSON.strin
// ── 3. Block Registry ──────────────────────────────────────────────────
+/** The authored file of each integration block, by block `dirName`. */
+const integrationBlockFiles = new Map();
+
async function generateBlockRegistry() {
console.log('Generating block registry...');
@@ -1527,6 +1535,11 @@ async function generateBlockRegistry() {
} catch {
/* ignore */
}
+ // Displayed source: the Code tab, Open in Playground, and the MCP server
+ // show each demo-content element as the placeholder a copy writes, and keep
+ // fixture media. The live preview renders the original file (see
+ // writeBlockPreview). A use that cannot be replaced safely fails the build.
+ source = replaceDemoContent(source).source;
const resolvedName = meta.name || basename;
blocks.push({
@@ -1565,6 +1578,7 @@ async function generateBlockRegistry() {
const integrationBlocks = templateList.data.filter(entry =>
CONFIGURED_COMPONENT_PACKAGES.has(entry.package),
);
+ const discovered = await discoverAll(DOCSITE_ROOT);
for (const entry of integrationBlocks) {
const shown = await queryTemplates(entry.id, {
show: true,
@@ -1572,8 +1586,14 @@ async function generateBlockRegistry() {
package: entry.package,
cwd: DOCSITE_ROOT,
});
+ const dirName = `${entry.package}-${entry.id}`.replace(/[^a-zA-Z0-9_-]/g, '-');
+ const authored = discovered.find(
+ t => t.type === 'block' && t.dirName === entry.id && pkgOf(t) === entry.package,
+ );
+ if (!authored) throw new Error(`No authored file for ${dirName}`);
+ integrationBlockFiles.set(dirName, authored.filePath);
blocks.push({
- dirName: `${entry.package}-${entry.id}`.replace(/[^a-zA-Z0-9_-]/g, '-'),
+ dirName,
name: entry.name,
displayName: entry.displayName || entry.name,
description: entry.description,
@@ -1688,6 +1708,10 @@ async function generateTemplateRegistry() {
/* ignore */
}
+ // Displayed source, like each block's: the playground and the MCP server
+ // hand out the demo-content replacement a copy applies, with fixture media.
+ source = replaceDemoContent(source).source;
+
templates.push({
slug: dir.name,
name: doc.name || dir.name,
@@ -2222,6 +2246,17 @@ function blockSourcePath(block) {
);
}
+function templateSourcePath(template) {
+ return path.join(
+ CLI_ROOT,
+ 'assets',
+ 'templates',
+ 'pages',
+ template.slug,
+ 'page.tsx',
+ );
+}
+
function writeBlockPreview(block, outDir, basename) {
const destFile = `${basename}.tsx`;
const destination = path.join(outDir, destFile);
@@ -2665,8 +2700,17 @@ async function main() {
outDir: path.join(DOCSITE_ROOT, 'public', 'shadcn'),
packages,
allComponents,
- blocks,
- templates,
+ // The registries carry displayed source. A shadcn install is a copy, so it
+ // starts from the file as authored.
+ blocks: blocks.map(block => ({
+ ...block,
+ authoredSourcePath:
+ blockSourcePath(block) ?? integrationBlockFiles.get(block.dirName),
+ })),
+ templates: templates.map(template => ({
+ ...template,
+ authoredSourcePath: templateSourcePath(template),
+ })),
cliRoot: CLI_ROOT,
dependencyTag: DOCSITE_TARGET === 'canary' ? 'canary' : null,
externalDependencySpecs: registryExternalDependencySpecs(),
diff --git a/apps/docsite/scripts/generate-shadcn-registry.mjs b/apps/docsite/scripts/generate-shadcn-registry.mjs
index ae4de07cd2..6a7106ff38 100644
--- a/apps/docsite/scripts/generate-shadcn-registry.mjs
+++ b/apps/docsite/scripts/generate-shadcn-registry.mjs
@@ -11,6 +11,8 @@
* items create public re-exports; blocks and pages copy app-level composition
* source that already imports published package paths and add adjacent receipts
* so Astryx can reconcile later releases without taking ownership of user edits.
+ * An install is a copy: it replaces demo content and demo media as `template
+ * copy` does. The item description discloses that; the receipt keeps its shape.
*/
import * as fs from 'node:fs';
@@ -21,6 +23,10 @@ import stylexPlugin from '@stylexjs/babel-plugin';
import ts from 'typescript';
import {registryItemSchema, registrySchema} from 'shadcn/schema';
import {stripCopyrightHeader} from '../../../packages/cli/foundation/text/copyright-header.mjs';
+import {
+ MARKED_VIDEO_PLACEHOLDER,
+ replaceTemplateDemos,
+} from '../../../packages/cli/foundation/discovery/template-adapter.mjs';
import {
createShadcnPrecompiledDeclaration,
shadcnJavaScriptTarget,
@@ -311,6 +317,42 @@ function precompiledDeclarationFile(itemName, sourceTarget) {
};
}
+/**
+ * The item description, plus a sentence that discloses the replaced demo
+ * content when there is any. The install writes into a project and returns no
+ * response, so the description and the marked placeholders are the disclosure.
+ * @param {string} description
+ * @param {{demoMediaReplaced: number, demoContentReplaced: number}} replaced
+ */
+export function withReplacementNote(description, replaced) {
+ const {demoMediaReplaced, demoContentReplaced} = replaced;
+ if (demoMediaReplaced + demoContentReplaced === 0) return description;
+ const counts = [
+ demoMediaReplaced > 0 &&
+ `${demoMediaReplaced} demo media ${demoMediaReplaced === 1 ? 'reference' : 'references'}`,
+ demoContentReplaced > 0 &&
+ `${demoContentReplaced} demo content ${demoContentReplaced === 1 ? 'element' : 'elements'}`,
+ ].filter(Boolean);
+ const lead = /[.!?]$/u.test(description.trimEnd())
+ ? description.trimEnd()
+ : `${description.trimEnd()}.`;
+ return `${lead} Astryx replaced ${counts.join(' and ')} with marked placeholders; put your own content there.`;
+}
+
+/**
+ * The entry with the source a copy starts from. An entry whose `source` is
+ * already a copy, such as `template show` output, names its authored file in
+ * `authoredSourcePath`; the install applies every copy replacement to that file.
+ * @template {{source: string, authoredSourcePath?: string | null}} T
+ * @param {T} entry
+ * @returns {T}
+ */
+function withAuthoredSource(entry) {
+ return entry.authoredSourcePath
+ ? {...entry, source: fs.readFileSync(entry.authoredSourcePath, 'utf-8')}
+ : entry;
+}
+
function withCompositionReceipt(item, identity, sourceVersion) {
const [sourceFile, ...supportFiles] = item.files;
const receiptTarget = registryReceiptTarget(sourceFile.target, item.name);
@@ -397,8 +439,12 @@ function blockItem(
block.category,
`${block.dirName}.tsx`,
);
+ const {source: copiedSource, ...replaced} = replaceTemplateDemos(
+ block.source,
+ {videoPlaceholder: MARKED_VIDEO_PLACEHOLDER},
+ );
const compiled = precompileStylexSource(
- stripCopyrightHeader(block.source),
+ stripCopyrightHeader(copiedSource),
fileName,
);
const sourceTarget = `components/astryx/${kind === 'block' ? 'blocks' : `${kind}s`}/${block.dirName}.${compiled.extension}`;
@@ -408,7 +454,10 @@ function blockItem(
name: itemName,
type: 'registry:block',
title: block.displayName || block.name,
- description: block.description || `Astryx ${kind}: ${block.name}.`,
+ description: withReplacementNote(
+ block.description || `Astryx ${kind}: ${block.name}.`,
+ replaced,
+ ),
author: 'Astryx',
dependencies: dependenciesForSource(
compiled.source,
@@ -460,8 +509,12 @@ function pageItem(
template.slug,
'page.tsx',
);
+ const {source: copiedSource, ...replaced} = replaceTemplateDemos(
+ template.source,
+ {videoPlaceholder: MARKED_VIDEO_PLACEHOLDER},
+ );
const compiled = precompileStylexSource(
- stripCopyrightHeader(template.source),
+ stripCopyrightHeader(copiedSource),
fileName,
);
const sourceTarget = `app/astryx/${template.slug}/page.${compiled.extension}`;
@@ -471,7 +524,10 @@ function pageItem(
name: itemName,
type: 'registry:page',
title: template.name,
- description: template.description || `Astryx page: ${template.name}.`,
+ description: withReplacementNote(
+ template.description || `Astryx page: ${template.name}.`,
+ replaced,
+ ),
author: 'Astryx',
dependencies: dependenciesForSource(
compiled.source,
@@ -617,7 +673,7 @@ export function buildShadcnRegistry({
const packageCatalog = new Map(packages.map(pkg => [pkg.name, pkg]));
const blockItems = [];
let skippedUnpublishedBlocks = 0;
- for (const block of blocks) {
+ for (const block of blocks.map(withAuthoredSource)) {
// A released subpath can still lack a named component added after the last
// package release. Production blocks must satisfy both contracts: the
// imported subpath below and the published component snapshot here.
@@ -663,7 +719,7 @@ export function buildShadcnRegistry({
const pageItems = [];
let skippedUnpublishedPages = 0;
- for (const template of templates) {
+ for (const template of templates.map(withAuthoredSource)) {
try {
pageItems.push(
pageItem(
diff --git a/apps/docsite/src/__tests__/data-extraction.test.ts b/apps/docsite/src/__tests__/data-extraction.test.ts
index d996628d28..b0575be9b2 100644
--- a/apps/docsite/src/__tests__/data-extraction.test.ts
+++ b/apps/docsite/src/__tests__/data-extraction.test.ts
@@ -18,6 +18,10 @@ import {docs as chatDocs} from '../../../../packages/core/src/Chat/Chat.doc.mjs'
import {docs as drawerDocs} from '../../../../packages/core/src/Drawer/Drawer.doc.mjs';
import {docs as drawerHeaderDocs} from '../../../../packages/core/src/Drawer/DrawerHeader.doc.mjs';
import docsiteConfig from '../../astryx.config.mjs';
+import {
+ DEMO_CONTENT_MODULE,
+ replaceDemoContent,
+} from '../../../../packages/cli/foundation/discovery/template-adapter.mjs';
import {packages} from '../generated/packageRegistry';
import {
components,
@@ -37,6 +41,8 @@ import {eagerShowcases} from '../components/eagerShowcases';
import {TEMPLATE_COMPONENTS} from '../components/templateComponents';
import {exampleRegistry} from '../generated/exampleRegistry';
import {normalizeComponentCategory} from '../lib/componentCategories';
+import {decompressCode} from '../lib/compress';
+import {buildPlaygroundHref} from '../components/playgroundLink';
const REPO_ROOT = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
@@ -1000,6 +1006,42 @@ describe('blockRegistry', () => {
}
});
+ it('shows each core block as a copy writes it, with no demo content (spec:AST-033 FR23)', () => {
+ const blocksDir = path.join(
+ REPO_ROOT,
+ 'packages/cli/assets/templates/blocks',
+ );
+ for (const block of blocks.filter(b => b.sourcePackage == null)) {
+ const file = path.join(blocksDir, block.category, `${block.dirName}.tsx`);
+ expect(block.source).toBe(
+ replaceDemoContent(fs.readFileSync(file, 'utf-8')).source,
+ );
+ expect(block.source).not.toContain(DEMO_CONTENT_MODULE);
+ }
+ for (const entry of Object.values(exampleRegistry).flat()) {
+ expect(entry.source).not.toContain(DEMO_CONTENT_MODULE);
+ }
+ });
+
+ it('opens the displayed source in the playground, with no demo content (spec:AST-033 FR23)', () => {
+ for (const entry of Object.values(exampleRegistry).flat()) {
+ const hash = buildPlaygroundHref(entry.source).split('#code=')[1];
+ const opened = decompressCode(hash);
+ expect(opened).not.toBeNull();
+ expect(opened).not.toContain(DEMO_CONTENT_MODULE);
+ }
+ const pagesDir = path.join(
+ REPO_ROOT,
+ 'packages/cli/assets/templates/pages',
+ );
+ for (const template of templates) {
+ const file = path.join(pagesDir, template.slug, 'page.tsx');
+ expect(template.source).toBe(
+ replaceDemoContent(fs.readFileSync(file, 'utf-8')).source,
+ );
+ }
+ });
+
it('decodes unicode escapes in block titles', () => {
const block = blocks.find(b => b.dirName === 'TabListTabsWithBadge');
expect(block).toBeDefined();
diff --git a/apps/docsite/src/__tests__/mcp-server.test.ts b/apps/docsite/src/__tests__/mcp-server.test.ts
index 2bebe27c1b..ed54dab99e 100644
--- a/apps/docsite/src/__tests__/mcp-server.test.ts
+++ b/apps/docsite/src/__tests__/mcp-server.test.ts
@@ -14,6 +14,11 @@ import {describe, it, expect} from 'vitest';
import {components} from '../generated/componentRegistry';
import {docTopics} from '../generated/docsRegistry';
import {templates} from '../generated/templateRegistry';
+import {blocks} from '../generated/blockRegistry';
+import {
+ DEMO_CONTENT_MODULE,
+ replaceDemoContent,
+} from '../../../../packages/cli/foundation/discovery/template-adapter.mjs';
import type {ComponentEntry} from '../generated/componentRegistry';
@@ -285,3 +290,22 @@ describe('MCP branding', () => {
expect(source).toContain('keywordIndex');
});
});
+
+describe('MCP get() example source (spec:AST-033 FR23)', () => {
+ // get() returns `source` from these registries: a component's showcase and
+ // one more example, and a template's examples or else its page source.
+ it('hands out each block and template after the demo-content replacement', () => {
+ const sources = [
+ ...blocks.map(block => block.source),
+ ...templates.map(template => template.source),
+ ];
+ expect(sources.length).toBeGreaterThan(0);
+ for (const source of sources) {
+ expect(source).not.toContain(DEMO_CONTENT_MODULE);
+ expect(replaceDemoContent(source)).toEqual({
+ source,
+ demoContentReplaced: 0,
+ });
+ }
+ });
+});
diff --git a/apps/docsite/src/templateDemoContent/demoContent.tsx b/apps/docsite/src/templateDemoContent/demoContent.tsx
new file mode 100644
index 0000000000..6d066305e7
--- /dev/null
+++ b/apps/docsite/src/templateDemoContent/demoContent.tsx
@@ -0,0 +1,115 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Docs-only demo content that catalog templates may show inside real
+ * Astryx components: a lightweight playing card's face and back.
+ * @input A rank and suit, and whether the card lies face down.
+ * @output Token-styled card contents sized to fill their container.
+ * @position The one demo-content module templates import, as
+ * `@astryx-docs/demo-content` (mapped by the docsite, sandbox, template
+ * viewer, test, and CLI type-check configs). It is not part of any package:
+ * every copy and every surface that hands out template source replace each
+ * element imported from it with a generic `<Text>` placeholder (the CLI's
+ * `replaceDemoContent`), so only live previews ever render it. Elements are
+ * used with no children, and each prop is a literal or a variable the
+ * template also reads elsewhere, so that replacement stays safe.
+ */
+
+import * as stylex from '@stylexjs/stylex';
+import {
+ colorVars,
+ radiusVars,
+ spacingVars,
+ textSizeVars,
+ typographyVars,
+} from '@astryxdesign/core/theme/tokens.stylex';
+
+const SUIT_SYMBOLS = {
+ hearts: '♥',
+ diamonds: '♦',
+ clubs: '♣',
+ spades: '♠',
+} as const;
+
+export type PlayingCardSuit = keyof typeof SUIT_SYMBOLS;
+
+export interface PlayingCardContentsProps {
+ /** The card's rank as printed in its corner: `A`, `2`–`10`, `J`, `Q`, `K`. */
+ rank: string;
+ suit: PlayingCardSuit;
+ /** Show the card's back: a token-colored pattern with no rank or suit. */
+ faceDown?: boolean;
+}
+
+/**
+ * A playing card: rank and suit in the corner and the suit at center, or its
+ * back when `faceDown`.
+ */
+export function PlayingCardContents({
+ rank,
+ suit,
+ faceDown = false,
+}: PlayingCardContentsProps) {
+ if (faceDown) {
+ return (
+ <span role="img" aria-label="Card back" {...stylex.props(styles.back)} />
+ );
+ }
+ const symbol = SUIT_SYMBOLS[suit];
+ return (
+ <span
+ role="img"
+ aria-label={`${rank} of ${suit}`}
+ {...stylex.props(
+ styles.face,
+ (suit === 'hearts' || suit === 'diamonds') && styles.red,
+ )}>
+ <span aria-hidden {...stylex.props(styles.corner)}>
+ <span>{rank}</span>
+ <span>{symbol}</span>
+ </span>
+ <span aria-hidden {...stylex.props(styles.center)}>
+ {symbol}
+ </span>
+ </span>
+ );
+}
+
+const styles = stylex.create({
+ face: {
+ position: 'relative',
+ display: 'grid',
+ placeItems: 'center',
+ aspectRatio: '5 / 7',
+ inlineSize: '100%',
+ color: colorVars['--color-text-primary'],
+ fontFamily: typographyVars['--font-family-heading'],
+ userSelect: 'none',
+ },
+ red: {
+ color: colorVars['--color-text-red'],
+ },
+ corner: {
+ position: 'absolute',
+ insetBlockStart: 0,
+ insetInlineStart: 0,
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ fontSize: textSizeVars['--font-size-lg'],
+ lineHeight: 1,
+ fontWeight: 600,
+ },
+ center: {
+ fontSize: textSizeVars['--font-size-4xl'],
+ lineHeight: 1,
+ },
+ back: {
+ display: 'block',
+ aspectRatio: '5 / 7',
+ inlineSize: '100%',
+ borderRadius: radiusVars['--radius-inner'],
+ backgroundColor: colorVars['--color-accent'],
+ backgroundImage: `repeating-linear-gradient(45deg, transparent 0 ${spacingVars['--spacing-1']}, ${colorVars['--color-accent-muted']} ${spacingVars['--spacing-1']} ${spacingVars['--spacing-2']})`,
+ },
+});
diff --git a/apps/docsite/tsconfig.json b/apps/docsite/tsconfig.json
index b575f7dac7..543c77d421 100644
--- a/apps/docsite/tsconfig.json
+++ b/apps/docsite/tsconfig.json
@@ -25,6 +25,9 @@
"paths": {
"@/*": [
"./src/*"
+ ],
+ "@astryx-docs/demo-content": [
+ "./src/templateDemoContent/demoContent.tsx"
]
}
},
diff --git a/apps/sandbox/tsconfig.json b/apps/sandbox/tsconfig.json
index 0186bc3564..329c0dab0c 100644
--- a/apps/sandbox/tsconfig.json
+++ b/apps/sandbox/tsconfig.json
@@ -15,7 +15,10 @@
"incremental": true,
"types": ["vite/client"],
"paths": {
- "@/*": ["./src/*"]
+ "@/*": ["./src/*"],
+ "@astryx-docs/demo-content": [
+ "../docsite/src/templateDemoContent/demoContent.tsx"
+ ]
}
},
"include": ["src/**/*.ts", "src/**/*.tsx", "vite.config.mts"],
diff --git a/apps/sandbox/vite.config.mts b/apps/sandbox/vite.config.mts
index f91d6d4d02..eb7c5f52dc 100644
--- a/apps/sandbox/vite.config.mts
+++ b/apps/sandbox/vite.config.mts
@@ -221,6 +221,11 @@ export default defineConfig({
// The app owns the Babel helpers emitted while compiling its template
// modules; pnpm does not hoist them to each sibling workspace package.
'@babel/runtime': path.join(appDir, 'node_modules/@babel/runtime'),
+ // Template previews render the docs-only demo content the docsite hosts.
+ '@astryx-docs/demo-content': path.join(
+ appDir,
+ '../docsite/src/templateDemoContent/demoContent.tsx',
+ ),
...(lexicalDist() ? {lexical: lexicalDist()} : {}),
},
},
diff --git a/apps/template-viewer/vite.config.ts b/apps/template-viewer/vite.config.ts
index 3c44af5084..89ae10081a 100644
--- a/apps/template-viewer/vite.config.ts
+++ b/apps/template-viewer/vite.config.ts
@@ -1,5 +1,6 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+import {fileURLToPath} from 'node:url';
import {defineConfig} from 'vite';
import react from '@vitejs/plugin-react';
import {astryxStylex} from '@astryxdesign/build/vite';
@@ -9,6 +10,17 @@ export default defineConfig({
// Templates that show imagery point at /template-assets/*, which the docsite
// serves from its own public dir. Reuse it so previews here match.
publicDir: '../docsite/public',
+ // Docs-only demo content templates import is hosted by the docsite too.
+ resolve: {
+ alias: {
+ '@astryx-docs/demo-content': fileURLToPath(
+ new URL(
+ '../docsite/src/templateDemoContent/demoContent.tsx',
+ import.meta.url,
+ ),
+ ),
+ },
+ },
// Templates live outside this app's root (packages/cli/assets/templates).
server: {fs: {allow: ['../..']}},
});
diff --git a/docs/specs/AST-028/spec.md b/docs/specs/AST-028/spec.md
index 66bed95096..9b0742291a 100644
--- a/docs/specs/AST-028/spec.md
+++ b/docs/specs/AST-028/spec.md
@@ -125,11 +125,17 @@ concerns require a separate contract.
copied source MUST NOT reference the repository-only code that defines a
demo-content element. The copies are `template copy` and the docsite's shadcn
Install item, which writes the example into the consumer's project. The copy
- receipt (FR11) MUST count the replaced elements as `demoContentReplaced`; the
- shadcn Install item's receipt is the `.astryx/<item>.json` file it already
- installs, which MUST carry `demoMediaReplaced` and `demoContentReplaced`.
+ receipt (FR11) MUST count the replaced elements as `demoContentReplaced`.
+ Until the next minor, the persisted `.astryx/<item>.json` receipt keeps its
+ v2 shape (released readers validate it strictly), so the replacement counts
+ appear in the copy response that `template copy` and `template show` report.
`template show` returns the same source a copy writes and MUST report
`demoContentReplaced` in its response, as it reports `demoMediaReplaced`.
+ For the shadcn Install item, whose output Astryx does not control, FR11's
+ disclosure is carried by the placeholders themselves (each replaced element
+ and media reference is a visibly marked placeholder at its replacement point)
+ and by the registry item's description. At 0.8.0, the next minor, the
+ persisted counts move to a v3 receipt, with a migration note (CLN-0027).
Surfaces other than these copies and `template show` that hand out example
source without writing it into a project replace only demo-content elements
and keep their fixture media:
@@ -138,12 +144,7 @@ concerns require a separate contract.
the originals (FR4). A check MUST fail when copied, shown, or handed-out
output still references a demo-content element or the code that defines it.
How a demo-content element is marked and replaced belongs to
- `architecture:template-authoring`. Implementation gap: the element
- replacement and `demoContentReplaced` in the copy receipt and the
- `template show` response are not built; `--showcase` prints the showcase file
- as read from disk; the shadcn Install item installs block source as read from
- disk, with its fixture media, and discloses no replacement (Current-state
- impact).
+ `architecture:template-authoring`.
### Boundary with icons
@@ -169,12 +170,17 @@ previously unwritten requirements for why assets are fixtures, which references
may be transformed, what a safe fallback means, how unsupported formats fail,
and why icons are separate.
-Demo-content elements (FR13) are not built: the copy and show paths replace no
-elements, and neither the copy receipt nor the `template show` response has a
-`demoContentReplaced` count. `astryx component <Name> --showcase` prints the
-showcase file as read from disk. The shadcn Install item installs block source
-as read from disk, so it writes `/template-assets/` references into the
-consumer's project and discloses no replacement.
+`template copy` and `template show` replace each demo-content element (FR13)
+with a `<Text>Card content</Text>` placeholder, import Astryx's `Text` for it
+when the source does not already import it, and remove the demo-content import.
+Both responses report the count as `demoContentReplaced`.
+`astryx template <name> --skeleton` outlines that replaced source and lists
+its components. `astryx component <Name> --showcase` prints the showcase source
+with each demo-content element replaced and its fixture media kept. The shadcn
+Install item installs block and page source with demo-content elements and
+fixture media both replaced, each as a visibly marked placeholder, and its
+registry item description says how many were replaced. Its
+`.astryx/<item>.json` receipt keeps the v2 shape until CLN-0027.
This specification-only change alters no package, template, asset, preview,
runtime, or public CLI behavior. Remaining implementation and verification
@@ -182,15 +188,15 @@ follow separately.
## Verification
-| Contract | Verification | Representative cases | Failure expectation |
-| -------- | -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| FR1–FR3 | Template-source and copy-boundary tests | built-in page, block, integration template; Astryx fixture; consumer path; third-party URL | Copied source retains a preview runtime dependency or rewrites consumer-owned content |
-| FR4–FR6 | Real preview request and rendered-media checks | local, docsite, main sandbox, PR preview; image and video; missing fixture | Representative media 404s, resolves to another file, or silently uses the wrong kind |
-| FR7–FR8 | End-to-end CLI copy tests | image-only, video-only, and no-media template | Generated source retains `/template-assets/` or does not parse/render without setup |
-| FR9–FR10 | Classifier and mixed-source mutation tests | upper/lower case; multi-dot filename; image poster plus video; unknown suffix | Last suffix is misread, image data enters video, or an unsupported kind is guessed |
-| FR11 | Human and structured copy-receipt tests | no replacement; one image; mixed media | The consumer is not told what must be replaced or is told assets were installed |
-| FR12 | Scope guard tests and review | Icon prop, registry icon, imported SVG component, static hero image | Icon behavior is silently folded into the static-fixture transformer |
-| FR13 | End-to-end CLI copy, show, and `--showcase` tests, a shadcn install test, and a real preview check | a motion or gesture example whose `Card` wraps one demo-content element; one with two; an example with none; its `template show` response; its `--showcase` output; its shadcn install into a project and its `.astryx/<item>.json` receipt; its live preview | Copied, shown, or installed output still references a demo-content element, the code that defines it, or `/template-assets/`; `--showcase` output references a demo-content element or changes its fixture media; the outer component or its props change; the copy receipt or the `template show` response omits or miscounts `demoContentReplaced`; the live preview stops rendering the original; or the shadcn install receipt lacks `demoMediaReplaced` or `demoContentReplaced` |
+| Contract | Verification | Representative cases | Failure expectation |
+| -------- | -------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| FR1–FR3 | Template-source and copy-boundary tests | built-in page, block, integration template; Astryx fixture; consumer path; third-party URL | Copied source retains a preview runtime dependency or rewrites consumer-owned content |
+| FR4–FR6 | Real preview request and rendered-media checks | local, docsite, main sandbox, PR preview; image and video; missing fixture | Representative media 404s, resolves to another file, or silently uses the wrong kind |
+| FR7–FR8 | End-to-end CLI copy tests | image-only, video-only, and no-media template | Generated source retains `/template-assets/` or does not parse/render without setup |
+| FR9–FR10 | Classifier and mixed-source mutation tests | upper/lower case; multi-dot filename; image poster plus video; unknown suffix | Last suffix is misread, image data enters video, or an unsupported kind is guessed |
+| FR11 | Human and structured copy-receipt tests | no replacement; one image; mixed media | The consumer is not told what must be replaced or is told assets were installed |
+| FR12 | Scope guard tests and review | Icon prop, registry icon, imported SVG component, static hero image | Icon behavior is silently folded into the static-fixture transformer |
+| FR13 | End-to-end CLI copy, show, and `--showcase` tests, a shadcn install test, and a real preview check | a motion or gesture example whose `Card` wraps one demo-content element; one with two; an example with none; its `template show` response; its `--showcase` output; its shadcn install into a project, its registry item description, and its `.astryx/<item>.json` receipt; its live preview | Copied, shown, or installed output still references a demo-content element, the code that defines it, or `/template-assets/`; `--showcase` output references a demo-content element or changes its fixture media; the outer component or its props change; the copy receipt or the `template show` response omits or miscounts `demoContentReplaced`; a shadcn install leaves a replaced element or media reference without a visibly marked placeholder, or its registry item description does not disclose the replacement; the installed `.astryx/<item>.json` receipt gains a field or fails the released strict v2 reader before CLN-0027; or the live preview stops rendering the original |
### Completion criteria
@@ -269,6 +275,18 @@ replaces fixture media like any copy (FR7).
Rejected: a docs-only duplicate of each example, which adds documents to keep in sync.
+## Deprecation and cleanup records
+
+### CLN-0027 — The installed receipt counts what the copy replaced
+
+| Field | Value |
+| --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| id | `CLN-0027` |
+| lifecycle | No deprecation: the staged `[breaking]` change for FR13 (`spec:AST-017` FR28) |
+| delta | The shadcn Install item writes a v3 `.astryx/<item>.json` receipt that adds `demoMediaReplaced` and `demoContentReplaced`. `astryx upgrade` reads v1, v2, and v3 receipts; a CLI released before 0.8.0 cannot read a v3 receipt, so the migration note tells consumers to upgrade the CLI before they upgrade an item installed from 0.8.0 on |
+| rollback | Restore the v2 receipt writer from the final-patch baseline |
+| state | `pending` — lands in 0.8.0, the next minor, with its `[breaking]` Changeset |
+
## Open questions
None.
diff --git a/docs/specs/AST-033/spec.md b/docs/specs/AST-033/spec.md
index 8c53d10c12..f2a199aee9 100644
--- a/docs/specs/AST-033/spec.md
+++ b/docs/specs/AST-033/spec.md
@@ -294,9 +294,9 @@ for each bug.
sources or, without them, its page source. The shadcn Install item writes
the example into the consumer's project, so it is a copy under
`spec:AST-028` FR13 and its registry item carries the source with fixture
- media and demo-content elements both replaced. Implementation gap: not
- built; each surface carries block source as read from disk (Current-state
- impact).
+ media and demo-content elements both replaced. Integration-package blocks
+ display `template show` output, so their displayed code has fixture media
+ replaced.
### Authority routing
@@ -346,13 +346,14 @@ Known conformance gaps remain implementation work:
navigation that owns it;
- analytics still permits unrestricted string context for item, package, category,
source, type, tab, view, and toggle-value fields, and nested template-preview
- activation can reach the same semantic action twice;
+ activation can reach the same semantic action twice; and
- existing interaction tests do not yet cover the complete primary-selection,
- Back/Forward, close, cancellation, and supersession matrix; and
-- the Code tab, Open in Playground, the Sandbox code view, the MCP server's
- `get()`, and the shadcn Install item carry block source as read from disk,
- with no demo-content element replacement, and the shadcn Install item also
- keeps its fixture media (FR23).
+ Back/Forward, close, cancellation, and supersession matrix.
+
+The Code tab, Open in Playground, the Sandbox code view, and the MCP server's
+`get()` carry example source after the demo-content element replacement, with
+fixture media kept. The shadcn Install item carries it with demo-content
+elements and fixture media both replaced (FR23).
Stable Storybook and Sandbox currently use a split deployment: pull-request
previews are staged inside the Vercel Docsite, while stable main is rebuilt and
@@ -367,17 +368,17 @@ exact source already serving those public surfaces.
## Verification
-| Contract | Verification | Representative states | Mutation or failure expectation |
-| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| FR1–FR3 | generator/data-extraction tests plus cross-projection inventory; search endpoint parity with `astryx search --json` | package, component, template, theme; gallery, sidebar, search, direct route, preview, playground | a local map changes membership or a canonical item fact, or availability and visibility collapse into one projection |
-| FR4–FR6 | latest/canary generation and projection tests | stable package, canary-only package, ready/unready item, overview-hidden item, invalid integration metadata | latest exposes canary package docs, workspace-backed content is called release-pinned, a second readiness state appears, or projections disagree |
-| FR7–FR9 | navigation-family checks plus real-browser navigation/history tests | direct link, modified click, new tab, deep link, primary selection, secondary tab/filter, canonicalization, Back/Forward | Docsite misclassifies a destination, canonical identity diverges, primary selections replace one another, or secondary state clutters history |
-| FR10–FR12 | selection/transition tests plus real-browser visible-content checks | initial open, reopen, deep link, direct selection, pending previous/next, close, supersede, reject, unmount | header/body/actions disagree, stale content paints without its owning pending state, or obsolete selection work commits after supersession |
-| FR13–FR15 | analytics schema and interaction tests with transport spies | navigation intent, successful/failed copy, cancel, URL restoration, render/effect, duplicate activation | event names/properties drift, free-form/high-cardinality data is logged, a passive lifecycle emits, success logs on failure, or one action emits twice |
-| FR16 | production-browser playground isolation and recovery tests | direct load, reload, hostile navigation, storage and parent-DOM denial | preview code reaches parent/storage or trusted recovery restores stale source/theme |
-| FR17–FR21 | exact-head Vercel build, route/asset probes, metadata checks, and Pages landing contract | production and PR Preview; Storybook manager/frame; Sandbox route/embed; old root/deep path; desktop/mobile; light/dark | one app is absent or stale, a direct asset/route fails, metadata claims the wrong owner, identity drifts, or Pages hosts more than the compatibility page |
-| FR22 | `e2e/blog-live-examples.spec.ts` (real-browser post, plain-text route, feed, sitemap, and index checks) and `blog-live-examples.test.tsx` (fence rule, static fallback, fixture listing, runner) | a post with a `tsx live` block; that post's plain-text route; a block importing a post-local asset; a block that fails to compile or throws; live fences in a blockquote, a list item, and quoted inside a longer fence | the live block does not run in the browser, the text route shows anything but the source fallback for a fence the page runs, a post-local import fails to resolve, a broken example breaks the page outside its frame, or the feed, sitemap, or index lists the fixture |
-| FR23 | Output checks for each surface plus real-browser live-example check | a motion or gesture example whose `Card` wraps a demo-content element; its Code tab and copied text; its Open in Playground source; its Sandbox code view and copied source; its MCP `get()` component and template results; its shadcn registry item and the `.astryx/<item>.json` receipt it installs; an example with fixture media; its live preview | any of those surfaces still references a demo-content element or the code that defines it; the outer component or its props change; fixture media changes on a surface that only hands out source; the shadcn registry item still references `/template-assets/`, or its installed receipt lacks `demoMediaReplaced` or `demoContentReplaced`; or the live preview stops rendering the original |
+| Contract | Verification | Representative states | Mutation or failure expectation |
+| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| FR1–FR3 | generator/data-extraction tests plus cross-projection inventory; search endpoint parity with `astryx search --json` | package, component, template, theme; gallery, sidebar, search, direct route, preview, playground | a local map changes membership or a canonical item fact, or availability and visibility collapse into one projection |
+| FR4–FR6 | latest/canary generation and projection tests | stable package, canary-only package, ready/unready item, overview-hidden item, invalid integration metadata | latest exposes canary package docs, workspace-backed content is called release-pinned, a second readiness state appears, or projections disagree |
+| FR7–FR9 | navigation-family checks plus real-browser navigation/history tests | direct link, modified click, new tab, deep link, primary selection, secondary tab/filter, canonicalization, Back/Forward | Docsite misclassifies a destination, canonical identity diverges, primary selections replace one another, or secondary state clutters history |
+| FR10–FR12 | selection/transition tests plus real-browser visible-content checks | initial open, reopen, deep link, direct selection, pending previous/next, close, supersede, reject, unmount | header/body/actions disagree, stale content paints without its owning pending state, or obsolete selection work commits after supersession |
+| FR13–FR15 | analytics schema and interaction tests with transport spies | navigation intent, successful/failed copy, cancel, URL restoration, render/effect, duplicate activation | event names/properties drift, free-form/high-cardinality data is logged, a passive lifecycle emits, success logs on failure, or one action emits twice |
+| FR16 | production-browser playground isolation and recovery tests | direct load, reload, hostile navigation, storage and parent-DOM denial | preview code reaches parent/storage or trusted recovery restores stale source/theme |
+| FR17–FR21 | exact-head Vercel build, route/asset probes, metadata checks, and Pages landing contract | production and PR Preview; Storybook manager/frame; Sandbox route/embed; old root/deep path; desktop/mobile; light/dark | one app is absent or stale, a direct asset/route fails, metadata claims the wrong owner, identity drifts, or Pages hosts more than the compatibility page |
+| FR22 | `e2e/blog-live-examples.spec.ts` (real-browser post, plain-text route, feed, sitemap, and index checks) and `blog-live-examples.test.tsx` (fence rule, static fallback, fixture listing, runner) | a post with a `tsx live` block; that post's plain-text route; a block importing a post-local asset; a block that fails to compile or throws; live fences in a blockquote, a list item, and quoted inside a longer fence | the live block does not run in the browser, the text route shows anything but the source fallback for a fence the page runs, a post-local import fails to resolve, a broken example breaks the page outside its frame, or the feed, sitemap, or index lists the fixture |
+| FR23 | Output checks for each surface plus real-browser live-example check | a motion or gesture example whose `Card` wraps a demo-content element; its Code tab and copied text; its Open in Playground source; its Sandbox code view and copied source; its MCP `get()` component and template results; its shadcn registry item and the `.astryx/<item>.json` receipt it installs; an example with fixture media; an integration-package block's displayed code; its live preview | any of those surfaces still references a demo-content element or the code that defines it; the outer component or its props change; fixture media changes on a surface that only hands out source; the shadcn registry item or an integration-package block's displayed code still references `/template-assets/`, or the installed receipt is not the released v2 shape; or the live preview stops rendering the original |
## Decision log
diff --git a/internal/shadcn-registry/generate-shadcn-registry.test.mjs b/internal/shadcn-registry/generate-shadcn-registry.test.mjs
index 1aecf90ddd..13cde79d62 100644
--- a/internal/shadcn-registry/generate-shadcn-registry.test.mjs
+++ b/internal/shadcn-registry/generate-shadcn-registry.test.mjs
@@ -35,6 +35,10 @@ import {
parseRegistryReceipt,
registryContentHash,
} from '../../packages/cli/authoring/shadcn/receipt.mjs';
+import {
+ DEMO_CONTENT_MODULE,
+ MARKED_VIDEO_PLACEHOLDER,
+} from '../../packages/cli/foundation/discovery/template-adapter.mjs';
import {
buildShadcnRegistry,
generateShadcnRegistry,
@@ -696,6 +700,158 @@ describe('buildShadcnRegistry', () => {
}
});
+ it('installs a block and a page as a copy writes them, with marked placeholders and a disclosing description', async () => {
+ const project = mkdtempSync(path.join(tmpdir(), 'astryx-shadcn-demo-'));
+ try {
+ writeConsumerProject(project);
+ const base = fixture();
+ const {items} = buildShadcnRegistry(
+ fixture({
+ packages: packages.map(pkg =>
+ pkg.name === '@astryxdesign/core'
+ ? {
+ ...pkg,
+ packageExports: {
+ ...pkg.packageExports,
+ './Card': './dist/Card/index.js',
+ './Text': './dist/Text/index.js',
+ },
+ }
+ : pkg,
+ ),
+ blocks: [
+ {
+ ...base.blocks[0],
+ componentsUsed: ['Card'],
+ source:
+ "import {Card} from '@astryxdesign/core/Card';\n" +
+ `import {PlayingCardContents} from '${DEMO_CONTENT_MODULE}';\n` +
+ 'export default function ButtonShowcase() {\n' +
+ ' return (\n' +
+ ' <Card padding={4}>\n' +
+ ' <PlayingCardContents rank="Q" suit="hearts" />\n' +
+ ' <img src="/template-assets/hero.jpg" alt="" />\n' +
+ ' <video src="/template-assets/clip.mp4" />\n' +
+ ' </Card>\n' +
+ ' );\n' +
+ '}\n',
+ },
+ ],
+ templates: [
+ {
+ ...base.templates[0],
+ source:
+ "import {Card} from '@astryxdesign/core/Card';\n" +
+ 'export default function Page() {\n' +
+ ' return <Card><img src="/template-assets/hero.jpg" alt="" /></Card>;\n' +
+ '}\n',
+ },
+ ],
+ }),
+ );
+ const block = items.find(
+ item => item.name === 'showcase-button-variants',
+ );
+ const page = items.find(item => item.name === 'template-dashboard');
+ for (const item of [block, page]) {
+ const copied = item.files[0].content;
+ expect(copied).not.toContain(DEMO_CONTENT_MODULE);
+ expect(copied).not.toContain('PlayingCardContents');
+ expect(copied).not.toContain('/template-assets/');
+ expect(copied).toContain('<img src="data:image/svg+xml,');
+ }
+ expect(block.files[0].content).toContain(
+ '<Card padding={4}>\n <Text>Card content</Text>',
+ );
+ expect(block.files[0].content).toContain(
+ `<video src="${MARKED_VIDEO_PLACEHOLDER}" />`,
+ );
+ expect(block.description).toBe(
+ 'Shows a primary button. Astryx replaced 2 demo media references and 1 demo content element with marked placeholders; put your own content there.',
+ );
+ expect(page.description).toBe(
+ 'A metrics dashboard. Astryx replaced 1 demo media reference with marked placeholders; put your own content there.',
+ );
+ expect(block.dependencies).not.toContainEqual(
+ expect.stringContaining('demo-content'),
+ );
+
+ const itemPath = path.join(project, 'block.json');
+ writeFileSync(itemPath, JSON.stringify(block));
+ await execFileAsync(
+ process.execPath,
+ [SHADCN_ENTRY, 'add', itemPath, '--yes'],
+ {cwd: project, timeout: 30_000, env: shadcnEnv(project)},
+ );
+ const showcases = path.join(
+ project,
+ 'src',
+ 'components',
+ 'astryx',
+ 'showcases',
+ );
+ const installedSource = readFileSync(
+ path.join(showcases, 'ButtonShowcase.tsx'),
+ 'utf8',
+ );
+ expect(installedSource).toBe(block.files[0].content);
+ // The released reader validates a version 2 receipt strictly, so an
+ // extra field would break `astryx upgrade` on an older CLI.
+ const installedReceipt = JSON.parse(
+ readFileSync(
+ path.join(showcases, '.astryx', 'showcase-button-variants.json'),
+ 'utf8',
+ ),
+ );
+ expect(Object.keys(installedReceipt).sort()).toEqual([
+ 'files',
+ 'item',
+ 'schemaVersion',
+ 'source',
+ ]);
+ expect(parseRegistryReceipt(installedReceipt)).toMatchObject({
+ schemaVersion: 2,
+ });
+ } finally {
+ rmSync(project, {recursive: true, force: true});
+ }
+ });
+
+ it('installs an integration-package block from its authored file, so it discloses its replacements', () => {
+ const dir = mkdtempSync(path.join(tmpdir(), 'astryx-shadcn-integration-'));
+ try {
+ const authoredSourcePath = path.join(dir, 'ButtonShowcase.tsx');
+ const source = src =>
+ `export default function ButtonShowcase() {\n return <video src="${src}" />;\n}\n`;
+ writeFileSync(authoredSourcePath, source('/template-assets/clip.mp4'));
+ const [base] = fixture().blocks;
+ // `source` is `template show` output, so its video source is already empty.
+ const block = {...base, sourcePackage: '@astryxdesign/lab', source: source('')};
+ const {items} = buildShadcnRegistry(
+ fixture({blocks: [{...block, authoredSourcePath}]}),
+ );
+ const item = items.find(({name}) => name === 'showcase-button-variants');
+ expect(item.files[0].content).toContain(
+ `<video src="${MARKED_VIDEO_PLACEHOLDER}" />`,
+ );
+ expect(item.description).toBe(
+ 'Shows a primary button. Astryx replaced 1 demo media reference with marked placeholders; put your own content there.',
+ );
+ } finally {
+ rmSync(dir, {recursive: true, force: true});
+ }
+ });
+
+ it('leaves the description of an item with no demo content as written', () => {
+ const {items} = buildShadcnRegistry(fixture());
+ expect(
+ items.find(item => item.name === 'showcase-button-variants').description,
+ ).toBe('Shows a primary button.');
+ expect(
+ items.find(item => item.name === 'template-dashboard').description,
+ ).toBe('A metrics dashboard.');
+ });
+
it('records the exact JavaScript bytes written by stock ShadCN', async () => {
const project = mkdtempSync(path.join(tmpdir(), 'astryx-shadcn-js-'));
try {
diff --git a/internal/shadcn-registry/verify-full-catalog.mjs b/internal/shadcn-registry/verify-full-catalog.mjs
index 78f961930b..45f04d9e40 100644
--- a/internal/shadcn-registry/verify-full-catalog.mjs
+++ b/internal/shadcn-registry/verify-full-catalog.mjs
@@ -35,6 +35,7 @@ import {
parseRegistryReceipt,
registryContentHash,
} from '../../packages/cli/authoring/shadcn/receipt.mjs';
+import {DEMO_CONTENT_MODULE} from '../../packages/cli/foundation/discovery/template-adapter.mjs';
import {expandWorkspaceDirs} from '../../scripts/lib/workspace-globs.mjs';
import {registryNameForPath} from '../../apps/docsite/src/lib/shadcnRegistry.mjs';
@@ -205,6 +206,14 @@ function verifyItemFileShape(item) {
if (receipt.schemaVersion !== 2) {
fail(`${item.name} receipt is not schema version 2`);
}
+ if (
+ source.content.includes('/template-assets/') ||
+ source.content.includes(DEMO_CONTENT_MODULE)
+ ) {
+ fail(
+ `${item.name} installs demo media or demo content that a copy replaces`,
+ );
+ }
const expectedJavaScriptTarget = shadcnJavaScriptTarget(source.target);
const javascript = receipt.files[0].variants.find(
variant => variant.format === 'javascript',
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 86fb485ad4..33b15d72d4 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -503,9 +503,9 @@ Every response has a `type` discriminant. The full set is below (generated from
| `gap-report.categories` | The fixed gap category values and human-readable labels; when a loaded integration names its own issues URL, meta.destinations lists every destination ({to, default, issuesUrl}) and meta.ask tells an agent to ask the person. |
| `gap-report.file` | An aggregate receipt: overall status, the selected package, issuesUrl (or null), deliveries in handler order, each {handlerType: project \| integration \| fallback, handler, audience, status, url, message}, and filedCount/routedOnlyCount totals; without --to, when a loaded integration names its own issues URL, destinations and ask as on gap-report.categories. |
| `template.list` | The effective discovered TemplateListEntry[] for pages and blocks. A winning replacement entry includes optional `replaces`, naming the Core id omitted from the default list. |
-| `template.show` | The resolved template's source, exactly as a copy writes it, plus its description, kind, the component names it composes, and demoMediaReplaced (how many Astryx demo media references were replaced with placeholders for you to swap for your own media). |
+| `template.show` | The resolved template's source, exactly as a copy writes it, plus its description, kind, the component names it composes, and demoMediaReplaced (how many Astryx demo media references were replaced with placeholders for you to swap for your own media), and demoContentReplaced (how many Astryx docs-only demo content elements were replaced with a Text placeholder for your own content). |
| `template.skeleton` | A layout skeleton (structural tags with spatial annotations) plus the template's description and the components it composes. The envelope's package names the npm package that owns the template. |
-| `template.copy` | A scaffold receipt: template id, output directory, written file name, file count, demoMediaReplaced (how many Astryx demo media references were replaced with placeholders), notes (setup notes naming what the template needs that the project lacks — missing packages, missing StyleX compiler; empty when satisfied), missingPackages (external package names the template imports that are not in the project), and installCommand (a ready-to-run install command with the detected package manager and workspace version ranges; null when nothing is missing, or when several lockfiles leave the package manager undetermined). The envelope's package names the npm package that owns the template. |
+| `template.copy` | A scaffold receipt: template id, output directory, written file name, file count, demoMediaReplaced (how many Astryx demo media references were replaced with placeholders), demoContentReplaced (how many Astryx docs-only demo content elements were replaced with a Text placeholder), notes (setup notes naming what the template needs that the project lacks — missing packages, missing StyleX compiler; empty when satisfied), missingPackages (external package names the template imports that are not in the project), and installCommand (a ready-to-run install command with the detected package manager and workspace version ranges; null when nothing is missing, or when several lockfiles leave the package manager undetermined). The envelope's package names the npm package that owns the template. |
| `template.cdn` | A write receipt for the no-build-step CDN starter page: the path (relative to cwd), the Astryx version every CDN URL was pinned to, whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |
| `hook.list` | The hook catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry. The envelope's package is @astryxdesign/core, the only package that ships hooks. |
| `hook.detail` | One hook's full authored HookDoc. The envelope's package is @astryxdesign/core. |
diff --git a/packages/cli/api/component/detail/showcase/showcase.mjs b/packages/cli/api/component/detail/showcase/showcase.mjs
index 1a05c3dd74..598478b526 100644
--- a/packages/cli/api/component/detail/showcase/showcase.mjs
+++ b/packages/cli/api/component/detail/showcase/showcase.mjs
@@ -1,7 +1,8 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file `component.detail.showcase` leaf — a component's hero showcase source.
+ * @file `component.detail.showcase` leaf — a component's hero showcase source,
+ * with each demo-content element replaced by a placeholder.
*
* @input a component name (+ cwd / package scope) or an explicit "no match"
* @output the `component.detail.showcase` envelope
@@ -11,7 +12,10 @@
import * as fs from 'node:fs';
import {AstryxError} from '../../../error.mjs';
import {ERROR_CODES} from '../../../../foundation/response/error-codes.mjs';
-import {findShowcase} from '../../../template/template.mjs';
+import {
+ findShowcase,
+ replaceDemoContent,
+} from '../../../template/template.mjs';
/**
* Resolve and read a component's showcase block into the
@@ -41,7 +45,9 @@ export async function componentDetailShowcase(componentName, {cwd, name, package
data: {
component: componentName,
aspectRatio: /** @type {number} */ (match.aspectRatio),
- source: fs.readFileSync(match.filePath, 'utf-8'),
+ // Handed-out source, not a copy: demo content becomes the placeholder a
+ // copy writes, and fixture media stays.
+ source: replaceDemoContent(fs.readFileSync(match.filePath, 'utf-8')).source,
},
};
}
diff --git a/packages/cli/api/component/detail/showcase/showcase.test.mjs b/packages/cli/api/component/detail/showcase/showcase.test.mjs
new file mode 100644
index 0000000000..678fe0d24c
--- /dev/null
+++ b/packages/cli/api/component/detail/showcase/showcase.test.mjs
@@ -0,0 +1,63 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `astryx component <Name> --showcase` hands out showcase source: each
+ * demo-content element becomes the placeholder a copy writes, and fixture
+ * media stays, because the output is not written into a project.
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {DEMO_CONTENT_MODULE} from '../../../../foundation/discovery/template-adapter.mjs';
+
+const findShowcase = vi.hoisted(() => vi.fn());
+vi.mock('../../../template/template.mjs', async importOriginal => ({
+ ...(await importOriginal()),
+ findShowcase,
+}));
+
+const {componentDetailShowcase} = await import('./showcase.mjs');
+
+describe('component.detail.showcase', () => {
+ let dir;
+ beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'showcase-demo-'));
+ });
+ afterEach(() => {
+ fs.rmSync(dir, {recursive: true, force: true});
+ findShowcase.mockReset();
+ });
+
+ it('replaces each demo-content element and keeps fixture media', async () => {
+ const filePath = path.join(dir, 'CardShowcase.tsx');
+ fs.writeFileSync(
+ filePath,
+ "import {Card} from '@astryxdesign/core/Card';\n" +
+ `import {PlayingCardContents} from '${DEMO_CONTENT_MODULE}';\n` +
+ 'export default function CardShowcase() {\n' +
+ ' return (\n' +
+ ' <Card padding={4}>\n' +
+ ' <PlayingCardContents rank="Q" suit="hearts" />\n' +
+ ' <img src="/template-assets/hero.jpg" alt="" />\n' +
+ ' </Card>\n' +
+ ' );\n' +
+ '}\n',
+ );
+ findShowcase.mockResolvedValue({filePath, aspectRatio: 1});
+
+ const result = await componentDetailShowcase('Card', {
+ cwd: dir,
+ name: 'Card',
+ ownerPackage: '@astryxdesign/core',
+ });
+
+ expect(result.data.source).not.toContain(DEMO_CONTENT_MODULE);
+ expect(result.data.source).not.toContain('PlayingCardContents');
+ expect(result.data.source).toContain(
+ '<Card padding={4}>\n <Text>Card content</Text>',
+ );
+ expect(result.data.source).toContain('/template-assets/hero.jpg');
+ });
+});
diff --git a/packages/cli/api/template/copy/copy.mjs b/packages/cli/api/template/copy/copy.mjs
index b2b947cfce..927251ea61 100644
--- a/packages/cli/api/template/copy/copy.mjs
+++ b/packages/cli/api/template/copy/copy.mjs
@@ -18,7 +18,10 @@ import {
} from '../../../foundation/fs/path-safety.mjs';
import {AstryxError, writeFailed} from '../../error.mjs';
import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
-import {pkgOf, replaceDemoMedia} from '../../../foundation/discovery/template-adapter.mjs';
+import {
+ pkgOf,
+ replaceTemplateDemos,
+} from '../../../foundation/discovery/template-adapter.mjs';
import {analyzeTemplateNeeds} from '../../../foundation/discovery/template-needs.mjs';
import {
NO_ICON_SETS,
@@ -89,12 +92,14 @@ export function templateCopy(
);
}
- // Strip demo image references so the scaffolded file renders without a
- // Meta-only network dependency. Read before any write, so a failure below
- // leaves nothing behind.
- const {source: withMedia, demoMediaReplaced} = replaceDemoMedia(
- fs.readFileSync(match.filePath, 'utf-8'),
- );
+ // Replace docs-only demo content and demo media references so the
+ // scaffolded file renders without anything only Astryx's previews provide.
+ // Read before any write, so a failure below leaves nothing behind.
+ const {
+ source: withMedia,
+ demoContentReplaced,
+ demoMediaReplaced,
+ } = replaceTemplateDemos(fs.readFileSync(match.filePath, 'utf-8'));
// Icons follow the project's icon set (AST-084 FR9). An icon with no match
// keeps its import, so its library stays a needed dependency below.
const {source: outputSource, icons} = mapTemplateIcons(
@@ -127,6 +132,7 @@ export function templateCopy(
fileName: outputFileName,
filesCopied: 1,
demoMediaReplaced,
+ demoContentReplaced,
notes,
missingPackages: missing,
installCommand,
diff --git a/packages/cli/api/template/copy/copy.receipt.test.mjs b/packages/cli/api/template/copy/copy.receipt.test.mjs
index c1b57e1459..a4b8f03bb9 100644
--- a/packages/cli/api/template/copy/copy.receipt.test.mjs
+++ b/packages/cli/api/template/copy/copy.receipt.test.mjs
@@ -1,9 +1,9 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file The template.copy receipt discloses replaced demo media. Templates are
- * picked by what their source contains, not by slug, so catalog renames do not
- * break the suite.
+ * @file The template.copy receipt discloses replaced demo media and demo
+ * content. Templates are picked by what their source contains, not by slug, so
+ * catalog renames do not break the suite.
*/
import {describe, it, expect, beforeEach, afterEach} from 'vitest';
@@ -11,6 +11,10 @@ import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import {template, discoverTemplates} from '../template.mjs';
+import {templateCopy} from './copy.mjs';
+import {templateShow} from '../show/show.mjs';
+import {templateSkeleton} from '../skeleton/skeleton.mjs';
+import {DEMO_CONTENT_MODULE} from '../../../foundation/discovery/template-adapter.mjs';
const SLOW = 60_000;
const FIXTURE_REF = /\/template-assets\/[\w.-]+\.(\w+)/g;
@@ -75,3 +79,107 @@ describe('template.copy receipt — replaced demo media', () => {
expect(res.data.demoMediaReplaced).toBe(0);
}, SLOW);
});
+
+describe('template.copy receipt — replaced demo content', () => {
+ let dir;
+ beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tmpl-receipt-'));
+ });
+ afterEach(() => fs.rmSync(dir, {recursive: true, force: true}));
+
+ const SOURCE =
+ "import {Card} from '@astryxdesign/core/Card';\n" +
+ `import {PlayingCardContents} from '${DEMO_CONTENT_MODULE}';\n\n` +
+ 'export default function CardDemo() {\n' +
+ ' return <Card><PlayingCardContents rank="Q" suit="hearts" /></Card>;\n' +
+ '}\n';
+
+ /** @returns {any} a resolved block whose source carries demo content */
+ function demoBlock() {
+ const filePath = path.join(dir, 'src', 'CardDemo.tsx');
+ fs.mkdirSync(path.dirname(filePath), {recursive: true});
+ fs.writeFileSync(filePath, SOURCE);
+ return {dirName: 'CardDemo', type: 'block', filePath, description: ''};
+ }
+
+ it('counts each demo-content element and writes the placeholder, not the demo import', () => {
+ const res = templateCopy(demoBlock(), {targetPath: './dest', cwd: dir});
+ expect(res.data.demoContentReplaced).toBe(1);
+ expect(res.data.demoMediaReplaced).toBe(0);
+ const written = fs.readFileSync(
+ path.join(dir, 'dest', 'CardDemo.tsx'),
+ 'utf-8',
+ );
+ expect(written).toContain('<Card><Text>Card content</Text></Card>');
+ expect(written).toContain("import {Text} from '@astryxdesign/core/Text';");
+ expect(written).not.toContain(DEMO_CONTENT_MODULE);
+ expect(written).not.toContain('PlayingCardContents');
+ });
+
+ it('show returns the same source the copy writes, with the same count', () => {
+ const match = demoBlock();
+ const shown = templateShow(match);
+ templateCopy(match, {targetPath: './dest', cwd: dir});
+ expect(shown.data.demoContentReplaced).toBe(1);
+ expect(shown.data.source).toBe(
+ fs.readFileSync(path.join(dir, 'dest', 'CardDemo.tsx'), 'utf-8'),
+ );
+ });
+
+ const PAGE_SOURCE =
+ "import {Card} from '@astryxdesign/core/Card';\n" +
+ "import {Badge} from '@astryxdesign/core/Badge';\n" +
+ `import {PlayingCardContents} from '${DEMO_CONTENT_MODULE}';\n\n` +
+ 'export default function CardDemo() {\n' +
+ ' return (\n' +
+ ' <Card padding={4}>\n' +
+ ' <Badge label="New" />\n' +
+ ' <PlayingCardContents rank="Q" suit="hearts" />\n' +
+ ' </Card>\n' +
+ ' );\n' +
+ '}\n';
+
+ /** @returns {any} a resolved page whose source carries demo content */
+ function demoPage() {
+ const filePath = path.join(dir, 'src', 'CardPage.tsx');
+ fs.mkdirSync(path.dirname(filePath), {recursive: true});
+ fs.writeFileSync(filePath, PAGE_SOURCE);
+ return {dirName: 'CardPage', type: 'page', filePath, description: ''};
+ }
+
+ it('show lists the components of the source it returns, not the demo content it replaced', () => {
+ const {data} = templateShow(demoPage());
+ expect(data.source).not.toContain('PlayingCardContents');
+ expect(data.components).toEqual(['Badge', 'Card']);
+ });
+
+ it('skeleton lists, and lays out, the components of the replaced source', () => {
+ const {data} = templateSkeleton(demoPage(), []);
+ expect(data.components).toEqual(['Badge', 'Card']);
+ expect(data.skeleton).not.toContain('PlayingCardContents');
+ expect(data.skeleton).toContain('<Card padding={4}>');
+ });
+
+ /** @returns {any} a resolved page that writes its own `Text` beside demo content */
+ function demoPageWithOwnText() {
+ const filePath = path.join(dir, 'src', 'OwnTextPage.tsx');
+ fs.mkdirSync(path.dirname(filePath), {recursive: true});
+ const source = `import {Text} from './Text';\n${PAGE_SOURCE}`;
+ fs.writeFileSync(filePath, source.replace('/>\n', '/>\n <Text>Note</Text>\n'));
+ return {dirName: 'OwnTextPage', type: 'page', filePath, description: ''};
+ }
+
+ it('show and skeleton list the canonical name, not the placeholder alias, when the file writes Text', () => {
+ const match = demoPageWithOwnText();
+ const shown = templateShow(match).data;
+ expect(shown.source).toContain("import {Text as AstryxText} from '@astryxdesign/core/Text';");
+ expect(shown.components).toEqual(['Badge', 'Card']);
+ expect(templateSkeleton(match, []).data.components).toEqual(['Badge', 'Card']);
+ });
+
+ it('reports 0 for a catalog template that carries no demo content', async () => {
+ const {id} = await findTemplate('page', r => r.length === 0);
+ const res = await template(id, {targetPath: './dest', cwd: dir});
+ expect(res.data.demoContentReplaced).toBe(0);
+ }, SLOW);
+});
diff --git a/packages/cli/api/template/show/show.mjs b/packages/cli/api/template/show/show.mjs
index fd493a23c4..1e2d6ec853 100644
--- a/packages/cli/api/template/show/show.mjs
+++ b/packages/cli/api/template/show/show.mjs
@@ -12,9 +12,9 @@ import * as fs from 'node:fs';
import {AstryxError} from '../../error.mjs';
import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
import {
- extractComponents,
+ componentsInSource,
pkgOf,
- replaceDemoMedia,
+ replaceTemplateDemos,
} from '../../../foundation/discovery/template-adapter.mjs';
import {
NO_ICON_SETS,
@@ -38,11 +38,14 @@ export function templateShow(match, {iconSets = NO_ICON_SETS} = {}) {
}
// The source template.copy writes (spec:AST-028 FR7): a template printed and
- // pasted must not keep a media path only Astryx's previews serve, and the
- // caller is told how many it replaced, the way the copy receipt tells it.
- const {source: withMedia, demoMediaReplaced} = replaceDemoMedia(
- fs.readFileSync(match.filePath, 'utf-8'),
- );
+ // pasted must not keep demo content or a media path only Astryx's previews
+ // serve, and the caller is told how many it replaced, the way the copy
+ // receipt tells it.
+ const {
+ source: withMedia,
+ demoContentReplaced,
+ demoMediaReplaced,
+ } = replaceTemplateDemos(fs.readFileSync(match.filePath, 'utf-8'));
// Icons follow the project's icon set, as template.copy writes them.
const {source, icons} = mapTemplateIcons(withMedia, iconSets, match.icons);
@@ -53,9 +56,10 @@ export function templateShow(match, {iconSets = NO_ICON_SETS} = {}) {
template: match.dirName,
description: match.description,
type: match.type,
- components: extractComponents(match.filePath),
+ components: componentsInSource(source),
source,
demoMediaReplaced,
+ demoContentReplaced,
...(icons ? {icons} : {}),
},
};
diff --git a/packages/cli/api/template/show/show.test.mjs b/packages/cli/api/template/show/show.test.mjs
index f6aece8207..cb8c9c1e2a 100644
--- a/packages/cli/api/template/show/show.test.mjs
+++ b/packages/cli/api/template/show/show.test.mjs
@@ -52,10 +52,11 @@ describe('template.show', () => {
let reported = 0;
for (const match of templates) {
const raw = read(match.filePath);
- const {source, demoMediaReplaced} = templateShow(match).data;
- if (source === raw) expect(demoMediaReplaced, match.dirName).toBe(0);
- else expect(demoMediaReplaced, match.dirName).toBeGreaterThan(0);
- reported += demoMediaReplaced;
+ const {source, demoMediaReplaced, demoContentReplaced} = templateShow(match).data;
+ const replaced = demoMediaReplaced + demoContentReplaced;
+ if (source === raw) expect(replaced, match.dirName).toBe(0);
+ else expect(replaced, match.dirName).toBeGreaterThan(0);
+ reported += replaced;
}
expect(reported).toBeGreaterThan(0);
}, SLOW);
diff --git a/packages/cli/api/template/skeleton/skeleton.mjs b/packages/cli/api/template/skeleton/skeleton.mjs
index 26461a7530..c0e4cd3943 100644
--- a/packages/cli/api/template/skeleton/skeleton.mjs
+++ b/packages/cli/api/template/skeleton/skeleton.mjs
@@ -5,13 +5,18 @@
* spatial annotations) plus the components a resolved template composes.
*
* @position api/template/skeleton — derives a compact layout reference from the
- * resolved match's source; the template dispatcher routes `--skeleton` here.
+ * resolved match's source, with demo content replaced as a copy replaces it;
+ * the template dispatcher routes `--skeleton` here.
*/
import * as fs from 'node:fs';
import {AstryxError} from '../../error.mjs';
import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
-import {extractComponents, pkgOf} from '../../../foundation/discovery/template-adapter.mjs';
+import {
+ componentsInSource,
+ pkgOf,
+ replaceTemplateDemos,
+} from '../../../foundation/discovery/template-adapter.mjs';
const STRUCTURAL = new Set([
'AppShell',
@@ -242,15 +247,19 @@ export function templateSkeleton(match, templates) {
ERROR_CODES.ERR_NO_SOURCE,
);
}
- const src = fs.readFileSync(match.filePath, 'utf-8');
+ // The skeleton outlines the source that template.show returns, so it never
+ // names demo content that a copy replaces.
+ const {source} = replaceTemplateDemos(
+ fs.readFileSync(match.filePath, 'utf-8'),
+ );
return {
type: 'template.skeleton',
package: pkgOf(match),
data: {
template: match.dirName,
description: match.description,
- components: extractComponents(match.filePath),
- skeleton: extractSkeleton(src),
+ components: componentsInSource(source),
+ skeleton: extractSkeleton(source),
},
};
}
diff --git a/packages/cli/api/template/template.doc.mjs b/packages/cli/api/template/template.doc.mjs
index 71fabf1a00..66f2f92b05 100644
--- a/packages/cli/api/template/template.doc.mjs
+++ b/packages/cli/api/template/template.doc.mjs
@@ -115,7 +115,7 @@ export const doc = {
{
type: 'template.show',
description:
- "The resolved template's source, exactly as a copy writes it, plus its description, kind, the component names it composes, and `demoMediaReplaced` — how many Astryx demo media references (images, posters, videos) in the source were replaced with placeholders for you to swap for your own media.",
+ "The resolved template's source, exactly as a copy writes it, plus its description, kind, the component names it composes, and `demoMediaReplaced` — how many Astryx demo media references (images, posters, videos) in the source were replaced with placeholders for you to swap for your own media, and `demoContentReplaced` — how many Astryx docs-only demo content elements were replaced with a `<Text>` placeholder for your own content.",
},
{
type: 'template.skeleton',
@@ -125,7 +125,7 @@ export const doc = {
{
type: 'template.copy',
description:
- 'A receipt after scaffolding the template into the project: the template id, output directory, written file name, file count, `demoMediaReplaced` — how many Astryx demo media references were replaced with placeholders, `notes` — setup notes naming what the template needs that the project lacks (missing packages, missing StyleX compiler; empty when satisfied), `missingPackages` — external package names the template imports that are not in the project, and `installCommand` — a ready-to-run install command with the detected package manager and workspace version ranges (null when nothing is missing, or when several lockfiles leave the package manager undetermined; `missingPackages` still names the packages).',
+ 'A receipt after scaffolding the template into the project: the template id, output directory, written file name, file count, `demoMediaReplaced` — how many Astryx demo media references were replaced with placeholders, `demoContentReplaced` — how many Astryx docs-only demo content elements were replaced with a `<Text>` placeholder, `notes` — setup notes naming what the template needs that the project lacks (missing packages, missing StyleX compiler; empty when satisfied), `missingPackages` — external package names the template imports that are not in the project, and `installCommand` — a ready-to-run install command with the detected package manager and workspace version ranges (null when nothing is missing, or when several lockfiles leave the package manager undetermined; `missingPackages` still names the packages).',
},
{
type: 'template.cdn',
diff --git a/packages/cli/api/template/template.mjs b/packages/cli/api/template/template.mjs
index 33e97af45b..98e4bbcfbc 100644
--- a/packages/cli/api/template/template.mjs
+++ b/packages/cli/api/template/template.mjs
@@ -44,6 +44,7 @@ export {
discoverIntegrationTemplatesForOne,
stripTemplateAssetRefs,
replaceDemoMedia,
+ replaceDemoContent,
listTemplates,
findRelatedBlocks,
findShowcase,
diff --git a/packages/cli/api/template/template.type.mjs b/packages/cli/api/template/template.type.mjs
index e760845ad9..b05faf780c 100644
--- a/packages/cli/api/template/template.type.mjs
+++ b/packages/cli/api/template/template.type.mjs
@@ -55,6 +55,7 @@
* @property {string[]} data.components
* @property {string} data.source
* @property {number} data.demoMediaReplaced Astryx demo media references (images, posters, videos) replaced in the returned source: images with a neutral placeholder, videos with an empty source. Swap in your own media at those points; no media is installed. 0 when the template carried none.
+ * @property {number} data.demoContentReplaced Astryx docs-only demo content elements (such as a playing card's face in a motion example) replaced in the returned source with a `<Text>Card content</Text>` placeholder. Put your own content there. 0 when the template carried none.
* @property {TemplateIconsReport} [data.icons] Experimental, present only when the project sets `experimental.iconSet`: how the template's icons follow the project's icon set, each icon `mapped` (source and target) or `kept`, and the icon-set state. It may change or be removed in a patch release.
*/
@@ -81,6 +82,7 @@
* @property {string} data.fileName
* @property {number} data.filesCopied
* @property {number} data.demoMediaReplaced Astryx demo media references (images, posters, videos) replaced in the written file: images with a neutral placeholder, videos with an empty source. Swap in your own media at those points; no media is installed. 0 when the template carried none.
+ * @property {number} data.demoContentReplaced Astryx docs-only demo content elements (such as a playing card's face in a motion example) replaced in the written file with a `<Text>Card content</Text>` placeholder. Put your own content there. 0 when the template carried none.
* @property {string[]} data.notes Setup notes: what the template needs that the project lacks (missing packages, missing StyleX compiler). Each note is one actionable line. Empty when the template needs nothing the project lacks.
* @property {string[]} data.missingPackages External package names the template imports that are not in the project's dependencies. Empty when none are missing.
* @property {string | null} data.installCommand A ready-to-run install command for the missing packages, using the project's package manager and the CLI workspace's version ranges. Null when no packages are missing, or when several lockfiles leave the package manager undetermined; missingPackages still names the packages.
diff --git a/packages/cli/clients/cli/commands/template.mjs b/packages/cli/clients/cli/commands/template.mjs
index b25003408b..ab08c9e7da 100644
--- a/packages/cli/clients/cli/commands/template.mjs
+++ b/packages/cli/clients/cli/commands/template.mjs
@@ -32,6 +32,20 @@ export {discoverTemplates, listTemplates} from '../../../api/template/template.m
* )} TemplateResponse
*/
+/**
+ * The line saying how many docs-only demo content elements became a
+ * placeholder, in the copied file when one is named.
+ * @param {number} count
+ * @param {string} [file]
+ * @returns {string}
+ */
+function demoContentNote(count, file) {
+ return (
+ `Replaced ${count} Astryx demo content element${count === 1 ? '' : 's'}${file ? ` in ${file}` : ''} ` +
+ 'with a <Text>Card content</Text> placeholder. Put your own content there.'
+ );
+}
+
/**
* The icon report as text lines (AST-084 FR10): one line per mapped or kept
* icon, or one line saying why nothing was mapped. Nothing when the project
@@ -245,7 +259,8 @@ export function registerTemplate(program) {
// from (cli-surface INV28) and the note about replaced demo media go
// to stderr, the note in the copy receipt's words. (Text mode only:
// --json returned above with both in the envelope.)
- const {source, demoMediaReplaced, icons} = result.data;
+ const {source, demoMediaReplaced, demoContentReplaced, icons} =
+ result.data;
console.error(`package: ${result.package}`);
emit(code(source));
if (demoMediaReplaced > 0) {
@@ -254,14 +269,23 @@ export function registerTemplate(program) {
'images now show a neutral placeholder and videos have an empty source. Supply your own media there.',
);
}
+ if (demoContentReplaced > 0) {
+ console.error(demoContentNote(demoContentReplaced));
+ }
// The icon report goes to stderr too, so stdout stays the source.
for (const line of iconLines(icons)) console.error(line);
break;
}
case 'template.copy': {
- const {outputDir, fileName, demoMediaReplaced, notes, icons} =
- result.data;
+ const {
+ outputDir,
+ fileName,
+ demoMediaReplaced,
+ demoContentReplaced,
+ notes,
+ icons,
+ } = result.data;
const file = `${outputDir}/${fileName}`;
const iconText = iconLines(icons);
emit(
@@ -272,6 +296,8 @@ export function registerTemplate(program) {
`Replaced ${demoMediaReplaced} Astryx demo media reference${demoMediaReplaced === 1 ? '' : 's'} in ${file}: ` +
'images now show a neutral placeholder and videos have an empty source. Supply your own media there.',
),
+ demoContentReplaced > 0 &&
+ text(demoContentNote(demoContentReplaced, file)),
...notes.map(/** @param {string} note */ note => text(note)),
iconText.length > 0 && text(iconText.join('\n')),
);
diff --git a/packages/cli/foundation/discovery/template-adapter.demo-content.test.mjs b/packages/cli/foundation/discovery/template-adapter.demo-content.test.mjs
new file mode 100644
index 0000000000..08dd9c0e25
--- /dev/null
+++ b/packages/cli/foundation/discovery/template-adapter.demo-content.test.mjs
@@ -0,0 +1,293 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Docs-only demo content (template-authoring INV8): every JSX element a
+ * template imports from the demo-content module becomes a generic `<Text>`
+ * placeholder in emitted source, the import goes, and anything that cannot be
+ * replaced without leaving a reference or dropping code throws.
+ */
+
+import {describe, expect, it} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {parse as parseModule} from '@babel/parser';
+import {
+ DEMO_CONTENT_MODULE,
+ replaceDemoContent,
+ replaceTemplateDemos,
+} from './template-adapter.mjs';
+
+/** @param {string} source */
+const parse = source =>
+ parseModule(source, {sourceType: 'module', plugins: ['jsx', 'typescript']});
+
+const CARD = "import {Card} from '@astryxdesign/core/Card';\n";
+const DEMO = `import {PlayingCardContents} from '${DEMO_CONTENT_MODULE}';\n`;
+
+describe('replaceDemoContent', () => {
+ it('replaces a demo element with a Text placeholder and imports Text in place of the demo import', () => {
+ const source =
+ CARD +
+ DEMO +
+ '\nexport default function Example() {\n' +
+ ' return <Card><PlayingCardContents rank="Q" suit="hearts" /></Card>;\n' +
+ '}\n';
+ expect(replaceDemoContent(source)).toEqual({
+ source:
+ CARD +
+ "import {Text} from '@astryxdesign/core/Text';\n" +
+ '\nexport default function Example() {\n' +
+ ' return <Card><Text>Card content</Text></Card>;\n' +
+ '}\n',
+ demoContentReplaced: 1,
+ });
+ });
+
+ it('reuses an existing Text import, under its local name, and counts each element', () => {
+ const source =
+ "import {Text as Label} from '@astryxdesign/core/Text';\n" +
+ `import {PlayingCardBack, PlayingCardContents as Face} from '${DEMO_CONTENT_MODULE}';\n` +
+ 'const a = <Face rank="A" suit={"spades"} />;\n' +
+ 'const b = (\n <PlayingCardBack>\n </PlayingCardBack>\n);\n';
+ const result = replaceDemoContent(source);
+ expect(result.demoContentReplaced).toBe(2);
+ expect(result.source).toBe(
+ "import {Text as Label} from '@astryxdesign/core/Text';\n" +
+ 'const a = <Label>Card content</Label>;\n' +
+ 'const b = (\n <Label>Card content</Label>\n);\n',
+ );
+ });
+
+ it('replaces an element whose prop reads a variable the file still reads', () => {
+ const source =
+ DEMO +
+ 'const [isFaceUp, setIsFaceUp] = useState(true);\n' +
+ 'const a = (\n <Card aria-pressed={!isFaceUp}>\n' +
+ ' <PlayingCardContents rank="Q" suit="hearts" faceDown={!isFaceUp} />\n' +
+ ' </Card>\n);\n';
+ expect(replaceDemoContent(source)).toEqual({
+ source:
+ "import {Text} from '@astryxdesign/core/Text';\n" +
+ 'const [isFaceUp, setIsFaceUp] = useState(true);\n' +
+ 'const a = (\n <Card aria-pressed={!isFaceUp}>\n' +
+ ' <Text>Card content</Text>\n' +
+ ' </Card>\n);\n',
+ demoContentReplaced: 1,
+ });
+ });
+
+ it('removes an unused demo import without adding Text', () => {
+ const source = `${DEMO}export const x = 1;\n`;
+ expect(replaceDemoContent(source)).toEqual({
+ source: 'export const x = 1;\n',
+ demoContentReplaced: 0,
+ });
+ });
+
+ it('returns source that never names the module unchanged', () => {
+ const source = `${CARD}export default () => <Card />;\n`;
+ expect(replaceDemoContent(source)).toEqual({
+ source,
+ demoContentReplaced: 0,
+ });
+ });
+
+ it('leaves a comment that mentions the module as written', () => {
+ const source = `// Demo content comes from ${DEMO_CONTENT_MODULE}.\nexport const x = 1;\n`;
+ expect(replaceDemoContent(source)).toEqual({
+ source,
+ demoContentReplaced: 0,
+ });
+ });
+
+ it('imports Text under a unique alias when a module-level destructuring already binds Text', () => {
+ const source =
+ CARD +
+ DEMO +
+ 'const {Text} = Typography;\n' +
+ 'export default function Example() {\n' +
+ ' return <Card><Text>Title</Text><PlayingCardContents rank="Q" suit="hearts" /></Card>;\n' +
+ '}\n';
+ const result = replaceDemoContent(source);
+ expect(result).toEqual({
+ source:
+ CARD +
+ "import {Text as AstryxText} from '@astryxdesign/core/Text';\n" +
+ 'const {Text} = Typography;\n' +
+ 'export default function Example() {\n' +
+ ' return <Card><Text>Title</Text><AstryxText>Card content</AstryxText></Card>;\n' +
+ '}\n',
+ demoContentReplaced: 1,
+ });
+ expect(() => parse(result.source)).not.toThrow();
+ });
+
+ it('imports Text under a unique alias when a local declaration named Text exists', () => {
+ const source = `${DEMO}function Text() { return null; }\nconst a = <PlayingCardContents rank="Q" suit="hearts" />;\n`;
+ expect(replaceDemoContent(source)).toEqual({
+ source:
+ "import {Text as AstryxText} from '@astryxdesign/core/Text';\n" +
+ 'function Text() { return null; }\n' +
+ 'const a = <AstryxText>Card content</AstryxText>;\n',
+ demoContentReplaced: 1,
+ });
+ });
+
+ it('does not use an Astryx Text import that a parameter named Text shadows at the element', () => {
+ const source =
+ "import {Text} from '@astryxdesign/core/Text';\n" +
+ DEMO +
+ 'export const title = <Text>Title</Text>;\n' +
+ 'export function Face({Text}) {\n' +
+ ' return <Text><PlayingCardContents rank="Q" suit="hearts" /></Text>;\n' +
+ '}\n';
+ const result = replaceDemoContent(source);
+ expect(result).toEqual({
+ source:
+ "import {Text} from '@astryxdesign/core/Text';\n" +
+ "import {Text as AstryxText} from '@astryxdesign/core/Text';\n" +
+ 'export const title = <Text>Title</Text>;\n' +
+ 'export function Face({Text}) {\n' +
+ ' return <Text><AstryxText>Card content</AstryxText></Text>;\n' +
+ '}\n',
+ demoContentReplaced: 1,
+ });
+ expect(() => parse(result.source)).not.toThrow();
+ });
+
+ it('reuses an Astryx Text import from the package root when it is the binding at every element', () => {
+ const source =
+ "import {Card, Text} from '@astryxdesign/core';\n" +
+ DEMO +
+ 'export const a = <Card><Text>Title</Text><PlayingCardContents rank="Q" suit="hearts" /></Card>;\n';
+ expect(replaceDemoContent(source)).toEqual({
+ source:
+ "import {Card, Text} from '@astryxdesign/core';\n" +
+ 'export const a = <Card><Text>Title</Text><Text>Card content</Text></Card>;\n',
+ demoContentReplaced: 1,
+ });
+ });
+
+ it.each([
+ [
+ 'a spread prop',
+ `${DEMO}const p = {rank: 'Q'};\nconst a = <PlayingCardContents {...p} />;\n`,
+ /spreads props/u,
+ ],
+ [
+ 'a prop that runs code',
+ `${DEMO}const a = <PlayingCardContents rank={pickRank()} suit="hearts" />;\n`,
+ /prop rank is not a literal value or a variable read/u,
+ ],
+ [
+ 'a prop whose variable nothing else reads',
+ `${DEMO}const r = 'Q';\nconst a = <PlayingCardContents rank={r} suit="hearts" />;\n`,
+ /reads r, and nothing else in the file reads it/u,
+ ],
+ [
+ 'a prop whose variable is only declared elsewhere',
+ `${DEMO}const [isOpen, setIsOpen] = useState(false);\nfunction f({isOpen: x} = {}) {}\nconst a = <PlayingCardContents rank="Q" suit="hearts" faceDown={!isOpen} />;\n`,
+ /reads isOpen, and nothing else in the file reads it/u,
+ ],
+ [
+ 'children',
+ `${DEMO}const a = <PlayingCardContents rank="Q" suit="hearts">Q</PlayingCardContents>;\n`,
+ /has children/u,
+ ],
+ [
+ 'a use outside JSX',
+ `${DEMO}const Face = PlayingCardContents;\n`,
+ /PlayingCardContents is used as a value/u,
+ ],
+ [
+ 'a shorthand object value',
+ `${DEMO}const parts = {PlayingCardContents};\n`,
+ /used as a value/u,
+ ],
+ [
+ 'a namespace import',
+ `import * as Demo from '${DEMO_CONTENT_MODULE}';\nconst a = <Demo.PlayingCardContents rank="Q" suit="hearts" />;\n`,
+ /only named value imports/u,
+ ],
+ [
+ 'a default import',
+ `import Demo from '${DEMO_CONTENT_MODULE}';\n`,
+ /only named value imports/u,
+ ],
+ [
+ 'a type import',
+ `import type {PlayingCardSuit} from '${DEMO_CONTENT_MODULE}';\n`,
+ /imported as a type/u,
+ ],
+ [
+ 'a re-export',
+ `export {PlayingCardContents} from '${DEMO_CONTENT_MODULE}';\n`,
+ /outside a static import/u,
+ ],
+ [
+ 'a dynamic import',
+ `const m = import('${DEMO_CONTENT_MODULE}');\n`,
+ /outside a static import/u,
+ ],
+ [
+ 'a prop whose variable only another component reads, by the same name',
+ `${DEMO}function Face() {\n const rank = 'Q';\n return <PlayingCardContents rank={rank} suit="hearts" />;\n}\nfunction Label({rank}) {\n return rank;\n}\n`,
+ /reads rank, and nothing else in the file reads it/u,
+ ],
+ [
+ 'source that does not parse',
+ `${DEMO}const a = <PlayingCardContents rank="Q" ;\n`,
+ /does not parse/u,
+ ],
+ ])('fails closed on %s', (_label, source, reason) => {
+ expect(() => replaceDemoContent(source)).toThrow(reason);
+ expect(() => replaceDemoContent(source)).toThrow(
+ `Demo content from ${DEMO_CONTENT_MODULE} cannot be replaced safely`,
+ );
+ });
+});
+
+describe('replaceTemplateDemos', () => {
+ it('reports both counts, replacing demo content and demo media in one pass', () => {
+ const source =
+ DEMO +
+ 'const a = (\n <>\n <PlayingCardContents rank="Q" suit="hearts" />\n' +
+ ' <img src="/template-assets/hero.png" alt="" />\n </>\n);\n';
+ const result = replaceTemplateDemos(source);
+ expect(result.demoContentReplaced).toBe(1);
+ expect(result.demoMediaReplaced).toBe(1);
+ expect(result.source).not.toContain(DEMO_CONTENT_MODULE);
+ expect(result.source).not.toContain('PlayingCardContents');
+ expect(result.source).not.toContain('/template-assets/');
+ });
+});
+
+describe('catalog blocks', () => {
+ const blocksDir = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '../../assets/templates/blocks',
+ );
+ /** @param {string} dir @returns {string[]} */
+ const tsxFiles = dir =>
+ fs.readdirSync(dir, {withFileTypes: true}).flatMap(entry => {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) return tsxFiles(full);
+ return entry.name.endsWith('.tsx') && !entry.name.includes('.test.')
+ ? [full]
+ : [];
+ });
+ const files = tsxFiles(blocksDir);
+
+ it('finds the catalog', () => {
+ expect(files.length).toBeGreaterThan(100);
+ });
+
+ it('leaves no demo-content reference in any block as a copy writes it', () => {
+ const remaining = files.filter(file => {
+ const {source} = replaceTemplateDemos(fs.readFileSync(file, 'utf8'));
+ return source.includes(DEMO_CONTENT_MODULE);
+ });
+ expect(remaining).toEqual([]);
+ });
+});
diff --git a/packages/cli/foundation/discovery/template-adapter.mjs b/packages/cli/foundation/discovery/template-adapter.mjs
index e6aa658592..778a8e1dd1 100644
--- a/packages/cli/foundation/discovery/template-adapter.mjs
+++ b/packages/cli/foundation/discovery/template-adapter.mjs
@@ -30,6 +30,13 @@ import {importDocModule} from '../doc-compiler/import.mjs';
import {CLI_ROOT, discoverExternalPackages} from '../fs/paths.mjs';
import {CORE_PROVIDER_ID} from '../identity/providers.mjs';
import {Project} from '../config/project.mjs';
+import {
+ isReference,
+ parseTemplateSource,
+ programPath,
+ traverseTemplateSource,
+ writtenNames,
+} from './template-source-tree.mjs';
const require = createRequire(import.meta.url);
@@ -233,6 +240,14 @@ const PLACEHOLDER_IMAGE =
*/
const VIDEO_EXTENSIONS = new Set(['mp4', 'webm', 'mov', 'ogv', 'm4v']);
+/**
+ * A video placeholder that names itself in the source, for a copy that has no
+ * response to disclose the replacement in, such as the shadcn install. It is a
+ * text data URL: it makes no request, it does not play, and it is not image
+ * data, so a video element never receives image bytes.
+ */
+export const MARKED_VIDEO_PLACEHOLDER = 'data:,placeholder-video-add-your-own';
+
const IMAGE_EXTENSIONS = new Set([
'svg',
'png',
@@ -334,9 +349,11 @@ export function stripTemplateAssetRefs(source) {
* third-party URL left as written. That count is what a receipt discloses.
*
* @param {string} source - Template source code.
+ * @param {{videoPlaceholder?: string}} [options] - `videoPlaceholder` replaces
+ * each video reference; the default is an empty source.
* @returns {{source: string, demoMediaReplaced: number}}
*/
-export function replaceDemoMedia(source) {
+export function replaceDemoMedia(source, {videoPlaceholder = ''} = {}) {
const needle = `/${FIXTURE_SEGMENT}`;
let output = '';
let copied = 0;
@@ -352,7 +369,7 @@ export function replaceDemoMedia(source) {
/** @type {{text: string, end: number} | null} */
let edit;
try {
- edit = fixtureEdit(source, start, at, end);
+ edit = fixtureEdit(source, start, at, end, videoPlaceholder);
} catch (err) {
comments ??= commentRanges(source);
if (!comments.some(([from, to]) => from <= at && at < to)) throw err;
@@ -368,6 +385,359 @@ export function replaceDemoMedia(source) {
return {source: output + source.slice(copied), demoMediaReplaced};
}
+/**
+ * The one module docs-only demo content is imported from. A template imports
+ * an element such as a playing card's face from here so its live preview shows
+ * real-looking content; the module exists only where Astryx's own previews
+ * build templates, so a copy replaces every element imported from it (see
+ * {@link replaceDemoContent}).
+ */
+export const DEMO_CONTENT_MODULE = '@astryx-docs/demo-content';
+
+/** What a demo-content element becomes in emitted source. */
+const DEMO_CONTENT_PLACEHOLDER_TEXT = 'Card content';
+
+/** Where emitted placeholders import Text from, as catalog templates do. */
+const TEXT_MODULE = '@astryxdesign/core/Text';
+
+/** The modules an existing Astryx Text import can come from. */
+const TEXT_MODULES = new Set([TEXT_MODULE, '@astryxdesign/core']);
+
+/** The local name a new Text import takes when the file already writes `Text`. */
+const TEXT_ALIAS = 'AstryxText';
+
+/**
+ * Replace each JSX element imported from {@link DEMO_CONTENT_MODULE} with a
+ * generic `<Text>` placeholder and remove that import, so emitted source never
+ * depends on content only Astryx's previews provide.
+ *
+ * Every check resolves a name to its binding through the module's scope, so a
+ * local declaration or parameter with the same name never counts as the same
+ * variable. The placeholder uses an existing Text import from Astryx when that
+ * import is the binding its name resolves to at every replaced element. Else
+ * the placeholder imports Text, under a unique alias when the file already
+ * writes the name `Text`.
+ *
+ * Only a plain static use is replaced: a named import used only as a JSX tag
+ * whose children, if any, are whitespace, and whose props are literal values or
+ * read only bindings that code outside the replaced elements still reads. So
+ * `faceDown={!isOpen}` is safe when the same `isOpen` is also read elsewhere.
+ * Anything else (a namespace or type import, a re-export, a dynamic import, the
+ * element used as a value or a type, a spread or computed prop, a prop whose
+ * binding nothing else reads, children) throws, naming the element, rather than
+ * leaving a reference behind, leaving a binding unused, or dropping code the
+ * rest of the file relies on. Source that never names the module is returned
+ * as is.
+ *
+ * @param {string} source - Template source code.
+ * @returns {{source: string, demoContentReplaced: number}}
+ */
+export function replaceDemoContent(source) {
+ if (!source.includes(DEMO_CONTENT_MODULE)) {
+ return {source, demoContentReplaced: 0};
+ }
+ /** @type {any} */
+ let file;
+ try {
+ file = parseTemplateSource(source);
+ } catch (err) {
+ throw unsafeDemoContent(
+ `the source does not parse (${/** @type {Error} */ (err).message})`,
+ );
+ }
+
+ /** @type {any[]} */
+ const demoImports = [];
+ for (const statement of file.program.body) {
+ if (
+ statement.type !== 'ImportDeclaration' ||
+ statement.source.value !== DEMO_CONTENT_MODULE
+ ) {
+ continue;
+ }
+ if (statement.importKind === 'type') {
+ throw unsafeDemoContent('it is imported as a type');
+ }
+ for (const specifier of statement.specifiers) {
+ if (
+ specifier.type !== 'ImportSpecifier' ||
+ specifier.importKind === 'type'
+ ) {
+ throw unsafeDemoContent(
+ 'only named value imports can be replaced; import each element by name',
+ );
+ }
+ }
+ demoImports.push(statement);
+ }
+
+ const program = programPath(file);
+ const demoBindings = new Set(
+ demoImports.flatMap(statement =>
+ statement.specifiers.map((/** @type {any} */ specifier) =>
+ program.scope.getBinding(specifier.local.name),
+ ),
+ ),
+ );
+ /** The paths of the JSX elements to replace. */
+ /** @type {any[]} */
+ const elements = [];
+ traverseTemplateSource(file, {
+ StringLiteral(/** @type {any} */ path) {
+ if (
+ path.node.value === DEMO_CONTENT_MODULE &&
+ !(path.parentPath.isImportDeclaration() && path.key === 'source')
+ ) {
+ throw unsafeDemoContent(
+ 'it is used outside a static import (a re-export, dynamic import, require, or string value)',
+ );
+ }
+ },
+ TemplateLiteral(/** @type {any} */ path) {
+ if (
+ path.node.quasis.some((/** @type {any} */ quasi) =>
+ quasi.value.cooked?.includes(DEMO_CONTENT_MODULE),
+ )
+ ) {
+ throw unsafeDemoContent('it is used outside a static import');
+ }
+ },
+ 'Identifier|JSXIdentifier'(/** @type {any} */ path) {
+ const {node, parentPath} = path;
+ if (!demoBindings.has(path.scope.getBinding(node.name))) return;
+ if (!isReference(node, path.parent, path.listKey ?? path.key)) return;
+ if (path.key === 'name' && parentPath.isJSXOpeningElement()) {
+ elements.push(parentPath.parentPath);
+ return;
+ }
+ if (path.key === 'name' && parentPath.isJSXClosingElement()) return;
+ if (parentPath.isJSXMemberExpression()) {
+ throw unsafeDemoContent(`${node.name} is used as a namespace`);
+ }
+ throw unsafeDemoContent(
+ `${node.name} is used as a value, not only as a JSX element`,
+ );
+ },
+ });
+
+ /** @param {any} node */
+ const isReplaced = node =>
+ elements.some(
+ element =>
+ element.node.start <= node.start && node.end <= element.node.end,
+ );
+ for (const element of elements) {
+ for (const variable of assertStaticDemoElement(element.node)) {
+ const binding = element.scope.getBinding(variable);
+ // An unbound name is a global: removing its read leaves nothing unused.
+ if (!binding || isExportedDeclaration(binding)) continue;
+ if (
+ binding.referencePaths.every((/** @type {any} */ ref) =>
+ isReplaced(ref.node),
+ )
+ ) {
+ throw unsafeDemoContent(
+ `<${element.node.openingElement.name.name}> reads ${variable}, and nothing else in the file reads it, so the copy would leave it unused`,
+ );
+ }
+ }
+ }
+
+ const reused =
+ elements.length === 0 ? null : astryxTextAtEvery(file, program, elements);
+ const written = writtenNames(file);
+ const textName =
+ reused ?? (written.has('Text') ? uniqueName(TEXT_ALIAS, written) : 'Text');
+ const textImport =
+ elements.length > 0 && reused === null
+ ? `import {${textName === 'Text' ? 'Text' : `Text as ${textName}`}} from '${TEXT_MODULE}';\n`
+ : '';
+ const placeholder = `<${textName}>${DEMO_CONTENT_PLACEHOLDER_TEXT}</${textName}>`;
+
+ /** @type {Array<{start: number, end: number, text: string}>} */
+ const edits = elements.map(element => ({
+ start: element.node.start,
+ end: element.node.end,
+ text: placeholder,
+ }));
+ demoImports.forEach((statement, index) => {
+ let end = statement.end;
+ if (source[end] === '\n') end += 1;
+ edits.push({
+ start: statement.start,
+ end,
+ text: index === 0 ? textImport : '',
+ });
+ });
+ edits.sort((a, b) => b.start - a.start);
+ let output = source;
+ for (const edit of edits) {
+ output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);
+ }
+ return {source: output, demoContentReplaced: elements.length};
+}
+
+/**
+ * The local name of an Astryx Text import that is the binding its name
+ * resolves to at every element, or null when no such import exists.
+ * @param {any} file
+ * @param {any} program - The program path, from {@link programPath}.
+ * @param {any[]} elements - Element paths.
+ * @returns {string | null}
+ */
+function astryxTextAtEvery(file, program, elements) {
+ for (const statement of file.program.body) {
+ if (
+ statement.type !== 'ImportDeclaration' ||
+ statement.importKind === 'type' ||
+ !TEXT_MODULES.has(statement.source.value)
+ ) {
+ continue;
+ }
+ for (const specifier of statement.specifiers) {
+ if (
+ specifier.type !== 'ImportSpecifier' ||
+ specifier.importKind === 'type' ||
+ (specifier.imported.name ?? specifier.imported.value) !== 'Text'
+ ) {
+ continue;
+ }
+ const name = specifier.local.name;
+ const imported = program.scope.getBinding(name);
+ if (
+ elements.every(element => element.scope.getBinding(name) === imported)
+ ) {
+ return name;
+ }
+ }
+ }
+ return null;
+}
+
+/**
+ * Whether a binding is declared in an export, so code outside the file can
+ * still read it.
+ * @param {any} binding
+ */
+function isExportedDeclaration(binding) {
+ const declaration = binding.path.isVariableDeclarator()
+ ? binding.path.parentPath
+ : binding.path;
+ return Boolean(declaration.parentPath?.isExportDeclaration());
+}
+
+/**
+ * `base`, or `base` with the first number from 2 that makes it a name the
+ * file does not write.
+ * @param {string} base
+ * @param {Set<string>} written
+ */
+function uniqueName(base, written) {
+ let name = base;
+ for (let n = 2; written.has(name); n++) name = `${base}${n}`;
+ return name;
+}
+
+/**
+ * Throw unless a demo-content element can be replaced without dropping code:
+ * each prop a literal or a read of variables (see {@link isVariableRead}), and
+ * no children but whitespace.
+ * @param {any} element
+ * @returns {string[]} The variables its props read.
+ */
+function assertStaticDemoElement(element) {
+ const name = element.openingElement.name.name;
+ /** @type {string[]} */
+ const variables = [];
+ for (const attribute of element.openingElement.attributes) {
+ if (attribute.type === 'JSXSpreadAttribute') {
+ throw unsafeDemoContent(`<${name}> spreads props`);
+ }
+ const value = attribute.value;
+ if (value === null || value.type === 'StringLiteral') continue;
+ if (
+ value.type === 'JSXExpressionContainer' &&
+ (isLiteralExpression(value.expression) ||
+ isVariableRead(value.expression, variables))
+ ) {
+ continue;
+ }
+ throw unsafeDemoContent(
+ `<${name}> prop ${attribute.name.name ?? ''} is not a literal value or a variable read`,
+ );
+ }
+ for (const child of element.children) {
+ if (child.type === 'JSXText' && child.value.trim() === '') continue;
+ throw unsafeDemoContent(`<${name}> has children`);
+ }
+ return variables;
+}
+
+/**
+ * Whether an expression only reads variables: a variable, a non-computed
+ * property of one, or its negation. Removing such a read runs no code. Adds
+ * each variable it reads to `variables`.
+ * @param {any} node
+ * @param {string[]} variables
+ * @returns {boolean}
+ */
+function isVariableRead(node, variables) {
+ switch (node.type) {
+ case 'Identifier':
+ variables.push(node.name);
+ return true;
+ case 'MemberExpression':
+ return !node.computed && isVariableRead(node.object, variables);
+ case 'UnaryExpression':
+ return node.operator === '!' && isVariableRead(node.argument, variables);
+ default:
+ return false;
+ }
+}
+
+/** @param {any} node */
+function isLiteralExpression(node) {
+ switch (node.type) {
+ case 'StringLiteral':
+ case 'NumericLiteral':
+ case 'BooleanLiteral':
+ case 'NullLiteral':
+ return true;
+ case 'TemplateLiteral':
+ return node.expressions.length === 0;
+ case 'UnaryExpression':
+ return node.operator === '-' && node.argument.type === 'NumericLiteral';
+ default:
+ return false;
+ }
+}
+
+/** @param {string} reason */
+function unsafeDemoContent(reason) {
+ return new Error(
+ `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.`,
+ );
+}
+
+/**
+ * Replace everything in a template that only Astryx's previews provide, in
+ * the order a copy applies it: demo-content elements
+ * ({@link replaceDemoContent}), then demo media ({@link replaceDemoMedia}).
+ * Both counts are what a receipt discloses.
+ *
+ * @param {string} source - Template source code.
+ * @param {{videoPlaceholder?: string}} [options] - As {@link replaceDemoMedia}.
+ * @returns {{source: string, demoContentReplaced: number, demoMediaReplaced: number}}
+ */
+export function replaceTemplateDemos(source, options) {
+ const {source: withContent, demoContentReplaced} = replaceDemoContent(source);
+ const {source: output, demoMediaReplaced} = replaceDemoMedia(
+ withContent,
+ options,
+ );
+ return {source: output, demoContentReplaced, demoMediaReplaced};
+}
+
/** @param {string | undefined} char */
function isTokenDelimiter(char) {
return char === undefined || /\s/u.test(char) || TOKEN_DELIMITERS.has(char);
@@ -402,9 +772,10 @@ function fixtureSegments(reference) {
* @param {number} start
* @param {number} at
* @param {number} end
+ * @param {string} videoPlaceholder
* @returns {{text: string, end: number} | null}
*/
-function fixtureEdit(source, start, at, end) {
+function fixtureEdit(source, start, at, end, videoPlaceholder) {
const token = source.slice(start, end);
if (ABSOLUTE_URL.test(token)) return null;
if (!token.startsWith('/')) {
@@ -472,7 +843,9 @@ function fixtureEdit(source, start, at, end) {
.extname(segments[segments.length - 1])
.slice(1)
.toLowerCase();
- if (VIDEO_EXTENSIONS.has(ext)) return {text: '', end: referenceEnd};
+ if (VIDEO_EXTENSIONS.has(ext)) {
+ return {text: videoPlaceholder, end: referenceEnd};
+ }
if (IMAGE_EXTENSIONS.has(ext)) {
return {text: PLACEHOLDER_IMAGE, end: referenceEnd};
}
@@ -1460,6 +1833,9 @@ export async function findShowcase(componentName, cwd, options) {
return null;
}
+/** The npm scope of every Astryx package. */
+const ASTRYX_PACKAGE_SCOPE = '@astryxdesign/';
+
const UBIQUITOUS = new Set([
'Text',
'Heading',
@@ -1472,16 +1848,21 @@ const UBIQUITOUS = new Set([
]);
/**
- * 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.
+ * The top-level bindings of a source. `declared` holds names bound by
+ * `function`, `class`, `const`, `let` or `var` declarations (exported or not).
+ * `astryxImports` maps each local name of a named Astryx import to the name the
+ * package exports, so `Text as AstryxText` maps `AstryxText` to `Text`. Both
+ * are empty when the source does not parse, so a parse failure never drops a
+ * real component.
*
* @param {string} src
- * @returns {Set<string>}
+ * @returns {{declared: Set<string>, astryxImports: Map<string, string>}}
*/
-function topLevelBindingNames(src) {
+function topLevelBindings(src) {
/** @type {Set<string>} */
const names = new Set();
+ /** @type {Map<string, string>} */
+ const astryxImports = new Map();
let program;
try {
program = templateSourceParser().parse(src, {
@@ -1490,9 +1871,21 @@ function topLevelBindingNames(src) {
errorRecovery: true,
}).program;
} catch {
- return names;
+ return {declared: names, astryxImports};
}
for (const statement of program.body) {
+ if (statement.type === 'ImportDeclaration') {
+ if (!statement.source.value.startsWith(ASTRYX_PACKAGE_SCOPE)) continue;
+ for (const specifier of statement.specifiers) {
+ if (specifier.type !== 'ImportSpecifier') continue;
+ const {imported} = specifier;
+ astryxImports.set(
+ specifier.local.name,
+ imported.type === 'Identifier' ? imported.name : imported.value,
+ );
+ }
+ continue;
+ }
const node =
statement.type === 'ExportNamedDeclaration' ||
statement.type === 'ExportDefaultDeclaration'
@@ -1513,15 +1906,26 @@ function topLevelBindingNames(src) {
}
}
}
- return names;
+ return {declared: names, astryxImports};
}
/**
+ * The components a template file composes, as written in the catalog.
* @param {string} pagePath
* @returns {string[]}
*/
export function extractComponents(pagePath) {
- const src = fs.readFileSync(pagePath, 'utf-8');
+ return componentsInSource(fs.readFileSync(pagePath, 'utf-8'));
+}
+
+/**
+ * The components a template source composes. A surface that returns rewritten
+ * source lists the components of that source, so a component the rewrite
+ * removed is not listed.
+ * @param {string} src
+ * @returns {string[]}
+ */
+export function componentsInSource(src) {
// Match JSX opening tags, e.g. `<Section` or the legacy `<XDSSection`.
// Templates author bare component names post un-prefix migration
// (P2380608025), so the `XDS` prefix is optional. Anchoring on the `<`
@@ -1547,12 +1951,13 @@ export function extractComponents(pagePath) {
// 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);
+ const {declared: localDeclNames, astryxImports} = topLevelBindings(src);
return [
...new Set(
matches
.filter(n => !localDeclNames.has(n))
+ .map(n => astryxImports.get(n) ?? n)
.filter(n => !['Theme', 'ThemeProvider'].includes(n))
.filter(n => !UBIQUITOUS.has(n))
.map(n =>
diff --git a/packages/cli/foundation/discovery/template-icons.mjs b/packages/cli/foundation/discovery/template-icons.mjs
index 9bd2b474a5..0f5f85a0a0 100644
--- a/packages/cli/foundation/discovery/template-icons.mjs
+++ b/packages/cli/foundation/discovery/template-icons.mjs
@@ -37,7 +37,12 @@
* @position packages/cli/foundation/discovery — read by template show/copy
*/
-import {parse} from '@babel/parser';
+import {
+ isReference,
+ parseTemplateSource as parseSource,
+ walk,
+ writtenNames,
+} from './template-source-tree.mjs';
import {definitionsByIcon} from './icon-set-discovery.mjs';
import {astryxDefinitionsByName} from './icon-definition-discovery.mjs';
@@ -219,86 +224,6 @@ function targetExport(icon, set, variant) {
return {module, export: icon.export};
}
-/** @param {string} source */
-function parseSource(source) {
- return parse(source, {
- sourceType: 'module',
- plugins: ['jsx', 'typescript'],
- errorRecovery: false,
- });
-}
-
-/**
- * Every node in the tree, with its parent and the key it sits under.
- * @param {any} node
- * @param {(node: any, parent: any, key: string) => void} visit
- * @param {any} [parent]
- * @param {string} [key]
- */
-function walk(node, visit, parent = null, key = '') {
- if (Array.isArray(node)) {
- for (const child of node) walk(child, visit, parent, key);
- return;
- }
- if (
- node == null ||
- typeof node !== 'object' ||
- typeof node.type !== 'string'
- ) {
- return;
- }
- visit(node, parent, key);
- for (const childKey of Object.keys(node)) {
- if (
- childKey === 'loc' ||
- childKey === 'extra' ||
- childKey.endsWith('Comments') ||
- childKey === 'comments' ||
- childKey === 'tokens'
- ) {
- continue;
- }
- const child = node[childKey];
- if (child != null && typeof child === 'object') {
- walk(child, visit, node, childKey);
- }
- }
-}
-
-/**
- * Whether an identifier node is a reference to a binding, not a property
- * name or a JSX attribute name.
- * @param {any} node
- * @param {any} parent
- * @param {string} key
- */
-function isReference(node, parent, key) {
- if (!parent) return true;
- switch (parent.type) {
- case 'ImportSpecifier':
- case 'ImportDefaultSpecifier':
- case 'ImportNamespaceSpecifier':
- return false;
- case 'MemberExpression':
- case 'OptionalMemberExpression':
- return key !== 'property' || parent.computed;
- case 'ObjectProperty':
- return key === 'value' || parent.computed;
- case 'ObjectMethod':
- case 'ClassMethod':
- case 'ClassProperty':
- return key !== 'key' || parent.computed;
- case 'JSXAttribute':
- return false;
- case 'JSXMemberExpression':
- return key === 'object';
- case 'TSPropertySignature':
- return key !== 'key';
- default:
- return true;
- }
-}
-
/**
* Whether a module is one of Astryx's own packages (`@astryxdesign/core`,
* its subpaths, and every other `@astryxdesign/` package).
@@ -453,14 +378,7 @@ export function mapTemplateIcons(source, {sets, choice}, declared = {}) {
);
/** Every name the file writes, to keep aliases collision-free. */
- const written = new Set();
- walk(ast.program, (node, parent, key) => {
- // The name an import specifier reads from its module binds nothing here.
- if (parent?.type === 'ImportSpecifier' && key === 'imported') return;
- if (node.type === 'Identifier' || node.type === 'JSXIdentifier') {
- written.add(node.name);
- }
- });
+ const written = writtenNames(ast);
/** @type {Array<{start: number, end: number, text: string}>} */
const edits = [];
diff --git a/packages/cli/foundation/discovery/template-source-tree.mjs b/packages/cli/foundation/discovery/template-source-tree.mjs
new file mode 100644
index 0000000000..d955533e15
--- /dev/null
+++ b/packages/cli/foundation/discovery/template-source-tree.mjs
@@ -0,0 +1,159 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file The syntax tree of a template's source, shared by every rewrite of
+ * it: parsing, a walk over every node, whether an identifier is a reference,
+ * the names a file writes, and the module scope that resolves bindings.
+ *
+ * @input Template source text
+ * @output Its parsed tree, node visits, names, and module scope
+ * @position packages/cli/foundation/discovery — read by template-icons and by
+ * the demo-content replacement in template-adapter
+ */
+
+import {createRequire} from 'node:module';
+
+const require = createRequire(import.meta.url);
+
+/** @type {typeof import('@babel/parser') | undefined} */
+let babelParser;
+/** @type {typeof import('@babel/core') | undefined} */
+let babelCore;
+
+/**
+ * Parse template source as TSX. Babel loads on first use, so a command that
+ * only lists templates never pays for it.
+ * @param {string} source
+ * @returns {any} The file node.
+ */
+export function parseTemplateSource(source) {
+ babelParser ??= /** @type {typeof import('@babel/parser')} */ (
+ require('@babel/parser')
+ );
+ return babelParser.parse(source, {
+ sourceType: 'module',
+ plugins: ['jsx', 'typescript'],
+ errorRecovery: false,
+ });
+}
+
+/**
+ * The module scope of a parsed file. Its bindings, and the scope of each path
+ * a traversal visits, resolve a name to the declaration it reads, so a rewrite
+ * acts on bindings and not on names.
+ * @param {any} file - A file node from {@link parseTemplateSource}.
+ * @returns {any} The program path; its `scope` is the module scope.
+ */
+export function programPath(file) {
+ /** @type {any} */
+ let program;
+ traverseTemplateSource(file, {
+ Program(/** @type {any} */ path) {
+ program = path;
+ path.stop();
+ },
+ });
+ return program;
+}
+
+/**
+ * Traverse a parsed file with scope tracking.
+ * @param {any} file - A file node from {@link parseTemplateSource}.
+ * @param {import('@babel/core').Visitor} visitor
+ */
+export function traverseTemplateSource(file, visitor) {
+ babelCore ??= /** @type {typeof import('@babel/core')} */ (
+ require('@babel/core')
+ );
+ babelCore.traverse(file, visitor);
+}
+
+/**
+ * Every node in the tree, with its parent and the key it sits under.
+ * @param {any} node
+ * @param {(node: any, parent: any, key: string) => void} visit
+ * @param {any} [parent]
+ * @param {string} [key]
+ */
+export function walk(node, visit, parent = null, key = '') {
+ if (Array.isArray(node)) {
+ for (const child of node) walk(child, visit, parent, key);
+ return;
+ }
+ if (
+ node == null ||
+ typeof node !== 'object' ||
+ typeof node.type !== 'string'
+ ) {
+ return;
+ }
+ visit(node, parent, key);
+ for (const childKey of Object.keys(node)) {
+ if (
+ childKey === 'loc' ||
+ childKey === 'extra' ||
+ childKey.endsWith('Comments') ||
+ childKey === 'comments' ||
+ childKey === 'tokens'
+ ) {
+ continue;
+ }
+ const child = node[childKey];
+ if (child != null && typeof child === 'object') {
+ walk(child, visit, node, childKey);
+ }
+ }
+}
+
+/**
+ * Whether an identifier node is a reference to a binding, not a property
+ * name or a JSX attribute name.
+ * @param {any} node
+ * @param {any} parent
+ * @param {string} key
+ */
+export function isReference(node, parent, key) {
+ if (!parent) return true;
+ switch (parent.type) {
+ case 'ImportSpecifier':
+ case 'ImportDefaultSpecifier':
+ case 'ImportNamespaceSpecifier':
+ return false;
+ case 'MemberExpression':
+ case 'OptionalMemberExpression':
+ return key !== 'property' || parent.computed;
+ case 'ObjectProperty':
+ return key === 'value' || parent.computed;
+ case 'ObjectMethod':
+ case 'ClassMethod':
+ case 'ClassProperty':
+ return key !== 'key' || parent.computed;
+ case 'JSXAttribute':
+ return false;
+ case 'JSXMemberExpression':
+ return key === 'object';
+ case 'TSPropertySignature':
+ return key !== 'key';
+ default:
+ return true;
+ }
+}
+
+/**
+ * Every name a file writes, so a name a rewrite adds collides with nothing
+ * and shadows nothing. The name an import specifier reads from its module
+ * binds nothing in the file, so it is not included.
+ * @param {any} file - A file node from {@link parseTemplateSource}.
+ * @returns {Set<string>}
+ */
+export function writtenNames(file) {
+ /** @type {Set<string>} */
+ const written = new Set();
+ walk(file.program, (node, parent, key) => {
+ if (parent?.type === 'ImportSpecifier' && key === 'imported') return;
+ if (node.type === 'Identifier' || node.type === 'JSXIdentifier') {
+ written.add(node.name);
+ }
+ });
+ return written;
+}
diff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
index 614507009e..3f2f06d361 100644
--- a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
@@ -336,6 +336,10 @@ const RUNNERS = {
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/template-source-tree.mjs': {
+ runs: '@babel/parser and @babel/core (CommonJS), each on first use, to read template source and resolve its bindings for demo-content replacement and icon mapping',
+ sites: ['require(@babel/core)', 'require(@babel/parser)'],
+ },
'foundation/discovery/theme-discovery.mjs': {
runs: '@babel/parser and jscodeshift (CommonJS), each on first use, so listing bundled themes never loads jscodeshift',
sites: ['require(@babel/parser)', 'require(jscodeshift)'],
diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjs
index 980338eaad..b13f3c2819 100644
--- a/packages/cli/foundation/response/response-types.doc.mjs
+++ b/packages/cli/foundation/response/response-types.doc.mjs
@@ -286,7 +286,7 @@ export const doc = {
{
value: 'template.show',
description:
- "The resolved template's source, exactly as a copy writes it, plus its description, kind, the component names it composes, and demoMediaReplaced (how many Astryx demo media references were replaced with placeholders for you to swap for your own media).",
+ "The resolved template's source, exactly as a copy writes it, plus its description, kind, the component names it composes, and demoMediaReplaced (how many Astryx demo media references were replaced with placeholders for you to swap for your own media), and demoContentReplaced (how many Astryx docs-only demo content elements were replaced with a Text placeholder for your own content).",
},
{
value: 'template.skeleton',
@@ -296,7 +296,7 @@ export const doc = {
{
value: 'template.copy',
description:
- "A scaffold receipt: template id, output directory, written file name, file count, demoMediaReplaced (how many Astryx demo media references were replaced with placeholders), notes (setup notes naming what the template needs that the project lacks — missing packages, missing StyleX compiler; empty when satisfied), missingPackages (external package names the template imports that are not in the project), and installCommand (a ready-to-run install command with the detected package manager and workspace version ranges; null when nothing is missing, or when several lockfiles leave the package manager undetermined). The envelope's package names the npm package that owns the template.",
+ "A scaffold receipt: template id, output directory, written file name, file count, demoMediaReplaced (how many Astryx demo media references were replaced with placeholders), demoContentReplaced (how many Astryx docs-only demo content elements were replaced with a Text placeholder), notes (setup notes naming what the template needs that the project lacks — missing packages, missing StyleX compiler; empty when satisfied), missingPackages (external package names the template imports that are not in the project), and installCommand (a ready-to-run install command with the detected package manager and workspace version ranges; null when nothing is missing, or when several lockfiles leave the package manager undetermined). The envelope's package names the npm package that owns the template.",
},
{
diff --git a/packages/cli/test/__golden__/no-icon-set/template-copy.json b/packages/cli/test/__golden__/no-icon-set/template-copy.json
index 180331c77e..464bc8b03d 100644
--- a/packages/cli/test/__golden__/no-icon-set/template-copy.json
+++ b/packages/cli/test/__golden__/no-icon-set/template-copy.json
@@ -8,6 +8,7 @@
"fileName": "page.tsx",
"filesCopied": 1,
"demoMediaReplaced": 0,
+ "demoContentReplaced": 0,
"notes": [
"<text>",
"<text>"
diff --git a/packages/cli/test/__golden__/no-icon-set/template-show.json b/packages/cli/test/__golden__/no-icon-set/template-show.json
index 07420d4704..eb53bbe63c 100644
--- a/packages/cli/test/__golden__/no-icon-set/template-show.json
+++ b/packages/cli/test/__golden__/no-icon-set/template-show.json
@@ -28,7 +28,8 @@
"Tooltip"
],
"source": "<text>",
- "demoMediaReplaced": 0
+ "demoMediaReplaced": 0,
+ "demoContentReplaced": 0
},
"meta": {
"answeredBy": {
diff --git a/packages/cli/test/__golden__/template.json b/packages/cli/test/__golden__/template.json
index 613d7639a2..ad938c258b 100644
--- a/packages/cli/test/__golden__/template.json
+++ b/packages/cli/test/__golden__/template.json
@@ -8,7 +8,8 @@
"type": "block",
"components": [],
"source": "export default function Hero() { return <section>zorblax</section>; }\n",
- "demoMediaReplaced": 0
+ "demoMediaReplaced": 0,
+ "demoContentReplaced": 0
},
"meta": {
"answeredBy": {
diff --git a/packages/cli/tsconfig.strict.json b/packages/cli/tsconfig.strict.json
index ff216c6940..79df0e3c21 100644
--- a/packages/cli/tsconfig.strict.json
+++ b/packages/cli/tsconfig.strict.json
@@ -6,7 +6,12 @@
"checkJs": true,
"noEmit": true,
"types": ["node"],
- "strict": true
+ "strict": true,
+ "paths": {
+ "@astryx-docs/demo-content": [
+ "../../apps/docsite/src/templateDemoContent/demoContent.tsx"
+ ]
+ }
},
"include": [
"api/**/*.mjs",
diff --git a/scripts/sync-templates.js b/scripts/sync-templates.js
index 4ccf08935a..30ad4e5ca1 100644
--- a/scripts/sync-templates.js
+++ b/scripts/sync-templates.js
@@ -14,6 +14,9 @@
const fs = require('node:fs');
const path = require('node:path');
+const {
+ replaceDemoContent,
+} = require('../packages/cli/foundation/discovery/template-adapter.mjs');
const COPYRIGHT = '// Copyright (c) Meta Platforms, Inc. and affiliates.\n\n';
const ROOT = path.resolve(__dirname, '..');
@@ -175,13 +178,16 @@ ${entries.join(',\n')}
function generateSourceRegistry(items) {
const entries = items.map(t => {
const sourcePath = path.join(t.sourceDir, t.sourceFile);
- const source = fs.readFileSync(sourcePath, 'utf-8');
+ // The code view hands out source, not a copy: demo content becomes the
+ // placeholder a copy writes, and fixture media stays. The preview route
+ // renders the original file.
+ const {source} = replaceDemoContent(fs.readFileSync(sourcePath, 'utf-8'));
return ` ${JSON.stringify('/templates/' + t.dirName + '/')}: ${JSON.stringify(source)}`;
});
return `${COPYRIGHT}/**
* AUTO-GENERATED by scripts/sync-templates.js — do not edit.
- * Maps template/block hrefs to their raw source code.
+ * Maps template/block hrefs to their displayed source code.
*/
export const sourceRegistry: Record<string, string> = {
@@ -312,9 +318,13 @@ async function main() {
console.log('Done.');
}
-main()
+module.exports = {generateSourceRegistry};
+
+// Importing the module for its helpers runs neither the sync nor the watch.
+const isCli = require.main === module;
+(isCli ? main() : Promise.resolve())
.then(() => {
- if (process.argv.includes('--watch')) {
+ if (isCli && process.argv.includes('--watch')) {
const chokidar = require('chokidar');
const watchPaths = [
PAGES_DIR + '/**/template.doc.mjs',
diff --git a/scripts/sync-templates.test.mjs b/scripts/sync-templates.test.mjs
new file mode 100644
index 0000000000..e4f3ffba59
--- /dev/null
+++ b/scripts/sync-templates.test.mjs
@@ -0,0 +1,56 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file The Sandbox code view and its Copy source action hand out source, not
+ * a copy: each demo-content element becomes the placeholder a copy writes, and
+ * fixture media stays.
+ */
+
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import * as fs from 'node:fs';
+import {createRequire} from 'node:module';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {DEMO_CONTENT_MODULE} from '../packages/cli/foundation/discovery/template-adapter.mjs';
+
+const {generateSourceRegistry} = createRequire(import.meta.url)(
+ './sync-templates.js',
+);
+
+describe('sync-templates source registry', () => {
+ let dir;
+ beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sandbox-source-'));
+ });
+ afterEach(() => fs.rmSync(dir, {recursive: true, force: true}));
+
+ it('replaces each demo-content element and keeps fixture media', () => {
+ fs.writeFileSync(
+ path.join(dir, 'CardDemo.tsx'),
+ "import {Card} from '@astryxdesign/core/Card';\n" +
+ `import {PlayingCardContents} from '${DEMO_CONTENT_MODULE}';\n` +
+ 'export default function CardDemo() {\n' +
+ ' return (\n' +
+ ' <Card padding={4}>\n' +
+ ' <PlayingCardContents rank="Q" suit="hearts" />\n' +
+ ' <img src="/template-assets/hero.jpg" alt="" />\n' +
+ ' </Card>\n' +
+ ' );\n' +
+ '}\n',
+ );
+
+ const registry = generateSourceRegistry([
+ {dirName: 'CardDemo', sourceDir: dir, sourceFile: 'CardDemo.tsx'},
+ ]);
+ const source = JSON.parse(
+ registry.match(/"\/templates\/CardDemo\/": (".*")/)[1],
+ );
+
+ expect(source).not.toContain(DEMO_CONTENT_MODULE);
+ expect(source).not.toContain('PlayingCardContents');
+ expect(source).toContain(
+ '<Card padding={4}>\n <Text>Card content</Text>',
+ );
+ expect(source).toContain('/template-assets/hero.jpg');
+ });
+});
diff --git a/vitest.config.ts b/vitest.config.ts
index 344e0abf73..0770b58dd2 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -137,6 +137,15 @@ export default defineConfig({
// `resolve` — the root's aliases do not reach it.
resolve: {
alias: [
+ // Catalog templates import docs-only demo content from the
+ // docsite. The docsite tsconfig maps the same specifier.
+ {
+ find: /^@astryx-docs\/demo-content$/,
+ replacement: path.join(
+ rootDir,
+ 'apps/docsite/src/templateDemoContent/demoContent.tsx',
+ ),
+ },
// Theme packages resolve to `dist/`, which no test run builds. The
// sandbox palette suite reads their palettes as a reference corpus,
// so point the BARE specifier at the authored source. Subpath