@astryxdesign/cli 0.6.5-canary.f261d2f → 0.6.5-canary.f27f749

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +14 -13
  2. package/api/error.d.mts +22 -0
  3. package/api/error.mjs +42 -0
  4. package/api/integration/add-contribution.d.mts +2 -1
  5. package/api/integration/add-contribution.mjs +7 -3
  6. package/api/integration/add-theme.mjs +243 -22
  7. package/api/integration/add-theme.test.mjs +213 -0
  8. package/api/integration/authoring-checks.mjs +10 -7
  9. package/api/integration/authoring-checks.type.d.mts +8 -0
  10. package/api/integration/authoring-checks.type.mjs +7 -3
  11. package/api/integration/integration-authoring.type.d.mts +4 -1
  12. package/api/integration/integration-authoring.type.mjs +6 -1
  13. package/api/integration/integrationAdd.doc.mjs +6 -0
  14. package/api/integration/integrationAddTheme.doc.mjs +10 -0
  15. package/api/integration/integrationComponentConflicts.doc.mjs +1 -1
  16. package/api/integration/integrationDocConflicts.doc.mjs +1 -1
  17. package/api/integration/integrationTemplateConflicts.doc.mjs +1 -1
  18. package/api/integration/validate-integration.d.mts +4 -2
  19. package/api/integration/validate-integration.mjs +7 -2
  20. package/api/integration/validate-integration.test.mjs +55 -0
  21. package/api/integration/validate-integration.type.d.mts +5 -0
  22. package/api/integration/validate-integration.type.mjs +5 -1
  23. package/api/integration/validateIntegration.doc.mjs +1 -1
  24. package/api/layout/expand/expand.mjs +12 -7
  25. package/api/layout/expand/expand.receipt.test.mjs +74 -0
  26. package/api/layout/layout.type.d.mts +1 -0
  27. package/api/layout/layout.type.mjs +1 -0
  28. package/api/layout/layoutExpand.doc.mjs +1 -1
  29. package/api/swizzle/copy/copy.mjs +66 -3
  30. package/api/swizzle/swizzle.doc.mjs +4 -0
  31. package/api/template/copy/copy.mjs +14 -8
  32. package/api/template/copy/copy.receipt.test.mjs +77 -0
  33. package/api/template/show/show.mjs +15 -4
  34. package/api/template/show/show.test.mjs +76 -0
  35. package/api/template/template.d.mts +1 -1
  36. package/api/template/template.doc.mjs +6 -2
  37. package/api/template/template.mjs +1 -0
  38. package/api/template/template.type.d.mts +2 -0
  39. package/api/template/template.type.mjs +2 -0
  40. package/api/theme/build/build.d.mts +24 -0
  41. package/api/theme/build/build.mjs +235 -8
  42. package/api/theme/build/build.project-core.test.mjs +165 -0
  43. package/api/upgrade/run/run.mjs +20 -3
  44. package/api/upgrade/run/run.test.mjs +45 -1
  45. package/api/upgrade/upgrade.doc.mjs +1 -1
  46. package/api/upgrade/upgrade.type.d.mts +1 -0
  47. package/api/upgrade/upgrade.type.mjs +1 -0
  48. package/assets/docs/icons.doc.mjs +1 -0
  49. package/assets/templates/themes/butter/icons.tsx +2 -0
  50. package/assets/templates/themes/chocolate/icons.tsx +2 -0
  51. package/assets/templates/themes/gothic/icons.tsx +2 -0
  52. package/assets/templates/themes/matcha/icons.tsx +2 -0
  53. package/assets/templates/themes/neutral/icons.tsx +2 -0
  54. package/assets/templates/themes/stone/icons.tsx +2 -0
  55. package/assets/templates/themes/y2k/icons.tsx +2 -0
  56. package/clients/cli/commands/doctor.mjs +4 -4
  57. package/clients/cli/commands/integration-add.doc.mjs +10 -0
  58. package/clients/cli/commands/integration-authoring.test.mjs +12 -2
  59. package/clients/cli/commands/integration.mjs +3 -1
  60. package/clients/cli/commands/layout-expand.doc.mjs +3 -1
  61. package/clients/cli/commands/layout.expand-receipt.test.mjs +94 -0
  62. package/clients/cli/commands/layout.mjs +16 -0
  63. package/clients/cli/commands/template.copy-receipt.test.mjs +60 -0
  64. package/clients/cli/commands/template.mjs +19 -5
  65. package/clients/cli/commands/template.show-media.test.mjs +62 -0
  66. package/clients/cli/commands/upgrade.ascii-output.test.mjs +14 -0
  67. package/clients/cli/commands/write-failure.test.mjs +175 -0
  68. package/clients/cli/lib/manifest.mjs +44 -165
  69. package/clients/cli/lib/manifest.test.mjs +98 -7
  70. package/foundation/discovery/template-adapter.d.mts +13 -0
  71. package/foundation/discovery/template-adapter.fixture-refs.test.mjs +37 -1
  72. package/foundation/discovery/template-adapter.mjs +16 -1
  73. package/foundation/doc-compiler/doc-loads.test.mjs +2 -2
  74. package/foundation/response/response-types.doc.d.mts +5 -5
  75. package/foundation/response/response-types.doc.mjs +13 -13
  76. package/package.json +9 -9
@@ -18,7 +18,7 @@ import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
18
18
  import {assertWithin, isFilePathArg, PathSafetyError} from '../../../foundation/fs/path-safety.mjs';
19
19
  import {detectForm} from '../../../foundation/xle/parse.mjs';
20
20
  import {expand} from '../../../foundation/xle/expand.mjs';
21
- import {stripTemplateAssetRefs} from '../../template/template.mjs';
21
+ import {replaceDemoMedia} from '../../template/template.mjs';
22
22
  import {analyze, formatIssue} from '../_adapter.mjs';
23
23
 
24
24
  /** @param {string} name */
@@ -59,28 +59,32 @@ function collectHintNames(doc) {
59
59
  /**
60
60
  * Build the blockModules map expand() needs: import-mode for app components,
61
61
  * splice-mode (reading + asset-stripping the block source) for template blocks.
62
- * Only blocks actually referenced are read.
62
+ * Only blocks actually referenced are read. Also returns how many demo media
63
+ * references the splice-mode sources had replaced.
63
64
  *
64
65
  * @param {import('../../../foundation/xle/xle-ast').XLEDoc} doc
65
66
  * @param {import('../_adapter.mjs').LayoutBlock[]} blocks
66
- * @returns {Map<string, import('../../../foundation/xle/xle-ast').BlockModule>}
67
+ * @returns {{modules: Map<string, import('../../../foundation/xle/xle-ast').BlockModule>, demoMediaReplaced: number}}
67
68
  */
68
69
  function buildBlockModules(doc, blocks) {
69
70
  const referenced = collectHintNames(doc);
70
- if (referenced.size === 0) return new Map();
71
+ if (referenced.size === 0) return {modules: new Map(), demoMediaReplaced: 0};
71
72
  const byKey = new Map(blocks.map(b => [normKey(b.dirName), b]));
72
73
  /** @type {Map<string, import('../../../foundation/xle/xle-ast').BlockModule>} */
73
74
  const modules = new Map();
75
+ let demoMediaReplaced = 0;
74
76
  for (const name of referenced) {
75
77
  const block = byKey.get(normKey(name));
76
78
  if (!block) continue;
77
79
  if (block.kind === 'component') {
78
80
  modules.set(name, /** @type {import('../../../foundation/xle/xle-ast').BlockModule} */ (/** @type {unknown} */ ({mode: 'import', componentName: block.name, importPath: block.importPath, isDefault: block.isDefault})));
79
81
  } else if (block.filePath && fs.existsSync(block.filePath)) {
80
- modules.set(name, /** @type {import('../../../foundation/xle/xle-ast').BlockModule} */ ({mode: 'splice', componentName: block.dirName, source: stripTemplateAssetRefs(fs.readFileSync(block.filePath, 'utf-8'))}));
82
+ const spliced = replaceDemoMedia(fs.readFileSync(block.filePath, 'utf-8'));
83
+ demoMediaReplaced += spliced.demoMediaReplaced;
84
+ modules.set(name, /** @type {import('../../../foundation/xle/xle-ast').BlockModule} */ ({mode: 'splice', componentName: block.dirName, source: spliced.source}));
81
85
  }
82
86
  }
83
- return modules;
87
+ return {modules, demoMediaReplaced};
84
88
  }
85
89
 
86
90
  /**
@@ -115,7 +119,7 @@ export async function layoutExpand(expression, options = {}) {
115
119
  ERROR_CODES.ERR_INVALID_ARGUMENT,
116
120
  );
117
121
  }
118
- const blockModules = buildBlockModules(doc, blocks);
122
+ const {modules: blockModules, demoMediaReplaced} = buildBlockModules(doc, blocks);
119
123
  const result = expand(doc, registry, {componentName, blockModules});
120
124
 
121
125
  let written = null;
@@ -150,6 +154,7 @@ export async function layoutExpand(expression, options = {}) {
150
154
  blocksReferenced: [...blockModules.entries()].map(([name, m]) => ({name, mode: m.mode})),
151
155
  warnings: warnings.map(formatIssue),
152
156
  written,
157
+ demoMediaReplaced,
153
158
  },
154
159
  };
155
160
  }
@@ -0,0 +1,74 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file The layout.expand receipt discloses demo media replaced in the template
5
+ * blocks it splices. Blocks are picked by what their source contains, not by
6
+ * name, so catalog renames do not break the suite.
7
+ */
8
+
9
+ import {describe, it, expect, beforeAll} from 'vitest';
10
+ import * as fs from 'node:fs';
11
+ import {layoutExpand} from '../layout.mjs';
12
+ import {discoverTemplates} from '../../template/template.mjs';
13
+ import {buildRegistry} from '../../../foundation/xle/registry.mjs';
14
+
15
+ const SLOW = 60_000;
16
+ const FIXTURE_REF = /\/template-assets\/[\w.-]+\.\w+/g;
17
+
18
+ beforeAll(async () => {
19
+ await buildRegistry();
20
+ }, 120_000);
21
+
22
+ /** @param {string} name */
23
+ const hintKey = name => name.toLowerCase().replace(/[^a-z0-9]/g, '');
24
+
25
+ /** @type {Promise<Array<{hint: string, refs: number}>> | undefined} */
26
+ let catalog;
27
+
28
+ /**
29
+ * Template blocks a `{hint}` resolves to unambiguously, with the number of demo
30
+ * media references in each one's source.
31
+ * @returns {Promise<Array<{hint: string, refs: number}>>}
32
+ */
33
+ function catalogBlocks() {
34
+ catalog ??= discoverTemplates().then(found => {
35
+ const all = /** @type {Array<{dirName: string, type: string, filePath: string}>} */ (
36
+ found
37
+ ).filter(t => t.type === 'block' && t.filePath && fs.existsSync(t.filePath));
38
+ const seen = new Map();
39
+ for (const t of all) seen.set(hintKey(t.dirName), (seen.get(hintKey(t.dirName)) ?? 0) + 1);
40
+ return all
41
+ .filter(t => seen.get(hintKey(t.dirName)) === 1)
42
+ .map(t => ({
43
+ hint: hintKey(t.dirName),
44
+ refs: (fs.readFileSync(t.filePath, 'utf-8').match(FIXTURE_REF) ?? []).length,
45
+ }));
46
+ });
47
+ return catalog;
48
+ }
49
+
50
+ describe('layout.expand receipt - replaced demo media', () => {
51
+ it('counts the demo media of a spliced block once, however often it is referenced', async () => {
52
+ const block = (await catalogBlocks()).find(b => b.refs > 0);
53
+ if (!block) throw new Error('no template block carries demo media');
54
+ const res = await layoutExpand(`V > {${block.hint}}*3`);
55
+ expect(res.type).toBe('layout.expand');
56
+ expect(res.data.blocksReferenced).toHaveLength(1);
57
+ expect(res.data.demoMediaReplaced).toBe(block.refs);
58
+ expect(res.data.code).not.toContain('/template-assets/');
59
+ }, SLOW);
60
+
61
+ it('sums the demo media of every spliced block', async () => {
62
+ const [a, b] = (await catalogBlocks()).filter(x => x.refs > 0);
63
+ if (!b) throw new Error('fewer than two template blocks carry demo media');
64
+ const res = await layoutExpand(`V > {${a.hint}} + {${b.hint}}`);
65
+ expect(res.data.demoMediaReplaced).toBe(a.refs + b.refs);
66
+ }, SLOW);
67
+
68
+ it('reports 0 when nothing spliced carries demo media', async () => {
69
+ const plain = (await catalogBlocks()).find(b => b.refs === 0);
70
+ if (!plain) throw new Error('every template block carries demo media');
71
+ expect((await layoutExpand(`V > {${plain.hint}}`)).data.demoMediaReplaced).toBe(0);
72
+ expect((await layoutExpand('V > B"Save"')).data.demoMediaReplaced).toBe(0);
73
+ }, SLOW);
74
+ });
@@ -36,6 +36,7 @@ export type LayoutExpandResponse = {
36
36
  blocksReferenced: LayoutBlockReference[];
37
37
  warnings: string[];
38
38
  written: string | null;
39
+ demoMediaReplaced: number;
39
40
  };
40
41
  };
41
42
  /**
@@ -48,6 +48,7 @@
48
48
  * @property {LayoutBlockReference[]} data.blocksReferenced
49
49
  * @property {string[]} data.warnings
50
50
  * @property {string | null} data.written
51
+ * @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.
51
52
  */
52
53
 
53
54
  /**
@@ -70,7 +70,7 @@ export const doc = {
70
70
  {
71
71
  type: 'layout.expand',
72
72
  description:
73
- '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).',
73
+ '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).',
74
74
  },
75
75
  ],
76
76
  throws: [
@@ -25,7 +25,7 @@ import {
25
25
  findIntegrationComponentSource,
26
26
  } from '../../../foundation/discovery/component-discovery.mjs';
27
27
  import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
28
- import {AstryxError} from '../../error.mjs';
28
+ import {AstryxError, writeFailed} from '../../error.mjs';
29
29
 
30
30
  /** Default issue tracker for maintainer feedback after swizzling. */
31
31
  const DEFAULT_ISSUES_URL = 'https://github.com/facebook/astryx/issues/new';
@@ -290,11 +290,21 @@ export async function swizzleCopy(component, options = {}) {
290
290
  );
291
291
  }
292
292
 
293
- fs.mkdirSync(outputDir, {recursive: true});
293
+ const outputDirExisted = fs.existsSync(outputDir);
294
+ try {
295
+ fs.mkdirSync(outputDir, {recursive: true});
296
+ } catch (err) {
297
+ throw writeFailed(outputDir, cwd, err);
298
+ }
294
299
 
295
300
  const files = fs.readdirSync(componentDir);
296
301
  let copied = 0;
297
302
  let usesStyleX = false;
303
+ // A copy that fails part-way undoes what it already wrote, so the report is
304
+ // true and a retry does not trip over half a component. Each entry keeps
305
+ // the bytes the file had before this run (null when the copy created it).
306
+ /** @type {Array<{dest: string, original: Buffer|null}>} */
307
+ const written = [];
298
308
  for (const file of files) {
299
309
  if (isExcludedFromCopy(file)) continue;
300
310
  const srcPath = path.join(componentDir, file);
@@ -309,7 +319,25 @@ export async function swizzleCopy(component, options = {}) {
309
319
  ) {
310
320
  usesStyleX = true;
311
321
  }
312
- fs.writeFileSync(path.join(outputDir, file), content);
322
+ const dest = path.join(outputDir, file);
323
+ try {
324
+ // The snapshot read is guarded too: a destination that cannot be read
325
+ // back (no permission, or a directory with this name) must still undo
326
+ // the earlier writes and report ERR_WRITE_FAILED.
327
+ const original = fs.existsSync(dest) ? fs.readFileSync(dest) : null;
328
+ written.push({dest, original});
329
+ fs.writeFileSync(dest, content);
330
+ } catch (err) {
331
+ const unrestored = undoCopy(written);
332
+ if (!outputDirExisted) {
333
+ try {
334
+ fs.rmdirSync(outputDir);
335
+ } catch {
336
+ // Not empty (something could not be undone), or already gone.
337
+ }
338
+ }
339
+ throw writeFailed(dest, cwd, err, unrestored);
340
+ }
313
341
  copied++;
314
342
  }
315
343
 
@@ -333,3 +361,38 @@ export async function swizzleCopy(component, options = {}) {
333
361
  if (feedback) data.feedback = feedback;
334
362
  return {type: 'swizzle.copy', data};
335
363
  }
364
+
365
+ /**
366
+ * Undo the writes of a copy that failed part-way, newest first: delete the
367
+ * files the copy created and put back the bytes of the files it replaced. A
368
+ * file whose bytes are already the original ones is left alone, so a write
369
+ * that failed before changing anything is not reported as unrestored.
370
+ *
371
+ * @param {Array<{dest: string, original: Buffer|null}>} written
372
+ * @returns {string[]} the files it could not restore
373
+ */
374
+ function undoCopy(written) {
375
+ /** @type {string[]} */
376
+ const unrestored = [];
377
+ for (const {dest, original} of [...written].reverse()) {
378
+ try {
379
+ if (original == null) {
380
+ fs.rmSync(dest, {force: true});
381
+ continue;
382
+ }
383
+ /** @type {Buffer|null} */
384
+ let current = null;
385
+ try {
386
+ current = fs.readFileSync(dest);
387
+ } catch {
388
+ current = null;
389
+ }
390
+ if (current == null || !current.equals(original)) {
391
+ fs.writeFileSync(dest, original);
392
+ }
393
+ } catch {
394
+ unrestored.push(dest);
395
+ }
396
+ }
397
+ return unrestored;
398
+ }
@@ -101,6 +101,10 @@ export const doc = {
101
101
  code: 'ERR_FILE_EXISTS',
102
102
  when: 'copying would overwrite existing files and overwrite is not set',
103
103
  },
104
+ {
105
+ code: 'ERR_WRITE_FAILED',
106
+ when: 'the output directory or a copied file could not be written (no permission, read-only mount, full disk)',
107
+ },
104
108
  ],
105
109
  examples: [
106
110
  {
@@ -16,9 +16,9 @@ import {
16
16
  isFilePathArg,
17
17
  PathSafetyError,
18
18
  } from '../../../foundation/fs/path-safety.mjs';
19
- import {AstryxError} from '../../error.mjs';
19
+ import {AstryxError, writeFailed} from '../../error.mjs';
20
20
  import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
21
- import {stripTemplateAssetRefs} from '../../../foundation/discovery/template-adapter.mjs';
21
+ import {replaceDemoMedia} from '../../../foundation/discovery/template-adapter.mjs';
22
22
 
23
23
  /**
24
24
  * Scaffold an already-resolved template to `targetPath` (relative to `cwd`) and
@@ -80,13 +80,18 @@ export function templateCopy(match, {targetPath, cwd, overwrite = false}) {
80
80
  );
81
81
  }
82
82
 
83
- fs.mkdirSync(outputDir, {recursive: true});
84
-
85
83
  // Strip demo image references so the scaffolded file renders without a
86
- // Meta-only network dependency.
87
- const source = fs.readFileSync(match.filePath, 'utf-8');
88
- const outputSource = stripTemplateAssetRefs(source);
89
- fs.writeFileSync(outputFilePath, outputSource);
84
+ // Meta-only network dependency. Read before any write, so a failure below
85
+ // leaves nothing behind.
86
+ const {source: outputSource, demoMediaReplaced} = replaceDemoMedia(
87
+ fs.readFileSync(match.filePath, 'utf-8'),
88
+ );
89
+ try {
90
+ fs.mkdirSync(outputDir, {recursive: true});
91
+ fs.writeFileSync(outputFilePath, outputSource);
92
+ } catch (err) {
93
+ throw writeFailed(outputFilePath, cwd, err);
94
+ }
90
95
 
91
96
  const relOutput = path.relative(cwd, outputDir) || '.';
92
97
  return {
@@ -96,6 +101,7 @@ export function templateCopy(match, {targetPath, cwd, overwrite = false}) {
96
101
  outputDir: relOutput,
97
102
  fileName: outputFileName,
98
103
  filesCopied: 1,
104
+ demoMediaReplaced,
99
105
  },
100
106
  };
101
107
  }
@@ -0,0 +1,77 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file The template.copy receipt discloses replaced demo media. Templates are
5
+ * picked by what their source contains, not by slug, so catalog renames do not
6
+ * break the suite.
7
+ */
8
+
9
+ import {describe, it, expect, beforeEach, afterEach} from 'vitest';
10
+ import * as fs from 'node:fs';
11
+ import * as os from 'node:os';
12
+ import * as path from 'node:path';
13
+ import {template, discoverTemplates} from '../template.mjs';
14
+
15
+ const SLOW = 60_000;
16
+ const FIXTURE_REF = /\/template-assets\/[\w.-]+\.(\w+)/g;
17
+ const VIDEO = new Set(['mp4', 'webm', 'mov', 'ogv', 'm4v']);
18
+
19
+ /** @param {string} filePath */
20
+ const fixtureRefs = filePath =>
21
+ [...fs.readFileSync(filePath, 'utf-8').matchAll(FIXTURE_REF)].map(m =>
22
+ m[1].toLowerCase(),
23
+ );
24
+
25
+ /**
26
+ * @param {(refs: string[]) => boolean} predicate
27
+ * @param {'page' | 'block'} type
28
+ */
29
+ async function findTemplate(type, predicate) {
30
+ const all = /** @type {Array<{dirName: string, type: string, filePath: string}>} */ (
31
+ await discoverTemplates()
32
+ );
33
+ const ids = new Map();
34
+ for (const t of all) ids.set(t.dirName, (ids.get(t.dirName) ?? 0) + 1);
35
+ const found = all.find(
36
+ t =>
37
+ t.type === type &&
38
+ ids.get(t.dirName) === 1 &&
39
+ fs.existsSync(t.filePath) &&
40
+ predicate(fixtureRefs(t.filePath)),
41
+ );
42
+ if (!found) throw new Error(`no ${type} template matches`);
43
+ return {id: found.dirName, refs: fixtureRefs(found.filePath)};
44
+ }
45
+
46
+ describe('template.copy receipt — replaced demo media', () => {
47
+ let dir;
48
+ beforeEach(() => {
49
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tmpl-receipt-'));
50
+ });
51
+ afterEach(() => fs.rmSync(dir, {recursive: true, force: true}));
52
+
53
+ it('counts every demo image a page template carried, and leaves none behind', async () => {
54
+ const {id, refs} = await findTemplate(
55
+ 'page',
56
+ r => r.length > 0 && r.every(ext => !VIDEO.has(ext)),
57
+ );
58
+ const res = await template(id, {targetPath: './dest', cwd: dir});
59
+ expect(res.type).toBe('template.copy');
60
+ expect(res.data.demoMediaReplaced).toBe(refs.length);
61
+ expect(
62
+ fs.readFileSync(path.join(dir, 'dest', 'page.tsx'), 'utf-8'),
63
+ ).not.toContain('/template-assets/');
64
+ }, SLOW);
65
+
66
+ it('counts a demo video in a block template', async () => {
67
+ const {id, refs} = await findTemplate('block', r => r.some(ext => VIDEO.has(ext)));
68
+ const res = await template(id, {targetPath: './dest', cwd: dir});
69
+ expect(res.data.demoMediaReplaced).toBe(refs.length);
70
+ }, SLOW);
71
+
72
+ it('reports 0 when the template carries no demo media', async () => {
73
+ const {id} = await findTemplate('page', r => r.length === 0);
74
+ const res = await template(id, {targetPath: './dest', cwd: dir});
75
+ expect(res.data.demoMediaReplaced).toBe(0);
76
+ }, SLOW);
77
+ });
@@ -1,8 +1,8 @@
1
1
  // Copyright (c) Meta Platforms, Inc. and affiliates.
2
2
 
3
3
  /**
4
- * @file `template.show` leaf — return a resolved template's raw source plus the
5
- * components it composes.
4
+ * @file `template.show` leaf — return a resolved template's source, exactly as
5
+ * `template.copy` writes it, plus the components it composes.
6
6
  *
7
7
  * @position api/template/show — reads the resolved match's source file; the
8
8
  * template dispatcher routes `show` (and the no-target-path default) here.
@@ -11,7 +11,10 @@
11
11
  import * as fs from 'node:fs';
12
12
  import {AstryxError} from '../../error.mjs';
13
13
  import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
14
- import {extractComponents} from '../../../foundation/discovery/template-adapter.mjs';
14
+ import {
15
+ extractComponents,
16
+ replaceDemoMedia,
17
+ } from '../../../foundation/discovery/template-adapter.mjs';
15
18
 
16
19
  /**
17
20
  * Build the `template.show` envelope for an already-resolved template.
@@ -27,6 +30,13 @@ export function templateShow(match) {
27
30
  );
28
31
  }
29
32
 
33
+ // The source template.copy writes (spec:AST-028 FR7): a template printed and
34
+ // pasted must not keep a media path only Astryx's previews serve, and the
35
+ // caller is told how many it replaced, the way the copy receipt tells it.
36
+ const {source, demoMediaReplaced} = replaceDemoMedia(
37
+ fs.readFileSync(match.filePath, 'utf-8'),
38
+ );
39
+
30
40
  return {
31
41
  type: 'template.show',
32
42
  data: {
@@ -34,7 +44,8 @@ export function templateShow(match) {
34
44
  description: match.description,
35
45
  type: match.type,
36
46
  components: extractComponents(match.filePath),
37
- source: fs.readFileSync(match.filePath, 'utf-8'),
47
+ source,
48
+ demoMediaReplaced,
38
49
  },
39
50
  };
40
51
  }
@@ -0,0 +1,76 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Colocated tests for the template.show leaf — the source it returns is
5
+ * the source template.copy writes. An agent that prints a template and pastes
6
+ * it must end up with the same file as one that scaffolds it, demo media
7
+ * included (spec:AST-028 FR7).
8
+ */
9
+
10
+ import {describe, it, expect, beforeAll, afterAll} from 'vitest';
11
+ import * as fs from 'node:fs';
12
+ import * as os from 'node:os';
13
+ import * as path from 'node:path';
14
+ import {discoverAll, template} from '../template.mjs';
15
+ import {templateCopy} from '../copy/copy.mjs';
16
+ import {templateShow} from './show.mjs';
17
+
18
+ const SLOW = 60_000;
19
+ /** Astryx's demo-media namespace: only its own previews serve these files. */
20
+ const FIXTURE = '/template-assets/';
21
+ const FIXTURE_IMAGE = /\/template-assets\/[^'"`\s]+\.(png|jpe?g|webp)/i;
22
+
23
+ const read = (/** @type {string} */ file) => fs.readFileSync(file, 'utf-8');
24
+
25
+ describe('template.show', () => {
26
+ /** @type {string} */
27
+ let dir;
28
+ /** @type {Awaited<ReturnType<typeof discoverAll>>} */
29
+ let templates;
30
+ beforeAll(async () => {
31
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tmpl-show-'));
32
+ templates = await discoverAll(dir);
33
+ }, SLOW);
34
+ afterAll(() => fs.rmSync(dir, {recursive: true, force: true}));
35
+
36
+ it('returns exactly the source copy writes, for every template', () => {
37
+ let withFixtures = 0;
38
+ templates.forEach((match, index) => {
39
+ if (read(match.filePath).includes(FIXTURE)) withFixtures += 1;
40
+ const shown = templateShow(match).data.source;
41
+ const copied = templateCopy(match, {targetPath: `out-${index}`, cwd: dir});
42
+ const written = read(
43
+ path.join(dir, copied.data.outputDir, copied.data.fileName),
44
+ );
45
+ expect(shown, match.dirName).toBe(written);
46
+ });
47
+ // The templates with demo media are the ones that used to differ.
48
+ expect(withFixtures).toBeGreaterThan(0);
49
+ }, SLOW);
50
+
51
+ it('reports a replaced count when the source changed, and 0 when it did not', () => {
52
+ let reported = 0;
53
+ for (const match of templates) {
54
+ const raw = read(match.filePath);
55
+ const {source, demoMediaReplaced} = templateShow(match).data;
56
+ if (source === raw) expect(demoMediaReplaced, match.dirName).toBe(0);
57
+ else expect(demoMediaReplaced, match.dirName).toBeGreaterThan(0);
58
+ reported += demoMediaReplaced;
59
+ }
60
+ expect(reported).toBeGreaterThan(0);
61
+ }, SLOW);
62
+
63
+ it('prints a placeholder where a template shows a demo image', async () => {
64
+ const match = templates.find(
65
+ t => t.type === 'page' && FIXTURE_IMAGE.test(read(t.filePath)),
66
+ );
67
+ expect(match).toBeDefined();
68
+ if (!match) return;
69
+ const res = await template(match.dirName, {type: 'page', cwd: dir});
70
+ expect(res.type).toBe('template.show');
71
+ if (res.type !== 'template.show') return;
72
+ expect(res.data.source).not.toContain(FIXTURE);
73
+ expect(res.data.source).toContain('data:image/svg+xml,');
74
+ expect(res.data.demoMediaReplaced).toBeGreaterThan(0);
75
+ }, SLOW);
76
+ });
@@ -41,4 +41,4 @@ export function template(name?: string, options?: {
41
41
  export type DiscoveredTemplate = import("../../foundation/discovery/template-adapter.mjs").DiscoveredTemplate;
42
42
  export type TemplateDiscoveryError = import("../../foundation/discovery/template-adapter.mjs").TemplateDiscoveryError;
43
43
  export type TemplateDocModule = import("../../foundation/discovery/template-adapter.mjs").TemplateDocModule;
44
- export { discoverAll, discoverAll as discoverTemplates, discoverAllWithErrors, discoverCoreTemplates, discoverIntegrationTemplatesForOne, stripTemplateAssetRefs, listTemplates, findRelatedBlocks, findShowcase, extractComponents } from "../../foundation/discovery/template-adapter.mjs";
44
+ export { discoverAll, discoverAll as discoverTemplates, discoverAllWithErrors, discoverCoreTemplates, discoverIntegrationTemplatesForOne, stripTemplateAssetRefs, replaceDemoMedia, listTemplates, findRelatedBlocks, findShowcase, extractComponents } from "../../foundation/discovery/template-adapter.mjs";
@@ -114,7 +114,7 @@ export const doc = {
114
114
  {
115
115
  type: 'template.show',
116
116
  description:
117
- "The resolved template's raw source plus its description, kind, and the component names it composes.",
117
+ "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.",
118
118
  },
119
119
  {
120
120
  type: 'template.skeleton',
@@ -124,7 +124,7 @@ export const doc = {
124
124
  {
125
125
  type: 'template.copy',
126
126
  description:
127
- 'A receipt after scaffolding the template into the project: the template id, output directory, written file name, and file count.',
127
+ '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.',
128
128
  },
129
129
  {
130
130
  type: 'template.cdn',
@@ -153,6 +153,10 @@ export const doc = {
153
153
  code: 'ERR_FILE_EXISTS',
154
154
  when: 'the copy target already exists and overwrite is not set',
155
155
  },
156
+ {
157
+ code: 'ERR_WRITE_FAILED',
158
+ when: 'the copy target could not be written (no permission, read-only mount, full disk); nothing is written',
159
+ },
156
160
  ],
157
161
  examples: [
158
162
  {label: 'List templates', code: 'const {data} = await template();'},
@@ -41,6 +41,7 @@ export {
41
41
  discoverCoreTemplates,
42
42
  discoverIntegrationTemplatesForOne,
43
43
  stripTemplateAssetRefs,
44
+ replaceDemoMedia,
44
45
  listTemplates,
45
46
  findRelatedBlocks,
46
47
  findShowcase,
@@ -67,6 +67,7 @@ export type TemplateShowResponse = {
67
67
  type: "page" | "block";
68
68
  components: string[];
69
69
  source: string;
70
+ demoMediaReplaced: number;
70
71
  };
71
72
  };
72
73
  /**
@@ -91,6 +92,7 @@ export type TemplateCopyResponse = {
91
92
  outputDir: string;
92
93
  fileName: string;
93
94
  filesCopied: number;
95
+ demoMediaReplaced: number;
94
96
  };
95
97
  };
96
98
  /**
@@ -53,6 +53,7 @@
53
53
  * @property {'page' | 'block'} data.type
54
54
  * @property {string[]} data.components
55
55
  * @property {string} data.source
56
+ * @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.
56
57
  */
57
58
 
58
59
  /**
@@ -75,6 +76,7 @@
75
76
  * @property {string} data.outputDir
76
77
  * @property {string} data.fileName
77
78
  * @property {number} data.filesCopied
79
+ * @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.
78
80
  */
79
81
 
80
82
  /**
@@ -1,6 +1,16 @@
1
1
  // @generated by scripts/sync-api-types.mjs from the JSDoc in api/**/*.mjs.
2
2
  // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
3
 
4
+ /**
5
+ * Why `theme build` has no Core to generate with, and the fix for where it
6
+ * ran: the Astryx repository builds Core, an app installs it, and an installed
7
+ * Core that will not load is named.
8
+ *
9
+ * @param {string} cwd
10
+ * @param {any} importError - Why the import failed, when it threw.
11
+ * @returns {string}
12
+ */
13
+ export function coreUnavailableMessage(cwd: string, importError: any): string;
4
14
  /**
5
15
  * Import specifier for install/scaffold instructions. Drops a leading `src/`
6
16
  * from the cwd-relative dir (most consumers import from a file under src/) but
@@ -106,3 +116,17 @@ export function themeBuildFamily(files: string[], options: {
106
116
  * validateAdaptationEnrollment)
107
117
  */
108
118
  export type ComponentValueClass = "builtin" | "enrollment" | "unresolved";
119
+ /**
120
+ * The bindings one Core provides: the namespaces interception spreads, the
121
+ * functions the build calls, and why the import failed, if it did.
122
+ */
123
+ export type CoreBindings = {
124
+ themeModule: any;
125
+ rootModule: any;
126
+ importError: any;
127
+ defineTheme: any;
128
+ generateThemeRulesSplit: any;
129
+ generateOnMediaCSS: any;
130
+ generateAdaptationCSS: any;
131
+ dataTokenDefaults: any;
132
+ };