An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): print the same template source that copy writes (#6870)
Joeyeb58bba5d305
diff --git a/.changeset/cli-template-show-matches-copy.md b/.changeset/cli-template-show-matches-copy.mdnew file mode 100644index 0000000000..bb11906e17--- /dev/null+++ b/.changeset/cli-template-show-matches-copy.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] `astryx template <name>` and `template()` now return the same source that `astryx template <name> <path>` writes, and say how many Astryx demo media references they replaced. Demo images and videos that only Astryx's own previews serve are replaced the same way in both, so code copied from the printed source no longer points at media your project doesn't have. `template.show` gains `demoMediaReplaced` (0 when the template carried none); in text mode the count is stated on stderr so the printed source stays exact.++@josephfarinadiff --git a/packages/cli/README.md b/packages/cli/README.mdindex ea4937a29a..c8c380a637 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -451,7 +451,7 @@ 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. || `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. || `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 raw source plus its description, kind, and the component names it composes. |+| `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.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. |diff --git a/packages/cli/api/template/show/show.mjs b/packages/cli/api/template/show/show.mjsindex 86a4ab6201..94dd41c24a 100644--- a/packages/cli/api/template/show/show.mjs+++ b/packages/cli/api/template/show/show.mjs@@ -1,8 +1,8 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file `template.show` leaf — return a resolved template's raw source plus the- * components it composes.+ * @file `template.show` leaf — return a resolved template's source, exactly as+ * `template.copy` writes it, plus the components it composes.** @position api/template/show — reads the resolved match's source file; the* template dispatcher routes `show` (and the no-target-path default) here.@@ -11,7 +11,10 @@import * as fs from 'node:fs';import {AstryxError} from '../../error.mjs';import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';-import {extractComponents} from '../../../foundation/discovery/template-adapter.mjs';+import {+ extractComponents,+ replaceDemoMedia,+} from '../../../foundation/discovery/template-adapter.mjs';/*** Build the `template.show` envelope for an already-resolved template.@@ -27,6 +30,13 @@ export function templateShow(match) {);}+ // 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, demoMediaReplaced} = replaceDemoMedia(+ fs.readFileSync(match.filePath, 'utf-8'),+ );+return {type: 'template.show',data: {@@ -34,7 +44,8 @@ export function templateShow(match) {description: match.description,type: match.type,components: extractComponents(match.filePath),- source: fs.readFileSync(match.filePath, 'utf-8'),+ source,+ demoMediaReplaced,},};}diff --git a/packages/cli/api/template/show/show.test.mjs b/packages/cli/api/template/show/show.test.mjsnew file mode 100644index 0000000000..f6aece8207--- /dev/null+++ b/packages/cli/api/template/show/show.test.mjs@@ -0,0 +1,76 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Colocated tests for the template.show leaf — the source it returns is+ * the source template.copy writes. An agent that prints a template and pastes+ * it must end up with the same file as one that scaffolds it, demo media+ * included (spec:AST-028 FR7).+ */++import {describe, it, expect, beforeAll, afterAll} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {discoverAll, template} from '../template.mjs';+import {templateCopy} from '../copy/copy.mjs';+import {templateShow} from './show.mjs';++const SLOW = 60_000;+/** Astryx's demo-media namespace: only its own previews serve these files. */+const FIXTURE = '/template-assets/';+const FIXTURE_IMAGE = /\/template-assets\/[^'"`\s]+\.(png|jpe?g|webp)/i;++const read = (/** @type {string} */ file) => fs.readFileSync(file, 'utf-8');++describe('template.show', () => {+ /** @type {string} */+ let dir;+ /** @type {Awaited<ReturnType<typeof discoverAll>>} */+ let templates;+ beforeAll(async () => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tmpl-show-'));+ templates = await discoverAll(dir);+ }, SLOW);+ afterAll(() => fs.rmSync(dir, {recursive: true, force: true}));++ it('returns exactly the source copy writes, for every template', () => {+ let withFixtures = 0;+ templates.forEach((match, index) => {+ if (read(match.filePath).includes(FIXTURE)) withFixtures += 1;+ const shown = templateShow(match).data.source;+ const copied = templateCopy(match, {targetPath: `out-${index}`, cwd: dir});+ const written = read(+ path.join(dir, copied.data.outputDir, copied.data.fileName),+ );+ expect(shown, match.dirName).toBe(written);+ });+ // The templates with demo media are the ones that used to differ.+ expect(withFixtures).toBeGreaterThan(0);+ }, SLOW);++ it('reports a replaced count when the source changed, and 0 when it did not', () => {+ 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;+ }+ expect(reported).toBeGreaterThan(0);+ }, SLOW);++ it('prints a placeholder where a template shows a demo image', async () => {+ const match = templates.find(+ t => t.type === 'page' && FIXTURE_IMAGE.test(read(t.filePath)),+ );+ expect(match).toBeDefined();+ if (!match) return;+ const res = await template(match.dirName, {type: 'page', cwd: dir});+ expect(res.type).toBe('template.show');+ if (res.type !== 'template.show') return;+ expect(res.data.source).not.toContain(FIXTURE);+ expect(res.data.source).toContain('data:image/svg+xml,');+ expect(res.data.demoMediaReplaced).toBeGreaterThan(0);+ }, SLOW);+});diff --git a/packages/cli/api/template/template.doc.mjs b/packages/cli/api/template/template.doc.mjsindex e9cdb51e33..81ff1914f7 100644--- a/packages/cli/api/template/template.doc.mjs+++ b/packages/cli/api/template/template.doc.mjs@@ -114,7 +114,7 @@ export const doc = {{type: 'template.show',description:- "The resolved template's raw source plus its description, kind, and the component names it composes.",+ "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.",},{type: 'template.skeleton',diff --git a/packages/cli/api/template/template.type.mjs b/packages/cli/api/template/template.type.mjsindex b4418f39aa..7218642938 100644--- a/packages/cli/api/template/template.type.mjs+++ b/packages/cli/api/template/template.type.mjs@@ -53,6 +53,7 @@* @property {'page' | 'block'} data.type* @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.*//**diff --git a/packages/cli/clients/cli/commands/template.mjs b/packages/cli/clients/cli/commands/template.mjsindex 4056c36f49..1fda20af16 100644--- a/packages/cli/clients/cli/commands/template.mjs+++ b/packages/cli/clients/cli/commands/template.mjs@@ -156,8 +156,17 @@ export function registerTemplate(program) {}case 'template.show': {- // Source must survive piping byte-for-byte.- emit(code(result.data.source));+ // Source must survive piping byte-for-byte, so the note about+ // replaced demo media goes to stderr, in the copy receipt's words.+ // (Text mode only: --json returned above with the count in data.)+ const {source, demoMediaReplaced} = result.data;+ emit(code(source));+ if (demoMediaReplaced > 0) {+ console.error(+ `Replaced ${demoMediaReplaced} Astryx demo media reference${demoMediaReplaced === 1 ? '' : 's'}: ` ++ 'images now show a neutral placeholder and videos have an empty source. Supply your own media there.',+ );+ }break;}diff --git a/packages/cli/clients/cli/commands/template.show-media.test.mjs b/packages/cli/clients/cli/commands/template.show-media.test.mjsnew file mode 100644index 0000000000..16c069e3d9--- /dev/null+++ b/packages/cli/clients/cli/commands/template.show-media.test.mjs@@ -0,0 +1,62 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx template <name>` says how many demo media references it+ * replaced: in `--json` as `demoMediaReplaced`, and in text on stderr, so that+ * stdout stays exactly the source a copy writes and can be piped into a file.+ */++import {describe, it, expect, beforeAll, afterAll} 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 show discloses replaced demo media', () => {+ /** @type {string} */+ let dir;+ beforeAll(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tmpl-show-cli-'));+ });+ afterAll(() => fs.rmSync(dir, {recursive: true, force: true}));++ it('--json carries demoMediaReplaced, and text states it on stderr with stdout left as the source', async () => {+ const {withMedia} = await pickPages();+ const json = await runCli(['template', withMedia, '--type', 'page', '--json'], dir);+ expect(json.status).toBe(0);+ const {data} = JSON.parse(json.stdout);+ expect(data.demoMediaReplaced).toBeGreaterThan(0);++ const human = await runCli(['template', withMedia, '--type', 'page'], dir);+ expect(human.status).toBe(0);+ expect(human.stdout.trimEnd()).toBe(data.source.trimEnd());+ expect(human.stderr).toContain(+ `Replaced ${data.demoMediaReplaced} Astryx demo media reference`,+ );+ }, SLOW);++ it('says nothing about media when none was replaced', async () => {+ const {without} = await pickPages();+ const json = await runCli(['template', without, '--type', 'page', '--json'], dir);+ expect(JSON.parse(json.stdout).data.demoMediaReplaced).toBe(0);+ const human = await runCli(['template', without, '--type', 'page'], dir);+ expect(human.status).toBe(0);+ expect(human.stderr).not.toMatch(/demo media/i);+ }, SLOW);+});diff --git a/packages/cli/foundation/discovery/template-adapter.fixture-refs.test.mjs b/packages/cli/foundation/discovery/template-adapter.fixture-refs.test.mjsindex 9665228072..54acc1cceb 100644--- a/packages/cli/foundation/discovery/template-adapter.fixture-refs.test.mjs+++ b/packages/cli/foundation/discovery/template-adapter.fixture-refs.test.mjs@@ -5,7 +5,7 @@ import * as fs from 'node:fs';import * as path from 'node:path';import {fileURLToPath} from 'node:url';import jscodeshift from 'jscodeshift';-import {stripTemplateAssetRefs} from './template-adapter.mjs';+import {replaceDemoMedia, stripTemplateAssetRefs} from './template-adapter.mjs';const PLACEHOLDER = stripTemplateAssetRefs("'/template-assets/x.png'").slice(1,@@ -212,6 +212,42 @@ describe('stripTemplateAssetRefs fixture references', () => {});});+describe('replaceDemoMedia', () => {+ it('counts a reference once, however many fixture paths its URL carries', () => {+ const source =+ "const hero = '/template-assets/a.png?f=/template-assets/b.png';";+ expect(replaceDemoMedia(source)).toEqual({+ source: stripTemplateAssetRefs(source),+ demoMediaReplaced: 1,+ });+ });++ it('counts a poster and a video as two references', () => {+ const source =+ '<video poster="/template-assets/poster.jpg" src="/template-assets/clip.mp4" />';+ const result = replaceDemoMedia(source);+ expect(result).toEqual({+ source: stripTemplateAssetRefs(source),+ demoMediaReplaced: 2,+ });+ expect(result.source).not.toContain('/template-assets/');+ });++ it.each([+ [+ 'a prose mention',+ '<p>Demo media lives under /template-assets/ in the docsite.</p>',+ ],+ [+ 'a third-party URL',+ "const u = 'https://example.com/template-assets/a.png';",+ ],+ ['source with no fixture', 'const x = 1;'],+ ])('counts nothing for %s it leaves as written', (_label, source) => {+ expect(replaceDemoMedia(source)).toEqual({source, demoMediaReplaced: 0});+ });+});+describe('shipped templates', () => {it('copy with every fixture replaced and still parse', () => {const root = path.resolve(diff --git a/packages/cli/foundation/discovery/template-adapter.mjs b/packages/cli/foundation/discovery/template-adapter.mjsindex 63cf5b858a..23b471a9d5 100644--- a/packages/cli/foundation/discovery/template-adapter.mjs+++ b/packages/cli/foundation/discovery/template-adapter.mjs@@ -321,9 +321,23 @@ function toPosixPath(p) {* @returns {string} Source with demo asset references replaced.*/export function stripTemplateAssetRefs(source) {+ return replaceDemoMedia(source).source;+}++/**+ * {@link stripTemplateAssetRefs}, plus how many references it replaced: one per+ * replaced reference, however many fixture paths its URL carries (a reference+ * is replaced whole, query included), and none for a prose mention or a+ * third-party URL left as written. That count is what a receipt discloses.+ *+ * @param {string} source - Template source code.+ * @returns {{source: string, demoMediaReplaced: number}}+ */+export function replaceDemoMedia(source) {const needle = `/${FIXTURE_SEGMENT}`;let output = '';let copied = 0;+ let demoMediaReplaced = 0;/** @type {Array<[number, number]> | undefined} */let comments;let at = source.indexOf(needle);@@ -344,10 +358,11 @@ export function stripTemplateAssetRefs(source) {if (edit) {output += source.slice(copied, start) + edit.text;copied = edit.end;+ demoMediaReplaced += 1;}at = source.indexOf(needle, end);}- return output + source.slice(copied);+ return {source: output + source.slice(copied), demoMediaReplaced};}/** @param {string | undefined} char */diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjsindex 20129eef45..f8f4179dbd 100644--- a/packages/cli/foundation/response/response-types.doc.mjs+++ b/packages/cli/foundation/response/response-types.doc.mjs@@ -184,7 +184,7 @@ export const doc = {{value: 'template.show',description:- "The resolved template's raw source plus its description, kind, and the component names it composes.",+ "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).",},{value: 'template.skeleton',diff --git a/packages/cli/test/__golden__/template.json b/packages/cli/test/__golden__/template.jsonindex 65f44af83f..4f8c24bc8f 100644--- a/packages/cli/test/__golden__/template.json+++ b/packages/cli/test/__golden__/template.json@@ -6,6 +6,7 @@"description": "A zorblax hero block.","type": "block","components": [],- "source": "export default function Hero() { return <section>zorblax</section>; }\n"+ "source": "export default function Hero() { return <section>zorblax</section>; }\n",+ "demoMediaReplaced": 0}}