Skip to content

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

TypeScript

feat(cli): accept .template suffix for template spec files (#4039)

EJ Hammond1d64659a5927
diff --git a/.changeset/template-suffix-discovery.md b/.changeset/template-suffix-discovery.md
new file mode 100644
index 0000000000..e3c5d9c90d
--- /dev/null
+++ b/.changeset/template-suffix-discovery.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feature] template: accept `.template.{ts,mjs,js}` as the canonical suffix for template-spec files, alongside the legacy `.doc.*` suffix. Template specs export `createBlockTemplate`/`createPageTemplate` — a scaffoldable template, not documentation — so they now get a descriptive name. Core, external-package, and integration discovery (`findShowcase`, `--blocks`, `astryx template <id>` scaffolding) all treat `Foo.template.ts` identically to a legacy `Foo.doc.mjs`; same-stem `.tsx` source resolves for either suffix, and `.template.ts` authoring is loaded via jiti. Additive only — no existing files are renamed.
+
+@ejhammond
diff --git a/packages/cli/src/api/template-suffix.test.mjs b/packages/cli/src/api/template-suffix.test.mjs
new file mode 100644
index 0000000000..f4ebbfa981
--- /dev/null
+++ b/packages/cli/src/api/template-suffix.test.mjs
@@ -0,0 +1,246 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file The canonical `.template.{ts,mjs,js}` suffix is discovered identically
+ * to the legacy `.doc.{ts,mjs,js}` suffix.
+ *
+ * Template-spec files are named for what they are: a scaffoldable TEMPLATE that
+ * exports `createBlockTemplate`/`createPageTemplate`. The `.doc.*` suffix was
+ * inherited from the component-doc convention and is still accepted during the
+ * transition. These tests stand up integration templates and external blocks in
+ * both families and assert byte-for-byte-equivalent discovery + scaffolding.
+ */
+
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {
+ template,
+ findShowcase,
+ findRelatedBlocks,
+} from './template.mjs';
+
+/** Absolute path to the CLI package so fixtures can import /src/template.mjs. */
+const CLI_PKG = path.resolve(import.meta.dirname, '..', '..');
+
+let tmpDir;
+let originalCwd;
+
+function makeConsumer() {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-template-suffix-'));
+ fs.writeFileSync(
+ path.join(dir, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+ fs.writeFileSync(
+ path.join(dir, 'astryx.config.mjs'),
+ `export default { integrations: ['@acme/widgets'] };\n`,
+ );
+ return dir;
+}
+
+function installWidgets(consumerDir) {
+ const pkgDir = path.join(consumerDir, 'node_modules', '@acme', 'widgets');
+ fs.mkdirSync(path.join(pkgDir, 'templates'), {recursive: true});
+ fs.writeFileSync(
+ path.join(pkgDir, 'package.json'),
+ JSON.stringify({name: '@acme/widgets', version: '2.0.0'}),
+ );
+ fs.writeFileSync(
+ path.join(pkgDir, 'astryx.integration.mjs'),
+ `export default { templates: './templates' };\n`,
+ );
+ return pkgDir;
+}
+
+/**
+ * Write a template-spec file (default-export createPageTemplate/BlockTemplate)
+ * plus its same-stem `.tsx` source under the templates root.
+ * @param {string} pkgDir
+ * @param {string} id
+ * @param {{kind: 'page'|'block', suffix: string}} opts
+ */
+function writeTemplate(pkgDir, id, {kind, suffix}) {
+ const docPath = path.join(pkgDir, 'templates', `${id}${suffix}`);
+ fs.mkdirSync(path.dirname(docPath), {recursive: true});
+ const create =
+ kind === 'page' ? 'createPageTemplate' : 'createBlockTemplate';
+ fs.writeFileSync(
+ docPath,
+ `import {${create}} from '${CLI_PKG}/src/template.mjs';\n` +
+ `export default ${create}({name: '${id} name', description: '${id} desc'});\n`,
+ );
+ fs.writeFileSync(
+ path.join(pkgDir, 'templates', `${id}.tsx`),
+ `export default function ${id.replace(/[^a-zA-Z0-9]/g, '')}() { return null; }\n`,
+ );
+}
+
+beforeEach(() => {
+ originalCwd = process.cwd();
+ tmpDir = makeConsumer();
+ process.chdir(tmpDir);
+});
+
+afterEach(() => {
+ process.chdir(originalCwd);
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('integration templates: .template.* discovered like legacy .doc.*', () => {
+ for (const suffix of ['.template.ts', '.template.mjs', '.doc.mjs']) {
+ it(`discovers + lists a page template authored as ${suffix}`, async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'pricing', {kind: 'page', suffix});
+
+ const result = await template(undefined, {list: true, cwd: tmpDir});
+ const entry = result.data.find(t => t.id === 'pricing');
+ expect(entry).toBeTruthy();
+ expect(entry.type).toBe('page');
+ expect(entry.package).toBe('@acme/widgets');
+ expect(entry.name).toBe('pricing name');
+ expect(entry.description).toBe('pricing desc');
+ });
+
+ it(`scaffolds a page template authored as ${suffix}`, async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'pricing', {kind: 'page', suffix});
+
+ const result = await template('pricing', {
+ targetPath: './dest',
+ cwd: tmpDir,
+ });
+ expect(result.type).toBe('template.copy');
+ expect(result.data.fileName).toBe('page.tsx');
+ expect(fs.existsSync(path.join(tmpDir, 'dest', 'page.tsx'))).toBe(true);
+ });
+
+ it(`scaffolds a nested block template authored as ${suffix}`, async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'marketing/hero', {kind: 'block', suffix});
+
+ const result = await template('marketing/hero', {
+ targetPath: './dest',
+ cwd: tmpDir,
+ });
+ expect(result.type).toBe('template.copy');
+ expect(result.data.fileName).toBe('hero.tsx');
+ expect(fs.existsSync(path.join(tmpDir, 'dest', 'hero.tsx'))).toBe(true);
+ });
+ }
+
+ it('treats a .template.ts and a legacy .doc.mjs identically (same shape)', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'gauge', {kind: 'block', suffix: '.template.ts'});
+ writeTemplate(pkgDir, 'chip', {kind: 'block', suffix: '.doc.mjs'});
+
+ const result = await template(undefined, {list: true, cwd: tmpDir});
+ const gauge = result.data.find(t => t.id === 'gauge');
+ const chip = result.data.find(t => t.id === 'chip');
+
+ // Both discovered, both blocks, both from the same package, both ready.
+ for (const entry of [gauge, chip]) {
+ expect(entry).toBeTruthy();
+ expect(entry.type).toBe('block');
+ expect(entry.package).toBe('@acme/widgets');
+ }
+ // Field-by-field parity apart from the (intentionally different) id/name.
+ expect(gauge.type).toBe(chip.type);
+ expect(gauge.package).toBe(chip.package);
+ });
+});
+
+describe('external showcase blocks: .template.* discovered like legacy .doc.*', () => {
+ /**
+ * Create a consumer whose @test/ext package contributes two showcase blocks,
+ * one authored as `Foo.template.ts` and one as legacy `Bar.doc.mjs`.
+ */
+ function makeShowcaseFixture() {
+ // Symlink the real core package (needed by findCoreDir during discovery).
+ const realCoreDir = path.resolve(
+ import.meta.dirname,
+ '..',
+ '..',
+ '..',
+ 'core',
+ );
+ const coreDir = path.join(tmpDir, 'packages', 'core');
+ fs.mkdirSync(path.dirname(coreDir), {recursive: true});
+ fs.symlinkSync(realCoreDir, coreDir);
+
+ const extDir = path.join(tmpDir, 'node_modules', '@test', 'ext');
+ const blocksDir = path.join(extDir, 'blocks', 'components');
+
+ // Foo showcase — canonical .template.ts (default-export createBlockTemplate).
+ const fooDir = path.join(blocksDir, 'Foo');
+ fs.mkdirSync(fooDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(fooDir, 'FooShowcase.template.ts'),
+ `import {createBlockTemplate} from '${CLI_PKG}/src/template.mjs';\n` +
+ `export default createBlockTemplate({\n` +
+ ` name: 'Foo — Showcase',\n` +
+ ` description: 'Foo showcase.',\n` +
+ ` isShowcase: true,\n` +
+ ` aspectRatio: 16 / 9,\n` +
+ ` componentsUsed: ['Foo'],\n` +
+ `});\n`,
+ );
+ fs.writeFileSync(
+ path.join(fooDir, 'FooShowcase.tsx'),
+ "'use client';\nexport default function FooShowcase() { return <div>Foo</div>; }",
+ );
+
+ // Bar showcase — legacy .doc.mjs (export const doc).
+ const barDir = path.join(blocksDir, 'Bar');
+ fs.mkdirSync(barDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(barDir, 'BarShowcase.doc.mjs'),
+ `export const doc = {\n` +
+ ` type: 'block',\n` +
+ ` name: 'Bar — Showcase',\n` +
+ ` description: 'Bar showcase.',\n` +
+ ` isReady: true,\n` +
+ ` isShowcase: true,\n` +
+ ` aspectRatio: 4 / 3,\n` +
+ ` componentsUsed: ['Bar', 'Chip'],\n` +
+ `};\n`,
+ );
+ fs.writeFileSync(
+ path.join(barDir, 'BarShowcase.tsx'),
+ "'use client';\nexport default function BarShowcase() { return <div>Bar</div>; }",
+ );
+
+ fs.writeFileSync(
+ path.join(extDir, 'package.json'),
+ JSON.stringify({
+ name: '@test/ext',
+ astryx: {docs: './src', category: 'Common', blocks: './blocks/components'},
+ }),
+ );
+ fs.mkdirSync(path.join(extDir, 'src'), {recursive: true});
+ }
+
+ it('findShowcase resolves a .template.ts external block by directory name', async () => {
+ makeShowcaseFixture();
+ const result = await findShowcase('Foo', tmpDir);
+ expect(result).not.toBeNull();
+ expect(result.name).toBe('Foo — Showcase');
+ expect(result.filePath).toContain('FooShowcase.tsx');
+ });
+
+ it('findShowcase resolves a legacy .doc.mjs external block by componentsUsed', async () => {
+ makeShowcaseFixture();
+ const result = await findShowcase('Bar', tmpDir);
+ expect(result).not.toBeNull();
+ expect(result.name).toBe('Bar — Showcase');
+ });
+
+ it('findRelatedBlocks finds both suffix families', async () => {
+ makeShowcaseFixture();
+ const foo = await findRelatedBlocks('Foo', tmpDir);
+ expect(foo.map(b => b.dirName)).toContain('FooShowcase');
+ const chip = await findRelatedBlocks('Chip', tmpDir);
+ expect(chip.map(b => b.dirName)).toContain('BarShowcase');
+ });
+});
diff --git a/packages/cli/src/api/template.mjs b/packages/cli/src/api/template.mjs
index 29e2715dfb..c85cc6734e 100644
--- a/packages/cli/src/api/template.mjs
+++ b/packages/cli/src/api/template.mjs
@@ -6,6 +6,7 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
+import {createJiti} from 'jiti';
import {loadModuleWithSchema} from '../lib/module-loader.mjs';
import {TemplateEnvelopeSchema} from '../template.mjs';
import {CLI_ROOT, discoverExternalPackages} from '../utils/paths.mjs';
@@ -21,9 +22,54 @@ import {Project} from '../lib/project.mjs';
/** Identity used for core (built-in) templates in package-scoped listings. */
const CORE_PACKAGE = '@astryxdesign/core';
-/** Doc-file basename suffixes for integration templates, in precedence order. */
+/**
+ * Canonical basename suffixes for template-spec files, in precedence order.
+ * A template spec exports a `createBlockTemplate`/`createPageTemplate` result
+ * (a scaffoldable TEMPLATE), so `.template.*` is the descriptive family name.
+ */
+const TEMPLATE_SUFFIXES = ['.template.ts', '.template.mjs', '.template.js'];
+
+/**
+ * Legacy basename suffixes for template-spec files, in precedence order.
+ * `.doc.*` was inherited from the component-doc convention before templates
+ * had their own name; it is still accepted during the transition window.
+ */
const DOC_SUFFIXES = ['.doc.ts', '.doc.mjs', '.doc.js'];
+/**
+ * The union of canonical + legacy template-spec suffixes, canonical first so
+ * `.template.*` wins over `.doc.*` when both stems exist. All template
+ * discovery matches this union so a `Foo.template.ts` file is treated exactly
+ * like a legacy `Foo.doc.mjs`.
+ */
+const ALL_TEMPLATE_SUFFIXES = [...TEMPLATE_SUFFIXES, ...DOC_SUFFIXES];
+
+/**
+ * The template-spec suffix present on `file`, or null if none matches.
+ * Recognizes both the canonical `.template.*` and legacy `.doc.*` families.
+ * @param {string} file
+ * @returns {string | null}
+ */
+function matchedTemplateSuffix(file) {
+ return ALL_TEMPLATE_SUFFIXES.find(suffix => file.endsWith(suffix)) ?? null;
+}
+
+/**
+ * RegExp matching either template-spec suffix family at end of a basename.
+ * Used where a per-file regex is convenient (e.g. block discovery walks).
+ */
+const TEMPLATE_SUFFIX_RE = /\.(template|doc)\.(ts|mjs|js)$/;
+
+let jitiInstance;
+/** Lazily-created jiti for loading `.ts` template specs (JSX-capable). */
+function getJiti() {
+ if (!jitiInstance) {
+ jitiInstance = createJiti(import.meta.url, {jsx: true});
+ }
+ return jitiInstance;
+}
+
+
/**
* Load an integration template doc module and validate it against the template
* envelope at the load boundary. Default export only — `.ts` via jiti,
@@ -87,12 +133,29 @@ export function stripTemplateAssetRefs(source) {
source,
);
}
+/**
+ * Load a template-spec module and return its metadata object. Supports both
+ * families of suffix:
+ * - Legacy `.doc.*` core/external specs export `export const doc = {...}`.
+ * - Specs authored with `createPageTemplate`/`createBlockTemplate` export the
+ * stamped object as the default export.
+ * Prefers the default export, falling back to the named `doc` export, so a
+ * `Foo.template.ts` (default export) is read identically to a legacy
+ * `Foo.doc.mjs` (`doc` export). `.ts` is loaded via jiti; `.mjs`/`.js` via a
+ * native dynamic import. Returns null if the file does not exist.
+ *
+ * @param {string} docPath absolute path to the spec file
+ * @returns {Promise<Record<string, unknown> | undefined | null>}
+ */
async function loadDocModule(docPath) {
if (!fs.existsSync(docPath)) return null;
- const docModule = await import(`file://${docPath}`);
- return docModule.doc;
+ const docModule = docPath.endsWith('.ts')
+ ? await getJiti().import(docPath)
+ : await import(`file://${docPath}`);
+ return docModule.default ?? docModule.doc;
}
+
export {discoverAll as discoverTemplates};
export function listTemplates() {
@@ -122,6 +185,20 @@ function findDocFiles(dir, pattern) {
return results;
}
+/**
+ * Resolve the template-spec file for a core page directory: the first existing
+ * `template.<suffix>` in canonical-then-legacy precedence, or null.
+ * @param {string} dirPath
+ * @returns {string | null}
+ */
+function findPageDocFile(dirPath) {
+ for (const suffix of ALL_TEMPLATE_SUFFIXES) {
+ const candidate = path.join(dirPath, `template${suffix}`);
+ if (fs.existsSync(candidate)) return candidate;
+ }
+ return null;
+}
+
async function discoverPages() {
if (!fs.existsSync(PAGES_DIR)) return [];
const dirs = fs
@@ -131,7 +208,9 @@ async function discoverPages() {
const templates = [];
for (const dir of dirs) {
const dirPath = path.join(PAGES_DIR, dir.name);
- const doc = await loadDocModule(path.join(dirPath, 'template.doc.mjs'));
+ const docPath =
+ findPageDocFile(dirPath) ?? path.join(dirPath, 'template.doc.mjs');
+ const doc = await loadDocModule(docPath);
templates.push({
type: 'page',
dirName: dir.name,
@@ -141,17 +220,18 @@ async function discoverPages() {
isReady: doc?.isReady ?? true,
scaffold: doc?.scaffold ?? false,
filePath: path.join(dirPath, 'page.tsx'),
- docPath: path.join(dirPath, 'template.doc.mjs'),
+ docPath,
});
}
return templates;
}
async function discoverBlocks() {
- const docFiles = findDocFiles(BLOCKS_DIR, /\.doc\.mjs$/);
+ const docFiles = findDocFiles(BLOCKS_DIR, TEMPLATE_SUFFIX_RE);
const blocks = [];
for (const docPath of docFiles) {
- const basename = path.basename(docPath, '.doc.mjs');
+ const suffix = matchedTemplateSuffix(docPath);
+ const basename = path.basename(docPath, suffix);
const tsxPath = path.join(path.dirname(docPath), basename + '.tsx');
if (!fs.existsSync(tsxPath)) continue;
const doc = await loadDocModule(docPath);
@@ -173,6 +253,7 @@ async function discoverBlocks() {
return blocks;
}
+
/**
* Discover blocks from external packages that declare `astryx.blocks` in
* their package.json. Same shape as discoverBlocks() output.
@@ -185,9 +266,10 @@ async function discoverExternalBlocks(cwd = process.cwd()) {
for (const ext of externals) {
if (!ext.blocksDir || !fs.existsSync(ext.blocksDir)) continue;
- const docFiles = findDocFiles(ext.blocksDir, /\.doc\.mjs$/);
+ const docFiles = findDocFiles(ext.blocksDir, TEMPLATE_SUFFIX_RE);
for (const docPath of docFiles) {
- const basename = path.basename(docPath, '.doc.mjs');
+ const suffix = matchedTemplateSuffix(docPath);
+ const basename = path.basename(docPath, suffix);
const tsxPath = path.join(path.dirname(docPath), basename + '.tsx');
if (!fs.existsSync(tsxPath)) continue;
const doc = await loadDocModule(docPath);
@@ -258,8 +340,9 @@ async function discoverAllWithErrors(cwd = process.cwd()) {
export {discoverAllWithErrors};
/**
- * Recursively collect integration template doc files under `root`.
- * Returns absolute paths to files ending in one of DOC_SUFFIXES.
+ * Recursively collect integration template-spec files under `root`.
+ * Returns absolute paths to files ending in one of ALL_TEMPLATE_SUFFIXES
+ * (canonical `.template.*` or legacy `.doc.*`).
*
* @param {string} root
* @returns {string[]}
@@ -272,7 +355,7 @@ function findIntegrationDocFiles(root) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
walk(full);
- } else if (DOC_SUFFIXES.some(suffix => entry.name.endsWith(suffix))) {
+ } else if (ALL_TEMPLATE_SUFFIXES.some(suffix => entry.name.endsWith(suffix))) {
results.push(full);
}
}
@@ -281,24 +364,17 @@ function findIntegrationDocFiles(root) {
return results;
}
-/**
- * The doc-file suffix present on `file`, or null if none matches.
- * @param {string} file
- */
-function matchedDocSuffix(file) {
- return DOC_SUFFIXES.find(suffix => file.endsWith(suffix)) ?? null;
-}
-
/**
* Discover templates contributed by configured integrations.
*
* For each integration with a resolved `templates` root, every
- * `<id>.doc.{ts,mjs,js}` file is a template whose id is its path relative to
- * the templates root with the `.doc.*` suffix stripped (kebab-case, may be
- * nested). The doc's `type` (page|block) decides scaffolding — there is no
- * `/pages` vs `/blocks` requirement. A same-stem sibling source file
- * (`<id>.tsx`) is required; a doc missing its source, or missing `type`, is
- * an integration error and that template is skipped (recorded in `errors`).
+ * `<id>.template.{ts,mjs,js}` (or legacy `<id>.doc.{ts,mjs,js}`) file is a
+ * template whose id is its path relative to the templates root with the
+ * matched suffix stripped (kebab-case, may be nested). The doc's `type`
+ * (page|block) decides scaffolding — there is no `/pages` vs `/blocks`
+ * requirement. A same-stem sibling source file (`<id>.tsx`) is required; a doc
+ * missing its source, or missing `type`, is an integration error and that
+ * template is skipped (recorded in `errors`).
*
* @param {string} [cwd]
* @returns {Promise<{templates: object[], errors: {package: string, template?: string, message: string}[]}>}
@@ -344,7 +420,7 @@ export async function discoverIntegrationTemplatesForOne(integration) {
if (!root || !fs.existsSync(root)) return {templates, errors};
for (const docPath of findIntegrationDocFiles(root)) {
- const suffix = matchedDocSuffix(docPath);
+ const suffix = matchedTemplateSuffix(docPath);
const id = path
.relative(root, docPath)
.slice(0, -suffix.length)