@astryxdesign/cli 0.1.6 → 0.1.7-canary.04cd8f7

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 (107) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +115 -19
  3. package/docs/cli-integrations.doc.mjs +150 -0
  4. package/docs/getting-started.doc.mjs +9 -9
  5. package/docs/internationalization.doc.mjs +243 -0
  6. package/docs/layout.doc.dense.mjs +5 -0
  7. package/docs/migration.doc.mjs +18 -18
  8. package/docs/principles.doc.dense.mjs +5 -5
  9. package/docs/principles.doc.mjs +6 -6
  10. package/docs/principles.doc.zh.mjs +5 -5
  11. package/docs/styling-libraries.doc.mjs +3 -3
  12. package/docs/styling.doc.mjs +4 -4
  13. package/docs/theme.doc.dense.mjs +12 -12
  14. package/docs/theme.doc.mjs +7 -7
  15. package/docs/theme.doc.zh.mjs +10 -10
  16. package/docs/tokens.doc.dense.mjs +6 -7
  17. package/docs/tokens.doc.mjs +1 -1
  18. package/docs/tokens.doc.zh.mjs +6 -7
  19. package/docs/working-with-ai.doc.mjs +18 -18
  20. package/package.json +13 -10
  21. package/src/api/docOverlays.test.mjs +133 -0
  22. package/src/api/docs.mjs +14 -2
  23. package/src/api/doctor.mjs +3 -3
  24. package/src/api/integration-block-exports.test.mjs +240 -0
  25. package/src/api/template-suffix.test.mjs +246 -0
  26. package/src/api/template.mjs +104 -28
  27. package/src/api/validate-integration.mjs +0 -8
  28. package/src/codemods/__tests__/registry.test.mjs +1 -0
  29. package/src/codemods/ensure-jscodeshift.mjs +11 -27
  30. package/src/codemods/registry.mjs +1 -0
  31. package/src/codemods/run-codemod.mjs +1 -1
  32. package/src/codemods/runner.mjs +2 -2
  33. package/src/codemods/transforms/v0.1.7/__tests__/migrate-table-tableprops-to-direct-props.test.mjs +120 -0
  34. package/src/codemods/transforms/v0.1.7/__tests__/rename-table-renderprops-styles-to-xstyle.test.mjs +112 -0
  35. package/src/codemods/transforms/v0.1.7/index.mjs +27 -0
  36. package/src/codemods/transforms/v0.1.7/migrate-table-tableprops-to-direct-props.mjs +188 -0
  37. package/src/codemods/transforms/v0.1.7/rename-table-renderprops-styles-to-xstyle.mjs +197 -0
  38. package/src/commands/agent-docs.mjs +21 -8
  39. package/src/commands/agent-docs.test.mjs +31 -4
  40. package/src/commands/build-theme.mjs +10 -71
  41. package/src/commands/build.mjs +15 -15
  42. package/src/commands/component/index.mjs +4 -4
  43. package/src/commands/discover.mjs +7 -5
  44. package/src/commands/docs.mjs +4 -4
  45. package/src/commands/hook/index.mjs +4 -4
  46. package/src/commands/init.mjs +48 -152
  47. package/src/commands/init.next-steps.test.mjs +1 -1
  48. package/src/commands/interactive-guard.test.mjs +19 -22
  49. package/src/commands/json-contract.test.mjs +1 -1
  50. package/src/commands/layout.mjs +1 -1
  51. package/src/commands/search.mjs +4 -4
  52. package/src/commands/swizzle.mjs +11 -34
  53. package/src/commands/template.mjs +11 -31
  54. package/src/commands/upgrade.mjs +9 -6
  55. package/src/commands/upgrade.test.mjs +1 -1
  56. package/src/config.mjs +5 -14
  57. package/src/doc.mjs +27 -0
  58. package/src/doc.test.mjs +383 -0
  59. package/src/index.mjs +5 -6
  60. package/src/integration.mjs +4 -15
  61. package/src/lib/component-discovery.importpath.test.mjs +59 -0
  62. package/src/lib/component-discovery.mjs +15 -5
  63. package/src/lib/component-format.mjs +47 -14
  64. package/src/lib/component-format.test.mjs +95 -1
  65. package/src/lib/component-loader.mjs +104 -2
  66. package/src/lib/componentDocOverlay.test.mjs +111 -0
  67. package/src/lib/config-schema.mjs +0 -30
  68. package/src/lib/hook-format.mjs +8 -3
  69. package/src/lib/term-log.mjs +48 -0
  70. package/src/lib/xle/registry.mjs +0 -5
  71. package/src/schemas/doc-schema.mjs +226 -0
  72. package/src/schemas/template-schema.mjs +47 -0
  73. package/src/template.mjs +9 -67
  74. package/src/types/config.d.ts +11 -66
  75. package/src/types/doc.d.ts +23 -0
  76. package/src/types/integration.d.ts +7 -18
  77. package/src/types/template-api.d.ts +14 -50
  78. package/src/utils/package-manager.mjs +78 -0
  79. package/src/utils/package-manager.test.mjs +108 -1
  80. package/src/utils/path-safety.mjs +0 -18
  81. package/src/utils/update-check.mjs +2 -1
  82. package/templates/blocks/components/Avatar/AvatarGroup.tsx +5 -7
  83. package/templates/blocks/components/Avatar/AvatarShowcase.tsx +4 -6
  84. package/templates/blocks/components/Avatar/AvatarUserCard.tsx +3 -5
  85. package/templates/blocks/components/Avatar/AvatarWithImage.tsx +8 -6
  86. package/templates/blocks/components/Avatar/AvatarWithStatus.tsx +3 -5
  87. package/templates/blocks/components/ChatComposerInput/ChatComposerInputControlledInput.tsx +1 -1
  88. package/templates/blocks/components/ChatComposerInput/ChatComposerInputDisabled.tsx +1 -1
  89. package/templates/blocks/components/ChatComposerInput/ChatComposerInputMentionTrigger.tsx +1 -1
  90. package/templates/blocks/components/ChatComposerInput/ChatComposerInputMultipleTriggers.tsx +1 -1
  91. package/templates/blocks/components/ChatComposerInput/ChatComposerInputShowcase.tsx +1 -1
  92. package/templates/blocks/components/ChatComposerInput/ChatComposerInputSlashCommands.tsx +1 -1
  93. package/templates/blocks/components/TabList/TabListTabsWithActions.doc.mjs +1 -1
  94. package/templates/blocks/components/TabList/TabListTabsWithActions.tsx +2 -7
  95. package/templates/blocks/components/VisuallyHidden/VisuallyHiddenLiveRegion.doc.mjs +14 -0
  96. package/templates/blocks/components/VisuallyHidden/VisuallyHiddenLiveRegion.tsx +41 -0
  97. package/templates/blocks/components/VisuallyHidden/VisuallyHiddenShowcase.doc.mjs +13 -0
  98. package/templates/blocks/components/VisuallyHidden/VisuallyHiddenShowcase.tsx +78 -0
  99. package/templates/blocks/components/VisuallyHidden/VisuallyHiddenStructuralHeading.doc.mjs +14 -0
  100. package/templates/blocks/components/VisuallyHidden/VisuallyHiddenStructuralHeading.tsx +38 -0
  101. package/templates/blocks/components/VisuallyHidden/VisuallyHiddenSupplementaryContext.doc.mjs +14 -0
  102. package/templates/blocks/components/VisuallyHidden/VisuallyHiddenSupplementaryContext.tsx +47 -0
  103. package/templates/pages/ide/page.tsx +35 -41
  104. package/templates/pages/theme-showcase/page.tsx +7 -7
  105. package/templates/themes/neutral/neutralTheme.ts +63 -32
  106. package/src/utils/interactive.mjs +0 -76
  107. package/src/utils/interactive.test.mjs +0 -70
@@ -0,0 +1,133 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Guards the --dense / --zh reference-doc overlays against drift (#2182).
5
+ * @input packages/cli/docs/{topic}.doc.mjs and its .doc.dense.mjs / .doc.zh.mjs overlays.
6
+ * @output Vitest failures naming any overlay section that does not anchor to a
7
+ * real base section, or whose content overrides land on the wrong block type.
8
+ * @position Regression gate for the docs API. Sits with the loader it guards.
9
+ *
10
+ * The overlays used to be applied BY ARRAY POSITION, so an overlay whose
11
+ * sections were ordered differently from the base grafted every title onto the
12
+ * wrong body. `docs tokens --dense` printed the entire colour table under a
13
+ * heading that said "## Spacing", above prose reading "gap props use
14
+ * space0-space12" — teaching any agent that spacing tokens are named
15
+ * `--color-*`. CLAUDE.md tells every agent to run that exact command at
16
+ * bootstrap, which is what made a doc bug into a codegen bug.
17
+ *
18
+ * Overlays now anchor to a base section by title, so a reordered or
19
+ * partial overlay is correct by construction. These tests keep it that way.
20
+ */
21
+
22
+ import {describe, it, expect} from 'vitest';
23
+ import * as fs from 'node:fs';
24
+ import * as path from 'node:path';
25
+ import {pathToFileURL} from 'node:url';
26
+ import {docs} from './docs.mjs';
27
+
28
+ const DOCS_DIR = path.join(import.meta.dirname, '..', '..', 'docs');
29
+
30
+ /** Every base reference doc that has at least one overlay. */
31
+ function overlayPairs() {
32
+ const pairs = [];
33
+ for (const file of fs.readdirSync(DOCS_DIR)) {
34
+ const m = file.match(/^(.+)\.doc\.(dense|zh)\.mjs$/);
35
+ if (!m) continue;
36
+ const [, topic, variant] = m;
37
+ pairs.push({
38
+ topic,
39
+ variant,
40
+ basePath: path.join(DOCS_DIR, `${topic}.doc.mjs`),
41
+ overlayPath: path.join(DOCS_DIR, file),
42
+ });
43
+ }
44
+ return pairs;
45
+ }
46
+
47
+ async function load(p) {
48
+ return await import(pathToFileURL(p).href);
49
+ }
50
+
51
+ describe('reference doc overlays (#2182)', () => {
52
+ const pairs = overlayPairs();
53
+
54
+ it('finds overlays to check', () => {
55
+ // A rename that stops overlays being discovered must not silently pass.
56
+ expect(pairs.length).toBeGreaterThan(0);
57
+ });
58
+
59
+ for (const {topic, variant, basePath, overlayPath} of pairs) {
60
+ it(`${topic} --${variant}: every overlay section anchors to a real base section`, async () => {
61
+ const base = await load(basePath);
62
+ const overlayMod = await load(overlayPath);
63
+ const overlay = overlayMod.docsDense || overlayMod.docsZh;
64
+
65
+ const baseTitles = base.docs.sections.map(s => s.title);
66
+ const unanchored = (overlay.sections || [])
67
+ .filter(s => s.section == null || !baseTitles.includes(s.section))
68
+ .map(s => s.section ?? `(no anchor) "${s.title}"`);
69
+
70
+ expect(
71
+ unanchored,
72
+ `${topic}.doc.${variant}.mjs has section entries that do not name a ` +
73
+ `base section via \`section:\`. Without an anchor the overlay is ` +
74
+ `applied by array position, which silently grafts each title onto ` +
75
+ `the wrong body. Base sections are: ${baseTitles.join(', ')}.`,
76
+ ).toEqual([]);
77
+ });
78
+
79
+ it(`${topic} --${variant}: no base section is overridden twice`, async () => {
80
+ const overlayMod = await load(overlayPath);
81
+ const overlay = overlayMod.docsDense || overlayMod.docsZh;
82
+ const anchors = (overlay.sections || []).map(s => s.section);
83
+ const dupes = anchors.filter((a, i) => anchors.indexOf(a) !== i);
84
+ expect(dupes, `${topic}.doc.${variant}.mjs overrides the same base section twice`).toEqual([]);
85
+ });
86
+ }
87
+ });
88
+
89
+ describe('the reported defect: docs tokens --dense (#2182)', () => {
90
+ it('does not print the colour table under the Spacing heading', async () => {
91
+ const result = await docs('tokens', null, {dense: true});
92
+ const spacing = result.data.sections.find(s => /spacing/i.test(s.title));
93
+ expect(spacing, 'tokens docs should have a spacing section').toBeTruthy();
94
+
95
+ const text = JSON.stringify(spacing);
96
+ expect(
97
+ text.includes('--color-'),
98
+ `The "${spacing.title}" section of \`docs tokens --dense\` contains ` +
99
+ `colour tokens. An agent reading this learns that spacing tokens are ` +
100
+ `named --color-*.`,
101
+ ).toBe(false);
102
+ expect(text).toContain('--spacing-');
103
+ });
104
+
105
+ it('keeps every base section reachable, even without an overlay entry', async () => {
106
+ // The tokens overlay compresses only 6 of 13 sections. The other 7 must
107
+ // still render (in English), not vanish or absorb a neighbour's title.
108
+ const full = await docs('tokens', null, {});
109
+ const dense = await docs('tokens', null, {dense: true});
110
+ expect(dense.data.sections.length).toBe(full.data.sections.length);
111
+ });
112
+
113
+ it('does not lose the Extending a Theme section from docs theme --dense', async () => {
114
+ const dense = await docs('theme', null, {dense: true});
115
+ const titles = dense.data.sections.map(s => s.title);
116
+ expect(titles).toContain('Extending a Theme');
117
+ });
118
+
119
+ it('does not emit a duplicate useTheme heading in docs theme --dense', async () => {
120
+ const dense = await docs('theme', null, {dense: true});
121
+ const titles = dense.data.sections.map(s => s.title.toLowerCase());
122
+ const useTheme = titles.filter(t => t.includes('usetheme'));
123
+ expect(useTheme.length).toBe(1);
124
+ });
125
+
126
+ it('does not leak English headings into docs theme --zh', async () => {
127
+ const zh = await docs('theme', null, {zh: true});
128
+ const titles = zh.data.sections.map(s => s.title);
129
+ // Every section the overlay translates must appear once, in Chinese only.
130
+ expect(titles).not.toContain('Light/Dark Mode');
131
+ expect(titles).toContain('亮/暗模式');
132
+ });
133
+ });
package/src/api/docs.mjs CHANGED
@@ -38,11 +38,23 @@ async function loadReferenceDocs(docPath, {lang} = {}) {
38
38
  const translation = translationMod.docsZh || translationMod.docsDense;
39
39
  if (!translation) return docs;
40
40
 
41
+ // Overlays are keyed to a base section by title (`section`), not by array
42
+ // position. Position-keying silently grafted each overlay title onto whatever
43
+ // base section happened to share its index, so an overlay that omitted or
44
+ // reordered a section corrupted every section after it — `docs tokens --dense`
45
+ // printed the colour table under a "Spacing" heading (#2182). An overlay may
46
+ // now cover any subset of sections, in any order; sections it does not name
47
+ // keep their base content.
48
+ const bySection = new Map();
49
+ for (const ts of translation.sections ?? []) {
50
+ if (ts?.section != null) bySection.set(ts.section, ts);
51
+ }
52
+
41
53
  return {
42
54
  ...docs,
43
55
  description: translation.description || docs.description,
44
- sections: docs.sections.map((section, si) => {
45
- const ts = translation.sections?.[si];
56
+ sections: docs.sections.map(section => {
57
+ const ts = bySection.get(section.title);
46
58
  if (!ts) return section;
47
59
  return {
48
60
  ...section,
@@ -26,7 +26,7 @@ import {createRequire} from 'node:module';
26
26
 
27
27
  import {MIN_NODE_VERSION, isNodeVersionSupported} from '../lib/node-version.mjs';
28
28
  import {CLI_ROOT, findCoreDir} from '../utils/paths.mjs';
29
- import {detectPackageManager} from '../utils/package-manager.mjs';
29
+ import {detectPackageManager, getCliInvocation} from '../utils/package-manager.mjs';
30
30
  import {findConfigPath, Project} from '../lib/project.mjs';
31
31
  import {semverCompare} from '../utils/semver.mjs';
32
32
 
@@ -343,7 +343,7 @@ export function checkAgentDocs(ctx) {
343
343
  label: 'AI agent docs',
344
344
  status: 'info',
345
345
  message: 'No agent docs (CLAUDE.md / AGENTS.md / .cursorrules) found.',
346
- fix: 'Generate agent docs with `astryx init --features agents`.',
346
+ fix: `Generate agent docs with \`${getCliInvocation(ctx.cwd)} init --features agents\`.`,
347
347
  };
348
348
  }
349
349
 
@@ -365,7 +365,7 @@ export function checkAgentDocs(ctx) {
365
365
  label: 'AI agent docs',
366
366
  status: 'warn',
367
367
  message: `Agent docs present (${present.join(', ')}) but no Astryx section markers found.`,
368
- fix: 'Add the Astryx section to your agent docs with `astryx init --features agents`.',
368
+ fix: `Add the Astryx section to your agent docs with \`${getCliInvocation(ctx.cwd)} init --features agents\`.`,
369
369
  };
370
370
  }
371
371
 
@@ -0,0 +1,240 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Proves the minimal `exports` recipe an integration package needs so a
5
+ * bundler-resolution consumer can `import()` its block templates AND type-check
6
+ * them under `moduleResolution: bundler`.
7
+ *
8
+ * Integration packages in this ecosystem ship TypeScript SOURCE — their block
9
+ * templates are `.tsx` files with no compiled `.d.ts`. A later feature renders
10
+ * showcase previews by a REAL dynamic `import()` of a block's `.tsx` source
11
+ * (e.g. `import('@acme/widgets/templates/Gauge/GaugeShowcase.tsx')`) instead of
12
+ * eval'ing source text. For that import to resolve, the integration's
13
+ * `package.json#exports` map must GATE the deep path.
14
+ *
15
+ * These tests stand up a throwaway `@acme/widgets` fixture and drive the two
16
+ * gates that matter with the repo's own toolchain:
17
+ * 1. `tsc --noEmit` under `moduleResolution: bundler` (the consumer profile
18
+ * used by the Next.js example apps — NO `allowImportingTsExtensions`).
19
+ * 2. `esbuild --bundle` (a real bundler resolving + loading the deep import).
20
+ *
21
+ * CANONICAL RECIPE (see integration-authoring.md):
22
+ * exports: { "./templates/*.tsx": "./templates/*.tsx" }
23
+ * import: import('@acme/widgets/templates/<Name>/<Name>Showcase.tsx') // WITH .tsx
24
+ *
25
+ * The negative controls lock in WHY the extension is required: a bare
26
+ * `./templates/*` export with an extensionless import fails to type-check under
27
+ * bundler resolution (TS cannot infer the `.tsx` extension for a deep
28
+ * specifier), and an extensionless import fails to bundle.
29
+ */
30
+
31
+ import {afterEach, beforeEach, describe, expect, it} from 'vitest';
32
+ import * as fs from 'node:fs';
33
+ import * as os from 'node:os';
34
+ import * as path from 'node:path';
35
+ import {createRequire} from 'node:module';
36
+ import {execFileSync} from 'node:child_process';
37
+
38
+ const require = createRequire(import.meta.url);
39
+
40
+ /** Resolve the workspace tsc/esbuild binaries; null if unavailable. */
41
+ function resolveBin(spec) {
42
+ try {
43
+ return require.resolve(spec);
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+ const TSC_BIN = resolveBin('typescript/bin/tsc');
49
+ const ESBUILD_BIN = resolveBin('esbuild/bin/esbuild');
50
+
51
+ let tmpDir;
52
+
53
+ /**
54
+ * Build an @acme/widgets fixture: a block template (`.template.ts` doc +
55
+ * same-stem `.tsx` source) under `templates/`, plus an astryx.integration
56
+ * manifest, plus a caller-supplied `exports` map.
57
+ * @param {Record<string, string> | undefined} exportsMap
58
+ */
59
+ function makeWidgets(exportsMap) {
60
+ const pkgDir = path.join(tmpDir, 'node_modules', '@acme', 'widgets');
61
+ const blockDir = path.join(pkgDir, 'templates', 'Gauge');
62
+ fs.mkdirSync(blockDir, {recursive: true});
63
+
64
+ const pkg = {name: '@acme/widgets', version: '2.0.0', type: 'module'};
65
+ if (exportsMap) pkg.exports = exportsMap;
66
+ fs.writeFileSync(
67
+ path.join(pkgDir, 'package.json'),
68
+ JSON.stringify(pkg, null, 2),
69
+ );
70
+ fs.writeFileSync(
71
+ path.join(pkgDir, 'astryx.integration.mjs'),
72
+ `export default { templates: './templates' };\n`,
73
+ );
74
+ // The template-spec doc (canonical `.template.*` family).
75
+ fs.writeFileSync(
76
+ path.join(blockDir, 'GaugeShowcase.template.ts'),
77
+ `export default { name: 'Gauge showcase', description: 'A gauge.' };\n`,
78
+ );
79
+ // The same-stem `.tsx` SOURCE that a preview will dynamically import().
80
+ // Returns a plain value so the fixture type-checks without React types.
81
+ fs.writeFileSync(
82
+ path.join(blockDir, 'GaugeShowcase.tsx'),
83
+ `const GaugeShowcase = (): string => 'gauge-showcase';\n` +
84
+ `export default GaugeShowcase;\n`,
85
+ );
86
+ return pkgDir;
87
+ }
88
+
89
+ /** Write a consumer that dynamically imports the given specifier. */
90
+ function writeConsumer(specifier) {
91
+ fs.writeFileSync(
92
+ path.join(tmpDir, 'consumer.ts'),
93
+ `const load = () => import('${specifier}');\nexport default load;\n`,
94
+ );
95
+ }
96
+
97
+ /**
98
+ * The realistic consumer tsconfig: matches the repo's Next.js example apps
99
+ * (`moduleResolution: bundler`, `noEmit`, and deliberately NO
100
+ * `allowImportingTsExtensions`).
101
+ */
102
+ function writeTsconfig() {
103
+ fs.writeFileSync(
104
+ path.join(tmpDir, 'tsconfig.json'),
105
+ JSON.stringify(
106
+ {
107
+ compilerOptions: {
108
+ target: 'ES2022',
109
+ lib: ['ES2022', 'DOM', 'DOM.Iterable'],
110
+ module: 'ESNext',
111
+ moduleResolution: 'bundler',
112
+ jsx: 'react-jsx',
113
+ strict: true,
114
+ skipLibCheck: true,
115
+ esModuleInterop: true,
116
+ noEmit: true,
117
+ isolatedModules: true,
118
+ },
119
+ include: ['consumer.ts'],
120
+ },
121
+ null,
122
+ 2,
123
+ ),
124
+ );
125
+ }
126
+
127
+ /** @returns {{ok: boolean, out: string}} */
128
+ function runTsc() {
129
+ try {
130
+ execFileSync(process.execPath, [TSC_BIN, '--noEmit', '-p', 'tsconfig.json'], {
131
+ cwd: tmpDir,
132
+ stdio: 'pipe',
133
+ });
134
+ return {ok: true, out: ''};
135
+ } catch (e) {
136
+ return {ok: false, out: `${e.stdout ?? ''}${e.stderr ?? ''}`};
137
+ }
138
+ }
139
+
140
+ /** @returns {{ok: boolean, out: string}} */
141
+ function runEsbuild() {
142
+ try {
143
+ // esbuild's bin is a native executable (not a node script), so invoke it
144
+ // directly rather than through process.execPath.
145
+ execFileSync(
146
+ ESBUILD_BIN,
147
+ [
148
+ 'consumer.ts',
149
+ '--bundle',
150
+ '--format=esm',
151
+ '--loader:.tsx=tsx',
152
+ '--outfile=/dev/null',
153
+ '--log-level=error',
154
+ ],
155
+ {cwd: tmpDir, stdio: 'pipe'},
156
+ );
157
+ return {ok: true, out: ''};
158
+ } catch (e) {
159
+ return {ok: false, out: `${e.stdout ?? ''}${e.stderr ?? ''}`};
160
+ }
161
+ }
162
+
163
+ beforeEach(() => {
164
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-block-exports-'));
165
+ fs.writeFileSync(
166
+ path.join(tmpDir, 'package.json'),
167
+ JSON.stringify({name: 'consumer', private: true, type: 'module'}),
168
+ );
169
+ writeTsconfig();
170
+ });
171
+
172
+ afterEach(() => {
173
+ fs.rmSync(tmpDir, {recursive: true, force: true});
174
+ });
175
+
176
+ const CANONICAL = 'import(@acme/widgets/templates/Gauge/GaugeShowcase.tsx)';
177
+ const SPEC = '@acme/widgets/templates/Gauge/GaugeShowcase.tsx';
178
+
179
+ describe('integration block-template exports recipe', () => {
180
+ it.runIf(TSC_BIN != null)(
181
+ `CANONICAL: exports {"./templates/*.tsx"} + ${CANONICAL} type-checks under bundler resolution`,
182
+ () => {
183
+ makeWidgets({'./templates/*.tsx': './templates/*.tsx'});
184
+ writeConsumer(SPEC);
185
+ const {ok, out} = runTsc();
186
+ expect(out).toBe('');
187
+ expect(ok).toBe(true);
188
+ },
189
+ 30_000,
190
+ );
191
+
192
+ it.runIf(ESBUILD_BIN != null)(
193
+ `CANONICAL: the same import resolves + bundles with a real bundler`,
194
+ () => {
195
+ makeWidgets({'./templates/*.tsx': './templates/*.tsx'});
196
+ writeConsumer(SPEC);
197
+ const {ok, out} = runEsbuild();
198
+ expect(out).toBe('');
199
+ expect(ok).toBe(true);
200
+ },
201
+ 30_000,
202
+ );
203
+
204
+ it.runIf(TSC_BIN != null)(
205
+ 'NEGATIVE: an extensionless import does NOT type-check (TS cannot infer .tsx)',
206
+ () => {
207
+ makeWidgets({'./templates/*.tsx': './templates/*.tsx'});
208
+ writeConsumer('@acme/widgets/templates/Gauge/GaugeShowcase');
209
+ const {ok, out} = runTsc();
210
+ expect(ok).toBe(false);
211
+ expect(out).toContain('TS2307');
212
+ },
213
+ 30_000,
214
+ );
215
+
216
+ it.runIf(TSC_BIN != null)(
217
+ 'NEGATIVE: a bare "./templates/*" export (no .tsx entry) does NOT type-check the .tsx import',
218
+ () => {
219
+ // Only a bare mapping — the extensionful subpath is not exported.
220
+ makeWidgets({'./templates/*': './templates/*'});
221
+ writeConsumer(SPEC);
222
+ const {ok, out} = runTsc();
223
+ expect(ok).toBe(false);
224
+ // Bare export forces the TS5097 opt-in requirement (allowImportingTsExtensions).
225
+ expect(out).toContain('TS5097');
226
+ },
227
+ 30_000,
228
+ );
229
+
230
+ it.runIf(ESBUILD_BIN != null)(
231
+ 'NEGATIVE: an extensionless import does NOT bundle against the .tsx-only export',
232
+ () => {
233
+ makeWidgets({'./templates/*.tsx': './templates/*.tsx'});
234
+ writeConsumer('@acme/widgets/templates/Gauge/GaugeShowcase');
235
+ const {ok} = runEsbuild();
236
+ expect(ok).toBe(false);
237
+ },
238
+ 30_000,
239
+ );
240
+ });
@@ -0,0 +1,246 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file The canonical `.template.{ts,mjs,js}` suffix is discovered identically
5
+ * to the legacy `.doc.{ts,mjs,js}` suffix.
6
+ *
7
+ * Template-spec files are named for what they are: a scaffoldable TEMPLATE that
8
+ * exports `createBlockTemplate`/`createPageTemplate`. The `.doc.*` suffix was
9
+ * inherited from the component-doc convention and is still accepted during the
10
+ * transition. These tests stand up integration templates and external blocks in
11
+ * both families and assert byte-for-byte-equivalent discovery + scaffolding.
12
+ */
13
+
14
+ import {afterEach, beforeEach, describe, expect, it} from 'vitest';
15
+ import * as fs from 'node:fs';
16
+ import * as path from 'node:path';
17
+ import * as os from 'node:os';
18
+ import {
19
+ template,
20
+ findShowcase,
21
+ findRelatedBlocks,
22
+ } from './template.mjs';
23
+
24
+ /** Absolute path to the CLI package so fixtures can import /src/template.mjs. */
25
+ const CLI_PKG = path.resolve(import.meta.dirname, '..', '..');
26
+
27
+ let tmpDir;
28
+ let originalCwd;
29
+
30
+ function makeConsumer() {
31
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-template-suffix-'));
32
+ fs.writeFileSync(
33
+ path.join(dir, 'package.json'),
34
+ JSON.stringify({name: 'consumer'}),
35
+ );
36
+ fs.writeFileSync(
37
+ path.join(dir, 'astryx.config.mjs'),
38
+ `export default { integrations: ['@acme/widgets'] };\n`,
39
+ );
40
+ return dir;
41
+ }
42
+
43
+ function installWidgets(consumerDir) {
44
+ const pkgDir = path.join(consumerDir, 'node_modules', '@acme', 'widgets');
45
+ fs.mkdirSync(path.join(pkgDir, 'templates'), {recursive: true});
46
+ fs.writeFileSync(
47
+ path.join(pkgDir, 'package.json'),
48
+ JSON.stringify({name: '@acme/widgets', version: '2.0.0'}),
49
+ );
50
+ fs.writeFileSync(
51
+ path.join(pkgDir, 'astryx.integration.mjs'),
52
+ `export default { templates: './templates' };\n`,
53
+ );
54
+ return pkgDir;
55
+ }
56
+
57
+ /**
58
+ * Write a template-spec file (default-export createPageTemplate/BlockTemplate)
59
+ * plus its same-stem `.tsx` source under the templates root.
60
+ * @param {string} pkgDir
61
+ * @param {string} id
62
+ * @param {{kind: 'page'|'block', suffix: string}} opts
63
+ */
64
+ function writeTemplate(pkgDir, id, {kind, suffix}) {
65
+ const docPath = path.join(pkgDir, 'templates', `${id}${suffix}`);
66
+ fs.mkdirSync(path.dirname(docPath), {recursive: true});
67
+ const create =
68
+ kind === 'page' ? 'createPageTemplate' : 'createBlockTemplate';
69
+ fs.writeFileSync(
70
+ docPath,
71
+ `import {${create}} from '${CLI_PKG}/src/template.mjs';\n` +
72
+ `export default ${create}({name: '${id} name', description: '${id} desc'});\n`,
73
+ );
74
+ fs.writeFileSync(
75
+ path.join(pkgDir, 'templates', `${id}.tsx`),
76
+ `export default function ${id.replace(/[^a-zA-Z0-9]/g, '')}() { return null; }\n`,
77
+ );
78
+ }
79
+
80
+ beforeEach(() => {
81
+ originalCwd = process.cwd();
82
+ tmpDir = makeConsumer();
83
+ process.chdir(tmpDir);
84
+ });
85
+
86
+ afterEach(() => {
87
+ process.chdir(originalCwd);
88
+ fs.rmSync(tmpDir, {recursive: true, force: true});
89
+ });
90
+
91
+ describe('integration templates: .template.* discovered like legacy .doc.*', () => {
92
+ for (const suffix of ['.template.ts', '.template.mjs', '.doc.mjs']) {
93
+ it(`discovers + lists a page template authored as ${suffix}`, async () => {
94
+ const pkgDir = installWidgets(tmpDir);
95
+ writeTemplate(pkgDir, 'pricing', {kind: 'page', suffix});
96
+
97
+ const result = await template(undefined, {list: true, cwd: tmpDir});
98
+ const entry = result.data.find(t => t.id === 'pricing');
99
+ expect(entry).toBeTruthy();
100
+ expect(entry.type).toBe('page');
101
+ expect(entry.package).toBe('@acme/widgets');
102
+ expect(entry.name).toBe('pricing name');
103
+ expect(entry.description).toBe('pricing desc');
104
+ });
105
+
106
+ it(`scaffolds a page template authored as ${suffix}`, async () => {
107
+ const pkgDir = installWidgets(tmpDir);
108
+ writeTemplate(pkgDir, 'pricing', {kind: 'page', suffix});
109
+
110
+ const result = await template('pricing', {
111
+ targetPath: './dest',
112
+ cwd: tmpDir,
113
+ });
114
+ expect(result.type).toBe('template.copy');
115
+ expect(result.data.fileName).toBe('page.tsx');
116
+ expect(fs.existsSync(path.join(tmpDir, 'dest', 'page.tsx'))).toBe(true);
117
+ });
118
+
119
+ it(`scaffolds a nested block template authored as ${suffix}`, async () => {
120
+ const pkgDir = installWidgets(tmpDir);
121
+ writeTemplate(pkgDir, 'marketing/hero', {kind: 'block', suffix});
122
+
123
+ const result = await template('marketing/hero', {
124
+ targetPath: './dest',
125
+ cwd: tmpDir,
126
+ });
127
+ expect(result.type).toBe('template.copy');
128
+ expect(result.data.fileName).toBe('hero.tsx');
129
+ expect(fs.existsSync(path.join(tmpDir, 'dest', 'hero.tsx'))).toBe(true);
130
+ });
131
+ }
132
+
133
+ it('treats a .template.ts and a legacy .doc.mjs identically (same shape)', async () => {
134
+ const pkgDir = installWidgets(tmpDir);
135
+ writeTemplate(pkgDir, 'gauge', {kind: 'block', suffix: '.template.ts'});
136
+ writeTemplate(pkgDir, 'chip', {kind: 'block', suffix: '.doc.mjs'});
137
+
138
+ const result = await template(undefined, {list: true, cwd: tmpDir});
139
+ const gauge = result.data.find(t => t.id === 'gauge');
140
+ const chip = result.data.find(t => t.id === 'chip');
141
+
142
+ // Both discovered, both blocks, both from the same package, both ready.
143
+ for (const entry of [gauge, chip]) {
144
+ expect(entry).toBeTruthy();
145
+ expect(entry.type).toBe('block');
146
+ expect(entry.package).toBe('@acme/widgets');
147
+ }
148
+ // Field-by-field parity apart from the (intentionally different) id/name.
149
+ expect(gauge.type).toBe(chip.type);
150
+ expect(gauge.package).toBe(chip.package);
151
+ });
152
+ });
153
+
154
+ describe('external showcase blocks: .template.* discovered like legacy .doc.*', () => {
155
+ /**
156
+ * Create a consumer whose @test/ext package contributes two showcase blocks,
157
+ * one authored as `Foo.template.ts` and one as legacy `Bar.doc.mjs`.
158
+ */
159
+ function makeShowcaseFixture() {
160
+ // Symlink the real core package (needed by findCoreDir during discovery).
161
+ const realCoreDir = path.resolve(
162
+ import.meta.dirname,
163
+ '..',
164
+ '..',
165
+ '..',
166
+ 'core',
167
+ );
168
+ const coreDir = path.join(tmpDir, 'packages', 'core');
169
+ fs.mkdirSync(path.dirname(coreDir), {recursive: true});
170
+ fs.symlinkSync(realCoreDir, coreDir);
171
+
172
+ const extDir = path.join(tmpDir, 'node_modules', '@test', 'ext');
173
+ const blocksDir = path.join(extDir, 'blocks', 'components');
174
+
175
+ // Foo showcase — canonical .template.ts (default-export createBlockTemplate).
176
+ const fooDir = path.join(blocksDir, 'Foo');
177
+ fs.mkdirSync(fooDir, {recursive: true});
178
+ fs.writeFileSync(
179
+ path.join(fooDir, 'FooShowcase.template.ts'),
180
+ `import {createBlockTemplate} from '${CLI_PKG}/src/template.mjs';\n` +
181
+ `export default createBlockTemplate({\n` +
182
+ ` name: 'Foo — Showcase',\n` +
183
+ ` description: 'Foo showcase.',\n` +
184
+ ` isShowcase: true,\n` +
185
+ ` aspectRatio: 16 / 9,\n` +
186
+ ` componentsUsed: ['Foo'],\n` +
187
+ `});\n`,
188
+ );
189
+ fs.writeFileSync(
190
+ path.join(fooDir, 'FooShowcase.tsx'),
191
+ "'use client';\nexport default function FooShowcase() { return <div>Foo</div>; }",
192
+ );
193
+
194
+ // Bar showcase — legacy .doc.mjs (export const doc).
195
+ const barDir = path.join(blocksDir, 'Bar');
196
+ fs.mkdirSync(barDir, {recursive: true});
197
+ fs.writeFileSync(
198
+ path.join(barDir, 'BarShowcase.doc.mjs'),
199
+ `export const doc = {\n` +
200
+ ` type: 'block',\n` +
201
+ ` name: 'Bar — Showcase',\n` +
202
+ ` description: 'Bar showcase.',\n` +
203
+ ` isReady: true,\n` +
204
+ ` isShowcase: true,\n` +
205
+ ` aspectRatio: 4 / 3,\n` +
206
+ ` componentsUsed: ['Bar', 'Chip'],\n` +
207
+ `};\n`,
208
+ );
209
+ fs.writeFileSync(
210
+ path.join(barDir, 'BarShowcase.tsx'),
211
+ "'use client';\nexport default function BarShowcase() { return <div>Bar</div>; }",
212
+ );
213
+
214
+ fs.writeFileSync(
215
+ path.join(extDir, 'package.json'),
216
+ JSON.stringify({
217
+ name: '@test/ext',
218
+ astryx: {docs: './src', category: 'Common', blocks: './blocks/components'},
219
+ }),
220
+ );
221
+ fs.mkdirSync(path.join(extDir, 'src'), {recursive: true});
222
+ }
223
+
224
+ it('findShowcase resolves a .template.ts external block by directory name', async () => {
225
+ makeShowcaseFixture();
226
+ const result = await findShowcase('Foo', tmpDir);
227
+ expect(result).not.toBeNull();
228
+ expect(result.name).toBe('Foo — Showcase');
229
+ expect(result.filePath).toContain('FooShowcase.tsx');
230
+ });
231
+
232
+ it('findShowcase resolves a legacy .doc.mjs external block by componentsUsed', async () => {
233
+ makeShowcaseFixture();
234
+ const result = await findShowcase('Bar', tmpDir);
235
+ expect(result).not.toBeNull();
236
+ expect(result.name).toBe('Bar — Showcase');
237
+ });
238
+
239
+ it('findRelatedBlocks finds both suffix families', async () => {
240
+ makeShowcaseFixture();
241
+ const foo = await findRelatedBlocks('Foo', tmpDir);
242
+ expect(foo.map(b => b.dirName)).toContain('FooShowcase');
243
+ const chip = await findRelatedBlocks('Chip', tmpDir);
244
+ expect(chip.map(b => b.dirName)).toContain('BarShowcase');
245
+ });
246
+ });