An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): astryx template --cdn — an ESM CDN recipe that is verified by rendering it, and drop the dead UMD bundle (#5068)
Cindy Zhangac850d9ea0a6
diff --git a/.changeset/cdn-remove-umd.md b/.changeset/cdn-remove-umd.mdnew file mode 100644index 0000000000..f0363c6890--- /dev/null+++ b/.changeset/cdn-remove-umd.md@@ -0,0 +1,23 @@+---+'@astryxdesign/core': patch+---++[chore] Remove the UMD bundle — it could not work with any React this package supports (#5068).++`dist/astryx.umd.js` is no longer built or published, and with it go the `unpkg` and `jsdelivr`+package fields, the `./astryx.umd.js` export and the `build:umd` step.++Nobody has a migration to make, because there was no working configuration to migrate from. The+bundle binds Astryx to `window.React` and `window.ReactDOM`, and React 19 does not ship a build that+defines them: "UMD builds removed: To load React 19 with a script tag, we recommend using an+ESM-based CDN such as esm.sh." `https://unpkg.com/[email protected]/umd/react.production.min.js` is a 404+where 18.3.1 is a 200. Our `peerDependencies` are `react >= 19.0.0`, so every supported React is one+without a global for the bundle to bind to — it documented a path that never had an entrance.++If you were loading it with an older React anyway, load the same components as modules instead: an+import map for `react`, `react/jsx-runtime`, `react-dom`, `react-dom/client` and+`@astryxdesign/core` (pinned, with `?external=react,react-dom`), then one `<script type="module">`.+`astryx template --cdn` writes that page for you, pinned to your installed version and annotated; the+recipe is also in the core README under "No build step (CDN)".++@cixzhangdiff --git a/.changeset/cdn-template.md b/.changeset/cdn-template.mdnew file mode 100644index 0000000000..c18217f734--- /dev/null+++ b/.changeset/cdn-template.md@@ -0,0 +1,38 @@+---+'@astryxdesign/cli': patch+'@astryxdesign/core': patch+---++[feat] `astryx template --cdn` writes a working no-build-step CDN starter page (#5068).++A CDN starter is a template, so it joins the template family beside `--skeleton` rather than+claiming a top-level command. It is a flag and not the positional `astryx template cdn` because the+positional resolves against everything `discoverAll()` finds, where a `cdn` id would shadow a+discovered template. `cdn.template.html` loads Astryx from jsDelivr and esm.sh with no bundler, no+install and no build step, with every CDN URL pinned to the Astryx version you have installed — an+unpinned CDN URL resolves to whatever is latest and is cached hard, so a page written today breaks+tomorrow without being edited. An existing file is never clobbered; `--overwrite` replaces it, and+`--json` returns the receipt.++The annotations are the things that are load-bearing and silent when missing: `?external=react,react-dom`+(without it esm.sh bundles a second React and every hook throws `Cannot read properties of null+(reading 'useState')`), `react/jsx-runtime` in the import map (the published bundle imports it;+omitting it fails the page with `Failed to resolve module specifier`), and a `font-family` on `body`+(nothing in the stylesheets sets a document font, so `Button` — which is `font: inherit` — otherwise+renders its label in the browser's default serif).++Three more lessons came out of building a real app on it. The page now `<link>`s the theme's webfont+from Google Fonts, because the theme _names_ Figtree and never loads it, so every viewer silently+got the fallback stack (#5015 again). It imports the theme OBJECT and wraps in+`<Theme theme={neutralTheme} mode="system">`, so light and dark follow the OS — the+`data-astryx-theme` attribute alone scopes the stylesheet but cannot switch modes. And `#root:empty`+carries a "Loading…" state, because ESM-from-CDN has real latency and a blank page reads as broken.+Markup is `htm`, with a comment saying it is optional and `createElement` is the dependency-free+alternative.++A recipe that is only read is a recipe that is only assumed to work, so CI renders it:+`.github/scripts/cdn-template-smoke-test.mjs` scaffolds the page with the real CLI and opens it in+headless Chromium, failing on any console error, page error or failed request, and on a page that+loads without rendering.++@cixzhangdiff --git a/.github/scripts/cdn-template-smoke-test.mjs b/.github/scripts/cdn-template-smoke-test.mjsnew file mode 100644index 0000000000..fe1dbb5e44--- /dev/null+++ b/.github/scripts/cdn-template-smoke-test.mjs@@ -0,0 +1,170 @@+#!/usr/bin/env node+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * CDN starter-page smoke test — scaffolds `astryx template --cdn` into a temp+ * directory, serves it, and opens it in headless Chromium. Fails on any console+ * error, page error, or failed request, and on a page that loaded without+ * rendering anything.+ *+ * This is the one recipe we ship that runs entirely outside the repo: no+ * bundler resolves its imports, no test double stands in for jsDelivr or+ * esm.sh, and the failure modes it is annotated against (a missing+ * react/jsx-runtime entry, a second React copy) are silent until a browser+ * executes it. Reading the file proves nothing; this does.+ *+ * Needs network access and `npx playwright install chromium`.+ *+ * Usage:+ * node .github/scripts/cdn-template-smoke-test.mjs+ *+ * Exit code 0 = the page rendered clean+ * Exit code 1 = it did not+ */++import {spawnSync} from 'node:child_process';+import {chromium} from 'playwright';+import * as fs from 'node:fs';+import * as http from 'node:http';+import * as os from 'node:os';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');+const CLI = path.join(ROOT, 'packages/cli/clients/cli/bin/astryx.mjs');+const PAGE = 'cdn.template.html';+const ATTEMPTS = 2;++const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-cdn-smoke-'));+const pagePath = path.join(tmpDir, PAGE);++function fail(message, detail) {+ console.log(` FAIL ${message}`);+ if (detail) console.log(detail);+ process.exitCode = 1;+}++// ── 1. Scaffold the page with the real CLI ───────────────────────────────────+fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'cdn-smoke', private: true}),+);+const scaffold = spawnSync(process.execPath, [CLI, '--json', 'template', '--cdn'], {+ cwd: tmpDir,+ encoding: 'utf8',+ timeout: 60_000,+});+if (scaffold.status !== 0 || !fs.existsSync(pagePath)) {+ fail(`astryx template --cdn (exit ${scaffold.status})`, scaffold.stderr);+ process.exit(1);+}+const pinned = JSON.parse(scaffold.stdout).data.version;+console.log(`scaffolded ${PAGE} pinned to ${pinned}`);++// ── 2. Point the page at a version that is actually on the CDN ───────────────+// The pin is the version in this checkout, which is unpublished for the whole+// life of a release PR (`changeset version` bumps package.json before npm has+// the tarball). Gating every PR on that would make the release PR unmergeable,+// so on an unpublished pin we re-point the page at the newest published version+// and still assert the recipe.+const published = await fetch('https://registry.npmjs.org/@astryxdesign/core')+ .then(r => r.json())+ .then(j => Object.keys(j.versions ?? {}))+ .catch(() => []);+if (published.length === 0) {+ fail('could not reach the npm registry to resolve a published version');+ process.exit(1);+}+let rendered = pinned;+if (!published.includes(pinned)) {+ rendered = published[published.length - 1];+ console.log(` note ${pinned} is not published yet — rendering against ${rendered}`);+ fs.writeFileSync(+ pagePath,+ fs.readFileSync(pagePath, 'utf8').replaceAll(`@${pinned}`, `@${rendered}`),+ );+}++// ── 3. Serve it, so the page loads the way a deployed one would ──────────────+const server = http.createServer((req, res) => {+ const body = fs.readFileSync(pagePath);+ res.writeHead(200, {'content-type': 'text/html; charset=utf-8'});+ res.end(body);+});+await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));+const url = `http://127.0.0.1:${server.address().port}/`;++/** Load the page once and report everything that went wrong. */+async function render() {+ const consoleErrors = [];+ const pageErrors = [];+ const failedRequests = [];++ const browser = await chromium.launch();+ try {+ const page = await browser.newPage();+ page.on('console', m => {+ if (m.type() === 'error') consoleErrors.push(m.text().slice(0, 300));+ });+ page.on('pageerror', e => pageErrors.push(String(e).slice(0, 300)));+ page.on('requestfailed', r =>+ failedRequests.push(`${r.url()} :: ${r.failure()?.errorText}`),+ );+ page.on('response', r => {+ if (r.status() >= 400) failedRequests.push(`${r.status()} ${r.url()}`);+ });++ await page.goto(url, {waitUntil: 'networkidle', timeout: 90_000});+ // A page that throws during render still reaches networkidle with an empty+ // root, so the render itself has to be asserted, not just the error streams.+ const button = await page+ .getByRole('button')+ .first()+ .textContent({timeout: 15_000})+ .catch(() => null);++ return {consoleErrors, pageErrors, failedRequests, button};+ } finally {+ await browser.close();+ }+}++// ── 4. Render, retrying once so a blip at a CDN is not a red build ───────────+let result;+for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {+ result = await render();+ const clean =+ result.consoleErrors.length === 0 &&+ result.pageErrors.length === 0 &&+ result.failedRequests.length === 0 &&+ result.button;+ if (clean) break;+ if (attempt < ATTEMPTS) console.log(` retry ${attempt} of ${ATTEMPTS - 1}`);+}+server.close();++// ── 5. Report ────────────────────────────────────────────────────────────────+console.log(`\n${PAGE} @ ${rendered}`);+for (const [label, entries] of [+ ['console error', result.consoleErrors],+ ['page error', result.pageErrors],+ ['failed request', result.failedRequests],+]) {+ if (entries.length === 0) {+ console.log(` ok no ${label}s`);+ } else {+ fail(`${entries.length} ${label}(s)`, entries.map(e => ` ${e}`).join('\n'));+ }+}+if (result.button) {+ console.log(` ok rendered a button: "${result.button.trim()}"`);+} else {+ fail('the page loaded but rendered no button');+}++fs.rmSync(tmpDir, {recursive: true, force: true});+if (process.exitCode) {+ console.log('\nCDN starter page is broken.');+} else {+ console.log('\nCDN starter page renders clean.');+}diff --git a/.github/workflows/cli-smoke-test.yml b/.github/workflows/cli-smoke-test.ymlindex 5592b4507f..7936e36362 100644--- a/.github/workflows/cli-smoke-test.yml+++ b/.github/workflows/cli-smoke-test.yml@@ -38,3 +38,12 @@ jobs:- name: API ↔ CLI parity testrun: node .github/scripts/api-cli-parity-test.mjs --no-baseline++ # The CDN starter page is the only thing we ship that runs with no+ # bundler and no test double for the CDNs, so it is verified by rendering+ # it. Needs network access to jsDelivr, esm.sh and the npm registry.+ - name: Install Playwright+ run: npx playwright install chromium++ - name: CDN starter page smoke test+ run: node .github/scripts/cdn-template-smoke-test.mjsdiff --git a/packages/cli/README.md b/packages/cli/README.mdindex 98050cb3d4..991d7d560f 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -383,49 +383,50 @@ Every response has a `type` discriminant. The full set is below (generated from<!-- BEGIN GENERATED: response-types -->-| Type | What `data` carries |-| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| `component.list` | The component catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of names+package, brief entries, or a full ComponentDoc per entry. |-| `component.detail` | One component's authored ComponentDoc plus ownership metadata (owner package, import specifier, and whether source is available). |-| `component.detail.props` | Just one component's props table (ComponentPropDoc[]). |-| `component.detail.source` | One component's source file, as {component, source}. |-| `component.detail.showcase` | One component's showcase example, as {component, aspectRatio, source}. |-| `component.detail.blocks` | One component's example blocks, as {component, showcase, examples, related} of BlockEntry. |-| `docs.list` | All reference-doc topics as DocsListEntry[] ({topic, description}), in discovery order. |-| `docs.detail` | One topic's full ReferenceDoc, with token-ref blocks inlined. |-| `docs.detail.section` | A single ReferenceSection of a topic: the first whose title contains the section query. |-| `blog.list` | The feed URL plus every post parsed from the RSS feed, each with slug, title, description, date, type, authors, link, and plaintext URL. |-| `blog.detail` | One post's metadata plus the feed URL and the post's full plaintext body. |-| `discover.list` | The configured external packages (name, category, components, version, description); when empty it carries meta.configured to tell "nothing configured" from "nothing discovered". |-| `discover.detail` | A single external package entry, for an @scope/name query. |-| `discover.detail.doc` | The validated ComponentDoc for one external component: an @scope/name/Component query, or a free-text term resolving to exactly one component. |-| `discover.search` | The echoed query plus the matching {package, component} pairs, when a free-text term matches several components. |-| `search` | The echoed query plus a ranked SearchResultEntry[] (domain, name, score, reason, description, follow-up command, and import path where relevant). |-| `build.help` | A marker (`playbook: true`) that the renderer expands into the how-to-build-a-page workflow; emitted when no query is given. |-| `build.kit` | The grouped composition kit: echoed query, hasResults/directMatch flags, the closest page templates, drop-in block patterns, idea-specific components/hooks, and the always-on frame + foundation component-name arrays. |-| `swizzle.list` | The names of swizzlable components discoverable from cwd's @astryxdesign/core. |-| `swizzle.copy` | An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and an optional maintainer note. |-| `template.list` | Every discovered template (page + block); each entry carries id, name, description, kind, owning package, optional category and componentsUsed, and readiness flags. |-| `template.show` | The resolved template's raw source plus its description, kind, and the component names it composes. |-| `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. |-| `hook.list` | The hook catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry. |-| `hook.detail` | One hook's full authored HookDoc. |-| `hook.detail.params` | Just one hook's parameters table (HookParamDoc[]). |-| `theme.build` | A theme build receipt: name, token- and component-override counts, output size, the written outputs {css, js, dts, and variantsDts when applicable}, and any validation warnings. |-| `theme.build.check` | The --check receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: missing \| outdated}), and the full list of checked paths. Writes nothing. |-| `theme.list` | Every bundled theme as a ThemeListEntry[]: each with slug, displayName, description, and a maintained flag. |-| `theme.add` | A scaffold receipt: resolved slug, displayName, maintained flag, outputDir (relative to cwd), the theme entry file, its exportName, and the files written. |-| `theme.template` | A write receipt for the annotated theme template: the path (relative to cwd), whether it was written, and the reason it was not — `exists` when a file was already there, which is a success. |-| `upgrade.list` | Every available codemod, oldest→newest, as {name, title, version, optional}; returned for --list without running anything. |-| `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. |-| `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, and (apply mode) filesChanged, transformsApplied, and per-codemod errors. |-| `manifest` | The self-describing CLI capability manifest: name, version, apiVersion, global options, the command tree (args, options, json flag, response types, examples), the jsonSupported allowlist, and the flat responseTypes index. |-| `doctor` | The health-check report: `checks` (each with id, label, status: pass \| warn \| fail \| info, a message, and a fix when not passing) plus a `summary` of counts per status. |-| `integration.validate` | The validation result: the package name and version (both null when no local manifest is found) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message}. |-| `layout.expand` | The expansion: parsed form, generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, and written (the output path, or null when nothing was written). |-| `layout.check` | The validation result: a valid flag, the detected form, errors (each with line/col, message, formatted text, and suggestions), warnings, and the expression re-printed in both canonical surfaces (compact and outline). |-| `layout.grammar` | The XLE/XLO grammar cheatsheet: a text field with the full reference plus an aliases map (short name → canonical component) generated from this install's registry. |+| Type | What `data` carries |+| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `component.list` | The component catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of names+package, brief entries, or a full ComponentDoc per entry. |+| `component.detail` | One component's authored ComponentDoc plus ownership metadata (owner package, import specifier, and whether source is available). |+| `component.detail.props` | Just one component's props table (ComponentPropDoc[]). |+| `component.detail.source` | One component's source file, as {component, source}. |+| `component.detail.showcase` | One component's showcase example, as {component, aspectRatio, source}. |+| `component.detail.blocks` | One component's example blocks, as {component, showcase, examples, related} of BlockEntry. |+| `docs.list` | All reference-doc topics as DocsListEntry[] ({topic, description}), in discovery order. |+| `docs.detail` | One topic's full ReferenceDoc, with token-ref blocks inlined. |+| `docs.detail.section` | A single ReferenceSection of a topic: the first whose title contains the section query. |+| `blog.list` | The feed URL plus every post parsed from the RSS feed, each with slug, title, description, date, type, authors, link, and plaintext URL. |+| `blog.detail` | One post's metadata plus the feed URL and the post's full plaintext body. |+| `discover.list` | The configured external packages (name, category, components, version, description); when empty it carries meta.configured to tell "nothing configured" from "nothing discovered". |+| `discover.detail` | A single external package entry, for an @scope/name query. |+| `discover.detail.doc` | The validated ComponentDoc for one external component: an @scope/name/Component query, or a free-text term resolving to exactly one component. |+| `discover.search` | The echoed query plus the matching {package, component} pairs, when a free-text term matches several components. |+| `search` | The echoed query plus a ranked SearchResultEntry[] (domain, name, score, reason, description, follow-up command, and import path where relevant). |+| `build.help` | A marker (`playbook: true`) that the renderer expands into the how-to-build-a-page workflow; emitted when no query is given. |+| `build.kit` | The grouped composition kit: echoed query, hasResults/directMatch flags, the closest page templates, drop-in block patterns, idea-specific components/hooks, and the always-on frame + foundation component-name arrays. |+| `swizzle.list` | The names of swizzlable components discoverable from cwd's @astryxdesign/core. |+| `swizzle.copy` | An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and an optional maintainer note. |+| `template.list` | Every discovered template (page + block); each entry carries id, name, description, kind, owning package, optional category and componentsUsed, and readiness flags. |+| `template.show` | The resolved template's raw source plus its description, kind, and the component names it composes. |+| `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. |+| `hook.list` | The hook catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry. |+| `hook.detail` | One hook's full authored HookDoc. |+| `hook.detail.params` | Just one hook's parameters table (HookParamDoc[]). |+| `theme.build` | A theme build receipt: name, token- and component-override counts, output size, the written outputs {css, js, dts, and variantsDts when applicable}, and any validation warnings. |+| `theme.build.check` | The --check receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: missing \| outdated}), and the full list of checked paths. Writes nothing. |+| `theme.list` | Every bundled theme as a ThemeListEntry[]: each with slug, displayName, description, and a maintained flag. |+| `theme.add` | A scaffold receipt: resolved slug, displayName, maintained flag, outputDir (relative to cwd), the theme entry file, its exportName, and the files written. |+| `theme.template` | A write receipt for the annotated theme template: the path (relative to cwd), whether it was written, and the reason it was not — `exists` when a file was already there, which is a success. |+| `upgrade.list` | Every available codemod, oldest→newest, as {name, title, version, optional}; returned for --list without running anything. |+| `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. |+| `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, and (apply mode) filesChanged, transformsApplied, and per-codemod errors. |+| `manifest` | The self-describing CLI capability manifest: name, version, apiVersion, global options, the command tree (args, options, json flag, response types, examples), the jsonSupported allowlist, and the flat responseTypes index. |+| `doctor` | The health-check report: `checks` (each with id, label, status: pass \| warn \| fail \| info, a message, and a fix when not passing) plus a `summary` of counts per status. |+| `integration.validate` | The validation result: the package name and version (both null when no local manifest is found) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message}. |+| `layout.expand` | The expansion: parsed form, generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, and written (the output path, or null when nothing was written). |+| `layout.check` | The validation result: a valid flag, the detected form, errors (each with line/col, message, formatted text, and suggestions), warnings, and the expression re-printed in both canonical surfaces (compact and outline). |+| `layout.grammar` | The XLE/XLO grammar cheatsheet: a text field with the full reference plus an aliases map (short name → canonical component) generated from this install's registry. |<!-- END GENERATED: response-types --><!-- Generated by scripts/generate-cli-readme.mjs from the response-types EnumDoc. Run `pnpm -F @astryxdesign/cli readme`. -->diff --git a/packages/cli/api/template/cdn/cdn.mjs b/packages/cli/api/template/cdn/cdn.mjsnew file mode 100644index 0000000000..aece20273b--- /dev/null+++ b/packages/cli/api/template/cdn/cdn.mjs@@ -0,0 +1,86 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `template.cdn` leaf — writes the annotated no-build-step starter page+ * into the consumer's project.+ *+ * A CDN starter is a template, so it lives in the template family. It is the+ * one member that is not discovered: it ships as an asset rather than as a+ * `page.tsx` + `template.doc.mjs` pair, which is why the dispatcher routes to+ * it from a flag instead of resolving a name.+ *+ * Every CDN URL in the asset carries the `__ASTRYX_VERSION__` placeholder, which+ * is substituted here. An unpinned CDN URL resolves to whatever is latest and is+ * cached hard, so a page written today can break tomorrow without being edited.+ *+ * @position api/template/cdn — writes the CDN starter asset; the template+ * dispatcher routes `--cdn` here before any discovery happens.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {CLI_ROOT, findCoreDir} from '../../../foundation/fs/paths.mjs';+import {assertWithin, PathSafetyError} from '../../../foundation/fs/path-safety.mjs';+import {stripCopyrightHeader} from '../../../foundation/text/copyright-header.mjs';+import {getXdsVersion} from '../../../foundation/agent-docs/agent-docs.mjs';+import {AstryxError} from '../../error.mjs';+import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';++/** The annotated CDN starter that ships with the CLI. */+export const CDN_TEMPLATE_SRC = path.join(CLI_ROOT, 'assets', 'cdn.template.html');++/** Where it lands when the caller does not say. */+export const CDN_TEMPLATE_DEFAULT_PATH = 'cdn.template.html';++/** The token every CDN URL in the asset carries in place of a version. */+export const CDN_VERSION_PLACEHOLDER = '__ASTRYX_VERSION__';++/**+ * Write the annotated CDN starter page into a project.+ *+ * Refuses to overwrite without `overwrite`: an edited copy is the consumer's+ * work, and this command is safe to re-run.+ *+ * @param {{targetPath?: string, overwrite?: boolean, cwd?: string}} [options]+ * @returns {import('../template.type.mjs').TemplateCdnResponse}+ */+export function templateCdn(options = {}) {+ const {+ targetPath = CDN_TEMPLATE_DEFAULT_PATH,+ overwrite = false,+ cwd = process.cwd(),+ } = options;++ let resolved;+ try {+ resolved = assertWithin(targetPath, cwd, {label: 'cdn template path'});+ } catch (err) {+ if (err instanceof PathSafetyError) {+ throw new AstryxError(err.message, undefined, ERROR_CODES.ERR_PATH_TRAVERSAL);+ }+ throw err;+ }++ const relative = path.relative(cwd, resolved) || targetPath;+ // The installed @astryxdesign/core when there is one, else this CLI's own+ // version. core, the themes and the CLI are released as one fixed group, so+ // either answer pins a set of packages that exist together.+ const version = getXdsVersion(findCoreDir(cwd));++ if (fs.existsSync(resolved) && !overwrite) {+ return {+ type: 'template.cdn',+ data: {path: relative, version, written: false, reason: 'exists'},+ };+ }++ const source = stripCopyrightHeader(fs.readFileSync(CDN_TEMPLATE_SRC, 'utf-8'));+ const contents = source.replaceAll(CDN_VERSION_PLACEHOLDER, version);+ fs.mkdirSync(path.dirname(resolved), {recursive: true});+ fs.writeFileSync(resolved, contents);++ return {+ type: 'template.cdn',+ data: {path: relative, version, written: true, reason: null},+ };+}diff --git a/packages/cli/api/template/cdn/cdn.test.mjs b/packages/cli/api/template/cdn/cdn.test.mjsnew file mode 100644index 0000000000..a8c1d0b54a--- /dev/null+++ b/packages/cli/api/template/cdn/cdn.test.mjs@@ -0,0 +1,108 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Direct API tests for `templateCdn()` — the function behind+ * `astryx template --cdn`.+ *+ * Two things matter here: it never destroys work (the page lands once, a second+ * run leaves an edited copy alone, a path that escapes the project is refused),+ * and the page it writes is pinned — a leftover version placeholder would ship+ * a file whose every CDN URL 404s.+ */++import {describe, it, expect, beforeEach, afterEach} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import * as os from 'node:os';+import {+ templateCdn,+ CDN_TEMPLATE_DEFAULT_PATH,+ CDN_VERSION_PLACEHOLDER,+} from './cdn.mjs';++let tmpDir;+beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-template-cdn-'));+});+afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++const written = () =>+ fs.readFileSync(path.join(tmpDir, CDN_TEMPLATE_DEFAULT_PATH), 'utf-8');++describe('templateCdn()', () => {+ it('writes the page and returns a template.cdn receipt', () => {+ const res = templateCdn({cwd: tmpDir});++ expect(res.type).toBe('template.cdn');+ expect(res.data.path).toBe(CDN_TEMPLATE_DEFAULT_PATH);+ expect(res.data.written).toBe(true);+ expect(res.data.reason).toBe(null);+ expect(res.data.version).toMatch(/^\d+\.\d+\.\d+/);+ expect(written()).toMatch(/<script type="importmap">/);+ });++ it('pins every CDN url to the reported version', () => {+ const {data} = templateCdn({cwd: tmpDir});+ const html = written();++ expect(html).not.toContain(CDN_VERSION_PLACEHOLDER);+ const urls = html.match(/https:\/\/(?:cdn\.jsdelivr\.net\/npm|esm\.sh)\/@astryxdesign\/[^"?]+/g);+ expect(urls?.length).toBeGreaterThan(0);+ for (const url of urls ?? []) {+ expect(url).toContain(`@${data.version}`);+ }+ });++ it('loads the font family the theme names', () => {+ templateCdn({cwd: tmpDir});+ const html = written();++ // The theme names Figtree and never loads it (#5015): without the webfont+ // link every viewer silently gets the fallback stack instead.+ expect(html).toMatch(/fonts\.googleapis\.com\/css2\?family=Figtree/);+ });++ it('does not carry our copyright header into the consumer tree', () => {+ templateCdn({cwd: tmpDir});++ expect(written()).not.toMatch(/Copyright \(c\) Meta Platforms/);+ expect(written().startsWith('<!doctype html>')).toBe(true);+ });++ it('leaves an existing file alone and says so', () => {+ const dest = path.join(tmpDir, CDN_TEMPLATE_DEFAULT_PATH);+ fs.writeFileSync(dest, '<!-- mine -->\n');++ const res = templateCdn({cwd: tmpDir});++ expect(res.data.written).toBe(false);+ expect(res.data.reason).toBe('exists');+ expect(fs.readFileSync(dest, 'utf-8')).toBe('<!-- mine -->\n');+ });++ it('overwrites when asked', () => {+ const dest = path.join(tmpDir, CDN_TEMPLATE_DEFAULT_PATH);+ fs.writeFileSync(dest, '<!-- mine -->\n');++ const res = templateCdn({cwd: tmpDir, overwrite: true});++ expect(res.data.written).toBe(true);+ expect(written()).toMatch(/importmap/);+ });++ it('honors a custom path and creates its directory', () => {+ const res = templateCdn({cwd: tmpDir, targetPath: 'public/demo.html'});++ expect(res.data.path).toBe(path.join('public', 'demo.html'));+ expect(fs.existsSync(path.join(tmpDir, 'public/demo.html'))).toBe(true);+ });++ it('refuses a path that escapes the project', () => {+ expect(() => templateCdn({cwd: tmpDir, targetPath: '../escaped.html'})).toThrow(+ /cdn template path/,+ );+ expect(fs.existsSync(path.join(path.dirname(tmpDir), 'escaped.html'))).toBe(false);+ });+});diff --git a/packages/cli/api/template/template.doc.mjs b/packages/cli/api/template/template.doc.mjsindex 1dcd1f047f..549afadbea 100644--- a/packages/cli/api/template/template.doc.mjs+++ b/packages/cli/api/template/template.doc.mjs@@ -18,11 +18,13 @@ export const doc = {"templates; with a name it returns that template's source, a layout skeleton, or " +'scaffolds it into the project. Templates are discovered across core, external ' +'packages, and integrations, so the same id can appear in more than one place; ' +- 'narrow an ambiguous name with type and/or package.',+ 'narrow an ambiguous name with type and/or package. The cdn option writes the ' ++ 'annotated no-build-step CDN starter page, which ships as an asset rather than as ' ++ 'a discovered template.',importPath: '@astryxdesign/cli/api',signature:- 'template(name?: string, options?: TemplateOptions): Promise<TemplateListResponse | TemplateShowResponse | TemplateSkeletonResponse | TemplateCopyResponse>',- keywords: ['template', 'scaffold', 'page', 'block', 'skeleton', 'starter'],+ 'template(name?: string, options?: TemplateOptions): Promise<TemplateListResponse | TemplateShowResponse | TemplateSkeletonResponse | TemplateCopyResponse | TemplateCdnResponse>',+ keywords: ['template', 'scaffold', 'page', 'block', 'skeleton', 'starter', 'cdn', 'esm', 'importmap', 'no-build'],params: [{name: 'name',@@ -43,6 +45,13 @@ export const doc = {'Return a compact layout skeleton (structural tags with spatial annotations) instead of the full source.',default: 'false',},+ {+ name: 'options.cdn',+ type: 'boolean | string',+ description:+ 'Write the annotated no-build-step CDN starter page instead of resolving a template. Answers before discovery, so no name is involved; pass a string to use it as the destination path.',+ default: 'false',+ },{name: 'options.show',type: 'boolean',@@ -102,6 +111,11 @@ export const doc = {description:'A receipt after scaffolding the template into the project: the template id, output directory, written file name, and file count.',},+ {+ type: 'template.cdn',+ description:+ 'A write receipt for the 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.',+ },],throws: [{@@ -136,6 +150,10 @@ export const doc = {label: 'Scaffold into the project',code: "await template('dashboard', {targetPath: './app/page.tsx'});",},+ {+ label: 'CDN starter page',+ code: 'await template(undefined, {cdn: true});',+ },],command: 'template',related: ['component', 'search', 'discover', 'init'],diff --git a/packages/cli/api/template/template.mjs b/packages/cli/api/template/template.mjsindex 469c94b956..a672be9171 100644--- a/packages/cli/api/template/template.mjs+++ b/packages/cli/api/template/template.mjs@@ -5,14 +5,14 @@** This module is BOTH the template dispatcher and the stable import surface for* the template family. `template()` discovers the available templates, resolves- * the requested one, and routes to a leaf (list/show/skeleton/copy). The shared+ * the requested one, and routes to a leaf (list/show/skeleton/copy/cdn). The shared* discovery/IO + cross-command helpers live in `foundation/discovery/template-adapter.mjs` and are* RE-EXPORTED here so external import paths (`api/template/template.mjs`) —* used by component, layout, search, init, discover, validate-integration, and* lib/project — keep resolving unchanged.** @position api/template — the template dispatcher + barrel; leaves live under- * ./list, ./show, ./skeleton, ./copy and shared discovery in foundation/discovery.+ * ./list, ./show, ./skeleton, ./copy, ./cdn and shared discovery in foundation/discovery.*/import {discoverAll, pkgOf} from '../../foundation/discovery/template-adapter.mjs';@@ -22,6 +22,7 @@ import {templateList} from './list/list.mjs';import {templateShow} from './show/show.mjs';import {templateSkeleton} from './skeleton/skeleton.mjs';import {templateCopy} from './copy/copy.mjs';+import {templateCdn} from './cdn/cdn.mjs';// Re-export the shared discovery/IO + cross-command helpers so this module// stays the single import surface for the template family (same exports as@@ -56,6 +57,7 @@ export {* @param {boolean} [options.overwrite]* @param {boolean} [options.list]* @param {boolean} [options.skeleton]+ * @param {boolean | string} [options.cdn] - Write the no-build-step CDN starter page; a string is used as the destination path.* @param {boolean} [options.show]* @param {'page'|'block'} [options.type] - Filter list views / narrow lookups by template kind.* @param {string} [options.package] - Narrow lookups to a specific package (id-only matches across packages are ambiguous).@@ -67,12 +69,24 @@ export async function template(name, options = {}) {list = false,skeleton = false,show = false,+ cdn = false,targetPath,overwrite = false,type,package: packageFilter,cwd = process.cwd(),} = options;++ // The CDN starter ships as an asset rather than as a discovered template, so+ // it answers before discovery — nothing here needs a name resolved.+ if (cdn) {+ return templateCdn({+ targetPath: typeof cdn === 'string' ? cdn : targetPath,+ overwrite,+ cwd,+ });+ }+const templates = await discoverAll(cwd);if (list || (!name && !skeleton)) {diff --git a/packages/cli/api/template/template.type.mjs b/packages/cli/api/template/template.type.mjsindex 2e07e6c676..80dae9b2e4 100644--- a/packages/cli/api/template/template.type.mjs+++ b/packages/cli/api/template/template.type.mjs@@ -12,6 +12,7 @@* xds --json template <name> -> template.show* xds --json template <name> --skeleton -> template.skeleton* xds --json template <name> [path] -> template.copy+ * xds --json template --cdn [path] -> template.cdn* (unknown template) -> CLIError*/@@ -69,12 +70,23 @@* @property {number} data.filesCopied*/+/**+ * xds --json template --cdn [path]+ * `written: false` with `reason: 'exists'` is a success: the command is safe to+ * re-run, and an edited page is the consumer's file to keep. `version` is the+ * Astryx version every CDN URL in the file was pinned to.+ * @typedef {object} TemplateCdnResponse+ * @property {'template.cdn'} type+ * @property {{path: string, version: string, written: boolean, reason: 'exists' | null}} data+ */+/*** Options for `template()`.* @typedef {object} TemplateOptions* @property {boolean} [list]* @property {boolean} [skeleton]* @property {boolean} [show]+ * @property {boolean | string} [cdn] Write the no-build-step CDN starter page instead of resolving a template. A string is used as the destination path.* @property {'page' | 'block'} [type] Filter templates by kind: 'page' or 'block'. Only applies to list views.* @property {string} [package] Narrow to templates from a specific package (id-only lookups across packages are ambiguous).* @property {string} [targetPath]diff --git a/packages/cli/assets/cdn.template.html b/packages/cli/assets/cdn.template.htmlnew file mode 100644index 0000000000..e3d0e252c3--- /dev/null+++ b/packages/cli/assets/cdn.template.html@@ -0,0 +1,124 @@+<!-- Copyright (c) Meta Platforms, Inc. and affiliates. -->+<!doctype html>+<!--+ Astryx from a CDN — no build step, no bundler, no install.++ Open this file in a browser (double-click works) or serve it from anywhere.+ Everything is pinned to the Astryx version you had installed when this was+ written; nothing here resolves to "latest", because an unpinned CDN URL+ silently changes under you.++ React 19 removed its UMD builds, so there is no global-script path any more:+ an import map plus `type="module"` is how you load Astryx without a bundler.++ Two things worth doing next:+ - `astryx theme template` writes an annotated theme you can point this page+ at. Its `color` scale generates a whole ramp from one seed colour and+ guarantees >= 4.5:1 for the text it generates against its surface.+ - `astryx component <Name>` prints any component's real prop surface.+-->+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <!--+ The theme names a font family; it never loads one. Without this link the+ whole page silently falls back to the next family in the stack, which is+ not the design you chose. `neutral` asks for Figtree — swap this for+ whatever your theme names, or self-host with @font-face.+ -->+ <link rel="preconnect" href="https://fonts.googleapis.com" />+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />+ <link+ rel="stylesheet"+ href="https://fonts.googleapis.com/css2?family=Figtree:wght@400;500;600;700&display=swap" />+ <!-- reset.css and astryx.css are the component styles; theme.css is the+ theme. Note /dist/theme.css — the package root has no theme.css. -->+ <link+ rel="stylesheet"+ href="https://cdn.jsdelivr.net/npm/@astryxdesign/core@__ASTRYX_VERSION__/src/reset.css" />+ <link+ rel="stylesheet"+ href="https://cdn.jsdelivr.net/npm/@astryxdesign/core@__ASTRYX_VERSION__/dist/astryx.css" />+ <link+ rel="stylesheet"+ href="https://cdn.jsdelivr.net/npm/@astryxdesign/theme-neutral@__ASTRYX_VERSION__/dist/theme.css" />+ <!--+ react/jsx-runtime is not decoration: the published bundle imports it, and+ leaving it out fails the page with "Failed to resolve module specifier".++ ?external=react,react-dom makes esm.sh reuse the React above instead of+ bundling its own. Two React copies means every hook throws+ "Cannot read properties of null (reading 'useState')".++ htm is optional — delete it and the `h` binding below if you would rather+ call createElement directly. It costs ~1KB and buys JSX-shaped markup,+ which is worth it as soon as the tree is more than a few levels deep.+ -->+ <script type="importmap">+ {+ "imports": {+ "react": "https://esm.sh/[email protected]",+ "react/jsx-runtime": "https://esm.sh/[email protected]/jsx-runtime",+ "react-dom": "https://esm.sh/[email protected]",+ "react-dom/client": "https://esm.sh/[email protected]/client",+ "htm": "https://esm.sh/[email protected]",+ "@astryxdesign/core": "https://esm.sh/@astryxdesign/core@__ASTRYX_VERSION__?external=react,react-dom",+ "@astryxdesign/theme-neutral": "https://esm.sh/@astryxdesign/theme-neutral@__ASTRYX_VERSION__?external=react,react-dom"+ }+ }+ </script>+ <!-- Nothing in the stylesheets sets a document font: the theme styles+ prose elements and each component styles itself, and Button is+ `font: inherit` by design. Without this line its label falls back to+ the browser default (Times). -->+ <style>+ body {+ font-family: var(--font-family-body);+ }+ /* Modules load over the network, so the page is empty for a moment.+ Say so, rather than showing a blank screen that reads as broken. */+ #root:empty::after {+ content: 'Loading…';+ display: block;+ padding: 2rem;+ color: var(--color-text-secondary);+ }+ </style>+ </head>+ <body>+ <div id="root"></div>+ <script type="module">+ import * as React from 'react';+ import {createRoot} from 'react-dom/client';+ import htm from 'htm';+ import {Theme, Card, Stack, Heading, Text, Button} from '@astryxdesign/core';+ import {neutralTheme} from '@astryxdesign/theme-neutral';++ // Nothing is compiling this file, so there is no JSX. htm gives the same+ // shape from a tagged template; `React.createElement` directly is the+ // dependency-free alternative.+ const h = htm.bind(React.createElement);++ // Passing the theme OBJECT is what makes `mode` work: 'system' follows+ // the OS, and light/dark switch at runtime. The `data-astryx-theme`+ // attribute alone only scopes the stylesheet — it cannot switch modes.+ createRoot(document.getElementById('root')).render(h`+ <${Theme} theme=${neutralTheme} mode="system">+ <${Stack} padding=${6} align="start">+ <${Card} maxWidth=${480} elevation="low">+ <${Stack} gap=${3} align="start">+ <${Heading} level=${1}>Hello from a CDN</${Heading}>+ <${Text}>No bundler, no install, no build step.</${Text}>+ <!-- Button's text comes from \`label\`, which is required — it is+ the accessible name. Children are optional and only change+ the visible text; the accessible name stays \`label\`. -->+ <${Button} variant="primary" label="Try me" />+ </${Stack}>+ </${Card}>+ </${Stack}>+ </${Theme}>+ `);+ </script>+ </body>+</html>diff --git a/packages/cli/clients/cli/commands/template-cdn.behavior.test.mjs b/packages/cli/clients/cli/commands/template-cdn.behavior.test.mjsnew file mode 100644index 0000000000..8dde9b6204--- /dev/null+++ b/packages/cli/clients/cli/commands/template-cdn.behavior.test.mjs@@ -0,0 +1,113 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file CLI behavior for `astryx template --cdn`.+ *+ * The API leaf is covered by api/template/cdn/cdn.test.mjs; what is only+ * reachable here is the terminal binding — that the flag short-circuits the+ * family's name resolution, which message the user sees, and the JSON envelope.+ * A receipt read at the wrong depth (`result.written` instead of+ * `result.data.written`) writes the file and then reports a skip, and no unit+ * test of the leaf can see it.+ */++import {describe, it, expect, beforeEach, afterEach} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import * as os from 'node:os';+import {runCli} from '../../../test-utils/run-cli.mjs';++let tmpDir;+beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-cli-template-cdn-'));+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'tmp', private: true}),+ );+});+afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++const read = f => fs.readFileSync(path.join(tmpDir, f), 'utf-8');++describe('astryx template --cdn', () => {+ it('writes the page and says it wrote it', async () => {+ const {status, stdout} = await runCli(['template', '--cdn'], {cwd: tmpDir});++ expect(status).toBe(0);+ expect(stdout).toMatch(/Wrote cdn\.template\.html/);+ expect(stdout).not.toMatch(/already exists/);+ expect(read('cdn.template.html')).toMatch(/<script type="importmap">/);+ });++ it('leaves an existing file alone, and says that instead', async () => {+ fs.writeFileSync(path.join(tmpDir, 'cdn.template.html'), '<!-- mine -->\n');++ const {status, stdout} = await runCli(['template', '--cdn'], {cwd: tmpDir});++ expect(status).toBe(0);+ expect(stdout).toMatch(/already exists/);+ expect(read('cdn.template.html')).toBe('<!-- mine -->\n');+ });++ it('replaces it with --overwrite', async () => {+ fs.writeFileSync(path.join(tmpDir, 'cdn.template.html'), '<!-- mine -->\n');++ const {status} = await runCli(['template', '--cdn', '--overwrite'], {+ cwd: tmpDir,+ });++ expect(status).toBe(0);+ expect(read('cdn.template.html')).toMatch(/importmap/);+ });++ it('writes to the path given to the flag', async () => {+ const {status} = await runCli(['template', '--cdn', 'public/demo.html'], {+ cwd: tmpDir,+ });++ expect(status).toBe(0);+ expect(read(path.join('public', 'demo.html'))).toMatch(/importmap/);+ });++ it('returns a template.cdn envelope under --json', async () => {+ const {status, stdout} = await runCli(['--json', 'template', '--cdn'], {+ cwd: tmpDir,+ });++ expect(status).toBe(0);+ const payload = JSON.parse(stdout);+ expect(payload.type).toBe('template.cdn');+ expect(payload.data).toEqual({+ path: 'cdn.template.html',+ version: expect.stringMatching(/^\d+\.\d+\.\d+/),+ written: true,+ reason: null,+ });+ });++ it('refuses a path that escapes the project', async () => {+ const {status, stderr} = await runCli(+ ['template', '--cdn', '../escaped.html'],+ {cwd: tmpDir},+ );++ expect(status).toBe(1);+ expect(stderr).toMatch(/outside the project root/);+ expect(fs.existsSync(path.join(path.dirname(tmpDir), 'escaped.html'))).toBe(+ false,+ );+ });++ // The flag exists because the positional cannot: `template cdn` would resolve+ // `cdn` against everything discoverAll() finds, so a template with that id+ // would shadow the starter page. The flag answers before discovery runs.+ it('does not shadow, or get shadowed by, a discovered template id', async () => {+ const {status, stderr} = await runCli(['template', 'cdn'], {cwd: tmpDir});++ expect(status).toBe(1);+ expect(stderr).toMatch(/Unknown template "cdn"/);+ expect(fs.existsSync(path.join(tmpDir, 'cdn.template.html'))).toBe(false);+ });+});diff --git a/packages/cli/clients/cli/commands/template.doc.mjs b/packages/cli/clients/cli/commands/template.doc.mjsindex a6500a6b70..0aa7ac5b44 100644--- a/packages/cli/clients/cli/commands/template.doc.mjs+++ b/packages/cli/clients/cli/commands/template.doc.mjs@@ -18,7 +18,9 @@ export const doc = {description:'One entry point for the template family: with no name it lists the discovered ' +'templates; with a name it shows the source or a layout skeleton, or scaffolds it ' +- 'into the project at a target path. Narrow an ambiguous name with --type and/or --package.',+ 'into the project at a target path. Narrow an ambiguous name with --type and/or --package. ' ++ '--cdn writes the no-build-step CDN starter page, which ships as an asset rather than as ' ++ 'a discovered template.',fn: 'template',args: [{name: 'name', param: 'name', required: false},@@ -43,6 +45,12 @@ export const doc = {description:'Show layout skeleton with spatial annotations (padding, gap, nesting)',},+ {+ flag: '--cdn [path]',+ param: 'options.cdn',+ description:+ 'Write the no-build-step CDN starter page (default: cdn.template.html)',+ },{flag: '-f, --overwrite',param: 'options.overwrite',@@ -55,9 +63,11 @@ export const doc = {label: 'Scaffold into the app',cli: 'astryx template dashboard ./src/app',},+ {label: 'CDN starter page', cli: 'astryx template --cdn'},+ {label: 'CDN starter page, elsewhere', cli: 'astryx template --cdn public/demo.html'},],exitCodes: [- {code: 0, when: 'success'},+ {code: 0, when: 'success, including a CDN page left untouched because it already exists'},{code: 1,when: 'unknown or ambiguous template, no source, a path escape, or an existing target without --overwrite',diff --git a/packages/cli/clients/cli/commands/template.mjs b/packages/cli/clients/cli/commands/template.mjsindex e064b8e989..8687ec4280 100644--- a/packages/cli/clients/cli/commands/template.mjs+++ b/packages/cli/clients/cli/commands/template.mjs@@ -41,7 +41,8 @@ export {discoverTemplates, listTemplates} from '../../../api/template/template.m* import('../../../api/template/template.type.mjs').TemplateListResponse |* import('../../../api/template/template.type.mjs').TemplateShowResponse |* import('../../../api/template/template.type.mjs').TemplateSkeletonResponse |- * import('../../../api/template/template.type.mjs').TemplateCopyResponse+ * import('../../../api/template/template.type.mjs').TemplateCopyResponse |+ * import('../../../api/template/template.type.mjs').TemplateCdnResponse* )} TemplateResponse*/@@ -55,7 +56,7 @@ export function registerTemplate(program) {/*** @param {string | undefined} name* @param {string | undefined} targetPath- * @param {{list?: boolean, type?: string, package?: string, skeleton?: boolean, overwrite?: boolean}} options+ * @param {{list?: boolean, type?: string, package?: string, skeleton?: boolean, cdn?: boolean | string, overwrite?: boolean}} options*/async (name, targetPath, options) => {const json = program.opts().json || false;@@ -83,7 +84,8 @@ export function registerTemplate(program) {name &&targetPath &&!options.list &&- !options.skeleton+ !options.skeleton &&+ !options.cdn) {const collision = await detectTemplateCollision(name, targetPath);if (collision && !options.overwrite) {@@ -103,6 +105,7 @@ export function registerTemplate(program) {await templateApi(name, {list: options.list,skeleton: options.skeleton,+ cdn: options.cdn,type: /** @type {'page' | 'block' | undefined} */ (options.type),package: options.package,targetPath,@@ -147,6 +150,7 @@ export function registerTemplate(program) {`${run} template <id> --skeleton Layout reference`,`${run} template --list --type block List only blocks`,`${run} template --list --package <pkg> List from one package`,+ `${run} template --cdn CDN starter page, no build step`,].join('\n'),),);@@ -179,6 +183,23 @@ export function registerTemplate(program) {);break;}++ case 'template.cdn': {+ if (!result.data.written) {+ emit(+ text(`[skip] ${result.data.path} already exists — left as is.`),+ text('Pass --overwrite to replace it with a fresh copy.'),+ );+ break;+ }+ emit(+ text(`[ok] Wrote ${result.data.path}`),+ text(+ `Open it in a browser — no bundler, no install, no build step. Every CDN URL is pinned to ${result.data.version}, and the annotations mark the parts that are load-bearing.`,+ ),+ );+ break;+ }}},});diff --git a/packages/cli/clients/cli/lib/manifest.mjs b/packages/cli/clients/cli/lib/manifest.mjsindex 16e2c75c10..227214e147 100644--- a/packages/cli/clients/cli/lib/manifest.mjs+++ b/packages/cli/clients/cli/lib/manifest.mjs@@ -70,6 +70,7 @@ export const RESPONSE_TYPES = {'template.show','template.skeleton','template.copy',+ 'template.cdn',],hook: ['hook.list', 'hook.detail', 'hook.detail.params'],'theme build': ['theme.build', 'theme.build.check'],@@ -103,7 +104,7 @@ const EXAMPLES = {],build: ['astryx build', 'astryx build "analytics dashboard" --json'],swizzle: ['astryx swizzle XDSButton'],- template: ['astryx template --json', 'astryx template dashboard ./src/app'],+ template: ['astryx template --json', 'astryx template dashboard ./src/app', 'astryx template --cdn'],hook: ['astryx hook', 'astryx hook useFocusTrap --json'],'theme build': ['astryx theme build ./src/themes/ocean.ts --out ./dist/ocean.css',diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjsindex 15ffa670ef..d021f1862c 100644--- a/packages/cli/foundation/response/response-types.doc.mjs+++ b/packages/cli/foundation/response/response-types.doc.mjs@@ -150,6 +150,12 @@ export const doc = {'A scaffold receipt: template id, output directory, written file name, and file count.',},+ {+ value: 'template.cdn',+ description:+ 'A write receipt for the no-build-step CDN starter page: the path (relative to cwd), the Astryx version every CDN URL was pinned to, whether it was written, and the reason it was not — `exists` when a file was already there, which is a success.',+ },+// hook{value: 'hook.list',diff --git a/packages/cli/foundation/text/copyright-header.mjs b/packages/cli/foundation/text/copyright-header.mjsindex b1e10f5ee8..a22aa872a8 100644--- a/packages/cli/foundation/text/copyright-header.mjs+++ b/packages/cli/foundation/text/copyright-header.mjs@@ -6,9 +6,9 @@** Every file in this repo carries the Meta copyright header, and several* commands copy repo files out verbatim — `theme add` (bundled theme sources),- * `init --features theme` (the annotated theme template). A consumer's own- * source tree should not inherit our boilerplate, and their lint may well- * reject it.+ * `init --features theme` (the annotated theme template), `template --cdn` (the+ * CDN starter page). A consumer's own source tree should not inherit our+ * boilerplate, and their lint may well reject it.** SYNC: the same regex is applied by apps/docsite/src/lib/codeExamples.ts for* rendered code samples. That copy lives in a different package (the docsite@@ -23,6 +23,11 @@const META_COPYRIGHT_HEADER_RE =/^(\uFEFF?(?:#![^\r\n]*(?:\r?\n))?)\/\/ Copyright \(c\) Meta Platforms, Inc\. and affiliates\.\r?\n(?:\r?\n)*/;+/** The same header in HTML comment syntax, as scripts/add-copyright.sh writes+ * it into the .html assets we scaffold. */+const META_COPYRIGHT_HEADER_HTML_RE =+ /^(\uFEFF?)<!-- Copyright \(c\) Meta Platforms, Inc\. and affiliates\. -->\r?\n(?:\r?\n)*/;+/*** Remove the leading Meta copyright header, preserving any BOM/shebang before* it. Returns the source unchanged when the header is absent.@@ -31,5 +36,7 @@ const META_COPYRIGHT_HEADER_RE =* @returns {string}*/export function stripCopyrightHeader(source) {- return source.replace(META_COPYRIGHT_HEADER_RE, '$1');+ return source+ .replace(META_COPYRIGHT_HEADER_RE, '$1')+ .replace(META_COPYRIGHT_HEADER_HTML_RE, '$1');}diff --git a/packages/core/README.md b/packages/core/README.mdindex 9c56337ab6..2891bc6803 100644--- a/packages/core/README.md+++ b/packages/core/README.md@@ -252,67 +252,101 @@ Same CSS imports and providers as above. No build plugins needed; Astryx ships p### No build step (CDN)For prototypes, embeds, or pages without a bundler, load the components straight-from a public CDN. Two delivery options ship in the published package:+from a public CDN as ES modules. React 19 removed its UMD builds ("To load React+19 with a script tag, we recommend using an ESM-based CDN such as esm.sh"), so an+import map is the way in — there is no `window.React` left for a global bundle to+bind to.-**1. UMD global (`<script>` tag).** A single pre-bundled file exposes every export-on `window.Astryx`. React and ReactDOM are peer dependencies — load them yourself.-Pair it with the precompiled stylesheet.+The CLI writes this page for you, annotated and pinned to the version you have+installed:++```bash+npx astryx template --cdn # writes cdn.template.html+``````html<!doctype html>-<html data-astryx-theme="neutral">+<html lang="en" data-astryx-theme="neutral"><head>+ <meta charset="utf-8" />+ <link+ rel="stylesheet"+ href="https://fonts.googleapis.com/css2?family=Figtree:wght@400;500;600;700&display=swap" />+ <link+ rel="stylesheet"+ href="https://cdn.jsdelivr.net/npm/@astryxdesign/[email protected]/src/reset.css" /><linkrel="stylesheet"- href="https://cdn.jsdelivr.net/npm/@astryxdesign/core/src/reset.css" />+ href="https://cdn.jsdelivr.net/npm/@astryxdesign/[email protected]/dist/astryx.css" /><linkrel="stylesheet"- href="https://cdn.jsdelivr.net/npm/@astryxdesign/core/dist/astryx.css" />+ href="https://cdn.jsdelivr.net/npm/@astryxdesign/[email protected]/dist/theme.css" />+ <script type="importmap">+ {+ "imports": {+ "react": "https://esm.sh/[email protected]",+ "react/jsx-runtime": "https://esm.sh/[email protected]/jsx-runtime",+ "react-dom": "https://esm.sh/[email protected]",+ "react-dom/client": "https://esm.sh/[email protected]/client",+ "@astryxdesign/core": "https://esm.sh/@astryxdesign/[email protected]?external=react,react-dom"+ }+ }+ </script>+ <style>+ body {+ font-family: var(--font-family-body);+ }+ </style></head><body><div id="root"></div>- <script- crossorigin- src="https://unpkg.com/react@19/umd/react.production.min.js"></script>- <script- crossorigin- src="https://unpkg.com/react-dom@19/umd/react-dom.production.min.js"></script>- <script src="https://cdn.jsdelivr.net/npm/@astryxdesign/core/dist/astryx.umd.js"></script>- <script>- const {Button, Card} = window.Astryx;+ <script type="module">+ import * as React from 'react';+ import {createRoot} from 'react-dom/client';+ import {Card, Stack, Heading, Text, Button} from '@astryxdesign/core';const e = React.createElement;- ReactDOM.createRoot(document.getElementById('root')).render(- e(Card, null, e(Button, {variant: 'primary'}, 'Hello from a CDN')),+ createRoot(document.getElementById('root')).render(+ e(+ Stack,+ {padding: 6, align: 'start'},+ e(+ Card,+ {maxWidth: 480, elevation: 'low'},+ e(+ Stack,+ {gap: 3, align: 'start'},+ e(Heading, {level: 1}, 'Hello from a CDN'),+ e(Text, null, 'No bundler, no install, no build step.'),+ e(Button, {variant: 'primary', label: 'Try me'}),+ ),+ ),+ ),);</script></body></html>```-**2. ES modules (no UMD, no globals).** Use [esm.sh](https://esm.sh), which rewrites-bare imports to browser-resolvable URLs. An import map keeps a single React instance.--```html-<link- rel="stylesheet"- href="https://cdn.jsdelivr.net/npm/@astryxdesign/core/dist/astryx.css" />-<script type="importmap">- {- "imports": {- "react": "https://esm.sh/react@19",- "react-dom/client": "https://esm.sh/react-dom@19/client",- "@astryxdesign/core": "https://esm.sh/@astryxdesign/core?external=react,react-dom"- }- }-</script>-<script type="module">- import {createRoot} from 'react-dom/client';- import {Button} from '@astryxdesign/core';- // ...render as usual-</script>-```--> Pin a version in production (e.g. `@astryxdesign/[email protected]`) — unversioned CDN URLs-> resolve to the latest release and are cached aggressively. The raw ESM entry-> (`dist/index.js`) uses bare `react` imports and will **not** run from a plain-> `<script src>`; use the UMD global or esm.sh as shown above.+Six details carry the whole recipe:++- **`data-astryx-theme` on `<html>`.** Theme CSS is scoped to that attribute, so+ without it the page renders with the built-in defaults instead of the theme you+ just loaded.+- **`?external=react,react-dom`.** Without it esm.sh bundles its own React and+ every hook throws `Cannot read properties of null (reading 'useState')`.+- **`react/jsx-runtime` in the import map.** The published bundle imports it;+ omit the entry and the page dies with `Failed to resolve module specifier`.+- **A font on `body`.** Nothing in the three stylesheets sets a document font:+ the theme styles prose elements and each component styles itself, and `Button`+ is `font: inherit`. Without that one declaration its label renders in the+ browser's default serif.+- **The webfont itself.** The theme _names_ Figtree; it never loads it. Without+ the Google Fonts link every viewer silently gets the next family in the stack.+- **No JSX.** Nothing is compiling this file, so elements are created with+ `React.createElement`.++> Pin every version. Unversioned CDN URLs resolve to the latest release and are+> cached aggressively (0.4.1 above is a real pin; `astryx template --cdn` writes+> yours). The raw ESM entry (`dist/index.js`) uses bare `react` imports and will+> not run from a plain `<script src>` — the import map is what makes those+> specifiers resolvable.diff --git a/packages/core/package.json b/packages/core/package.jsonindex bc670b2a48..76e473459a 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -27,8 +27,6 @@"type": "module","main": "./dist/index.js","types": "./dist/index.d.ts",- "unpkg": "./dist/astryx.umd.js",- "jsdelivr": "./dist/astryx.umd.js","sideEffects": ["**/*.stylex.ts","**/*.stylex.js",@@ -49,7 +47,6 @@"types": "./src/astryx.css.d.ts","default": "./dist/astryx.css"},- "./astryx.umd.js": "./dist/astryx.umd.js","./tailwind-theme.css": {"types": "./src/tailwind-theme.css.d.ts","default": "./src/tailwind-theme.css"@@ -651,11 +648,10 @@"scripts": {"prepack": "pnpm build","postinstall": "node scripts/postinstall.mjs",- "build": "rimraf dist && pnpm build:i18n && pnpm build:esm && tsc --project tsconfig.build.json && pnpm build:css && pnpm build:umd && node ../../scripts/check-no-dev-jsx.mjs && node ../../scripts/check-fully-specified.mjs",+ "build": "rimraf dist && pnpm build:i18n && pnpm build:esm && tsc --project tsconfig.build.json && pnpm build:css && node ../../scripts/check-no-dev-jsx.mjs && node ../../scripts/check-fully-specified.mjs","build:i18n": "node scripts/build-pseudo-locale.mjs","build:esm": "babel src --out-dir dist --extensions .ts,.tsx --out-file-extension .js --ignore \"**/*.test.ts,**/*.test.tsx,**/__tests__/**,**/*.perf.test.*,**/*.doc.mjs,**/*.d.ts,**/*.css,**/*.css.d.ts\" --config-file ./babel.config.json","build:css": "node ../../scripts/build-css.mjs",- "build:umd": "node ../../scripts/build-umd.mjs","dev": "babel src --watch --out-dir dist --extensions .ts,.tsx --out-file-extension .js --ignore \"**/*.test.*,**/*.doc.mjs,**/*.d.ts,**/*.css*\" --config-file ./babel.config.json","test": "vitest run --root ../..","test:watch": "vitest --root ../..",diff --git a/scripts/build-umd.mjs b/scripts/build-umd.mjsdeleted file mode 100644index 5b81989647..0000000000--- a/scripts/build-umd.mjs+++ /dev/null@@ -1,126 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--/**- * @file build-umd.mjs- * Post-build script that bundles the compiled ESM (dist/index.js) into a single- * browser-global IIFE file for direct <script> / CDN usage.- *- * Usage: node scripts/build-umd.mjs (runs after build:esm + build:css)- *- * Output:- * packages/core/dist/astryx.umd.js global: window.Astryx- * packages/core/dist/astryx.umd.js.map- *- * react / react-dom are EXTERNAL, resolved to the browser globals React /- * ReactDOM (matching peerDependencies) — consumers load React via their own- * <script> tags. The StyleX runtime (@stylexjs/stylex) IS bundled in, since- * components call stylex.props() at runtime and CDN users should not need a- * second global.- *- * Drop-in usage (pair with the precompiled stylesheet):- * <link rel="stylesheet" href=".../@astryxdesign/core/dist/astryx.css" />- * <script crossorigin src="https://unpkg.com/react@19/umd/react.production.min.js"></script>- * <script crossorigin src="https://unpkg.com/react-dom@19/umd/react-dom.production.min.js"></script>- * <script src=".../@astryxdesign/core/dist/astryx.umd.js"></script>- * <script>const { Button } = window.Astryx; ...</script>- */--import {build} from 'esbuild';-import path from 'node:path';-import {fileURLToPath} from 'node:url';--const __dirname = path.dirname(fileURLToPath(import.meta.url));-const CORE = path.resolve(__dirname, '..', 'packages/core');-const ENTRY = path.resolve(CORE, 'dist/index.js');-const OUTFILE = path.resolve(CORE, 'dist/astryx.umd.js');--// React 19 public named exports that compiled component code may import.-// Anything not listed falls back to a property lookup on the global at runtime.-const REACT_NAMED = [- 'Children', 'Component', 'Fragment', 'Profiler', 'PureComponent',- 'StrictMode', 'Suspense', 'cloneElement', 'createContext', 'createElement',- 'createRef', 'forwardRef', 'isValidElement', 'lazy', 'memo', 'startTransition',- 'use', 'useActionState', 'useCallback', 'useContext', 'useDebugValue',- 'useDeferredValue', 'useEffect', 'useId', 'useImperativeHandle',- 'useInsertionEffect', 'useLayoutEffect', 'useMemo', 'useOptimistic',- 'useReducer', 'useRef', 'useState', 'useSyncExternalStore', 'useTransition',- 'version',-];--const REACT_DOM_NAMED = [- 'createPortal', 'flushSync', 'preconnect', 'prefetchDNS', 'preinit',- 'preinitModule', 'preload', 'preloadModule', 'requestFormReset', 'version',-];--function reactGlobalsPlugin() {- const filter = /^(react|react-dom|react-dom\/client|react\/jsx-runtime)$/;- return {- name: 'react-globals',- setup(b) {- b.onResolve({filter}, args => ({path: args.path, namespace: 'rg'}));- b.onLoad({filter: /.*/, namespace: 'rg'}, args => {- if (args.path === 'react') {- return {loader: 'js', contents: namedReexport('React', REACT_NAMED)};- }- if (args.path === 'react-dom') {- return {- loader: 'js',- contents:- namedReexport('ReactDOM', REACT_DOM_NAMED) +- `\nexport const render = R.render;\nexport const unmountComponentAtNode = R.unmountComponentAtNode;`,- };- }- if (args.path === 'react-dom/client') {- return {- loader: 'js',- contents: `const R = globalThis.ReactDOM;-export const createRoot = R.createRoot;-export const hydrateRoot = R.hydrateRoot;-export default R;`,- };- }- // react/jsx-runtime — map to React.jsx / jsxs / Fragment with a- // createElement fallback for React builds that omit the runtime helpers.- return {- loader: 'js',- contents: `const R = globalThis.React;-const _h = (type, props, key) => {- const p = props || {};- const {children, ...rest} = p;- if (key !== undefined) rest.key = key;- const kids = children === undefined ? [] : (Array.isArray(children) ? children : [children]);- return R.createElement(type, rest, ...kids);-};-export const jsx = R.jsx || _h;-export const jsxs = R.jsxs || _h;-export const Fragment = R.Fragment;-export default R;`,- };- });- },- };-}--function namedReexport(globalName, names) {- const lines = names.map(n => `export const ${n} = R.${n};`).join('\n');- return `const R = globalThis.${globalName};\n${lines}\nexport default R;`;-}--await build({- entryPoints: [ENTRY],- outfile: OUTFILE,- bundle: true,- format: 'iife',- globalName: 'Astryx',- platform: 'browser',- target: ['es2020'],- minify: true,- sourcemap: true,- legalComments: 'none',- banner: {- js: '/* @astryxdesign/core UMD bundle — requires global React & ReactDOM (see dist/astryx.umd.js header). */',- },- plugins: [reactGlobalsPlugin()],-});--console.log('Built dist/astryx.umd.js (global: Astryx)');diff --git a/scripts/sync-exports.js b/scripts/sync-exports.jsindex 61c382ebf5..64ef048a49 100644--- a/scripts/sync-exports.js+++ b/scripts/sync-exports.js@@ -58,7 +58,6 @@ const STATIC_EXPORTS = {types: './src/astryx.css.d.ts',default: './dist/astryx.css',},- './astryx.umd.js': './dist/astryx.umd.js','./tailwind-theme.css': {types: './src/tailwind-theme.css.d.ts',default: './src/tailwind-theme.css',