An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): say when template copy or layout expand replaced demo media (#6567)
Joey5e7c2077c9bb
diff --git a/.changeset/cli-spec-template-copy-media-receipt.md b/.changeset/cli-spec-template-copy-media-receipt.mdnew file mode 100644index 0000000000..c5f21c7453--- /dev/null+++ b/.changeset/cli-spec-template-copy-media-receipt.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] `astryx template <name> <path>` and `astryx layout expand` now say when they replaced Astryx demo media. The `template.copy` and `layout.expand` receipts carry `demoMediaReplaced`, the number of demo image and video references that became placeholders (one per reference, however many fixture paths its URL carries), and the text output names the file to update (when `layout expand` prints the code instead, the same line follows it as a comment, so the output is still valid TSX). Nothing about the copy itself changed.++@josephfarinadiff --git a/packages/cli/README.md b/packages/cli/README.mdindex c8c380a637..13b89696cc 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -453,7 +453,7 @@ Every response has a `type` discriminant. The full set is below (generated from| `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.skeleton` | A layout skeleton (structural tags with spatial annotations) plus the template's description and the components it composes. |-| `template.copy` | A scaffold receipt: template id, output directory, written file name, and file count. |+| `template.copy` | A scaffold receipt: template id, output directory, written file name, file count, and demoMediaReplaced (how many Astryx demo media references were replaced with placeholders for you to swap for your own media). || `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. || `hook.detail` | One hook's full authored HookDoc. |@@ -480,7 +480,7 @@ Every response has a `type` discriminant. The full set is below (generated from| `integration.template-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking Core template-id conflicts as {id, severity: warning, integrationPackage, integrationType, integrationName, coreMatches, message, command}. || `integration.component-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking conflicts where an integration component name is also owned by Core; each conflict includes the exact package-qualified command. || `integration.doc-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and Core doc overlaps. Each finding includes `severity` (`info` \| `error`) and `relationship` (`replaces` \| `extends` \| `accidental`). |-| `layout.expand` | The expansion: parsed form, generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, and written (the output path, or null when nothing was written). |+| `layout.expand` | The expansion: parsed form, generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, written (the output path, or null when nothing was written), and demoMediaReplaced (count of demo media placeholders). || `layout.check` | The validation result: a valid flag, the detected form, errors (each with line/col, message, formatted text, and suggestions), warnings, and the expression re-printed in both canonical surfaces (compact and outline). || `layout.grammar` | The XLE/XLO grammar cheatsheet: a text field with the full reference plus an aliases map (short name → canonical component) generated from this install's registry. |diff --git a/packages/cli/api/layout/expand/expand.mjs b/packages/cli/api/layout/expand/expand.mjsindex 3363ed69aa..5907128e4c 100644--- a/packages/cli/api/layout/expand/expand.mjs+++ b/packages/cli/api/layout/expand/expand.mjs@@ -18,7 +18,7 @@ import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';import {assertWithin, isFilePathArg, PathSafetyError} from '../../../foundation/fs/path-safety.mjs';import {detectForm} from '../../../foundation/xle/parse.mjs';import {expand} from '../../../foundation/xle/expand.mjs';-import {stripTemplateAssetRefs} from '../../template/template.mjs';+import {replaceDemoMedia} from '../../template/template.mjs';import {analyze, formatIssue} from '../_adapter.mjs';/** @param {string} name */@@ -59,28 +59,32 @@ function collectHintNames(doc) {/*** Build the blockModules map expand() needs: import-mode for app components,* splice-mode (reading + asset-stripping the block source) for template blocks.- * Only blocks actually referenced are read.+ * Only blocks actually referenced are read. Also returns how many demo media+ * references the splice-mode sources had replaced.** @param {import('../../../foundation/xle/xle-ast').XLEDoc} doc* @param {import('../_adapter.mjs').LayoutBlock[]} blocks- * @returns {Map<string, import('../../../foundation/xle/xle-ast').BlockModule>}+ * @returns {{modules: Map<string, import('../../../foundation/xle/xle-ast').BlockModule>, demoMediaReplaced: number}}*/function buildBlockModules(doc, blocks) {const referenced = collectHintNames(doc);- if (referenced.size === 0) return new Map();+ if (referenced.size === 0) return {modules: new Map(), demoMediaReplaced: 0};const byKey = new Map(blocks.map(b => [normKey(b.dirName), b]));/** @type {Map<string, import('../../../foundation/xle/xle-ast').BlockModule>} */const modules = new Map();+ let demoMediaReplaced = 0;for (const name of referenced) {const block = byKey.get(normKey(name));if (!block) continue;if (block.kind === 'component') {modules.set(name, /** @type {import('../../../foundation/xle/xle-ast').BlockModule} */ (/** @type {unknown} */ ({mode: 'import', componentName: block.name, importPath: block.importPath, isDefault: block.isDefault})));} else if (block.filePath && fs.existsSync(block.filePath)) {- modules.set(name, /** @type {import('../../../foundation/xle/xle-ast').BlockModule} */ ({mode: 'splice', componentName: block.dirName, source: stripTemplateAssetRefs(fs.readFileSync(block.filePath, 'utf-8'))}));+ const spliced = replaceDemoMedia(fs.readFileSync(block.filePath, 'utf-8'));+ demoMediaReplaced += spliced.demoMediaReplaced;+ modules.set(name, /** @type {import('../../../foundation/xle/xle-ast').BlockModule} */ ({mode: 'splice', componentName: block.dirName, source: spliced.source}));}}- return modules;+ return {modules, demoMediaReplaced};}/**@@ -115,7 +119,7 @@ export async function layoutExpand(expression, options = {}) {ERROR_CODES.ERR_INVALID_ARGUMENT,);}- const blockModules = buildBlockModules(doc, blocks);+ const {modules: blockModules, demoMediaReplaced} = buildBlockModules(doc, blocks);const result = expand(doc, registry, {componentName, blockModules});let written = null;@@ -150,6 +154,7 @@ export async function layoutExpand(expression, options = {}) {blocksReferenced: [...blockModules.entries()].map(([name, m]) => ({name, mode: m.mode})),warnings: warnings.map(formatIssue),written,+ demoMediaReplaced,},};}diff --git a/packages/cli/api/layout/expand/expand.receipt.test.mjs b/packages/cli/api/layout/expand/expand.receipt.test.mjsnew file mode 100644index 0000000000..7b14ca7ae7--- /dev/null+++ b/packages/cli/api/layout/expand/expand.receipt.test.mjs@@ -0,0 +1,74 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The layout.expand receipt discloses demo media replaced in the template+ * blocks it splices. Blocks are picked by what their source contains, not by+ * name, so catalog renames do not break the suite.+ */++import {describe, it, expect, beforeAll} from 'vitest';+import * as fs from 'node:fs';+import {layoutExpand} from '../layout.mjs';+import {discoverTemplates} from '../../template/template.mjs';+import {buildRegistry} from '../../../foundation/xle/registry.mjs';++const SLOW = 60_000;+const FIXTURE_REF = /\/template-assets\/[\w.-]+\.\w+/g;++beforeAll(async () => {+ await buildRegistry();+}, 120_000);++/** @param {string} name */+const hintKey = name => name.toLowerCase().replace(/[^a-z0-9]/g, '');++/** @type {Promise<Array<{hint: string, refs: number}>> | undefined} */+let catalog;++/**+ * Template blocks a `{hint}` resolves to unambiguously, with the number of demo+ * media references in each one's source.+ * @returns {Promise<Array<{hint: string, refs: number}>>}+ */+function catalogBlocks() {+ catalog ??= discoverTemplates().then(found => {+ const all = /** @type {Array<{dirName: string, type: string, filePath: string}>} */ (+ found+ ).filter(t => t.type === 'block' && t.filePath && fs.existsSync(t.filePath));+ const seen = new Map();+ for (const t of all) seen.set(hintKey(t.dirName), (seen.get(hintKey(t.dirName)) ?? 0) + 1);+ return all+ .filter(t => seen.get(hintKey(t.dirName)) === 1)+ .map(t => ({+ hint: hintKey(t.dirName),+ refs: (fs.readFileSync(t.filePath, 'utf-8').match(FIXTURE_REF) ?? []).length,+ }));+ });+ return catalog;+}++describe('layout.expand receipt - replaced demo media', () => {+ it('counts the demo media of a spliced block once, however often it is referenced', async () => {+ const block = (await catalogBlocks()).find(b => b.refs > 0);+ if (!block) throw new Error('no template block carries demo media');+ const res = await layoutExpand(`V > {${block.hint}}*3`);+ expect(res.type).toBe('layout.expand');+ expect(res.data.blocksReferenced).toHaveLength(1);+ expect(res.data.demoMediaReplaced).toBe(block.refs);+ expect(res.data.code).not.toContain('/template-assets/');+ }, SLOW);++ it('sums the demo media of every spliced block', async () => {+ const [a, b] = (await catalogBlocks()).filter(x => x.refs > 0);+ if (!b) throw new Error('fewer than two template blocks carry demo media');+ const res = await layoutExpand(`V > {${a.hint}} + {${b.hint}}`);+ expect(res.data.demoMediaReplaced).toBe(a.refs + b.refs);+ }, SLOW);++ it('reports 0 when nothing spliced carries demo media', async () => {+ const plain = (await catalogBlocks()).find(b => b.refs === 0);+ if (!plain) throw new Error('every template block carries demo media');+ expect((await layoutExpand(`V > {${plain.hint}}`)).data.demoMediaReplaced).toBe(0);+ expect((await layoutExpand('V > B"Save"')).data.demoMediaReplaced).toBe(0);+ }, SLOW);+});diff --git a/packages/cli/api/layout/layout.type.mjs b/packages/cli/api/layout/layout.type.mjsindex 5644026ec0..57a29fb0cd 100644--- a/packages/cli/api/layout/layout.type.mjs+++ b/packages/cli/api/layout/layout.type.mjs@@ -48,6 +48,7 @@* @property {LayoutBlockReference[]} data.blocksReferenced* @property {string[]} data.warnings* @property {string | null} data.written+ * @property {number} data.demoMediaReplaced Astryx demo media references (images, posters, videos) replaced in the spliced template blocks: images with a neutral placeholder, videos with an empty source. Swap in your own media at those points in the code; no media is installed. 0 when no spliced block carried any.*//**diff --git a/packages/cli/api/layout/layoutExpand.doc.mjs b/packages/cli/api/layout/layoutExpand.doc.mjsindex 806c9daf59..bf95b805a6 100644--- a/packages/cli/api/layout/layoutExpand.doc.mjs+++ b/packages/cli/api/layout/layoutExpand.doc.mjs@@ -70,7 +70,7 @@ export const doc = {{type: 'layout.expand',description:- 'The expansion: the parsed form, the generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, and written (the relative output path, or null when nothing was written).',+ 'The expansion: the parsed form, the generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, written (the relative output path, or null when nothing was written), and demoMediaReplaced (how many Astryx demo media references in the spliced template blocks, such as images, posters and videos, were replaced with placeholders for you to swap for your own media).',},],throws: [diff --git a/packages/cli/api/template/copy/copy.mjs b/packages/cli/api/template/copy/copy.mjsindex 803b856db8..86d98d864f 100644--- a/packages/cli/api/template/copy/copy.mjs+++ b/packages/cli/api/template/copy/copy.mjs@@ -18,7 +18,7 @@ import {} from '../../../foundation/fs/path-safety.mjs';import {AstryxError, writeFailed} from '../../error.mjs';import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';-import {stripTemplateAssetRefs} from '../../../foundation/discovery/template-adapter.mjs';+import {replaceDemoMedia} from '../../../foundation/discovery/template-adapter.mjs';/*** Scaffold an already-resolved template to `targetPath` (relative to `cwd`) and@@ -83,8 +83,9 @@ export function templateCopy(match, {targetPath, cwd, overwrite = false}) {// 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 = fs.readFileSync(match.filePath, 'utf-8');- const outputSource = stripTemplateAssetRefs(source);+ const {source: outputSource, demoMediaReplaced} = replaceDemoMedia(+ fs.readFileSync(match.filePath, 'utf-8'),+ );try {fs.mkdirSync(outputDir, {recursive: true});fs.writeFileSync(outputFilePath, outputSource);@@ -100,6 +101,7 @@ export function templateCopy(match, {targetPath, cwd, overwrite = false}) {outputDir: relOutput,fileName: outputFileName,filesCopied: 1,+ demoMediaReplaced,},};}diff --git a/packages/cli/api/template/copy/copy.receipt.test.mjs b/packages/cli/api/template/copy/copy.receipt.test.mjsnew file mode 100644index 0000000000..c1b57e1459--- /dev/null+++ b/packages/cli/api/template/copy/copy.receipt.test.mjs@@ -0,0 +1,77 @@+// 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.+ */++import {describe, it, expect, beforeEach, afterEach} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {template, discoverTemplates} from '../template.mjs';++const SLOW = 60_000;+const FIXTURE_REF = /\/template-assets\/[\w.-]+\.(\w+)/g;+const VIDEO = new Set(['mp4', 'webm', 'mov', 'ogv', 'm4v']);++/** @param {string} filePath */+const fixtureRefs = filePath =>+ [...fs.readFileSync(filePath, 'utf-8').matchAll(FIXTURE_REF)].map(m =>+ m[1].toLowerCase(),+ );++/**+ * @param {(refs: string[]) => boolean} predicate+ * @param {'page' | 'block'} type+ */+async function findTemplate(type, predicate) {+ const all = /** @type {Array<{dirName: string, type: string, filePath: string}>} */ (+ await discoverTemplates()+ );+ const ids = new Map();+ for (const t of all) ids.set(t.dirName, (ids.get(t.dirName) ?? 0) + 1);+ const found = all.find(+ t =>+ t.type === type &&+ ids.get(t.dirName) === 1 &&+ fs.existsSync(t.filePath) &&+ predicate(fixtureRefs(t.filePath)),+ );+ if (!found) throw new Error(`no ${type} template matches`);+ return {id: found.dirName, refs: fixtureRefs(found.filePath)};+}++describe('template.copy receipt — replaced demo media', () => {+ let dir;+ beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tmpl-receipt-'));+ });+ afterEach(() => fs.rmSync(dir, {recursive: true, force: true}));++ it('counts every demo image a page template carried, and leaves none behind', async () => {+ const {id, refs} = await findTemplate(+ 'page',+ r => r.length > 0 && r.every(ext => !VIDEO.has(ext)),+ );+ const res = await template(id, {targetPath: './dest', cwd: dir});+ expect(res.type).toBe('template.copy');+ expect(res.data.demoMediaReplaced).toBe(refs.length);+ expect(+ fs.readFileSync(path.join(dir, 'dest', 'page.tsx'), 'utf-8'),+ ).not.toContain('/template-assets/');+ }, SLOW);++ it('counts a demo video in a block template', async () => {+ const {id, refs} = await findTemplate('block', r => r.some(ext => VIDEO.has(ext)));+ const res = await template(id, {targetPath: './dest', cwd: dir});+ expect(res.data.demoMediaReplaced).toBe(refs.length);+ }, SLOW);++ it('reports 0 when the template carries no demo media', async () => {+ const {id} = await findTemplate('page', r => r.length === 0);+ const res = await template(id, {targetPath: './dest', cwd: dir});+ expect(res.data.demoMediaReplaced).toBe(0);+ }, SLOW);+});diff --git a/packages/cli/api/template/template.doc.mjs b/packages/cli/api/template/template.doc.mjsindex 81ff1914f7..923e3fc539 100644--- a/packages/cli/api/template/template.doc.mjs+++ b/packages/cli/api/template/template.doc.mjs@@ -124,7 +124,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, and file count.',+ 'A receipt after scaffolding the template into the project: the template id, output directory, written file name, file count, and `demoMediaReplaced` — how many Astryx demo media references (images, posters, videos) in the written file were replaced with placeholders for you to swap for your own media.',},{type: 'template.cdn',diff --git a/packages/cli/api/template/template.mjs b/packages/cli/api/template/template.mjsindex 77afdef1c1..3c06aff992 100644--- a/packages/cli/api/template/template.mjs+++ b/packages/cli/api/template/template.mjs@@ -41,6 +41,7 @@ export {discoverCoreTemplates,discoverIntegrationTemplatesForOne,stripTemplateAssetRefs,+ replaceDemoMedia,listTemplates,findRelatedBlocks,findShowcase,diff --git a/packages/cli/api/template/template.type.mjs b/packages/cli/api/template/template.type.mjsindex 7218642938..a6405f6f62 100644--- a/packages/cli/api/template/template.type.mjs+++ b/packages/cli/api/template/template.type.mjs@@ -76,6 +76,7 @@* @property {string} data.outputDir* @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.*//**diff --git a/packages/cli/clients/cli/commands/layout-expand.doc.mjs b/packages/cli/clients/cli/commands/layout-expand.doc.mjsindex d164e43160..347f3a7990 100644--- a/packages/cli/clients/cli/commands/layout-expand.doc.mjs+++ b/packages/cli/clients/cli/commands/layout-expand.doc.mjs@@ -18,7 +18,9 @@ export const doc = {description:'Parses and validates a compressed XLE/XLO expression, then expands it into ' +'ready-to-use XDS TSX, routing children into slots, scaffolding typed useState for ' +- 'interactive controls, and splicing referenced blocks. Writes to a path, or returns the code.',+ 'interactive controls, and splicing referenced blocks. Writes to a path, or returns the code. ' ++ 'Astryx demo media in a spliced block becomes a placeholder, and the output says how many ' ++ 'references were replaced (as a closing line comment when it prints the code).',fn: 'layoutExpand',args: [{diff --git a/packages/cli/clients/cli/commands/layout.expand-receipt.test.mjs b/packages/cli/clients/cli/commands/layout.expand-receipt.test.mjsnew file mode 100644index 0000000000..ca809866ef--- /dev/null+++ b/packages/cli/clients/cli/commands/layout.expand-receipt.test.mjs@@ -0,0 +1,94 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx layout expand` tells the caller, in JSON and in text, when demo+ * media in a spliced template block was replaced with placeholders. Printed+ * code stays verbatim and valid TSX: the disclosure follows it as a comment.+ */++import {describe, it, expect, beforeEach, afterEach} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import ts from 'typescript';+import {runCli} from '../../../test-utils/run-cli.mjs';+import {discoverTemplates} from '../../../api/template/template.mjs';++const SLOW = 60_000;+const DISCLOSURE = /demo media/i;++/** @param {string} name */+const hintKey = name => name.toLowerCase().replace(/[^a-z0-9]/g, '');++/** @param {string} source */+const tsxErrors = source =>+ /** @type {any} */ (+ ts.createSourceFile('out.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX)+ ).parseDiagnostics.map((/** @type {ts.Diagnostic} */ d) =>+ ts.flattenDiagnosticMessageText(d.messageText, ' '),+ );++/** A `{hint}` for a template block whose source carries demo media. */+async function mediaBlockHint() {+ const blocks = /** @type {Array<{dirName: string, type: string, filePath: string}>} */ (+ await discoverTemplates()+ ).filter(t => t.type === 'block' && t.filePath && fs.existsSync(t.filePath));+ const seen = new Map();+ for (const t of blocks) seen.set(hintKey(t.dirName), (seen.get(hintKey(t.dirName)) ?? 0) + 1);+ const found = blocks.find(+ t =>+ seen.get(hintKey(t.dirName)) === 1 &&+ /\/template-assets\/[\w.-]+\.\w+/.test(fs.readFileSync(t.filePath, 'utf-8')),+ );+ if (!found) throw new Error('no template block carries demo media');+ return hintKey(found.dirName);+}++describe('layout expand discloses replaced demo media', () => {+ let cwd;+ beforeEach(() => {+ // Inside the workspace so @astryxdesign/core resolves.+ cwd = fs.mkdtempSync(path.join(process.cwd(), '.xle-media-receipt-'));+ });+ afterEach(() => fs.rmSync(cwd, {recursive: true, force: true}));++ it('--json carries demoMediaReplaced; the text receipt states it for the written file', async () => {+ const expr = `V > {${await mediaBlockHint()}}`;+ const json = await runCli(['layout', 'expand', expr, './a', '--json'], cwd);+ expect(json.status).toBe(0);+ const {data} = JSON.parse(json.stdout);+ expect(data.demoMediaReplaced).toBeGreaterThan(0);++ const human = await runCli(['layout', 'expand', expr, './b'], cwd);+ expect(human.status).toBe(0);+ expect(human.stdout).toContain(+ `Replaced ${data.demoMediaReplaced} Astryx demo media reference`,+ );+ expect(human.stdout).toContain(path.join('b', 'GeneratedLayout.tsx'));+ }, SLOW);++ it('prints the code verbatim, then states the count in a comment that keeps it valid TSX', async () => {+ const expr = `V > {${await mediaBlockHint()}}`;+ const {data} = JSON.parse((await runCli(['layout', 'expand', expr, '--json'], cwd)).stdout);++ const human = await runCli(['layout', 'expand', expr], cwd);+ expect(human.status).toBe(0);+ expect(human.stdout.startsWith(data.code)).toBe(true);+ expect(human.stdout.slice(data.code.length).trim()).toMatch(+ new RegExp(`^// Replaced ${data.demoMediaReplaced} Astryx demo media references? in the code above: [^\\n]+$`),+ );+ expect(tsxErrors(human.stdout)).toEqual([]);+ }, SLOW);++ it('says nothing about demo media when none was replaced', async () => {+ const json = await runCli(['layout', 'expand', 'V > B"Save"', '--json'], cwd);+ const {data} = JSON.parse(json.stdout);+ expect(data.demoMediaReplaced).toBe(0);++ const written = await runCli(['layout', 'expand', 'V > B"Save"', './a'], cwd);+ expect(written.status).toBe(0);+ expect(written.stdout).not.toMatch(DISCLOSURE);+ const printed = await runCli(['layout', 'expand', 'V > B"Save"'], cwd);+ expect(printed.status).toBe(0);+ expect(printed.stdout).toBe(`${data.code}\n`);+ }, SLOW);+});diff --git a/packages/cli/clients/cli/commands/layout.mjs b/packages/cli/clients/cli/commands/layout.mjsindex 1c316cfd99..0c26115f86 100644--- a/packages/cli/clients/cli/commands/layout.mjs+++ b/packages/cli/clients/cli/commands/layout.mjs@@ -120,6 +120,20 @@ async function readExpression(expr, options = {}) {return expr ?? '';}+/**+ * The disclosure for demo media replaced in spliced template blocks, or '' when+ * none was. After printed code it is a line comment, so piped output stays TSX.+ * @param {LayoutExpandResponse['data']} data+ * @returns {string}+ */+function demoMediaNotice({demoMediaReplaced, written}) {+ if (demoMediaReplaced === 0) return '';+ const notice =+ `Replaced ${demoMediaReplaced} Astryx demo media reference${demoMediaReplaced === 1 ? '' : 's'} in ${written ?? 'the code above'}: ` ++ 'images now show a neutral placeholder and videos have an empty source. Supply your own media there.';+ return written ? notice : `// ${notice}`;+}+/*** @param {import('commander').Command} program*/@@ -181,6 +195,8 @@ export function registerLayout(program) {// Raw expanded TSX (no target path) — preformatted, emitted verbatim.out.push(code(result.data.code));}+ const mediaNotice = demoMediaNotice(result.data);+ if (mediaNotice) out.push(text(mediaNotice));emit(...out);return NO_RESULT_SET;},diff --git a/packages/cli/clients/cli/commands/template.copy-receipt.test.mjs b/packages/cli/clients/cli/commands/template.copy-receipt.test.mjsnew file mode 100644index 0000000000..ab76b2e680--- /dev/null+++ b/packages/cli/clients/cli/commands/template.copy-receipt.test.mjs@@ -0,0 +1,60 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx template <name> <path>` tells the caller, in JSON and in text,+ * when demo media in the copied file was replaced with placeholders.+ */++import {describe, it, expect, beforeEach, afterEach} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {runCli} from '../../../test-utils/run-cli.mjs';+import {discoverTemplates} from '../../../api/template/template.mjs';++const SLOW = 60_000;++/** A page template whose source carries demo media, and one that carries none. */+async function pickPages() {+ const pages = /** @type {Array<{dirName: string, type: string, filePath: string}>} */ (+ await discoverTemplates()+ ).filter(t => t.type === 'page' && fs.existsSync(t.filePath));+ const hasMedia = (/** @type {{filePath: string}} */ t) =>+ /\/template-assets\/[\w.-]+\.\w+/.test(fs.readFileSync(t.filePath, 'utf-8'));+ const withMedia = pages.find(hasMedia);+ const without = pages.find(t => !hasMedia(t));+ if (!withMedia || !without) throw new Error('catalog lacks a page with and without demo media');+ return {withMedia: withMedia.dirName, without: without.dirName};+}++describe('template copy receipt discloses replaced demo media', () => {+ let dir;+ beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tmpl-receipt-cli-'));+ });+ afterEach(() => fs.rmSync(dir, {recursive: true, force: true}));++ it('--json carries demoMediaReplaced and the text states the same count', async () => {+ const {withMedia} = await pickPages();+ const json = await runCli(['template', withMedia, './a', '--json'], dir);+ expect(json.status).toBe(0);+ const {data} = JSON.parse(json.stdout);+ expect(data.demoMediaReplaced).toBeGreaterThan(0);++ const human = await runCli(['template', withMedia, './b'], dir);+ expect(human.status).toBe(0);+ expect(human.stdout).toContain(+ `Replaced ${data.demoMediaReplaced} Astryx demo media reference`,+ );+ expect(human.stdout).toContain('b/page.tsx');+ }, SLOW);++ it('says nothing about media when none was replaced', async () => {+ const {without} = await pickPages();+ const json = await runCli(['template', without, './a', '--json'], dir);+ expect(JSON.parse(json.stdout).data.demoMediaReplaced).toBe(0);+ const human = await runCli(['template', without, './b'], dir);+ expect(human.status).toBe(0);+ expect(human.stdout).not.toMatch(/demo media/i);+ }, SLOW);+});diff --git a/packages/cli/clients/cli/commands/template.mjs b/packages/cli/clients/cli/commands/template.mjsindex 1fda20af16..af3f233df0 100644--- a/packages/cli/clients/cli/commands/template.mjs+++ b/packages/cli/clients/cli/commands/template.mjs@@ -171,10 +171,15 @@ export function registerTemplate(program) {}case 'template.copy': {+ const {outputDir, fileName, demoMediaReplaced} = result.data;+ const file = `${outputDir}/${fileName}`;emit(- text(- `Copied template to ${result.data.outputDir}/${result.data.fileName}`,- ),+ text(`Copied template to ${file}`),+ demoMediaReplaced > 0 &&+ text(+ `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.',+ ),);break;}diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjsindex f8f4179dbd..92dd6c7396 100644--- a/packages/cli/foundation/response/response-types.doc.mjs+++ b/packages/cli/foundation/response/response-types.doc.mjs@@ -194,7 +194,7 @@ export const doc = {{value: 'template.copy',description:- 'A scaffold receipt: template id, output directory, written file name, and file count.',+ 'A scaffold receipt: template id, output directory, written file name, file count, and demoMediaReplaced (how many Astryx demo media references were replaced with placeholders for you to swap for your own media).',},{@@ -342,7 +342,7 @@ export const doc = {{value: 'layout.expand',description:- 'The expansion: parsed form, generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, and written (the output path, or null when nothing was written).',+ 'The expansion: parsed form, generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, written (the output path, or null when nothing was written), and demoMediaReplaced (count of demo media placeholders).',},{value: 'layout.check',