Skip to content

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

TypeScript

feat(cli): `xds layout` — token-compressed layout expressions (XLE/XLO) (#2800)

David Petersena21bfc3495ed
diff --git a/apps/docsite/.gitignore b/apps/docsite/.gitignore
index a22b86b707..bf7b05ab56 100644
--- a/apps/docsite/.gitignore
+++ b/apps/docsite/.gitignore
@@ -18,3 +18,4 @@ public/vendor/
src/themes/astryx.js
src/themes/astryx.css
src/themes/astryx.d.ts
+public/xle-tokenizer.mjs
diff --git a/apps/docsite/package.json b/apps/docsite/package.json
index e097336f49..678fddd38f 100644
--- a/apps/docsite/package.json
+++ b/apps/docsite/package.json
@@ -4,7 +4,7 @@
"private": true,
"scripts": {
"build:theme": "astryx theme build src/themes/astryxTheme.ts --out src/themes/astryx.css",
- "generate": "pnpm build:theme && node scripts/generate-data.mjs && node scripts/generate-scope.mjs && node scripts/generate-playground-types.mjs && node scripts/copy-vendor.mjs",
+ "generate": "pnpm build:theme && node scripts/generate-data.mjs && node scripts/generate-scope.mjs && node scripts/generate-xle-registry.mjs && node scripts/generate-xle-tokenizer.mjs && node scripts/generate-playground-types.mjs && node scripts/copy-vendor.mjs",
"dev": "pnpm generate && next dev",
"build": "pnpm generate && next build",
"start": "next start",
@@ -45,6 +45,7 @@
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"autoprefixer": "^10.4.0",
+ "gpt-tokenizer": "^2.0.0",
"typescript": "^6.0.3",
"vitest": "^3.2.1"
},
diff --git a/apps/docsite/scripts/copy-vendor.mjs b/apps/docsite/scripts/copy-vendor.mjs
index 87d67de242..45fed79392 100644
--- a/apps/docsite/scripts/copy-vendor.mjs
+++ b/apps/docsite/scripts/copy-vendor.mjs
@@ -20,22 +20,41 @@ const require = createRequire(import.meta.url);
const __dirname = dirname(fileURLToPath(import.meta.url));
const publicDir = join(__dirname, '..', 'public');
+/**
+ * Resolve a vendored dependency, returning null (with a warning) instead of
+ * throwing when it isn't installed. A partial/offline install shouldn't abort
+ * the whole `generate` chain — data generation already ran; only the
+ * playground editor/preview degrade until a full install provides these.
+ */
+function tryResolve(spec) {
+ try {
+ return require.resolve(spec);
+ } catch {
+ console.warn(`vendor: '${spec}' not installed — skipping (run a full install to enable it)`);
+ return null;
+ }
+}
+
// --- Monaco editor (min/vs) ---
-const monacoPkg = require.resolve('monaco-editor/package.json');
-const monacoVs = join(dirname(monacoPkg), 'min', 'vs');
+const monacoPkg = tryResolve('monaco-editor/package.json');
const monacoDest = join(publicDir, 'monaco', 'vs');
-if (existsSync(join(monacoDest, 'loader.js'))) {
+if (!monacoPkg) {
+ // skipped — warned above
+} else if (existsSync(join(monacoDest, 'loader.js'))) {
console.log('monaco: already present at public/monaco/vs — skipping');
} else {
+ const monacoVs = join(dirname(monacoPkg), 'min', 'vs');
mkdirSync(dirname(monacoDest), {recursive: true});
cpSync(monacoVs, monacoDest, {recursive: true});
console.log('monaco: copied min/vs -> public/monaco/vs');
}
// --- TypeScript (browser UMD) ---
-const tsLib = require.resolve('typescript/lib/typescript.js');
+const tsLib = tryResolve('typescript/lib/typescript.js');
const tsDest = join(publicDir, 'vendor', 'typescript.js');
-if (existsSync(tsDest) && statSync(tsDest).size === statSync(tsLib).size) {
+if (!tsLib) {
+ // skipped — warned above
+} else if (existsSync(tsDest) && statSync(tsDest).size === statSync(tsLib).size) {
console.log(
'typescript: already present at public/vendor/typescript.js — skipping',
);
diff --git a/apps/docsite/scripts/generate-xle-registry.mjs b/apps/docsite/scripts/generate-xle-registry.mjs
new file mode 100644
index 0000000000..849effe91d
--- /dev/null
+++ b/apps/docsite/scripts/generate-xle-registry.mjs
@@ -0,0 +1,55 @@
+#!/usr/bin/env node
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Generates apps/docsite/src/generated/xle-registry.json
+ *
+ * The XLE/XLO layout language validates against @astryxdesign/core .doc.mjs metadata,
+ * which the CLI reads from disk (Node-only). The browser playground can't do
+ * that, so we build the registry here at deploy time and ship it as plain
+ * JSON. Mirrors generate-scope.mjs; runs in the `pnpm generate` chain so new
+ * components/blocks are picked up automatically.
+ *
+ * Run: node scripts/generate-xle-registry.mjs
+ */
+
+import {writeFileSync, mkdirSync} from 'node:fs';
+import {dirname, resolve} from 'node:path';
+import {fileURLToPath} from 'node:url';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const ROOT = resolve(__dirname, '..');
+const REPO = resolve(ROOT, '../..');
+const OUT = resolve(ROOT, 'src/generated/xle-registry.json');
+
+const {buildRegistry, serializeRegistry} = await import(
+ resolve(REPO, 'packages/cli/src/lib/xle/registry.mjs')
+);
+const {discoverTemplates} = await import(
+ resolve(REPO, 'packages/cli/src/api/template.mjs')
+);
+
+const registry = await buildRegistry({cwd: REPO});
+
+let blocks = [];
+try {
+ const all = await discoverTemplates(REPO);
+ blocks = all
+ .filter((t) => t.type === 'block')
+ .map((b) => ({dirName: b.dirName, description: b.description || '', category: b.category || ''}));
+} catch {
+ // blocks are optional — {hint} just won't resolve in the playground
+}
+
+const payload = {
+ generated: 'scripts/generate-xle-registry.mjs',
+ registry: serializeRegistry(registry),
+ blocks,
+};
+
+mkdirSync(dirname(OUT), {recursive: true});
+writeFileSync(OUT, JSON.stringify(payload));
+console.log(
+ `✓ xle-registry.json: ${payload.registry.components.length} components, ` +
+ `${payload.registry.aliases.length} aliases, ${blocks.length} blocks`,
+);
diff --git a/apps/docsite/scripts/generate-xle-tokenizer.mjs b/apps/docsite/scripts/generate-xle-tokenizer.mjs
new file mode 100644
index 0000000000..f783d2ce96
--- /dev/null
+++ b/apps/docsite/scripts/generate-xle-tokenizer.mjs
@@ -0,0 +1,58 @@
+#!/usr/bin/env node
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Generates apps/docsite/public/xle-tokenizer.mjs
+ *
+ * The XLE playground counts tokens CLIENT-SIDE. Rather than bundle
+ * gpt-tokenizer through webpack (which hard-fails the whole build if the
+ * package isn't installed), we esbuild-bundle its o200k_base encoding into a
+ * single self-contained ESM module here, served from public/ and loaded via a
+ * `webpackIgnore` dynamic import. If esbuild or gpt-tokenizer are unavailable,
+ * we emit a heuristic module with the same export shape — so the docsite
+ * always builds and the playground always has a counter.
+ *
+ * Mirrors the standalone playground's served tokenizer. Runs in `pnpm generate`.
+ */
+
+import {writeFileSync, mkdirSync} from 'node:fs';
+import {dirname, resolve} from 'node:path';
+import {fileURLToPath} from 'node:url';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const ROOT = resolve(__dirname, '..');
+const REPO = resolve(ROOT, '../..');
+const OUT = resolve(ROOT, 'public/xle-tokenizer.mjs');
+
+const HEURISTIC =
+ '// @generated fallback — gpt-tokenizer not bundled; using a heuristic.\n' +
+ "export const ENCODER = 'est.';\n" +
+ 'export const countTokens = s => (String(s).match(/\\w+|[^\\s\\w]/g) || []).length;\n';
+
+let out = HEURISTIC;
+try {
+ const esbuild = await import('esbuild');
+ const built = await esbuild.build({
+ stdin: {
+ contents:
+ "import {countTokens as c} from 'gpt-tokenizer/encoding/o200k_base';\n" +
+ "export const ENCODER = 'o200k_base';\n" +
+ 'export const countTokens = s => c(String(s));\n',
+ resolveDir: REPO,
+ loader: 'js',
+ },
+ bundle: true,
+ format: 'esm',
+ platform: 'browser',
+ write: false,
+ legalComments: 'none',
+ logLevel: 'silent',
+ });
+ out = built.outputFiles[0].text;
+ console.log(`✓ xle-tokenizer.mjs: gpt-tokenizer o200k_base (${(out.length / 1024 / 1024).toFixed(1)} MB bundled)`);
+} catch {
+ console.warn('xle-tokenizer.mjs: gpt-tokenizer/esbuild unavailable — wrote heuristic fallback');
+}
+
+mkdirSync(dirname(OUT), {recursive: true});
+writeFileSync(OUT, out);
diff --git a/apps/docsite/src/app/playground/PlaygroundClient.tsx b/apps/docsite/src/app/playground/PlaygroundClient.tsx
index 7dd21ea9e7..d60731a1c1 100644
--- a/apps/docsite/src/app/playground/PlaygroundClient.tsx
+++ b/apps/docsite/src/app/playground/PlaygroundClient.tsx
@@ -68,6 +68,7 @@ import {
Maximize2,
RotateCw,
Crosshair,
+ Wand2,
} from 'lucide-react';
import githubLight from './codeEditorThemes/github-light.json';
import githubDark from './codeEditorThemes/github-dark.json';
@@ -81,6 +82,7 @@ import {templates} from '../../generated/templateRegistry';
import {PreviewStage, type Viewport} from './PreviewStage';
import {ConfirmDialog} from './ConfirmDialog';
import {AstryxIcon} from '../../components/logos';
+import {XLEPanel} from './XLEPanel';
import {annotateInstanceIds} from './propertyEditor/componentInstances';
import {trackCopy} from '../../lib/analytics';
import {ThemeEditor} from './themeEditor/ThemeEditor';
@@ -132,7 +134,7 @@ function updateURL(code: string) {
window.history.replaceState(null, '', `#code=${compressed}`);
}
-type LeftView = 'code' | 'theme';
+type LeftView = 'code' | 'theme' | 'layout';
type MobileTopTab = 'preview' | 'code' | 'theme';
type BuildStatus = 'idle' | 'building' | 'finished' | 'error';
const MOBILE_BREAKPOINT_QUERY = '(max-width: 768px)';
@@ -762,6 +764,15 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
setMobileTab('theme');
}}
/>
+ <SideNavItem
+ label="Layout DSL"
+ icon={Wand2}
+ isSelected={activeView === 'layout'}
+ onClick={() => {
+ setActiveView('layout');
+ setMobileTab('code');
+ }}
+ />
</SideNavSection>
</SideNav>
);
@@ -837,6 +848,9 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
onThemeChange={postCustomTheme}
/>
</VStack>
+ <VStack xstyle={[s.pane, activeView !== 'layout' && s.hidden]}>
+ <XLEPanel onApplyCode={setCode} />
+ </VStack>
</VStack>
</VStack>
diff --git a/apps/docsite/src/app/playground/XLEPanel.tsx b/apps/docsite/src/app/playground/XLEPanel.tsx
new file mode 100644
index 0000000000..629f4020a4
--- /dev/null
+++ b/apps/docsite/src/app/playground/XLEPanel.tsx
@@ -0,0 +1,461 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Playground tab for XLE/XLO layout expressions.
+ *
+ * Type a compressed layout expression (compact XLE or indented outline XLO),
+ * see it live-validated against the @astryxdesign/core registry shipped as build-time
+ * JSON, watch the expanded TSX render inline with input/output token counts,
+ * browse a searchable example library, and "Expand to code" to push it into
+ * the shared editor/preview. The whole pipeline runs in-browser via the pure
+ * @astryxdesign/cli/xle barrel.
+ *
+ * @input user-typed expression + onApplyCode(tsx) from the playground
+ * @output validity/errors, token metrics, live expanded TSX, example browser
+ * @position playground left-panel tab (LeftView 'layout')
+ */
+
+'use client';
+
+import {useEffect, useMemo, useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {VStack, HStack} from '@astryxdesign/core/Stack';
+import {Text} from '@astryxdesign/core/Text';
+import {Heading} from '@astryxdesign/core/Heading';
+import {Button} from '@astryxdesign/core/Button';
+import {Badge} from '@astryxdesign/core/Badge';
+import {SegmentedControl, SegmentedControlItem} from '@astryxdesign/core/SegmentedControl';
+import {Banner} from '@astryxdesign/core/Banner';
+import {checkExpression, expandExpression} from '@astryxdesign/cli/xle';
+import xleData from '@/generated/xle-registry.json';
+import {XLE_EXAMPLES, XLE_CATEGORIES} from './xleExamples';
+
+type Surface = 'auto' | 'compact' | 'outline';
+
+/** Heuristic fallback used until the BPE tokenizer loads (or if it can't). */
+function heuristicTokens(src: string): number {
+ return (src.match(/\w+|[^\s\w]/g) || []).length;
+}
+
+/**
+ * Loads the build-time tokenizer module from /xle-tokenizer.mjs (esbuild-bundled
+ * gpt-tokenizer o200k_base, or a heuristic fallback — see
+ * scripts/generate-xle-tokenizer.mjs). Loaded client-side via a webpackIgnore
+ * runtime import so the docsite build never depends on gpt-tokenizer resolving
+ * through webpack. Falls back to the inline heuristic until it's ready.
+ */
+type TokenizerModule = {countTokens: (s: string) => number; ENCODER: string};
+// Variable specifier: keeps the path out of webpack's static graph (paired
+// with webpackIgnore) and out of TS module resolution — it's a runtime asset.
+const TOKENIZER_URL = '/xle-tokenizer.mjs';
+
+function useTokenCounter() {
+ const [bpe, setBpe] = useState<((s: string) => number) | null>(null);
+ const [encoder, setEncoder] = useState('est.');
+ useEffect(() => {
+ let alive = true;
+ (import(/* webpackIgnore: true */ TOKENIZER_URL) as Promise<TokenizerModule>)
+ .then(m => {
+ if (!alive) {
+ return;
+ }
+ setBpe(() => (s: string) => m.countTokens(s));
+ setEncoder(m.ENCODER || 'o200k_base');
+ })
+ .catch(() => {
+ /* keep heuristic */
+ });
+ return () => {
+ alive = false;
+ };
+ }, []);
+ return {count: bpe ?? heuristicTokens, encoder: bpe ? encoder : 'est.'};
+}
+
+const s = stylex.create({
+ panel: {
+ flex: 1,
+ minHeight: 0,
+ overflowY: 'auto',
+ padding: 'var(--spacing-3)',
+ gap: 'var(--spacing-3)',
+ display: 'flex',
+ flexDirection: 'column',
+ },
+ editor: {
+ width: '100%',
+ minHeight: 120,
+ resize: 'vertical',
+ fontFamily: 'var(--font-family-mono, ui-monospace, monospace)',
+ fontSize: 'var(--text-sm, 13px)',
+ lineHeight: 1.6,
+ padding: 'var(--spacing-3)',
+ borderRadius: 'var(--radius-inner)',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: 'var(--color-border)',
+ backgroundColor: 'var(--color-background-base)',
+ color: 'var(--color-content-primary)',
+ tabSize: 2,
+ },
+ metrics: {
+ display: 'flex',
+ gap: 'var(--spacing-2)',
+ flexWrap: 'wrap',
+ alignItems: 'stretch',
+ },
+ metric: {
+ flex: 1,
+ minWidth: 96,
+ padding: 'var(--spacing-2)',
+ borderRadius: 'var(--radius-inner)',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: 'var(--color-border)',
+ backgroundColor: 'var(--color-background-muted)',
+ },
+ metricValue: {fontVariantNumeric: 'tabular-nums'},
+ source: {
+ whiteSpace: 'pre',
+ fontFamily: 'var(--font-family-mono, ui-monospace, monospace)',
+ fontSize: 'var(--text-xsm, 12px)',
+ color: 'var(--color-content-primary)',
+ backgroundColor: 'var(--color-background-base)',
+ borderRadius: 'var(--radius-inner)',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: 'var(--color-border)',
+ padding: 'var(--spacing-3)',
+ margin: 0,
+ maxHeight: 360,
+ overflow: 'auto',
+ },
+ echo: {
+ whiteSpace: 'pre-wrap',
+ fontFamily: 'var(--font-family-mono, ui-monospace, monospace)',
+ fontSize: 'var(--text-xsm, 12px)',
+ color: 'var(--color-content-secondary)',
+ backgroundColor: 'var(--color-background-muted)',
+ borderRadius: 'var(--radius-inner)',
+ padding: 'var(--spacing-2)',
+ margin: 0,
+ overflowX: 'auto',
+ },
+ errorRow: {
+ fontFamily: 'var(--font-family-mono, ui-monospace, monospace)',
+ fontSize: 'var(--text-xsm, 12px)',
+ },
+ // Example browser
+ search: {
+ width: '100%',
+ padding: 'var(--spacing-2)',
+ borderRadius: 'var(--radius-inner)',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: 'var(--color-border)',
+ backgroundColor: 'var(--color-background-base)',
+ color: 'var(--color-content-primary)',
+ fontSize: 'var(--text-sm, 13px)',
+ },
+ browser: {
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: 'var(--color-border)',
+ borderRadius: 'var(--radius-inner)',
+ maxHeight: 320,
+ overflowY: 'auto',
+ },
+ catHeader: {
+ position: 'sticky',
+ top: 0,
+ backgroundColor: 'var(--color-background-muted)',
+ paddingBlock: 'var(--spacing-1)',
+ paddingInline: 'var(--spacing-2)',
+ fontSize: 'var(--text-2xs, 10px)',
+ textTransform: 'uppercase',
+ letterSpacing: '0.05em',
+ color: 'var(--color-content-secondary)',
+ borderBottomWidth: '1px',
+ borderBottomStyle: 'solid',
+ borderBottomColor: 'var(--color-border)',
+ },
+ row: {
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ gap: 'var(--spacing-2)',
+ width: '100%',
+ textAlign: 'start',
+ paddingBlock: 'var(--spacing-1)',
+ paddingInline: 'var(--spacing-2)',
+ border: 'none',
+ backgroundColor: {default: 'transparent', ':hover': 'var(--color-background-hover, var(--color-background-muted))'},
+ cursor: 'pointer',
+ color: 'var(--color-content-primary)',
+ borderBottomWidth: '1px',
+ borderBottomStyle: 'solid',
+ borderBottomColor: 'var(--color-border-subtle, var(--color-border))',
+ },
+ rowActive: {
+ backgroundColor: 'var(--color-background-active, var(--color-background-muted))',
+ },
+ rowLabel: {fontSize: 'var(--text-sm, 13px)', fontWeight: 600},
+ rowExpr: {
+ fontFamily: 'var(--font-family-mono, ui-monospace, monospace)',
+ fontSize: 'var(--text-2xs, 11px)',
+ color: 'var(--color-content-secondary)',
+ whiteSpace: 'nowrap',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ maxWidth: '100%',
+ },
+ rowTok: {
+ flexShrink: 0,
+ fontVariantNumeric: 'tabular-nums',
+ fontSize: 'var(--text-2xs, 11px)',
+ color: 'var(--color-content-secondary)',
+ },
+ min0: {minWidth: 0},
+});
+
+function Metric({label, value, sub}: {label: string; value: string; sub?: string}) {
+ return (
+ <div {...stylex.props(s.metric)}>
+ <Text type="supporting">{label}</Text>
+ <Text weight="semibold" xstyle={s.metricValue}>
+ {value}
+ </Text>
+ {sub && <Text type="supporting">{sub}</Text>}
+ </div>
+ );
+}
+
+export function XLEPanel({onApplyCode}: {onApplyCode: (code: string) => void}) {
+ const [expr, setExpr] = useState(XLE_EXAMPLES[0].expr);
+ // 'surface' is the displayed dialect; parsing is always auto-detected, so a
+ // compact expression never "fails" just because Outline is selected.
+ const [surface, setSurface] = useState<Surface>('auto');
+ const [query, setQuery] = useState('');
+ const [activeLabel, setActiveLabel] = useState(XLE_EXAMPLES[0].label);
+ const {count: countTokens, encoder} = useTokenCounter();
+
+ const check = useMemo(
+ () => checkExpression(expr, xleData.registry, {blocks: xleData.blocks, form: 'auto'}),
+ [expr],
+ );
+
+ const valid = check.ok && check.valid;
+
+ const expanded = useMemo(
+ () =>
+ valid
+ ? expandExpression(expr, xleData.registry, {
+ blocks: xleData.blocks,
+ form: 'auto',
+ name: 'PlaygroundLayout',
+ })
+ : null,
+ [expr, valid],
+ );
+
+ const inTokens = countTokens(expr);
+ const outCode = expanded?.ok ? expanded.code : '';
+ const outTokens = outCode ? countTokens(outCode) : 0;
+
+ const filtered = useMemo(() => {
+ const q = query.trim().toLowerCase();
+ if (!q) {
+ return XLE_EXAMPLES;
+ }
+ return XLE_EXAMPLES.filter(
+ e =>
+ e.label.toLowerCase().includes(q) ||
+ e.category.toLowerCase().includes(q) ||
+ e.expr.toLowerCase().includes(q),
+ );
+ }, [query]);
+
+ // Switching the dialect converts the current expression to that surface
+ // (using the canonical printers) rather than forcing a mismatched parse.
+ const switchSurface = (next: Surface) => {
+ setSurface(next);
+ if (next === 'auto') {
+ return;
+ }
+ const c = checkExpression(expr, xleData.registry, {blocks: xleData.blocks, form: 'auto'});
+ if (c.ok && c.valid) {
+ const converted = next === 'compact' ? c.compact : c.outline;
+ if (converted) {
+ setExpr(converted);
+ }
+ }
+ };
+
+ const pick = (label: string, exprText: string) => {
+ setActiveLabel(label);
+ setExpr(exprText);
+ setSurface('auto'); // examples carry their own surface; let auto-detect handle it
+ const r = expandExpression(exprText, xleData.registry, {
+ blocks: xleData.blocks,
+ form: 'auto',
+ name: 'PlaygroundLayout',
+ });
+ if (r.ok) {
+ onApplyCode(r.code);
+ }
+ };
+
+ return (
+ <div {...stylex.props(s.panel)}>
+ <VStack gap={1}>
+ <Heading level={4}>Layout expression (XLE / XLO)</Heading>
+ <Text type="supporting">
+ Write a compressed layout. Validated live against @astryxdesign/core; the
+ expanded TSX and token counts update below.
+ </Text>
+ </VStack>
+
+ <SegmentedControl
+ label="Surface"
+ size="sm"
+ value={surface}
+ onChange={v => v && switchSurface(v as Surface)}>
+ <SegmentedControlItem value="auto" label="Auto" />
+ <SegmentedControlItem value="compact" label="Compact (XLE)" />
+ <SegmentedControlItem value="outline" label="Outline (XLO)" />
+ </SegmentedControl>
+
+ <textarea
+ {...stylex.props(s.editor)}
+ value={expr}
+ spellCheck={false}
+ onChange={e => setExpr(e.target.value)}
+ aria-label="Layout expression"
+ />
+
+ <HStack gap={2} align="center">
+ <Button
+ variant="primary"
+ size="sm"
+ label="Expand to code → preview"
+ isDisabled={!valid}
+ onClick={() => expanded?.ok && onApplyCode(expanded.code)}
+ />
+ <Badge
+ variant={valid ? 'success' : 'error'}
+ label={
+ check.ok
+ ? valid
+ ? `Valid · ${check.form}`
+ : `${check.errors.length} error${check.errors.length === 1 ? '' : 's'}`
+ : 'Parse error'
+ }
+ />
+ {valid && check.warnings.length > 0 && (
+ <Badge variant="warning" label={`${check.warnings.length} warning`} />
+ )}
+ </HStack>
+
+ {/* Token economics (BPE via gpt-tokenizer o200k_base; 'est.' until loaded) */}
+ <div {...stylex.props(s.metrics)}>
+ <Metric label={`XLE input · ${encoder}`} value={`${inTokens} tok`} sub={`${expr.length} chars`} />
+ <Metric
+ label={`Output TSX · ${encoder}`}
+ value={`${outTokens} tok`}
+ sub={outCode ? `${outCode.length} chars` : '—'}
+ />
+ <Metric
+ label="Expansion"
+ value={inTokens > 0 && outTokens > 0 ? `${(outTokens / inTokens).toFixed(1)}×` : '—'}
+ sub="output ÷ input"
+ />
+ </div>
+
+ {!valid && check.errors.length > 0 && (
+ <VStack gap={1}>
+ {check.errors.map((e, i) => (
+ <Banner
+ key={i}
+ status="error"
+ title={
+ <span {...stylex.props(s.errorRow)}>
+ {e.formatted}
+ {e.suggestions && e.suggestions.length > 0
+ ? ` — did you mean: ${e.suggestions.join(', ')}?`
+ : ''}
+ </span>
+ }
+ />
+ ))}
+ </VStack>
+ )}
+
+ {valid && expanded?.ok && (
+ <VStack gap={1}>
+ <HStack gap={2} align="center">
+ <Text type="label">Rendered source (TSX)</Text>
+ {expanded.componentsUsed.length > 0 && (
+ <Text type="supporting">
+ {expanded.componentsUsed.length} components
+ {expanded.states ? ` · ${expanded.states} state hooks` : ''}
+ {expanded.todos.length ? ` · ${expanded.todos.length} TODO` : ''}
+ </Text>
+ )}
+ </HStack>
+ <pre {...stylex.props(s.source)}>{expanded.code}</pre>
+ </VStack>
+ )}
+
+ {valid && (
+ <VStack gap={1}>
+ <Text type="label">Canonical forms</Text>
+ <pre {...stylex.props(s.echo)}>{`compact:\n${check.compact}\n\noutline:\n${check.outline}`}</pre>
+ </VStack>
+ )}
+
+ {/* Example browser */}
+ <VStack gap={1}>
+ <HStack gap={2} align="center" justify="between">
+ <Text type="label">Examples</Text>
+ <Text type="supporting">
+ {filtered.length} of {XLE_EXAMPLES.length}
+ </Text>
+ </HStack>
+ <input
+ {...stylex.props(s.search)}
+ type="search"
+ placeholder="Search examples (label, category, or expression)…"
+ value={query}
+ onChange={e => setQuery(e.target.value)}
+ aria-label="Search examples"
+ />
+ <div {...stylex.props(s.browser)}>
+ {XLE_CATEGORIES.map(cat => {
+ const rows = filtered.filter(e => e.category === cat);
+ if (rows.length === 0) {
+ return null;
+ }
+ return (
+ <div key={cat}>
+ <div {...stylex.props(s.catHeader)}>{cat}</div>
+ {rows.map(ex => (
+ <button
+ key={ex.label}
+ type="button"
+ {...stylex.props(s.row, ex.label === activeLabel && s.rowActive)}
+ onClick={() => pick(ex.label, ex.expr)}>
+ <VStack gap={0} xstyle={s.min0}>
+ <span {...stylex.props(s.rowLabel)}>{ex.label}</span>
+ <span {...stylex.props(s.rowExpr)}>{ex.expr.replace(/\n/g, ' ⏎ ')}</span>
+ </VStack>
+ <span {...stylex.props(s.rowTok)}>{countTokens(ex.expr)} tok</span>
+ </button>
+ ))}
+ </div>
+ );
+ })}
+ </div>
+ </VStack>
+ </div>
+ );
+}
diff --git a/apps/docsite/src/app/playground/xleExamples.ts b/apps/docsite/src/app/playground/xleExamples.ts
new file mode 100644
index 0000000000..3a69f0013b
--- /dev/null
+++ b/apps/docsite/src/app/playground/xleExamples.ts
@@ -0,0 +1,95 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file XLE/XLO playground examples — every entry verified against the
+ * validator. @generated-ish: curated then machine-formatted; edit the
+ * source list in tooling rather than by hand.
+ */
+
+export type XLEExample = {category: string; label: string; expr: string};
+
+export const XLE_EXAMPLES: XLEExample[] = [
+ {category: "Pages", label: "Analytics dashboard", expr: "A[cp6 @topNav=TN @sideNav=SN] > L > LC > V[g6] > (H[j=between a=center] > Hd\"Analytics\"[level=2] + (H[g2] > B\"Export\" + B.primary\"New report\")) + (G[c4 g4] > (C[p6] > V[g1] > Tx.lg\"\\$42k\" + Tx[t=supporting]\"Revenue\")*4) + (G[c{min:340} g4] > C{card-callout} + C{card-callout}) + (C[p0] > T[striped] > (TR>THC\"Order\"+THC\"Customer\"+THC\"Status\"+THC\"Total\") + (TR>TC\"#10$\"+TC\"Acme Inc\"+(TC>Bd.success\"Paid\")+TC\"\\$120\")*5)"},
+ {category: "Pages", label: "Settings page", expr: "A[cp6 @topNav=TN @sideNav=SN] > L > LC > S[p6] > V[g6] > Hd\"Settings\"[level=2] + (C[p6] > V[g4] > Hd\"Profile\"[level=4] + (F > TI\"Name\"[req] + TI\"Email\"[t=email req]) + B.primary\"Save\") + (C[p6] > V[g4] > Hd\"Notifications\"[level=4] + (H[j=between a=center] > Tx\"Email alerts\" + SW\"Email alerts\") + (H[j=between a=center] > Tx\"Push\" + SW\"Push\"))"},
+ {category: "Pages", label: "Order detail", expr: "A[cp6 @topNav=TN] > L > LC > V[g6] > (H[j=between a=center] > (V[g1] > Hd\"Order #1042\"[level=2] + Tx[t=supporting]\"Created today\") + Bd.success\"Paid\") + (G[c{min:280} g6] > (C[p6] > V[g4] > Hd\"Items\"[level=4] + (T > (TR>THC\"Item\"+THC\"Qty\") + (TR>TC\"Widget\"+TC\"2\")*3)) + (C[p6] > V[g3] > Hd\"Customer\"[level=4] + (ML > MLI\"Name\":\"Acme\" + MLI\"Email\":\"[email protected]\" + MLI\"Plan\":\"Pro\")))"},
+ {category: "Pages", label: "Users table page", expr: "A[cp6 @topNav=TN @sideNav=SN] > L > LC > V[g4] > (Tbar\"Users\" > B\"Filter\" + B\"Export\" + B.primary\"Invite\") + (C[p0] > T[striped] > (TR>THC\"Name\"+THC\"Role\"+THC\"Status\") + (TR>TC\"Person $\"+TC\"Engineer\"+(TC>Bd.success\"Active\"))*8) + (H[j=end] > PG[variant=count])"},
+ {category: "Pages", label: "Pricing page", expr: "S[p8] > V[g8] > (Ctr > V[g2] > Hd\"Pricing\"[level=1] + Tx[t=supporting]\"Pick a plan that fits\") + (G[c3 g6] > (C[p6] > V[g4] > Hd\"Pro\"[level=3] + Tx.lg\"\\$29/mo\" + (UL > LI\"Feature one\" + LI\"Feature two\" + LI\"Feature three\") + B.primary\"Choose Pro\")*3)"},
+ {category: "Pages", label: "Login split", expr: "G[c2 h=\"100dvh\"] > (S[p8 v=muted] > Ctr > V[g2] > Hd\"Acme\"[level=1] + Tx[t=supporting]\"Welcome back\") + (Ctr > C[w=360 p8] > V[g6] > (F > TI\"Email\"[t=email req] + TI\"Password\"[t=password req]) + (H[j=between a=center] > CB\"Remember me\" + Lk[href=\"/forgot\"]\"Forgot?\") + B.primary\"Sign in\")"},
+ {category: "Pages", label: "Profile header", expr: "C[p6] > H[j=between a=center] > (H[g4 a=center] > Av + (V[g1] > Hd\"Jane Doe\"[level=3] + Tx[t=supporting]\"Product Designer\")) + (H[g2] > B\"Message\" + B.primary\"Follow\")"},
+ {category: "Pages", label: "Kanban board", expr: "G[c3 g4] > (C[p4] > V[g3] > (H[j=between a=center] > Hd\"To Do\"[level=5] + Bd\"3\") + (V[g2] > (C[p3] > Tx\"Task item\")*3))*3"},
+ {category: "Pages", label: "Dashboard with sidebar nav", expr: "A[cp0 @sideNav=(SN > (SNS\"Main\" > SNI\"Dashboard\" + SNI\"Reports\" + SNI\"Settings\"))] > L > LC > S[p6] > V[g6] > Hd\"Dashboard\"[level=2] + (G[c4 g4] > (C[p6] > V[g1] > Tx.lg\"128\" + Tx[t=supporting]\"Metric\")*4)"},
+ {category: "Pages", label: "Feed with composer", expr: "Ctr > C[w=560 p0] > V > (C[p4] > V[g3] > (H[g2 a=center] > Av + Tx\"Share an update\") + (H[j=end] > B.primary\"Post\")) + D + (V[g0] > (C[p4] > V[g2] > (H[g2 a=center] > Av + (V[g0.5] > Tx\"User $\" + Tx[t=supporting]\"2h ago\")) + Tx\"A post body goes here.\")*3)"},
+ {category: "Pages", label: "Two-column form", expr: "A[cp6 @topNav=TN] > L > LC > S[p6] > C[p6] > V[g4] > Hd\"New employee\"[level=3] + (G[c2 g4] > TI\"First name\"[req] + TI\"Last name\"[req] + TI\"Email\"[t=email req] + TI\"Phone\" + (RL\"Department\" > RLI\"Engineering\" + RLI\"Design\") + (CL\"Access\" > CLI\"Admin\" + CLI\"Billing\")) + (H[j=end g2] > B\"Cancel\" + B.primary\"Create\")"},
+ {category: "Pages", label: "Stats + chart + activity", expr: "V[g6] > (G[c3 g4] > (C[p6] > V[g1] > Tx.lg\"\\$12k\" + Tx[t=supporting]\"This week\")*3) + (G[c{min:320} g6] > C{card-callout} + (C[p6] > V[g3] > Hd\"Recent activity\"[level=4] + (UL > LI\"Event one\" + LI\"Event two\" + LI\"Event three\")))"},
+ {category: "Pages", label: "Confirm dialog flow", expr: "V[g4] > (Tbar\"Document\" > B\"Share\" + B.destructive\"Delete\"[opens=#del]) + (C[p6] > Tx\"Document body content\") ;; AD#del\"Delete this document?\""},
+ {category: "Pages", label: "Outline settings (XLO)", expr: "AppShell cp=6\n topNav: TN\n sideNav: SN\n Layout > LayoutContent\n Section p=6\n VStack g=6\n Heading \"Settings\" level=2\n Card p=6\n VStack g=4\n Heading \"Profile\" level=4\n FormLayout\n TextInput \"Name\" req\n TextInput \"Email\" t=email req\n Button.primary \"Save\"\n Card p=6\n VStack g=4\n Heading \"Danger zone\" level=4\n Button.destructive \"Delete account\" opens=#del\n\noverlays:\n AlertDialog#del \"Delete your account?\""},
+ {category: "Pages", label: "Outline product page (XLO)", expr: "Section p=8\n Grid c={min:320} g=8\n Card p=0\n Center h=240\n Text t=supporting \"Image\"\n VStack g=4\n Heading \"Product name\" level=1\n Text.lg \"\\$129\"\n Text t=supporting \"A short product description goes here.\"\n HStack g=2\n Button.primary \"Add to cart\"\n Button \"Save\""},
+ {category: "Layout", label: "Centered box", expr: "Ctr[h=\"100dvh\"] > C[w=400 p8] > Tx\"Hello world\""},
+ {category: "Layout", label: "App shell", expr: "A[cp6 @topNav=TN @sideNav=SN] > L > LC > S[p6] > Tx\"Page content\""},
+ {category: "Layout", label: "App shell + header", expr: "A[cp4 @topNav=TN] > L > LH\"Page header\" + LC > S[p4] > Tx\"Body\""},
+ {category: "Layout", label: "Vertical stack", expr: "V[g4] > Tx\"One\" + Tx\"Two\" + Tx\"Three\""},
+ {category: "Layout", label: "Spread row", expr: "H[j=between a=center] > Tx.lg\"Title\" + B.primary\"Action\""},
+ {category: "Layout", label: "Grid 4-up", expr: "G[c4 g4] > C[p6]*4"},
+ {category: "Layout", label: "Responsive grid", expr: "G[c{min:320} g4] > C{card-callout}*3"},
+ {category: "Layout", label: "Section muted", expr: "S[p6 v=muted] > Tx\"Muted section\""},
+ {category: "Layout", label: "Nested stacks", expr: "V[g6] > (H[j=between] > Tx.lg\"Header\" + B\"Edit\") + (G[c3 g4] > C[p4]*3)"},
+ {category: "Layout", label: "Layout regions", expr: "L > LH\"Header\" + LC > S[p4] > Tx\"Body\""},
+ {category: "Layout", label: "Divider between", expr: "V[g4] > Tx\"Above\" + D + Tx\"Below\""},
+ {category: "Layout", label: "Fill stack item", expr: "H[g4] > Tx\"Fixed\" + (SI[size=fill] > Tx\"Grows\")"},
+ {category: "Layout", label: "Toolbar + content", expr: "V[g4] > (Tbar\"Actions\" > B\"Filter\" + B.primary\"New\") + S[p4] > Tx\"Below toolbar\""},
+ {category: "Cards", label: "Titled card", expr: "C[p6] > V[g2] > Hd\"Card title\"[level=3] + Tx[t=supporting]\"Supporting copy\""},
+ {category: "Cards", label: "KPI tile", expr: "C[p6] > V[g1] > Tx.lg\"1,284\" + Tx[t=supporting]\"Active users\""},
+ {category: "Cards", label: "KPI grid", expr: "G[c4 g4] > (C[p6] > V[g1] > Tx.lg\"\\$42k\" + Tx[t=supporting]\"Revenue\")*4"},
+ {category: "Cards", label: "Clickable card", expr: "CC[p6] > H[j=between a=center] > Tx\"Open project\" + Ic[icon=arrow-right]"},
+ {category: "Cards", label: "Card grid", expr: "G[c3 g4] > (C[p6] > V[g2] > Hd\"A\"[level=4] + Tx\"text\")*3"},
+ {category: "Cards", label: "Callout block", expr: "S[p6] > C{card-callout}"},
+ {category: "Cards", label: "Badge row", expr: "H[g2] > Bd.success\"Active\" + Bd.warning\"Pending\" + Bd.error\"Failed\" + Bd.info\"New\""},
+ {category: "Cards", label: "Avatar row", expr: "H[g2 a=center] > Av + (V[g0.5] > Tx\"Jane Doe\" + Tx[t=supporting]\"Admin\")"},
+ {category: "Cards", label: "Metadata list", expr: "C[p6] > ML > MLI\"Status\":\"Active\" + MLI\"Owner\":\"Jane\" + MLI\"Region\":\"us-east\""},
+ {category: "Content", label: "List", expr: "UL > LI\"First item\" + LI\"Second item\" + LI\"Third item\""},
+ {category: "Content", label: "Kbd hint", expr: "H[g2 a=center] > Tx\"Press\" + K\"mod+k\" + Tx\"to search\""},
+ {category: "Content", label: "Headings scale", expr: "V[g3] > Hd\"H1\"[level=1] + Hd\"H2\"[level=2] + Hd\"H3\"[level=3]"},
+ {category: "Content", label: "Text + link", expr: "H[g1] > Tx\"Read\" + Lk[href=\"/docs\"]\"the docs\""},
+ {category: "Content", label: "Tokens", expr: "H[g2] > Tk\"react\" + Tk\"typescript\" + Tk\"stylex\""},
+ {category: "Tables", label: "Simple table", expr: "C[p0] > T[striped] > (TR > THC\"Name\" + THC\"Email\") + (TR > TC\"Alice\" + TC\"[email protected]\")*5"},
+ {category: "Tables", label: "Table + status cell", expr: "T > (TR > THC\"Service\" + THC\"Status\") + (TR > TC\"api-gateway\" + (TC > Bd.success\"Up\"))*4"},
+ {category: "Tables", label: "Dense table", expr: "T[density=compact dividers=rows] > (TR > THC\"ID\" + THC\"Value\") + (TR > TC\"row-$\" + TC\"\\$12.00\")*6"},
+ {category: "Tables", label: "Table in card", expr: "C[p0] > T[striped] > (TR>THC\"Item\"+THC\"Qty\") + (TR>TC\"Widget\"+TC\"3\")*3"},
+ {category: "Forms", label: "Login form", expr: "Ctr[h=\"100dvh\"] > C[w=400 p8] > V[g6] > (F > TI\"Email\"[t=email req] + TI\"Password\"[t=password req]) + B.primary\"Sign in\""},
+ {category: "Forms", label: "Field set", expr: "F > TI\"Full name\"[req] + TI\"Email\"[t=email req] + TA\"Bio\" + B.primary\"Save\""},
+ {category: "Forms", label: "Inline controls", expr: "H[j=between a=center] > CB\"Remember me\" + Lk[href=\"/forgot\"]\"Forgot password?\""},
+ {category: "Forms", label: "Number + switch", expr: "V[g4] > NI\"Quantity\" + (H[j=between a=center] > Tx\"Notifications\" + SW\"Enable notifications\")"},
+ {category: "Forms", label: "Two column form", expr: "G[c2 g4] > TI\"First name\"[req] + TI\"Last name\"[req] + TI\"Email\"[t=email req] + TI\"Phone\""},
+ {category: "Forms", label: "Checkbox list", expr: "CL\"Permissions\" > CLI\"Read\" + CLI\"Write\" + CLI\"Admin\""},
+ {category: "Forms", label: "Radio list", expr: "RL\"Plan\" > RLI\"Free\" + RLI\"Pro\" + RLI\"Enterprise\""},
+ {category: "Forms", label: "Slider", expr: "V[g4] > SL\"Volume\" + SL\"Brightness\""},
+ {category: "Forms", label: "Date input", expr: "F > DI\"Start date\" + DI\"End date\""},
+ {category: "Forms", label: "Search field", expr: "TI\"Search\"[t=text]"},
+ {category: "Nav", label: "Tabs", expr: "TL > Tab\"Overview\"! + Tab\"Activity\" + Tab\"Settings\""},
+ {category: "Nav", label: "Breadcrumbs", expr: "BC > BCI\"Home\"[href=\"/\"] + BCI\"Projects\"[href=\"/projects\"] + BCI\"Detail\""},
+ {category: "Nav", label: "Segmented control", expr: "SG > SGI\"Day\" + SGI\"Week\" + SGI\"Month\""},
+ {category: "Nav", label: "Top nav", expr: "TN > TNH\"Acme\" + TNI\"Docs\" + TNI\"Pricing\""},
+ {category: "Nav", label: "Side nav", expr: "SN > (SNS\"Main\" > SNI\"Dashboard\" + SNI\"Reports\") + (SNS\"Settings\" > SNI\"Profile\")"},
+ {category: "Nav", label: "Pagination", expr: "PG[variant=count]"},
+ {category: "Nav", label: "Tabs + content", expr: "V[g4] > (TL > Tab\"All\"! + Tab\"Active\") + S[p4] > Tx\"Tab body\""},
+ {category: "Feedback", label: "Success banner", expr: "Bn.success\"Changes saved successfully\""},
+ {category: "Feedback", label: "Empty state", expr: "ES\"No results found\"[description=\"Try adjusting your filters\"]"},
+ {category: "Feedback", label: "Spinner", expr: "Ctr[h=200] > Sp"},
+ {category: "Feedback", label: "Progress bar", expr: "V[g4] > PB[value=60] + PB[value=90]"},
+ {category: "Feedback", label: "Skeletons", expr: "V[g2] > Sk*4"},
+ {category: "Feedback", label: "Delete dialog", expr: "V > B.destructive\"Delete\"[opens=#confirm] ;; AD#confirm\"Delete this item?\""},
+ {category: "Feedback", label: "Status dots", expr: "V[g2] > (H[g2 a=center] > SD.success + Tx\"Operational\") + (H[g2 a=center] > SD.error + Tx\"Outage\")"},
+ {category: "Feedback", label: "Toolbar actions", expr: "Tbar\"Actions\" > B\"Filter\" + B\"Export\" + B.primary\"New\""},
+ {category: "Blocks", label: "Splice block", expr: "S[p6] > C{card-callout}"},
+ {category: "Blocks", label: "Block grid", expr: "G[c2 g4] > {card-callout}*2"},
+ {category: "Blocks", label: "Standalone block", expr: "{card-callout}"},
+ {category: "Outline", label: "Outline app shell", expr: "AppShell cp=6\n topNav: TN\n Layout > LayoutContent\n Section p=6\n Grid cols=4 gap=4\n Card p=6 x4"},
+ {category: "Outline", label: "Outline form", expr: "Center h=\"100dvh\"\n Card w=400 p=8\n VStack g=6\n FormLayout\n TextInput \"Email\" t=email req\n TextInput \"Password\" t=password req\n Button.primary \"Sign in\""},
+ {category: "Outline", label: "Outline dashboard", expr: "Section p=6\n VStack g=6\n HStack j=between a=center\n Heading \"Dashboard\" level=2\n Button.primary \"New\"\n Grid c=4 g=4\n Card {card-callout} x4"},
+ {category: "Outline", label: "Outline table", expr: "Card p=0\n Table striped\n TableRow\n TableHeaderCell \"Name\"\n TableHeaderCell \"Role\"\n repeat 4:\n TableRow\n TableCell \"Person\"\n TableCell \"Engineer\""},
+ {category: "Outline", label: "Outline with overlay", expr: "VStack g=4\n Button.destructive \"Delete\" opens=#confirm\n\noverlays:\n AlertDialog#confirm \"Delete this item?\""},
+ {category: "Outline", label: "Outline tabs", expr: "VStack g=4\n TabList\n Tab \"Overview\" !\n Tab \"Activity\"\n Tab \"Settings\"\n Section p=4\n Text \"Tab content\""},
+ {category: "Chat", label: "Chat layout", expr: "ChL > ChML > ChS\"Today\" + (ChM > ChB\"Hello there\") + (ChM > ChB\"Hi, how can I help?\")"},
+];
+
+export const XLE_CATEGORIES = [...new Set(XLE_EXAMPLES.map(e => e.category))];
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 14d7ffe745..4dccce8f37 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -42,6 +42,10 @@
"./config": {
"types": "./src/types/config.d.ts",
"import": "./src/config.mjs"
+ },
+ "./xle": {
+ "types": "./src/lib/xle/browser.d.ts",
+ "import": "./src/lib/xle/browser.mjs"
}
},
"files": [
@@ -66,7 +70,8 @@
"peerDependencies": {
"@astryxdesign/core": "*",
"@astryxdesign/lab": "*",
- "@astryxdesign/theme-neutral": "*"
+ "@astryxdesign/theme-neutral": "*",
+ "gpt-tokenizer": "^2.0.0"
},
"peerDependenciesMeta": {
"@astryxdesign/core": {
@@ -82,6 +87,7 @@
"devDependencies": {
"@astryxdesign/core": "*",
"@astryxdesign/lab": "*",
- "@astryxdesign/theme-neutral": "*"
+ "@astryxdesign/theme-neutral": "*",
+ "gpt-tokenizer": "^2.0.0"
}
}
diff --git a/packages/cli/playground/index.html b/packages/cli/playground/index.html
new file mode 100644
index 0000000000..1d1740dced
--- /dev/null
+++ b/packages/cli/playground/index.html
@@ -0,0 +1,286 @@
+<!doctype html>
+<!-- Copyright (c) Meta Platforms, Inc. and affiliates. -->
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<title>XLE / XLO playground</title>
+<style>
+ :root { color-scheme: light dark; --bg:#fff; --fg:#1c1e21; --muted:#65676b; --line:#dadde1; --panel:#f5f6f7; --ok:#1a7f37; --err:#cf222e; --warn:#9a6700; --accent:#0866ff; }
+ @media (prefers-color-scheme: dark) { :root { --bg:#18191a; --fg:#e4e6eb; --muted:#b0b3b8; --line:#3a3b3c; --panel:#242526; --accent:#4b9bff; } }
+ * { box-sizing: border-box; }
+ body { margin:0; font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif; background:var(--bg); color:var(--fg); }
+ header { padding:14px 20px; border-bottom:1px solid var(--line); display:flex; align-items:baseline; gap:12px; }
+ header h1 { font-size:16px; margin:0; }
+ header span { color:var(--muted); font-size:12px; }
+ main { display:grid; grid-template-columns:1fr 1fr; gap:0; height:calc(100vh - 53px); }
+ .col { display:flex; flex-direction:column; min-width:0; }
+ .col + .col { border-left:1px solid var(--line); }
+ .bar { padding:10px 16px; border-bottom:1px solid var(--line); display:flex; align-items:center; gap:10px; flex-wrap:wrap; }
+ .bar label { font-size:12px; color:var(--muted); }
+ select, button { font:inherit; padding:4px 10px; border-radius:6px; border:1px solid var(--line); background:var(--panel); color:var(--fg); cursor:pointer; }
+ button.primary { background:var(--accent); color:#fff; border-color:transparent; }
+ button:disabled { opacity:.5; cursor:not-allowed; }
+ textarea { flex:0 0 200px; resize:vertical; border:0; border-bottom:1px solid var(--line); padding:14px 16px; font:13px/1.6 ui-monospace,SFMono-Regular,Menlo,monospace; background:var(--bg); color:var(--fg); outline:none; tab-size:2; }
+ .status { padding:8px 16px; font-size:12px; display:flex; gap:8px; align-items:center; border-bottom:1px solid var(--line); }
+ .pill { padding:2px 8px; border-radius:999px; font-weight:600; font-size:11px; }
+ .pill.ok { background:color-mix(in srgb,var(--ok) 18%,transparent); color:var(--ok); }
+ .pill.err { background:color-mix(in srgb,var(--err) 18%,transparent); color:var(--err); }
+ .pill.warn { background:color-mix(in srgb,var(--warn) 20%,transparent); color:var(--warn); }
+ .scroll { flex:1; overflow:auto; }
+ pre { margin:0; padding:14px 16px; font:12px/1.55 ui-monospace,SFMono-Regular,Menlo,monospace; white-space:pre; }
+ .err-list { padding:10px 16px; }
+ .err-row { color:var(--err); font:12px/1.5 ui-monospace,monospace; padding:4px 0; border-bottom:1px dashed var(--line); }
+ .err-row b { color:var(--accent); font-weight:600; }
+ .section-label { padding:8px 16px 2px; font-size:11px; text-transform:uppercase; letter-spacing:.04em; color:var(--muted); border-top:1px solid var(--line); }
+ .metrics { display:flex; gap:8px; padding:8px 16px; border-bottom:1px solid var(--line); }
+ .metric { flex:1; border:1px solid var(--line); border-radius:6px; padding:6px 8px; background:var(--panel); }
+ .metric .m-label { font-size:11px; color:var(--muted); }
+ .metric .m-val { font-size:15px; font-weight:600; font-variant-numeric:tabular-nums; }
+ .metric .m-sub { font-size:11px; color:var(--muted); }
+ .ex-head { display:flex; align-items:center; gap:8px; padding:8px 16px 4px; }
+ .ex-head .section-label { border:0; padding:0; flex-shrink:0; }
+ .search { flex:1; padding:4px 8px; border:1px solid var(--line); border-radius:6px; background:var(--bg); color:var(--fg); font:inherit; font-size:12px; }
+ .browser { margin:0 16px 10px; border:1px solid var(--line); border-radius:6px; max-height:260px; overflow-y:auto; }
+ .ex-cat { position:sticky; top:0; background:var(--panel); padding:3px 10px; font-size:10px; text-transform:uppercase; letter-spacing:.05em; color:var(--muted); border-bottom:1px solid var(--line); }
+ .ex-item { display:flex; justify-content:space-between; align-items:center; gap:8px; width:100%; text-align:left; border:0; border-bottom:1px solid var(--line); background:transparent; color:var(--fg); cursor:pointer; padding:5px 10px; }
+ .ex-item:hover { background:var(--panel); }
+ .ex-item.active { background:color-mix(in srgb,var(--accent) 14%,transparent); }
+ .ex-item .ex-label { font-size:12px; font-weight:600; }
+ .ex-item .ex-expr { font-family:ui-monospace,monospace; font-size:10px; color:var(--muted); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
+ .ex-item .ex-tok { flex-shrink:0; font-size:10px; color:var(--muted); font-variant-numeric:tabular-nums; }
+ .ex-col { min-width:0; display:flex; flex-direction:column; }
+</style>
+</head>
+<body>
+<header>
+ <h1>XLE / XLO playground</h1>
+ <span>compressed layout expressions → validated XDS TSX · standalone (no build)</span>
+</header>
+<main>
+ <div class="col">
+ <div class="bar">
+ <label for="surface">Surface</label>
+ <select id="surface">
+ <option value="auto">Auto</option>
+ <option value="compact">Compact (XLE)</option>
+ <option value="outline">Outline (XLO)</option>
+ </select>
+ <button id="expand" class="primary">Expand →</button>
+ </div>
+ <textarea id="src" spellcheck="false"></textarea>
+ <div class="status" id="status"><span class="pill warn">loading…</span></div>
+ <div class="metrics" id="metrics"></div>
+ <div class="err-list" id="errors"></div>
+ <div class="ex-head">
+ <span class="section-label">Examples</span>
+ <input id="search" class="search" type="search" placeholder="Search examples…" />
+ </div>
+ <div class="browser" id="examples"></div>
+ <div class="section-label">Canonical compact</div>
+ <div class="scroll"><pre id="compact"></pre></div>
+ <div class="section-label">Canonical outline</div>
+ <div class="scroll"><pre id="outline"></pre></div>
+ </div>
+ <div class="col">
+ <div class="bar"><label>Expanded TSX</label></div>
+ <div class="scroll"><pre id="code">Press “Expand →”.</pre></div>
+ </div>
+</main>
+
+<script type="module">
+import {checkExpression, expandExpression} from '/xle/browser.mjs';
+
+const EXAMPLES = [
+ ["Pages", "Analytics dashboard", "A[cp6 @topNav=TN @sideNav=SN] > L > LC > V[g6] > (H[j=between a=center] > Hd\"Analytics\"[level=2] + (H[g2] > B\"Export\" + B.primary\"New report\")) + (G[c4 g4] > (C[p6] > V[g1] > Tx.lg\"\\$42k\" + Tx[t=supporting]\"Revenue\")*4) + (G[c{min:340} g4] > C{card-callout} + C{card-callout}) + (C[p0] > T[striped] > (TR>THC\"Order\"+THC\"Customer\"+THC\"Status\"+THC\"Total\") + (TR>TC\"#10$\"+TC\"Acme Inc\"+(TC>Bd.success\"Paid\")+TC\"\\$120\")*5)"],
+ ["Pages", "Settings page", "A[cp6 @topNav=TN @sideNav=SN] > L > LC > S[p6] > V[g6] > Hd\"Settings\"[level=2] + (C[p6] > V[g4] > Hd\"Profile\"[level=4] + (F > TI\"Name\"[req] + TI\"Email\"[t=email req]) + B.primary\"Save\") + (C[p6] > V[g4] > Hd\"Notifications\"[level=4] + (H[j=between a=center] > Tx\"Email alerts\" + SW\"Email alerts\") + (H[j=between a=center] > Tx\"Push\" + SW\"Push\"))"],
+ ["Pages", "Order detail", "A[cp6 @topNav=TN] > L > LC > V[g6] > (H[j=between a=center] > (V[g1] > Hd\"Order #1042\"[level=2] + Tx[t=supporting]\"Created today\") + Bd.success\"Paid\") + (G[c{min:280} g6] > (C[p6] > V[g4] > Hd\"Items\"[level=4] + (T > (TR>THC\"Item\"+THC\"Qty\") + (TR>TC\"Widget\"+TC\"2\")*3)) + (C[p6] > V[g3] > Hd\"Customer\"[level=4] + (ML > MLI\"Name\":\"Acme\" + MLI\"Email\":\"[email protected]\" + MLI\"Plan\":\"Pro\")))"],
+ ["Pages", "Users table page", "A[cp6 @topNav=TN @sideNav=SN] > L > LC > V[g4] > (Tbar\"Users\" > B\"Filter\" + B\"Export\" + B.primary\"Invite\") + (C[p0] > T[striped] > (TR>THC\"Name\"+THC\"Role\"+THC\"Status\") + (TR>TC\"Person $\"+TC\"Engineer\"+(TC>Bd.success\"Active\"))*8) + (H[j=end] > PG[variant=count])"],
+ ["Pages", "Pricing page", "S[p8] > V[g8] > (Ctr > V[g2] > Hd\"Pricing\"[level=1] + Tx[t=supporting]\"Pick a plan that fits\") + (G[c3 g6] > (C[p6] > V[g4] > Hd\"Pro\"[level=3] + Tx.lg\"\\$29/mo\" + (UL > LI\"Feature one\" + LI\"Feature two\" + LI\"Feature three\") + B.primary\"Choose Pro\")*3)"],
+ ["Pages", "Login split", "G[c2 h=\"100dvh\"] > (S[p8 v=muted] > Ctr > V[g2] > Hd\"Acme\"[level=1] + Tx[t=supporting]\"Welcome back\") + (Ctr > C[w=360 p8] > V[g6] > (F > TI\"Email\"[t=email req] + TI\"Password\"[t=password req]) + (H[j=between a=center] > CB\"Remember me\" + Lk[href=\"/forgot\"]\"Forgot?\") + B.primary\"Sign in\")"],
+ ["Pages", "Profile header", "C[p6] > H[j=between a=center] > (H[g4 a=center] > Av + (V[g1] > Hd\"Jane Doe\"[level=3] + Tx[t=supporting]\"Product Designer\")) + (H[g2] > B\"Message\" + B.primary\"Follow\")"],
+ ["Pages", "Kanban board", "G[c3 g4] > (C[p4] > V[g3] > (H[j=between a=center] > Hd\"To Do\"[level=5] + Bd\"3\") + (V[g2] > (C[p3] > Tx\"Task item\")*3))*3"],
+ ["Pages", "Dashboard with sidebar nav", "A[cp0 @sideNav=(SN > (SNS\"Main\" > SNI\"Dashboard\" + SNI\"Reports\" + SNI\"Settings\"))] > L > LC > S[p6] > V[g6] > Hd\"Dashboard\"[level=2] + (G[c4 g4] > (C[p6] > V[g1] > Tx.lg\"128\" + Tx[t=supporting]\"Metric\")*4)"],
+ ["Pages", "Feed with composer", "Ctr > C[w=560 p0] > V > (C[p4] > V[g3] > (H[g2 a=center] > Av + Tx\"Share an update\") + (H[j=end] > B.primary\"Post\")) + D + (V[g0] > (C[p4] > V[g2] > (H[g2 a=center] > Av + (V[g0.5] > Tx\"User $\" + Tx[t=supporting]\"2h ago\")) + Tx\"A post body goes here.\")*3)"],
+ ["Pages", "Two-column form", "A[cp6 @topNav=TN] > L > LC > S[p6] > C[p6] > V[g4] > Hd\"New employee\"[level=3] + (G[c2 g4] > TI\"First name\"[req] + TI\"Last name\"[req] + TI\"Email\"[t=email req] + TI\"Phone\" + (RL\"Department\" > RLI\"Engineering\" + RLI\"Design\") + (CL\"Access\" > CLI\"Admin\" + CLI\"Billing\")) + (H[j=end g2] > B\"Cancel\" + B.primary\"Create\")"],
+ ["Pages", "Stats + chart + activity", "V[g6] > (G[c3 g4] > (C[p6] > V[g1] > Tx.lg\"\\$12k\" + Tx[t=supporting]\"This week\")*3) + (G[c{min:320} g6] > C{card-callout} + (C[p6] > V[g3] > Hd\"Recent activity\"[level=4] + (UL > LI\"Event one\" + LI\"Event two\" + LI\"Event three\")))"],
+ ["Pages", "Confirm dialog flow", "V[g4] > (Tbar\"Document\" > B\"Share\" + B.destructive\"Delete\"[opens=#del]) + (C[p6] > Tx\"Document body content\") ;; AD#del\"Delete this document?\""],
+ ["Pages", "Outline settings (XLO)", "AppShell cp=6\n topNav: TN\n sideNav: SN\n Layout > LayoutContent\n Section p=6\n VStack g=6\n Heading \"Settings\" level=2\n Card p=6\n VStack g=4\n Heading \"Profile\" level=4\n FormLayout\n TextInput \"Name\" req\n TextInput \"Email\" t=email req\n Button.primary \"Save\"\n Card p=6\n VStack g=4\n Heading \"Danger zone\" level=4\n Button.destructive \"Delete account\" opens=#del\n\noverlays:\n AlertDialog#del \"Delete your account?\""],
+ ["Pages", "Outline product page (XLO)", "Section p=8\n Grid c={min:320} g=8\n Card p=0\n Center h=240\n Text t=supporting \"Image\"\n VStack g=4\n Heading \"Product name\" level=1\n Text.lg \"\\$129\"\n Text t=supporting \"A short product description goes here.\"\n HStack g=2\n Button.primary \"Add to cart\"\n Button \"Save\""],
+ ["Layout", "Centered box", "Ctr[h=\"100dvh\"] > C[w=400 p8] > Tx\"Hello world\""],
+ ["Layout", "App shell", "A[cp6 @topNav=TN @sideNav=SN] > L > LC > S[p6] > Tx\"Page content\""],
+ ["Layout", "App shell + header", "A[cp4 @topNav=TN] > L > LH\"Page header\" + LC > S[p4] > Tx\"Body\""],
+ ["Layout", "Vertical stack", "V[g4] > Tx\"One\" + Tx\"Two\" + Tx\"Three\""],
+ ["Layout", "Spread row", "H[j=between a=center] > Tx.lg\"Title\" + B.primary\"Action\""],
+ ["Layout", "Grid 4-up", "G[c4 g4] > C[p6]*4"],
+ ["Layout", "Responsive grid", "G[c{min:320} g4] > C{card-callout}*3"],
+ ["Layout", "Section muted", "S[p6 v=muted] > Tx\"Muted section\""],
+ ["Layout", "Nested stacks", "V[g6] > (H[j=between] > Tx.lg\"Header\" + B\"Edit\") + (G[c3 g4] > C[p4]*3)"],
+ ["Layout", "Layout regions", "L > LH\"Header\" + LC > S[p4] > Tx\"Body\""],
+ ["Layout", "Divider between", "V[g4] > Tx\"Above\" + D + Tx\"Below\""],
+ ["Layout", "Fill stack item", "H[g4] > Tx\"Fixed\" + (SI[size=fill] > Tx\"Grows\")"],
+ ["Layout", "Toolbar + content", "V[g4] > (Tbar\"Actions\" > B\"Filter\" + B.primary\"New\") + S[p4] > Tx\"Below toolbar\""],
+ ["Cards", "Titled card", "C[p6] > V[g2] > Hd\"Card title\"[level=3] + Tx[t=supporting]\"Supporting copy\""],
+ ["Cards", "KPI tile", "C[p6] > V[g1] > Tx.lg\"1,284\" + Tx[t=supporting]\"Active users\""],
+ ["Cards", "KPI grid", "G[c4 g4] > (C[p6] > V[g1] > Tx.lg\"\\$42k\" + Tx[t=supporting]\"Revenue\")*4"],
+ ["Cards", "Clickable card", "CC[p6] > H[j=between a=center] > Tx\"Open project\" + Ic[icon=arrow-right]"],
+ ["Cards", "Card grid", "G[c3 g4] > (C[p6] > V[g2] > Hd\"A\"[level=4] + Tx\"text\")*3"],
+ ["Cards", "Callout block", "S[p6] > C{card-callout}"],
+ ["Cards", "Badge row", "H[g2] > Bd.success\"Active\" + Bd.warning\"Pending\" + Bd.error\"Failed\" + Bd.info\"New\""],
+ ["Cards", "Avatar row", "H[g2 a=center] > Av + (V[g0.5] > Tx\"Jane Doe\" + Tx[t=supporting]\"Admin\")"],
+ ["Cards", "Metadata list", "C[p6] > ML > MLI\"Status\":\"Active\" + MLI\"Owner\":\"Jane\" + MLI\"Region\":\"us-east\""],
+ ["Content", "List", "UL > LI\"First item\" + LI\"Second item\" + LI\"Third item\""],
+ ["Content", "Kbd hint", "H[g2 a=center] > Tx\"Press\" + K\"mod+k\" + Tx\"to search\""],
+ ["Content", "Headings scale", "V[g3] > Hd\"H1\"[level=1] + Hd\"H2\"[level=2] + Hd\"H3\"[level=3]"],
+ ["Content", "Text + link", "H[g1] > Tx\"Read\" + Lk[href=\"/docs\"]\"the docs\""],
+ ["Content", "Tokens", "H[g2] > Tk\"react\" + Tk\"typescript\" + Tk\"stylex\""],
+ ["Tables", "Simple table", "C[p0] > T[striped] > (TR > THC\"Name\" + THC\"Email\") + (TR > TC\"Alice\" + TC\"[email protected]\")*5"],
+ ["Tables", "Table + status cell", "T > (TR > THC\"Service\" + THC\"Status\") + (TR > TC\"api-gateway\" + (TC > Bd.success\"Up\"))*4"],
+ ["Tables", "Dense table", "T[density=compact dividers=rows] > (TR > THC\"ID\" + THC\"Value\") + (TR > TC\"row-$\" + TC\"\\$12.00\")*6"],
+ ["Tables", "Table in card", "C[p0] > T[striped] > (TR>THC\"Item\"+THC\"Qty\") + (TR>TC\"Widget\"+TC\"3\")*3"],
+ ["Forms", "Login form", "Ctr[h=\"100dvh\"] > C[w=400 p8] > V[g6] > (F > TI\"Email\"[t=email req] + TI\"Password\"[t=password req]) + B.primary\"Sign in\""],
+ ["Forms", "Field set", "F > TI\"Full name\"[req] + TI\"Email\"[t=email req] + TA\"Bio\" + B.primary\"Save\""],
+ ["Forms", "Inline controls", "H[j=between a=center] > CB\"Remember me\" + Lk[href=\"/forgot\"]\"Forgot password?\""],
+ ["Forms", "Number + switch", "V[g4] > NI\"Quantity\" + (H[j=between a=center] > Tx\"Notifications\" + SW\"Enable notifications\")"],
+ ["Forms", "Two column form", "G[c2 g4] > TI\"First name\"[req] + TI\"Last name\"[req] + TI\"Email\"[t=email req] + TI\"Phone\""],
+ ["Forms", "Checkbox list", "CL\"Permissions\" > CLI\"Read\" + CLI\"Write\" + CLI\"Admin\""],
+ ["Forms", "Radio list", "RL\"Plan\" > RLI\"Free\" + RLI\"Pro\" + RLI\"Enterprise\""],
+ ["Forms", "Slider", "V[g4] > SL\"Volume\" + SL\"Brightness\""],
+ ["Forms", "Date input", "F > DI\"Start date\" + DI\"End date\""],
+ ["Forms", "Search field", "TI\"Search\"[t=text]"],
+ ["Nav", "Tabs", "TL > Tab\"Overview\"! + Tab\"Activity\" + Tab\"Settings\""],
+ ["Nav", "Breadcrumbs", "BC > BCI\"Home\"[href=\"/\"] + BCI\"Projects\"[href=\"/projects\"] + BCI\"Detail\""],
+ ["Nav", "Segmented control", "SG > SGI\"Day\" + SGI\"Week\" + SGI\"Month\""],
+ ["Nav", "Top nav", "TN > TNH\"Acme\" + TNI\"Docs\" + TNI\"Pricing\""],
+ ["Nav", "Side nav", "SN > (SNS\"Main\" > SNI\"Dashboard\" + SNI\"Reports\") + (SNS\"Settings\" > SNI\"Profile\")"],
+ ["Nav", "Pagination", "PG[variant=count]"],
+ ["Nav", "Tabs + content", "V[g4] > (TL > Tab\"All\"! + Tab\"Active\") + S[p4] > Tx\"Tab body\""],
+ ["Feedback", "Success banner", "Bn.success\"Changes saved successfully\""],
+ ["Feedback", "Empty state", "ES\"No results found\"[description=\"Try adjusting your filters\"]"],
+ ["Feedback", "Spinner", "Ctr[h=200] > Sp"],
+ ["Feedback", "Progress bar", "V[g4] > PB[value=60] + PB[value=90]"],
+ ["Feedback", "Skeletons", "V[g2] > Sk*4"],
+ ["Feedback", "Delete dialog", "V > B.destructive\"Delete\"[opens=#confirm] ;; AD#confirm\"Delete this item?\""],
+ ["Feedback", "Status dots", "V[g2] > (H[g2 a=center] > SD.success + Tx\"Operational\") + (H[g2 a=center] > SD.error + Tx\"Outage\")"],
+ ["Feedback", "Toolbar actions", "Tbar\"Actions\" > B\"Filter\" + B\"Export\" + B.primary\"New\""],
+ ["Blocks", "Splice block", "S[p6] > C{card-callout}"],
+ ["Blocks", "Block grid", "G[c2 g4] > {card-callout}*2"],
+ ["Blocks", "Standalone block", "{card-callout}"],
+ ["Outline", "Outline app shell", "AppShell cp=6\n topNav: TN\n Layout > LayoutContent\n Section p=6\n Grid cols=4 gap=4\n Card p=6 x4"],
+ ["Outline", "Outline form", "Center h=\"100dvh\"\n Card w=400 p=8\n VStack g=6\n FormLayout\n TextInput \"Email\" t=email req\n TextInput \"Password\" t=password req\n Button.primary \"Sign in\""],
+ ["Outline", "Outline dashboard", "Section p=6\n VStack g=6\n HStack j=between a=center\n Heading \"Dashboard\" level=2\n Button.primary \"New\"\n Grid c=4 g=4\n Card {card-callout} x4"],
+ ["Outline", "Outline table", "Card p=0\n Table striped\n TableRow\n TableHeaderCell \"Name\"\n TableHeaderCell \"Role\"\n repeat 4:\n TableRow\n TableCell \"Person\"\n TableCell \"Engineer\""],
+ ["Outline", "Outline with overlay", "VStack g=4\n Button.destructive \"Delete\" opens=#confirm\n\noverlays:\n AlertDialog#confirm \"Delete this item?\""],
+ ["Outline", "Outline tabs", "VStack g=4\n TabList\n Tab \"Overview\" !\n Tab \"Activity\"\n Tab \"Settings\"\n Section p=4\n Text \"Tab content\""],
+ ["Chat", "Chat layout", "ChL > ChML > ChS\"Today\" + (ChM > ChB\"Hello there\") + (ChM > ChB\"Hi, how can I help?\")"],
+];
+
+const $ = id => document.getElementById(id);
+const data = await fetch('/registry.json').then(r => r.json());
+const REG = data.registry, BLOCKS = data.blocks;
+
+const escapeHtml = s => String(s).replace(/[&<>]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;'}[c]));
+
+// Tokenization is fully client-side: import the bundled tokenizer module the
+// server emits (gpt-tokenizer o200k_base, esbuild-bundled; heuristic fallback).
+const {countTokens: tok, ENCODER} = await import('/vendor/tokenizer.mjs');
+
+function metricsHtml(inTok, inChars, outTok, outChars) {
+ const ratio = inTok > 0 && outTok > 0 ? (outTok / inTok).toFixed(1) + '×' : '—';
+ const cell = (label, val, sub) =>
+ `<div class="metric"><div class="m-label">${label}</div><div class="m-val">${val}</div><div class="m-sub">${sub}</div></div>`;
+ return cell('XLE input · ' + ENCODER, inTok + ' tok', inChars + ' chars') +
+ cell('Output TSX · ' + ENCODER, outTok ? outTok + ' tok' : '—', outChars ? outChars + ' chars' : '—') +
+ cell('Expansion', ratio, 'output ÷ input');
+}
+
+function paintMetrics(expr, code) {
+ $('metrics').innerHTML = metricsHtml(tok(expr), expr.length, code ? tok(code) : 0, code ? code.length : 0);
+}
+
+function render() {
+ const expr = $('src').value;
+ // Always auto-detect: a compact expression never "fails" under an Outline view.
+ const r = checkExpression(expr, REG, {blocks: BLOCKS, form: 'auto'});
+ const status = $('status'), errors = $('errors');
+ status.innerHTML = '';
+ errors.innerHTML = '';
+ if (r.ok && r.valid) {
+ status.innerHTML = `<span class="pill ok">Valid · ${r.form}</span>` +
+ (r.warnings.length ? `<span class="pill warn">${r.warnings.length} warning</span>` : '');
+ $('compact').textContent = r.compact;
+ $('outline').textContent = r.outline;
+ $('expand').disabled = false;
+ const code = doExpand(); // live "rendered source"
+ paintMetrics(expr, code);
+ } else {
+ status.innerHTML = `<span class="pill err">${r.errors.length} error${r.errors.length===1?'':'s'}</span>`;
+ errors.innerHTML = r.errors.map(e =>
+ `<div class="err-row">${escapeHtml(e.formatted)}${e.suggestions?.length ? ` <b>→ ${escapeHtml(e.suggestions.join(', '))}</b>` : ''}</div>`
+ ).join('');
+ $('compact').textContent = '';
+ $('outline').textContent = '';
+ $('code').textContent = '';
+ $('expand').disabled = true;
+ paintMetrics(expr, '');
+ }
+}
+
+function doExpand() {
+ const r = expandExpression($('src').value, REG, {blocks: BLOCKS, form: 'auto', name: 'PlaygroundLayout'});
+ const code = r.ok ? r.code : r.errors.map(e => e.formatted).join('\n');
+ $('code').textContent = code;
+ return r.ok ? code : '';
+}
+
+// Switching surface converts the current expression to that dialect.
+function switchSurface() {
+ const v = $('surface').value;
+ if (v !== 'auto') {
+ const c = checkExpression($('src').value, REG, {blocks: BLOCKS, form: 'auto'});
+ if (c.ok && c.valid) $('src').value = v === 'compact' ? c.compact : c.outline;
+ }
+ render();
+}
+
+// Searchable, categorized example browser.
+let activeLabel = EXAMPLES[0][1];
+function renderBrowser(query) {
+ const q = (query || '').trim().toLowerCase();
+ const match = ([cat, label, expr]) =>
+ !q || label.toLowerCase().includes(q) || cat.toLowerCase().includes(q) || expr.toLowerCase().includes(q);
+ const cats = [...new Set(EXAMPLES.map(e => e[0]))];
+ let html = '';
+ for (const cat of cats) {
+ const rows = EXAMPLES.map((e, i) => [e, i]).filter(([e]) => e[0] === cat && match(e));
+ if (!rows.length) continue;
+ html += `<div class="ex-cat">${escapeHtml(cat)}</div>`;
+ for (const [e, i] of rows) {
+ const active = e[1] === activeLabel ? ' active' : '';
+ html += `<button class="ex-item${active}" data-i="${i}"><span class="ex-col"><span class="ex-label">${escapeHtml(e[1])}</span><span class="ex-expr">${escapeHtml(e[2].replace(/\n/g, ' ⏎ '))}</span></span><span class="ex-tok">${tok(e[2])} tok</span></button>`;
+ }
+ }
+ $('examples').innerHTML = html || '<div class="ex-cat">No matches</div>';
+}
+
+$('examples').addEventListener('click', e => {
+ const btn = e.target.closest('.ex-item');
+ if (!btn) return;
+ const ex = EXAMPLES[btn.dataset.i];
+ activeLabel = ex[1];
+ $('src').value = ex[2];
+ $('surface').value = 'auto'; // examples carry their own surface
+ render();
+ renderBrowser($('search').value);
+});
+$('search').addEventListener('input', e => renderBrowser(e.target.value));
+$('src').addEventListener('input', render);
+$('surface').addEventListener('change', switchSurface);
+$('expand').addEventListener('click', doExpand);
+
+renderBrowser('');
+$('src').value = EXAMPLES[0][2];
+render();
+</script>
+</body>
+</html>
diff --git a/packages/cli/playground/serve.mjs b/packages/cli/playground/serve.mjs
new file mode 100644
index 0000000000..302b6a26a2
--- /dev/null
+++ b/packages/cli/playground/serve.mjs
@@ -0,0 +1,129 @@
+#!/usr/bin/env node
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Standalone, zero-dependency XLE/XLO playground.
+ *
+ * The docsite playground (apps/docsite) is the production home, but it needs
+ * the full Next/Monaco/StyleX toolchain. This is a dependency-free way to
+ * exercise the layout language in a browser — handy offline, in CI smoke
+ * checks, or for a quick demo. It serves the pure browser barrel as native
+ * ESM and builds the registry on the fly with the same code the CLI uses, so
+ * it never goes stale.
+ *
+ * node packages/cli/playground/serve.mjs [--port 4321]
+ *
+ * Routes:
+ * GET / the playground page
+ * GET /registry.json buildRegistry() + serializeRegistry() + blocks
+ * GET /xle/<file>.mjs the pure lib/xle modules + string-utils
+ *
+ * @position dev tool — no build step; imports lib/xle directly
+ */
+
+import {createServer} from 'node:http';
+import {readFileSync} from 'node:fs';
+import {join, dirname} from 'node:path';
+import {fileURLToPath} from 'node:url';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const CLI_SRC = join(__dirname, '..', 'src');
+const REPO = join(__dirname, '..', '..', '..');
+
+const portArg = process.argv.indexOf('--port');
+const PORT = portArg !== -1 ? Number(process.argv[portArg + 1]) : 4321;
+
+const {buildRegistry, serializeRegistry} = await import(join(CLI_SRC, 'lib/xle/registry.mjs'));
+const {discoverTemplates} = await import(join(CLI_SRC, 'api/template.mjs'));
+
+function send(res, status, type, body) {
+ res.writeHead(status, {'content-type': type, 'cache-control': 'no-store'});
+ res.end(body);
+}
+
+// Tokenization runs CLIENT-SIDE. The browser can't import gpt-tokenizer's
+// package graph directly, so we esbuild-bundle the o200k_base encoding into a
+// single self-contained ESM module the page imports. If esbuild or the
+// package isn't available, we serve a heuristic module so counting still
+// works offline — same module shape either way.
+const HEURISTIC_MODULE =
+ "export const ENCODER = 'est.';\n" +
+ "export const countTokens = s => (String(s).match(/\\w+|[^\\s\\w]/g) || []).length;\n";
+let tokenizerModule = null;
+async function getTokenizerModule() {
+ if (tokenizerModule != null) return tokenizerModule;
+ try {
+ const esbuild = await import('esbuild');
+ const out = await esbuild.build({
+ stdin: {
+ contents:
+ "import {countTokens as c} from 'gpt-tokenizer/encoding/o200k_base';\n" +
+ "export const ENCODER = 'o200k_base';\n" +
+ "export const countTokens = s => c(String(s));\n",
+ resolveDir: REPO,
+ loader: 'js',
+ },
+ bundle: true,
+ format: 'esm',
+ platform: 'browser',
+ write: false,
+ legalComments: 'none',
+ logLevel: 'silent',
+ });
+ tokenizerModule = out.outputFiles[0].text;
+ } catch {
+ tokenizerModule = HEURISTIC_MODULE;
+ }
+ return tokenizerModule;
+}
+
+const server = createServer(async (req, res) => {
+ try {
+ const url = new URL(req.url, `http://localhost:${PORT}`);
+ const path = url.pathname;
+
+ if (path === '/') {
+ return send(res, 200, 'text/html; charset=utf-8', readFileSync(join(__dirname, 'index.html')));
+ }
+
+ if (path === '/registry.json') {
+ const registry = await buildRegistry({cwd: REPO});
+ let blocks = [];
+ try {
+ const all = await discoverTemplates(REPO);
+ blocks = all.filter(t => t.type === 'block').map(b => ({dirName: b.dirName, description: b.description || ''}));
+ } catch {
+ /* blocks optional */
+ }
+ return send(res, 200, 'application/json', JSON.stringify({registry: serializeRegistry(registry), blocks}));
+ }
+
+ if (path === '/vendor/tokenizer.mjs') {
+ return send(res, 200, 'text/javascript; charset=utf-8', await getTokenizerModule());
+ }
+
+ if (path.startsWith('/xle/')) {
+ // Serve the pure language modules (+ levenshtein from lib/) as ESM.
+ const file = path.slice('/xle/'.length);
+ const abs = file === 'levenshtein.mjs'
+ ? join(CLI_SRC, 'lib/levenshtein.mjs')
+ : join(CLI_SRC, 'lib/xle', file);
+ if (!abs.startsWith(CLI_SRC) || !file.endsWith('.mjs')) {
+ return send(res, 403, 'text/plain', 'forbidden');
+ }
+ // validate.mjs imports '../levenshtein.mjs' — rewrite to a flat /xle path.
+ const body = readFileSync(abs, 'utf-8').replace(/from '\.\.\/levenshtein\.mjs'/g, "from './levenshtein.mjs'");
+ return send(res, 200, 'text/javascript; charset=utf-8', body);
+ }
+
+ send(res, 404, 'text/plain', 'not found');
+ } catch (e) {
+ // Log details server-side; don't leak stack traces to the client.
+ console.error('[xle-playground]', e);
+ send(res, 500, 'text/plain', 'Internal error — see the server console.');
+ }
+});
+
+server.listen(PORT, () => {
+ console.log(`XLE/XLO playground → http://localhost:${PORT}`);
+});
diff --git a/packages/cli/src/api/layout.mjs b/packages/cli/src/api/layout.mjs
new file mode 100644
index 0000000000..aeed02d61a
--- /dev/null
+++ b/packages/cli/src/api/layout.mjs
@@ -0,0 +1,301 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Programmatic API for the layout command (XLE/XLO).
+ *
+ * `astryx layout` turns token-compressed layout expressions into validated
+ * XDS TSX. Two input surfaces — compact (Emmet-derived XLE) and outline
+ * (indentation-based XLO) — share one AST, one validator, and one
+ * expander. See the research: pastes P2376666892 (spec) and P2376717669
+ * (outline surface).
+ *
+ * @input expression string (+ options)
+ * @output {type, data} envelopes: layout.expand / layout.check / layout.grammar
+ * @position api — pure orchestration over lib/xle; command wrapper in commands/layout.mjs
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {AstryxError} from './error.mjs';
+import {ERROR_CODES} from '../lib/error-codes.mjs';
+import {assertWithin, isFilePathArg, PathSafetyError} from '../utils/path-safety.mjs';
+import {parse, detectForm, XLEParseError} from '../lib/xle/parse.mjs';
+import {validate} from '../lib/xle/validate.mjs';
+import {expand} from '../lib/xle/expand.mjs';
+import {toCompact, toOutline} from '../lib/xle/print.mjs';
+import {buildRegistry, ALIAS_TABLE} from '../lib/xle/registry.mjs';
+import {discoverTemplates, stripTemplateAssetRefs} from './template.mjs';
+import {loadConfig} from '../lib/config.mjs';
+
+/**
+ * The catalog a `{hint}` can resolve to: template blocks (spliced inline) plus
+ * any app-registered local components from astryx.config.mjs `layout.components`
+ * (imported by name). App components are how XLE reaches domain pieces — the
+ * KpiCard/chart/drawer set that the @astryxdesign/core registry can't see.
+ */
+async function loadBlocks(cwd) {
+ const blocks = [];
+ try {
+ const all = await discoverTemplates(cwd);
+ for (const t of all) if (t.type === 'block') blocks.push({...t, kind: 'template'});
+ } catch {
+ // discovery is best-effort
+ }
+ try {
+ const config = await loadConfig(cwd);
+ const components = config.layout?.components || {};
+ for (const [name, spec] of Object.entries(components)) {
+ const importPath = typeof spec === 'string' ? spec : spec.from;
+ if (!importPath) continue;
+ blocks.push({
+ type: 'block',
+ kind: 'component',
+ dirName: name,
+ name,
+ description: typeof spec === 'object' ? spec.description || '' : '',
+ category: 'app',
+ importPath,
+ isDefault: typeof spec === 'object' ? Boolean(spec.default) : false,
+ });
+ }
+ } catch {
+ // config is optional
+ }
+ return blocks;
+}
+
+const normKey = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, '');
+
+/** Collect the block names referenced by {hints} anywhere in the doc. */
+function collectHintNames(doc) {
+ const names = new Set();
+ const visitNode = (node) => {
+ if (!node || node.kind === 'group') {
+ (node?.children || []).forEach(visit);
+ return;
+ }
+ if (node.hint?.block) names.add(node.hint.block.name);
+ for (const slot of node.slots || []) {
+ if (slot.value?.hint?.block) names.add(slot.value.hint.block.name);
+ (slot.value?.subexpr || []).forEach(visit);
+ }
+ (node.children || []).forEach(visit);
+ };
+ const visit = (item) => (item?.kind === 'group' ? item.children.forEach(visit) : visitNode(item));
+ doc.roots.forEach(visit);
+ doc.overlays.forEach(visit);
+ return names;
+}
+
+/**
+ * Build the blockModules map expand() needs: import-mode for app components,
+ * splice-mode (reading + asset-stripping the block source) for template blocks.
+ * Only blocks actually referenced are read.
+ */
+function buildBlockModules(doc, blocks) {
+ const referenced = collectHintNames(doc);
+ if (referenced.size === 0) return new Map();
+ const byKey = new Map(blocks.map(b => [normKey(b.dirName), b]));
+ const modules = new Map();
+ for (const name of referenced) {
+ const block = byKey.get(normKey(name));
+ if (!block) continue;
+ if (block.kind === 'component') {
+ modules.set(name, {mode: 'import', componentName: block.name, importPath: block.importPath, isDefault: block.isDefault});
+ } else if (block.filePath && fs.existsSync(block.filePath)) {
+ modules.set(name, {mode: 'splice', componentName: block.dirName, source: stripTemplateAssetRefs(fs.readFileSync(block.filePath, 'utf-8'))});
+ }
+ }
+ return modules;
+}
+
+function formatIssue(issue) {
+ const where = issue.line != null ? `line ${issue.line}: ` : '';
+ return `${where}${issue.message}`;
+}
+
+/**
+ * Parse + validate, throwing structured XDSErrors on failure.
+ * Returns {doc, registry, blocks, warnings}.
+ */
+async function analyze(expression, {form = 'auto', loose = false, cwd = process.cwd()} = {}) {
+ const registry = await buildRegistry({cwd});
+ const blocks = await loadBlocks(cwd);
+
+ let doc;
+ try {
+ doc = parse(expression, {form});
+ } catch (e) {
+ if (e instanceof XLEParseError) {
+ throw new AstryxError(
+ `Layout expression syntax error at line ${e.line}, col ${e.col}: ${e.message}`,
+ undefined,
+ ERROR_CODES.ERR_LAYOUT_PARSE,
+ );
+ }
+ throw e;
+ }
+
+ const {errors, warnings} = validate(doc, registry, blocks, {loose});
+ return {doc, registry, blocks, errors, warnings};
+}
+
+/**
+ * `astryx layout expand "<expr>" [path]`
+ *
+ * @param {string} expression
+ * @param {object} [options]
+ * @param {string} [options.targetPath] - write TSX here (validated against cwd)
+ * @param {'compact'|'outline'|'auto'} [options.form]
+ * @param {boolean} [options.loose] - downgrade unknown {hints} to TODO warnings
+ * @param {string} [options.name] - generated component name
+ * @param {string} [options.cwd]
+ */
+export async function layoutExpand(expression, options = {}) {
+ const {targetPath, form = 'auto', loose = false, name, cwd = process.cwd()} = options;
+ const {doc, registry, blocks, errors, warnings} = await analyze(expression, {form, loose, cwd});
+
+ if (errors.length > 0) {
+ throw new AstryxError(
+ `Layout expression is invalid:\n` + errors.map(e => ` - ${formatIssue(e)}`).join('\n'),
+ errors.flatMap(e => (e.suggestions || []).map(s => ({name: s, reason: 'did you mean this?'}))),
+ ERROR_CODES.ERR_LAYOUT_INVALID,
+ );
+ }
+
+ const componentName = name || 'GeneratedLayout';
+ if (!/^[A-Z][A-Za-z0-9]*$/.test(componentName)) {
+ throw new AstryxError(
+ `--name must be a PascalCase component name, got '${componentName}'`,
+ undefined,
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
+ }
+ const blockModules = buildBlockModules(doc, blocks);
+ const result = expand(doc, registry, {componentName, blockModules});
+
+ let written = null;
+ if (targetPath) {
+ let resolved;
+ try {
+ resolved = assertWithin(targetPath, cwd, {label: 'layout target path'});
+ } catch (err) {
+ if (err instanceof PathSafetyError) {
+ throw new AstryxError(err.message, undefined, ERROR_CODES.ERR_PATH_TRAVERSAL);
+ }
+ throw err;
+ }
+ const filePath = isFilePathArg(targetPath)
+ ? resolved
+ : path.join(resolved, `${componentName}.tsx`);
+ fs.mkdirSync(path.dirname(filePath), {recursive: true});
+ fs.writeFileSync(filePath, result.code);
+ written = path.relative(cwd, filePath);
+ }
+
+ return {
+ type: 'layout.expand',
+ data: {
+ form: form === 'auto' ? detectForm(expression) : form,
+ code: result.code,
+ componentsUsed: result.componentsUsed,
+ states: result.states,
+ todos: result.todos,
+ blocksReferenced: [...blockModules.entries()].map(([name, m]) => ({name, mode: m.mode})),
+ warnings: warnings.map(formatIssue),
+ written,
+ },
+ };
+}
+
+/**
+ * `astryx layout check "<expr>" [--form compact|outline]`
+ * Validates without expanding; echoes both canonical surfaces.
+ */
+export async function layoutCheck(expression, options = {}) {
+ const {form = 'auto', loose = false, cwd = process.cwd()} = options;
+ const {doc, errors, warnings} = await analyze(expression, {form, loose, cwd});
+
+ return {
+ type: 'layout.check',
+ data: {
+ valid: errors.length === 0,
+ form: doc.form,
+ errors: errors.map(e => ({...e, formatted: formatIssue(e)})),
+ warnings: warnings.map(formatIssue),
+ compact: toCompact(doc),
+ outline: toOutline(doc),
+ },
+ };
+}
+
+/**
+ * `astryx layout grammar` — the agent cheatsheet, with the alias table
+ * generated from this branch's registry (never hand-maintained).
+ */
+export async function layoutGrammar(options = {}) {
+ const {cwd = process.cwd()} = options;
+ const registry = await buildRegistry({cwd});
+
+ const aliasLines = [];
+ const byTarget = new Map();
+ for (const [alias, target] of registry.aliases) {
+ if (!byTarget.has(target)) byTarget.set(target, []);
+ byTarget.get(target).push(alias);
+ }
+ for (const [target, aliases] of [...byTarget.entries()].sort(([a], [b]) => a.localeCompare(b))) {
+ aliasLines.push(`${aliases.join('/')}=${target}`);
+ }
+
+ const text = `XLE/XLO — XDS layout expressions (branch-generated; aliases reflect this install)
+
+WORKFLOW
+ astryx layout check "<expr>" validate; echoes canonical compact + outline forms
+ astryx layout expand "<expr>" [path] emit validated TSX (path optional; --name <Pascal>)
+ Errors carry line/col + suggestions. Fix and resubmit; nothing is guessed.
+
+TWO SURFACES, ONE LANGUAGE (autodetected; --form to force)
+ compact: A[cp6 @topNav=TN] > L > LC > S[p6] > (C{card-callout}*4) + T
+ outline: indentation = nesting · same-indent = siblings · "repeat N:" block = (...)*N
+ slot lines: topNav: TN (or a block: topNav:\\n TN ...)
+
+NODE ANATOMY Name#id.enum"payload"[attrs]{hint}*N > children
+ .enum unique enum value of any prop: Bd.success Tx.lg B.primary
+ "payload" primary text prop (label/title/heading) or text child: TI"Email" B"Save"
+ {hint} kebab-case template/component reference (see TEMPLATE REFERENCING) — NEVER text
+ *N / xN repeat (use $ for the counter: Tk"item-$"*3)
+ trailing ! initial selection for scaffolded state: Tab"Overview"!
+
+ATTRS [...] (outline: bare tokens after the name, no brackets)
+ fused p6 g4 c4 w240 h2 cp2 mw960 rg2 cg2 (per-component: padding lives on Card/Section/AppShell.cp — p6 on AppShell/Layout/VStack errors with a correction)
+ key=value t=email href='/x' c{min:340} dv=[top,bottom] — keys validated per component
+ flags req opt dis striped hover divider … (isX/hasX props) · negate: !scroll
+ align j= main axis, a= cross axis — expander picks hAlign/vAlign per stack direction
+ slots @slotName=Node | @slotName=(sub > expr) | @slotName='text' | @slotName=#id
+ trigger opens=#id (a plain attr, no @ — binds an onClick that opens the overlay)
+ fill on a stack child → wraps in <StackItem size="fill">
+
+TEMPLATE REFERENCING ({hint} pulls in real content — this is how XLE reaches past the @astryxdesign/core shell)
+ C{card-callout} splice a template block (astryx template --list --type block):
+ the block is co-defined once in the file, referenced, imports merged
+ {kpi-card} standalone reference (no wrapper element) — place a component directly
+ {kpi-card}*4 repeat a reference; the definition/import is emitted once
+ app components register local ones in astryx.config.mjs to import them by name:
+ export default {layout: {components: {KpiCard: '@/components/KpiCard'}}}
+ then {kpi-card} → import {KpiCard} + <KpiCard /> (kebab ↔ Pascal)
+
+STRUCTURE THE EXPANDER HANDLES
+ Layout > LH + LC + LF + LP children auto-route into header/content/footer/start slots
+ T > (TR>THC*4) + (TR>TC*4)*6 rows partition into TableHeader/TableBody automatically
+ TabList/inputs required value+onChange scaffold typed useState automatically
+ overlays compact: tree ;; Dlg#confirm[...] · outline: overlays: section
+ trigger: B"Delete"[opens=#confirm]
+
+ALIASES (full component names always valid; XDS prefix optional)
+ ${aliasLines.join(' ')}
+`;
+
+ return {type: 'layout.grammar', data: {text, aliases: Object.fromEntries(registry.aliases)}};
+}
+
+export {ALIAS_TABLE};
diff --git a/packages/cli/src/api/layout.test.mjs b/packages/cli/src/api/layout.test.mjs
new file mode 100644
index 0000000000..81d900a75c
--- /dev/null
+++ b/packages/cli/src/api/layout.test.mjs
@@ -0,0 +1,238 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Integration tests for the layout API against the real @astryxdesign/core
+ * registry and real template blocks. Every expansion is additionally
+ * checked for TSX syntactic validity with the TypeScript parser, so the
+ * "expansion emits compilable JSX" contract is enforced, not assumed.
+ */
+
+import {describe, it, expect, beforeAll} from 'vitest';
+import {mkdtempSync, writeFileSync, rmSync} from 'node:fs';
+import {tmpdir} from 'node:os';
+import {join} from 'node:path';
+import ts from 'typescript';
+import {layoutExpand, layoutCheck, layoutGrammar} from './layout.mjs';
+import {buildRegistry} from '../lib/xle/registry.mjs';
+
+// The registry imports ~140 .doc.mjs modules on first use; under full-suite
+// parallel load that can exceed the default 5s test timeout. Warm it once.
+beforeAll(async () => {
+ await buildRegistry();
+}, 120_000);
+
+const SLOW = 30_000;
+
+/** Assert TSX parses cleanly; returns the source file for inspection. */
+function expectValidTsx(code) {
+ const sourceFile = ts.createSourceFile('generated.tsx', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+ const diagnostics = sourceFile.parseDiagnostics || [];
+ const messages = diagnostics.map(d => ts.flattenDiagnosticMessageText(d.messageText, ' '));
+ expect(messages).toEqual([]);
+ return sourceFile;
+}
+
+const LOGIN_COMPACT =
+ 'Ctr[h="100dvh"] > C[w=400 p8] > V[g6] > ' +
+ '(V[g1] > Tx"Welcome back" + Tx[t=supporting]"Sign in to your account") + ' +
+ '(F > TI"Email"[t=email req] + TI"Password"[t=password req]) + ' +
+ '(H[j=between a=center] > CB"Remember me" + Lk[href="/forgot"]"Forgot password?") + ' +
+ 'B.primary"Sign in"';
+
+const CHAT_OUTLINE = `
+AppShell
+ topNav: TN
+ Layout > LC !scroll
+ ChL
+ composer:
+ ChC
+ ChML
+ ChS "Today"
+ repeat 2:
+ ChM
+ ChB "Reply $"
+ Tbar "Actions"
+ B "Delete" opens=#confirm
+
+overlays:
+ AD#confirm "Delete item?"
+`;
+
+const DASHBOARD_COMPACT =
+ 'A[@topNav=TN @sideNav=SN] > L > V[g6] > ' +
+ '(G[c4 g4] > C{card-callout}*4) + ' +
+ '(C[p0] > T[striped] > (TR > THC"Name" + THC"Amount") + (TR > TC"Order $" + TC"\\$12.00")*3)';
+
+describe('layoutExpand', () => {
+ it('expands the login card with typed state scaffolds', async () => {
+ const result = await layoutExpand(LOGIN_COMPACT);
+ expect(result.type).toBe('layout.expand');
+ const {code} = result.data;
+ expectValidTsx(code);
+
+ expect(code).toContain(`const [email, setEmail] = useState('');`);
+ expect(code).toContain(`const [rememberMe, setRememberMe] = useState(false);`);
+ expect(code).toContain('<XDSCenter height="100dvh">');
+ expect(code).toContain('variant="primary"');
+ // axis-neutral j/a resolved onto the HStack's real props
+ expect(code).toContain('hAlign="between"');
+ expect(code).toContain('vAlign="center"');
+ // payload routed to label props, not duplicated as children
+ expect(code).not.toMatch(/label="Forgot password\?"[\s\S]{0,80}Forgot password\?/);
+ }, SLOW);
+
+ it('expands the outline chat page: slots, repeat blocks, overlays, triggers', async () => {
+ const result = await layoutExpand(CHAT_OUTLINE);
+ const {code, form} = result.data;
+ expect(form).toBe('outline');
+ expectValidTsx(code);
+
+ expect(code).toContain('composer={');
+ // slot satisfied required prop — no double assignment, no TODO for it
+ expect(code.match(/composer=/g)).toHaveLength(1);
+ expect(code).toContain('TODO(xle): open #confirm');
+ expect(code).toContain('overlays — wire open state');
+ expect((code.match(/<XDSChatMessage\b/g) || [])).toHaveLength(2);
+ }, SLOW);
+
+ it('expands the dashboard: table partition, repeats with $ counter and \\$ escape', async () => {
+ const result = await layoutExpand(DASHBOARD_COMPACT);
+ const {code} = result.data;
+ expectValidTsx(code);
+
+ expect(code).toContain('<XDSTableHeader>');
+ expect(code).toContain('<XDSTableBody>');
+ expect(code).toContain('Order 1');
+ expect(code).toContain('Order 3');
+ expect(code).toContain('$12.00');
+ expect(code).not.toContain('112.00');
+ // {card-callout} now splices: the block is co-defined once and referenced
+ // four times — no TODO marker.
+ expect((code.match(/^function CardCallout\(\)/gm) || [])).toHaveLength(1);
+ expect((code.match(/<CardCallout \/>/g) || [])).toHaveLength(4);
+ expect(code).not.toContain("TODO(xle): content block 'CardCallout'");
+ }, SLOW);
+
+ it('compact and outline surfaces expand to identical TSX', async () => {
+ const check = await layoutCheck(LOGIN_COMPACT);
+ const fromCompact = await layoutExpand(LOGIN_COMPACT);
+ const fromOutline = await layoutExpand(check.data.outline, {form: 'outline'});
+ expect(fromOutline.data.code).toEqual(fromCompact.data.code);
+ }, SLOW);
+
+ it('expansion is deterministic', async () => {
+ const a = await layoutExpand(DASHBOARD_COMPACT);
+ const b = await layoutExpand(DASHBOARD_COMPACT);
+ expect(a.data.code).toEqual(b.data.code);
+ }, SLOW);
+
+ it('throws structured errors with suggestions on invalid expressions', async () => {
+ await expect(layoutExpand('A[p6] > Grdi')).rejects.toMatchObject({
+ code: 'ERR_LAYOUT_INVALID',
+ message: expect.stringMatching(/AppShell has no prop 'padding'/),
+ });
+ });
+
+ it('rejects non-PascalCase --name', async () => {
+ await expect(layoutExpand('V > C', {name: 'not pascal'})).rejects.toMatchObject({
+ code: 'ERR_INVALID_ARGUMENT',
+ });
+ });
+
+ it('surfaces parse errors with positions', async () => {
+ await expect(layoutExpand('V > > C')).rejects.toMatchObject({
+ code: 'ERR_LAYOUT_PARSE',
+ message: expect.stringMatching(/line 1/),
+ });
+ });
+});
+
+describe('layoutCheck', () => {
+ it('returns both canonical surfaces for valid input', async () => {
+ const result = await layoutCheck('V[g6] > C{card-callout}*2');
+ expect(result.data.valid).toBe(true);
+ expect(result.data.compact).toContain('{card-callout}');
+ expect(result.data.outline).toContain('C {card-callout} x2');
+ });
+
+ it('collects all errors instead of stopping at the first', async () => {
+ const result = await layoutCheck('A[p6] > V[g7] > Bd.sucess"x" + C{not-a-block}');
+ expect(result.data.valid).toBe(false);
+ expect(result.data.errors.length).toBeGreaterThanOrEqual(4);
+ const all = result.data.errors.map(e => e.message).join('\n');
+ expect(all).toMatch(/no prop 'padding'/);
+ expect(all).toMatch(/must be one of/);
+ expect(all).toMatch(/Unknown block/);
+ });
+});
+
+describe('template referencing', () => {
+ it('splices a template block: co-defined once, referenced, imports merged', async () => {
+ const result = await layoutExpand('S[p6] > C{card-callout}*3', {name: 'Demo'});
+ const {code} = result.data;
+ expectValidTsx(code);
+ // co-defined exactly once, referenced three times, no TODO
+ expect((code.match(/^function CardCallout\(\)/gm) || [])).toHaveLength(1);
+ expect((code.match(/<CardCallout \/>/g) || [])).toHaveLength(3);
+ expect(code).not.toContain('TODO(xle)');
+ // the block's own import is hoisted, and shared specifiers dedupe
+ expect((code.match(/from '@astryxdesign\/core\/Card'/g) || [])).toHaveLength(1);
+ // the block lost its export — it's a local declaration now
+ expect(code).not.toContain('export default function CardCallout');
+ expect(result.data.blocksReferenced).toEqual([{name: 'CardCallout', mode: 'splice'}]);
+ }, SLOW);
+
+ it('merges a stateful block useState into a single react import', async () => {
+ const result = await layoutExpand(
+ 'V > TI"Search"[t=text] + {table-column-settings-table}',
+ {name: 'Demo'},
+ );
+ const {code} = result.data;
+ expectValidTsx(code);
+ // page TextInput scaffolds useState; block also uses useState → one import
+ expect((code.match(/^import \{useState\} from 'react';$/gm) || [])).toHaveLength(1);
+ expect(code).toContain('function TableColumnSettingsTable()');
+ }, SLOW);
+
+ it('imports app-registered local components (the local-component bridge)', async () => {
+ // Inside the workspace so @astryxdesign/core resolves; cleaned up after.
+ const cwd = mkdtempSync(join(process.cwd(), '.xle-imp-test-'));
+ try {
+ writeFileSync(
+ join(cwd, 'astryx.config.mjs'),
+ `export default {layout: {components: {KpiCard: '@/components/KpiCard', TimeRangePicker: {from: '@/components/TimeRangePicker'}}}};\n`,
+ );
+ const result = await layoutExpand('S[p6] > (G[c4 g4] > {kpi-card}*4) + {time-range-picker}', {
+ name: 'Demo',
+ cwd,
+ });
+ const {code} = result.data;
+ expectValidTsx(code);
+ expect(code).toContain("import {KpiCard} from '@/components/KpiCard';");
+ expect(code).toContain("import {TimeRangePicker} from '@/components/TimeRangePicker';");
+ expect((code.match(/<KpiCard \/>/g) || [])).toHaveLength(4);
+ expect(code).toContain('<TimeRangePicker />');
+ expect(result.data.blocksReferenced).toContainEqual({name: 'KpiCard', mode: 'import'});
+ } finally {
+ rmSync(cwd, {recursive: true, force: true});
+ }
+ }, SLOW);
+
+ it('parses a standalone {block} in both surfaces', async () => {
+ const check = await layoutCheck('G[c4 g4] > {card-callout}*2');
+ expect(check.data.valid).toBe(true);
+ expect(check.data.compact).toContain('{card-callout}*2');
+ expect(check.data.outline).toMatch(/\{card-callout\} x2/);
+ });
+});
+
+describe('layoutGrammar', () => {
+ it('emits the cheatsheet with branch-generated aliases', async () => {
+ const result = await layoutGrammar();
+ expect(result.data.text).toContain('TWO SURFACES');
+ expect(result.data.aliases.V).toBe('VStack');
+ expect(result.data.aliases.TB).toBe('TableBody');
+ // every alias target must exist — the table is registry-filtered
+ expect(Object.values(result.data.aliases)).not.toContain(undefined);
+ });
+});
diff --git a/packages/cli/src/commands/layout.mjs b/packages/cli/src/commands/layout.mjs
new file mode 100644
index 0000000000..ac1fb9c09b
--- /dev/null
+++ b/packages/cli/src/commands/layout.mjs
@@ -0,0 +1,139 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file layout command — thin CLI wrapper around api/layout.mjs.
+ *
+ * Subcommands:
+ * astryx layout expand "<expr>" [path] compressed expression → validated TSX
+ * astryx layout check "<expr>" validate + echo both canonical surfaces
+ * astryx layout grammar agent cheatsheet (alias table is branch-generated)
+ *
+ * The expression argument may also come from --file or stdin (`-`),
+ * which is how multi-line outline (XLO) input usually arrives.
+ */
+
+import * as fs from 'node:fs';
+import {jsonOut, humanLog} from '../lib/json.mjs';
+import {cliError} from '../lib/cli-error.mjs';
+import {layoutExpand, layoutCheck, layoutGrammar} from '../api/layout.mjs';
+
+/** Resolve the expression from arg, --file, or stdin ('-'). */
+async function readExpression(expr, options) {
+ if (options.file) return fs.readFileSync(options.file, 'utf-8');
+ if (expr === '-' || (!expr && !process.stdin.isTTY)) {
+ const chunks = [];
+ for await (const chunk of process.stdin) chunks.push(chunk);
+ return Buffer.concat(chunks).toString('utf-8');
+ }
+ return expr;
+}
+
+export function registerLayout(program) {
+ const layoutCmd = program
+ .command('layout')
+ .description('Generate XDS layouts from compressed expressions (XLE/XLO)');
+
+ layoutCmd
+ .command('expand [expression] [path]')
+ .description('Expand a layout expression into validated XDS TSX')
+ .option('--file <file>', 'Read the expression from a file')
+ .option('--form <form>', 'Input surface: compact, outline, or auto', 'auto')
+ .option('--name <name>', 'Generated component name (PascalCase)', 'GeneratedLayout')
+ .option('--loose', 'Downgrade unknown {block} hints to TODO placeholders')
+ .action(async (expression, targetPath, options) => {
+ const json = program.opts().json || false;
+ const source = await readExpression(expression, options);
+ if (!source || source.trim() === '') {
+ cliError('No layout expression given — pass it as an argument, via --file, or on stdin');
+ return;
+ }
+ let result;
+ try {
+ result = await layoutExpand(source, {
+ targetPath,
+ form: options.form,
+ loose: options.loose || false,
+ name: options.name,
+ cwd: process.cwd(),
+ });
+ } catch (e) {
+ cliError(e.message, {suggestions: e.suggestions || [], code: e.code});
+ return;
+ }
+ if (json) return jsonOut(result.type, result.data);
+
+ for (const warning of result.data.warnings) humanLog(`⚠ ${warning}`);
+ if (result.data.written) {
+ humanLog(`\n✓ Expanded to ${result.data.written}`);
+ humanLog(` Components: ${result.data.componentsUsed.join(', ')}`);
+ if (result.data.todos.length > 0) {
+ humanLog(` TODOs: ${result.data.todos.length} (search for "TODO(xle)")`);
+ }
+ humanLog('');
+ } else {
+ humanLog(result.data.code);
+ }
+ });
+
+ layoutCmd
+ .command('check [expression]')
+ .description('Validate a layout expression and echo canonical compact/outline forms')
+ .option('--file <file>', 'Read the expression from a file')
+ .option('--form <form>', 'Input surface: compact, outline, or auto', 'auto')
+ .option('--loose', 'Downgrade unknown {block} hints to TODO placeholders')
+ .action(async (expression, options) => {
+ const json = program.opts().json || false;
+ const source = await readExpression(expression, options);
+ if (!source || source.trim() === '') {
+ cliError('No layout expression given — pass it as an argument, via --file, or on stdin');
+ return;
+ }
+ let result;
+ try {
+ result = await layoutCheck(source, {
+ form: options.form,
+ loose: options.loose || false,
+ cwd: process.cwd(),
+ });
+ } catch (e) {
+ cliError(e.message, {suggestions: e.suggestions || [], code: e.code});
+ return;
+ }
+ if (json) return jsonOut(result.type, result.data);
+
+ const {valid, form, errors, warnings, compact, outline} = result.data;
+ if (!valid) {
+ humanLog(`\n✗ Invalid (${errors.length} error${errors.length === 1 ? '' : 's'}):`);
+ for (const e of errors) {
+ humanLog(` - ${e.formatted}`);
+ if (e.suggestions?.length > 0) humanLog(` did you mean: ${e.suggestions.join(', ')}?`);
+ }
+ humanLog('');
+ process.exitCode = 1;
+ return;
+ }
+ humanLog(`\n✓ Valid (parsed as ${form})`);
+ for (const warning of warnings) humanLog(`⚠ ${warning}`);
+ humanLog('\ncompact:');
+ humanLog(` ${compact}`);
+ humanLog('\noutline:');
+ humanLog(outline.split('\n').map(l => ` ${l}`).join('\n'));
+ humanLog('');
+ });
+
+ layoutCmd
+ .command('grammar')
+ .description('Print the XLE/XLO cheatsheet (alias table generated from this branch)')
+ .action(async () => {
+ const json = program.opts().json || false;
+ let result;
+ try {
+ result = await layoutGrammar({cwd: process.cwd()});
+ } catch (e) {
+ cliError(e.message, {suggestions: e.suggestions || [], code: e.code});
+ return;
+ }
+ if (json) return jsonOut(result.type, result.data);
+ humanLog(result.data.text);
+ });
+}
diff --git a/packages/cli/src/index.mjs b/packages/cli/src/index.mjs
index 02490ca7bf..748ce45c08 100644
--- a/packages/cli/src/index.mjs
+++ b/packages/cli/src/index.mjs
@@ -63,6 +63,9 @@ export const JSON_SUPPORTED = new Set([
'upgrade',
'manifest',
'doctor',
+ 'layout expand',
+ 'layout check',
+ 'layout grammar',
]);
program
@@ -243,6 +246,7 @@ const commands = [
{name: 'swizzle', path: './commands/swizzle.mjs', register: 'registerSwizzle'},
// agent-docs folded into init — functions still importable from agent-docs.mjs
{name: 'template', path: './commands/template.mjs', register: 'registerTemplate'},
+ {name: 'layout', path: './commands/layout.mjs', register: 'registerLayout'},
{name: 'gap-report', path: './commands/gap-report.mjs', register: 'registerGapReport'},
{name: 'upgrade', path: './commands/upgrade.mjs', register: 'registerUpgrade'},
{name: 'theme', path: './commands/build-theme.mjs', register: 'registerTheme'},
diff --git a/packages/cli/src/lib/error-codes.mjs b/packages/cli/src/lib/error-codes.mjs
index 48404f3d5a..d765661e2f 100644
--- a/packages/cli/src/lib/error-codes.mjs
+++ b/packages/cli/src/lib/error-codes.mjs
@@ -75,6 +75,8 @@
* | 'ERR_DEP_MISSING'
* | 'ERR_GH_CLI'
* | 'ERR_GAP_REPORT_FAILED'
+ * | 'ERR_LAYOUT_PARSE'
+ * | 'ERR_LAYOUT_INVALID'
* )} ErrorCode
*/
@@ -180,6 +182,12 @@ export const ERROR_CODES = Object.freeze({
ERR_GH_CLI: 'ERR_GH_CLI',
/** Filing a gap report failed at the command/integration boundary. */
ERR_GAP_REPORT_FAILED: 'ERR_GAP_REPORT_FAILED',
+
+ // ── Layout expressions (XLE/XLO) ─────────────────────────────────
+ /** A layout expression failed to parse (syntax error, with line/col). */
+ ERR_LAYOUT_PARSE: 'ERR_LAYOUT_PARSE',
+ /** A layout expression parsed but failed validation (unknown component/prop/enum/block). */
+ ERR_LAYOUT_INVALID: 'ERR_LAYOUT_INVALID',
});
/**
diff --git a/packages/cli/src/lib/levenshtein.mjs b/packages/cli/src/lib/levenshtein.mjs
new file mode 100644
index 0000000000..a6b6df59d0
--- /dev/null
+++ b/packages/cli/src/lib/levenshtein.mjs
@@ -0,0 +1,29 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Levenshtein edit distance — pure, dependency-free.
+ *
+ * Lives apart from string-utils.mjs (which dynamically imports node:fs/path
+ * for component search) so browser-bundled code — the XLE/XLO layout
+ * language — can use fuzzy matching without dragging node: schemes into the
+ * webpack graph.
+ *
+ * @input two strings
+ * @output edit distance (number)
+ * @position lib — shared by string-utils.mjs and lib/xle/validate.mjs
+ */
+
+export function levenshteinDistance(a, b) {
+ const m = a.length, n = b.length;
+ const dp = Array.from({length: m + 1}, () => Array(n + 1).fill(0));
+ for (let i = 0; i <= m; i++) dp[i][0] = i;
+ for (let j = 0; j <= n; j++) dp[0][j] = j;
+ for (let i = 1; i <= m; i++) {
+ for (let j = 1; j <= n; j++) {
+ dp[i][j] = a[i-1] === b[j-1]
+ ? dp[i-1][j-1]
+ : 1 + Math.min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]);
+ }
+ }
+ return dp[m][n];
+}
diff --git a/packages/cli/src/lib/manifest.mjs b/packages/cli/src/lib/manifest.mjs
index 7892e580fa..728cb49426 100644
--- a/packages/cli/src/lib/manifest.mjs
+++ b/packages/cli/src/lib/manifest.mjs
@@ -64,6 +64,9 @@ export const RESPONSE_TYPES = {
'gap-report': ['gap-report.categories', 'gap-report.dryRun', 'gap-report.file'],
manifest: ['manifest'],
doctor: ['doctor'],
+ 'layout expand': ['layout.expand'],
+ 'layout check': ['layout.check'],
+ 'layout grammar': ['layout.grammar'],
};
/**
@@ -83,6 +86,9 @@ const EXAMPLES = {
manifest: ['astryx manifest --json', 'astryx --json'],
doctor: ['astryx doctor', 'astryx doctor --json'],
init: ['astryx init'],
+ 'layout expand': [`astryx layout expand 'V[g6] > C{card-callout}*4' ./src/Page.tsx`],
+ 'layout check': [`astryx layout check 'A[cp6] > L > LC > S[p6]' --json`],
+ 'layout grammar': ['astryx layout grammar'],
};
/**
diff --git a/packages/cli/src/lib/string-utils.mjs b/packages/cli/src/lib/string-utils.mjs
index cd5ac271d4..15816c4fd5 100644
--- a/packages/cli/src/lib/string-utils.mjs
+++ b/packages/cli/src/lib/string-utils.mjs
@@ -4,20 +4,11 @@
* @file String utilities — fuzzy matching and semantic search for component names
*/
-export function levenshteinDistance(a, b) {
- const m = a.length, n = b.length;
- const dp = Array.from({length: m + 1}, () => Array(n + 1).fill(0));
- for (let i = 0; i <= m; i++) dp[i][0] = i;
- for (let j = 0; j <= n; j++) dp[0][j] = j;
- for (let i = 1; i <= m; i++) {
- for (let j = 1; j <= n; j++) {
- dp[i][j] = a[i-1] === b[j-1]
- ? dp[i-1][j-1]
- : 1 + Math.min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]);
- }
- }
- return dp[m][n];
-}
+// levenshteinDistance lives in its own pure module so browser-bundled code
+// (the XLE/XLO language) can use it without this file's dynamic node:fs/path
+// imports landing in the webpack graph. Re-exported for existing consumers.
+import {levenshteinDistance} from './levenshtein.mjs';
+export {levenshteinDistance} from './levenshtein.mjs';
/**
* Find the closest component names to a given (possibly misspelled) name.
diff --git a/packages/cli/src/lib/xle/browser.d.ts b/packages/cli/src/lib/xle/browser.d.ts
new file mode 100644
index 0000000000..e634486dc8
--- /dev/null
+++ b/packages/cli/src/lib/xle/browser.d.ts
@@ -0,0 +1,91 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** Type surface for `@astryxdesign/cli/xle` — the browser-safe layout language. */
+
+export interface XLEIssue {
+ message: string;
+ line?: number;
+ col?: number;
+ formatted: string;
+ suggestions?: string[];
+ kind?: string;
+}
+
+export interface SerializedRegistry {
+ components: Array<{
+ name: string;
+ exportName: string;
+ dirName: string;
+ importPath: string;
+ undocumented?: boolean;
+ props: Array<Record<string, unknown>>;
+ }>;
+ aliases: Array<[string, string]>;
+ componentNames: string[];
+}
+
+export interface XLEBlock {
+ dirName: string;
+ description?: string;
+ category?: string;
+}
+
+export interface CheckOptions {
+ blocks?: XLEBlock[];
+ form?: 'auto' | 'compact' | 'outline';
+ loose?: boolean;
+}
+
+export interface CheckResult {
+ ok: boolean;
+ valid?: boolean;
+ form?: 'compact' | 'outline';
+ errors: XLEIssue[];
+ warnings: string[];
+ compact?: string;
+ outline?: string;
+ parseError?: {message: string; line?: number; col?: number};
+}
+
+export interface ExpandOptions extends CheckOptions {
+ name?: string;
+}
+
+export type ExpandResult =
+ | {ok: false; errors: XLEIssue[]}
+ | {
+ ok: true;
+ form: 'compact' | 'outline';
+ code: string;
+ componentsUsed: string[];
+ states: number;
+ todos: string[];
+ warnings: string[];
+ };
+
+export function checkExpression(
+ expression: string,
+ registry: SerializedRegistry | object,
+ opts?: CheckOptions,
+): CheckResult;
+
+export function expandExpression(
+ expression: string,
+ registry: SerializedRegistry | object,
+ opts?: ExpandOptions,
+): ExpandResult;
+
+export function hydrateRegistry(json: SerializedRegistry): object;
+export function serializeRegistry(registry: object): SerializedRegistry;
+export function parse(source: string, opts?: {form?: string}): unknown;
+export function detectForm(source: string): 'compact' | 'outline';
+export function validate(doc: unknown, registry: object, blocks?: XLEBlock[], opts?: {loose?: boolean}): {errors: XLEIssue[]; warnings: XLEIssue[]};
+export function expand(doc: unknown, registry: object, opts?: {componentName?: string}): {code: string; componentsUsed: string[]; states: number; todos: string[]};
+export function toCompact(doc: unknown): string;
+export function toOutline(doc: unknown): string;
+export const ALIAS_TABLE: Record<string, string>;
+export const SPACING_STEPS: number[];
+export class XLEParseError extends Error {
+ line: number;
+ col: number;
+}
diff --git a/packages/cli/src/lib/xle/browser.mjs b/packages/cli/src/lib/xle/browser.mjs
new file mode 100644
index 0000000000..1f07161ea6
--- /dev/null
+++ b/packages/cli/src/lib/xle/browser.mjs
@@ -0,0 +1,120 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file XLE/XLO browser barrel — the layout language without Node deps.
+ *
+ * The CLI builds its registry by reading .doc.mjs from disk (registry.mjs,
+ * Node-only). The browser playground instead receives a *serialized*
+ * registry (built at deploy time) and hydrates it here, then runs the same
+ * pure parse → validate → expand → print pipeline. Importing this module
+ * never pulls in node:fs, so it bundles cleanly for the web.
+ *
+ * @input expression string + a serialized-or-hydrated registry (+ blocks)
+ * @output checkExpression / expandExpression + the raw pipeline pieces
+ * @position lib/xle — exported as `@astryxdesign/cli/xle`
+ */
+
+import {parse, detectForm, XLEParseError} from './parse.mjs';
+import {validate} from './validate.mjs';
+import {expand} from './expand.mjs';
+import {toCompact, toOutline} from './print.mjs';
+import {hydrateRegistry} from './registry-core.mjs';
+
+export {parse, detectForm, XLEParseError, validate, expand, toCompact, toOutline};
+export {hydrateRegistry, serializeRegistry, ALIAS_TABLE, resolveComponent, SPACING_STEPS} from './registry-core.mjs';
+
+/** Accept either a hydrated registry (Map fields) or serialized JSON. */
+function asRegistry(registry) {
+ return registry && registry.components instanceof Map ? registry : hydrateRegistry(registry);
+}
+
+function formatIssue(issue) {
+ const where = issue.line != null ? `line ${issue.line}: ` : '';
+ return `${where}${issue.message}`;
+}
+
+/**
+ * Validate an expression and return both canonical surfaces — the browser
+ * twin of `layout check`. Never throws on invalid input; returns the errors.
+ *
+ * @param {string} expression
+ * @param {object} registry - serialized or hydrated
+ * @param {object} [opts]
+ * @param {Array} [opts.blocks] - block list for {hint} resolution (default [])
+ * @param {'compact'|'outline'|'auto'} [opts.form]
+ * @param {boolean} [opts.loose]
+ * @returns {{ok: boolean, valid?: boolean, form?: string, errors: Array, warnings: string[], compact?: string, outline?: string, parseError?: object}}
+ */
+export function checkExpression(expression, registry, opts = {}) {
+ const {blocks = [], form = 'auto', loose = false} = opts;
+ let doc;
+ try {
+ doc = parse(expression, {form});
+ } catch (e) {
+ if (e instanceof XLEParseError) {
+ return {
+ ok: false,
+ valid: false,
+ errors: [{message: e.message, line: e.line, col: e.col, formatted: formatIssue(e), kind: 'parse'}],
+ warnings: [],
+ parseError: {message: e.message, line: e.line, col: e.col},
+ };
+ }
+ throw e;
+ }
+ const {errors, warnings} = validate(doc, asRegistry(registry), blocks, {loose});
+ return {
+ ok: true,
+ valid: errors.length === 0,
+ form: doc.form,
+ errors: errors.map(e => ({...e, formatted: formatIssue(e)})),
+ warnings: warnings.map(formatIssue),
+ compact: toCompact(doc),
+ outline: toOutline(doc),
+ };
+}
+
+/**
+ * Validate + expand to TSX — the browser twin of `layout expand`.
+ * Returns either {code, ...} or {errors} (never writes files).
+ *
+ * @param {string} expression
+ * @param {object} registry
+ * @param {object} [opts]
+ * @param {Array} [opts.blocks]
+ * @param {'compact'|'outline'|'auto'} [opts.form]
+ * @param {boolean} [opts.loose]
+ * @param {string} [opts.name] - generated component name (PascalCase)
+ * @param {Map} [opts.blockModules] - prepared block sources/imports for splicing;
+ * omit in the browser (hints stay as TODO markers without sources)
+ */
+export function expandExpression(expression, registry, opts = {}) {
+ const {blocks = [], form = 'auto', loose = false, name = 'GeneratedLayout', blockModules} = opts;
+ const reg = asRegistry(registry);
+ let doc;
+ try {
+ doc = parse(expression, {form});
+ } catch (e) {
+ if (e instanceof XLEParseError) {
+ return {ok: false, errors: [{message: e.message, line: e.line, col: e.col, formatted: formatIssue(e), kind: 'parse'}]};
+ }
+ throw e;
+ }
+ const {errors, warnings} = validate(doc, reg, blocks, {loose});
+ if (errors.length > 0) {
+ return {ok: false, errors: errors.map(e => ({...e, formatted: formatIssue(e)}))};
+ }
+ if (!/^[A-Z][A-Za-z0-9]*$/.test(name)) {
+ return {ok: false, errors: [{message: `Component name must be PascalCase, got '${name}'`, formatted: `Component name must be PascalCase, got '${name}'`}]};
+ }
+ const result = expand(doc, reg, {componentName: name, blockModules});
+ return {
+ ok: true,
+ form: form === 'auto' ? detectForm(expression) : form,
+ code: result.code,
+ componentsUsed: result.componentsUsed,
+ states: result.states,
+ todos: result.todos,
+ warnings: warnings.map(formatIssue),
+ };
+}
diff --git a/packages/cli/src/lib/xle/expand.mjs b/packages/cli/src/lib/xle/expand.mjs
new file mode 100644
index 0000000000..07ddc72e90
--- /dev/null
+++ b/packages/cli/src/lib/xle/expand.mjs
@@ -0,0 +1,622 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file XLE expander — bound AST → TSX.
+ *
+ * Expansion is codegen, not templating: required value/onChange pairs
+ * become typed useState scaffolds, Layout children auto-route into its
+ * slot props, Table rows partition into header/body, `fill`-flagged
+ * stack children wrap in StackItem, and {hint} blocks become structured
+ * TODO(xle) markers pointing at the real block template.
+ *
+ * Output is deterministic: same bound AST → byte-identical TSX.
+ *
+ * @input validated doc (nodes carry .bound) + registry
+ * @output expand() → {code, componentsUsed, states, todos}
+ * @position lib/xle — last stage; api/layout.mjs orchestrates
+ */
+
+import {PAYLOAD_PROPS} from './validate.mjs';
+import {mergeImports, renderImport, prepareSpliceModule} from './splice.mjs';
+
+const INDENT = ' ';
+
+function slugify(text) {
+ return String(text).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
+}
+
+function camelCase(text) {
+ const parts = slugify(text).split('-').filter(Boolean);
+ if (parts.length === 0) return 'item';
+ return parts[0] + parts.slice(1).map(p => p[0].toUpperCase() + p.slice(1)).join('');
+}
+
+function escapeAttr(value) {
+ return String(value).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
+}
+
+function cloneItem(item) {
+ // .bound holds a registry reference (Map props) — rebuild it after the
+ // JSON round-trip of the plain AST fields.
+ const {bound, ...rest} = item;
+ const copy = JSON.parse(JSON.stringify(rest, (key, value) => {
+ if (key === 'bound') return undefined;
+ return value;
+ }));
+ if (item.kind === 'node') {
+ copy.bound = bound
+ ? {component: bound.component, props: new Map(bound.props), slots: bound.slots, stray: []}
+ : null;
+ copy.children = item.children.map(cloneItem);
+ copy.slots = item.slots; // slot subexprs are emitted from the original binding
+ } else {
+ copy.children = item.children.map(cloneItem);
+ }
+ return copy;
+}
+
+/**
+ * Substitute Emmet-style `$` counters in payloads and string props.
+ * `\$` escapes a literal dollar sign (prices etc.).
+ */
+function subCounterText(text, index) {
+ return text.replace(/\\\$|\$/g, m => (m === '\\$' ? '$' : String(index)));
+}
+
+/** Strip `\$` escapes when a node is NOT repeated (single emission). */
+function unescapeCounterText(text) {
+ return text.replace(/\\\$/g, '$');
+}
+
+function substituteCounter(node, index) {
+ if (node.kind === 'group') {
+ for (const child of node.children) substituteCounter(child, index);
+ return;
+ }
+ if (node.payload) node.payload = subCounterText(node.payload, index);
+ if (node.payload2) node.payload2 = subCounterText(node.payload2, index);
+ if (node.bound) {
+ for (const [key, value] of node.bound.props) {
+ if (typeof value === 'string' && value.includes('$')) {
+ node.bound.props.set(key, subCounterText(value, index));
+ }
+ }
+ }
+ for (const child of node.children) substituteCounter(child, index);
+}
+
+class Emitter {
+ constructor(registry, options = {}) {
+ this.registry = registry;
+ // importPath → {named:Set, types:Set, default, namespace, sideEffect}
+ this.imports = new Map();
+ this.states = [];
+ this.usedStateNames = new Set();
+ this.todos = [];
+ this.componentsUsed = new Set();
+ this.componentName = options.componentName || 'GeneratedLayout';
+ // canonical block key → prepared module ({mode, componentName, ...})
+ this.blockModules = options.blockModules || new Map();
+ // names of blocks already co-defined in this module (dedup)
+ this.splicedBlocks = new Map(); // key → componentName
+ this.blockDefs = []; // co-defined block source bodies, in first-use order
+ }
+
+ importEntry(source) {
+ if (!this.imports.has(source)) {
+ this.imports.set(source, {named: new Set(), types: new Set(), default: null, namespace: null, sideEffect: false});
+ }
+ return this.imports.get(source);
+ }
+
+ addImport(component) {
+ this.importEntry(component.importPath).named.add(component.exportName);
+ this.componentsUsed.add(component.name);
+ }
+
+ addNamedImport(source, name) {
+ this.importEntry(source).named.add(name);
+ }
+
+ requireComponent(name) {
+ const component = this.registry.components.get(name);
+ if (component) this.addImport(component);
+ return component;
+ }
+
+ stateName(base) {
+ let name = camelCase(base);
+ if (!/^[a-z]/.test(name)) name = 'v' + name;
+ let candidate = name;
+ let n = 2;
+ while (this.usedStateNames.has(candidate)) candidate = name + n++;
+ this.usedStateNames.add(candidate);
+ return candidate;
+ }
+
+ addState(base, initial) {
+ const name = this.stateName(base);
+ const setter = 'set' + name[0].toUpperCase() + name.slice(1);
+ this.states.push({name, setter, initial});
+ return {name, setter};
+ }
+
+ // ── value → JSX prop text ────────────────────────────────────────────
+
+ jsxValue(value) {
+ if (value === true) return null; // bare flag
+ if (value === false) return '{false}';
+ if (typeof value === 'number') return `{${value}}`;
+ if (typeof value === 'string') return `"${escapeAttr(value)}"`;
+ if (value && value.__expr) return `{${value.__expr}}`;
+ if (Array.isArray(value)) {
+ return `{[${value.map(v => (typeof v === 'string' ? `'${v}'` : String(v))).join(', ')}]}`;
+ }
+ if (typeof value === 'object' && value !== null) {
+ const inner = Object.entries(value)
+ .map(([k, v]) => `${k}: ${typeof v === 'string' ? `'${v}'` : String(v)}`)
+ .join(', ');
+ return `{{${inner}}}`;
+ }
+ return `{${String(value)}}`;
+ }
+
+ propText(key, value) {
+ const v = this.jsxValue(value);
+ return v === null ? key : `${key}=${v}`;
+ }
+
+ // ── scaffolding ──────────────────────────────────────────────────────
+
+ initialFor(prop, node) {
+ const type = (prop.type || '').trim();
+ if (node.bound.component.name === 'TabList') {
+ const tabs = node.children.filter(c => c.kind === 'node');
+ const chosen = tabs.find(t => t.selected) || tabs[0];
+ return chosen ? `'${slugify(chosen.payload || chosen.name)}'` : `''`;
+ }
+ if (type === 'string') return `''`;
+ if (type.startsWith('boolean')) return 'false';
+ if (type === 'number') return '1';
+ if (prop.enumValues && prop.enumValues.length > 0) {
+ const first = prop.enumValues[0];
+ return typeof first === 'string' ? `'${first}'` : String(first);
+ }
+ return 'undefined';
+ }
+
+ scaffoldState(node, component, props) {
+ for (const valueKey of ['value', 'page']) {
+ const valueProp = component.props.get(valueKey);
+ const onChange = component.props.get('onChange');
+ if (!valueProp || !valueProp.required || !onChange) continue;
+ if (props.has(valueKey)) continue;
+ const base = node.payload || node.id || component.name;
+ const {name, setter} = this.addState(base, this.initialFor(valueProp, node));
+ props.set(valueKey, {__expr: name});
+ if (!props.has('onChange')) props.set('onChange', {__expr: setter});
+ return;
+ }
+ }
+
+ fillRequired(node, component, props, slotKeys) {
+ for (const prop of component.props.values()) {
+ if (!prop.required || props.has(prop.name) || slotKeys.has(prop.name)) continue;
+ if (prop.name === 'children') continue; // handled by child emission
+ if (prop.name === 'value' || prop.name === 'onChange' || prop.name === 'page') continue;
+ if (prop.isFunction) { props.set(prop.name, {__expr: '() => {}'}); continue; }
+ if (prop.enumValues && prop.enumValues.length > 0) {
+ props.set(prop.name, prop.enumValues[0]);
+ continue;
+ }
+ if (prop.type === 'string') {
+ props.set(prop.name, node.payload || component.name);
+ continue;
+ }
+ // Unfillable required prop (data arrays etc.) — structured TODO.
+ this.todos.push(`${component.name}.${prop.name} (required ${prop.type}) needs real data`);
+ props.set(prop.name, {__expr: `undefined /* TODO(xle): required ${prop.type} */`});
+ }
+ }
+
+ // ── node emission ────────────────────────────────────────────────────
+
+ emitItems(items, depth, context = {}) {
+ const lines = [];
+ for (const item of items) {
+ if (item.kind === 'group') {
+ const count = item.repeat || 1;
+ for (let i = 1; i <= count; i++) {
+ for (const child of item.children) {
+ const clone = count > 1 ? cloneItem(child) : child;
+ if (count > 1) substituteCounter(clone, i);
+ lines.push(...this.emitItems([clone], depth, context));
+ }
+ }
+ continue;
+ }
+ const count = item.repeat || 1;
+ for (let i = 1; i <= count; i++) {
+ const clone = count > 1 ? cloneItem(item) : item;
+ if (count > 1) {
+ clone.repeat = null;
+ substituteCounter(clone, i);
+ }
+ lines.push(...this.emitNode(clone, depth, context));
+ }
+ }
+ return lines;
+ }
+
+ emitNode(node, depth, context = {}) {
+ if (!node.bound) {
+ // Anonymous block reference — emit just the block, no wrapper element.
+ if (node.hint) return this.emitHint(node.hint, depth);
+ return [`${INDENT.repeat(depth)}{/* unresolved: ${node.name} */}`];
+ }
+ const component = node.bound.component;
+ this.addImport(component);
+ const pad = INDENT.repeat(depth);
+
+ const props = new Map(node.bound.props);
+ let textChild = null;
+
+ // Payload → primary text prop, else text child. Required props win
+ // (Button.label) over optional ones; a required children slot wins
+ // over an optional label (Link).
+ if (node.payload != null) {
+ node.payload = unescapeCounterText(node.payload);
+ const required = PAYLOAD_PROPS.find(p => component.props.get(p)?.required);
+ const childrenRequired = component.props.get('children')?.required;
+ const target = required
+ || (childrenRequired ? null : PAYLOAD_PROPS.find(p => component.props.has(p)));
+ if (target && !props.has(target)) props.set(target, node.payload);
+ else textChild = node.payload;
+ }
+ if (node.payload2 != null && component.props.has('value') && !component.props.get('value').required) {
+ props.set('value', node.payload2);
+ }
+
+ // `fill` in a stack context → wrap in StackItem.
+ const needsFillWrap = context.inStack && props.get('__fill') === true;
+
+ // Tab value synthesis inside TabList.
+ if (component.name === 'Tab' && !props.has('value')) {
+ props.set('value', slugify(node.payload || node.name));
+ }
+
+ this.scaffoldState(node, component, props);
+
+ // Trigger binding: opens=#id → onClick TODO.
+ const opens = props.get('__opens');
+ props.delete('__opens');
+ props.delete('__fill');
+ if (opens) {
+ const target = opens.idref || opens;
+ const handler = component.props.has('onClick') ? 'onClick' : 'clickAction';
+ props.set(handler, {__expr: `() => {/* TODO(xle): open #${target.idref ?? target} */}`});
+ }
+
+ // Slots → element-valued props (keys collected first so required-prop
+ // fill knows they're already satisfied).
+ const slotKeys = new Set(node.bound.slots.map(s => s.key));
+ this.fillRequired(node, component, props, slotKeys);
+
+ const slotEntries = [];
+ for (const slot of node.bound.slots) {
+ slotEntries.push([slot.key, this.emitSlotValue(slot, depth + 1)]);
+ }
+
+ // Structural routing.
+ let children = node.children;
+ if (component.name === 'Layout') {
+ const routed = this.routeLayoutChildren(node, props, slotEntries, depth);
+ children = routed;
+ } else if (component.name === 'Table') {
+ children = this.partitionTableChildren(node);
+ }
+
+ const childContext = {
+ inStack: component.name === 'VStack' || component.name === 'HStack',
+ };
+
+ // Mark fill-flagged children before emitting them.
+ for (const child of children) {
+ if (child.kind === 'node' && child.bound) {
+ const fillIdx = child.attrs.findIndex(a => a.kind === 'flag' && a.key === 'fill');
+ if (fillIdx !== -1 && childContext.inStack) {
+ child.bound.props.set('__fill', true);
+ child.bound.props.delete('fill');
+ }
+ }
+ }
+
+ const bodyLines = [];
+ if (node.hint) bodyLines.push(...this.emitHint(node.hint, depth + 1));
+ if (textChild != null) bodyLines.push(`${INDENT.repeat(depth + 1)}${textChild}`);
+ bodyLines.push(...this.emitItems(children, depth + 1, childContext));
+
+ // Required children with nothing to render → placeholder text.
+ const childrenProp = component.props.get('children');
+ if (bodyLines.length === 0 && childrenProp?.required) {
+ bodyLines.push(`${INDENT.repeat(depth + 1)}${node.payload || component.name}`);
+ }
+
+ const lines = this.renderTag(component, props, slotEntries, bodyLines, depth);
+ if (needsFillWrap) {
+ const stackItem = this.requireComponent('StackItem');
+ if (stackItem) {
+ return [
+ `${pad}<${stackItem.exportName} size="fill">`,
+ ...lines.map(l => INDENT + l),
+ `${pad}</${stackItem.exportName}>`,
+ ];
+ }
+ }
+ return lines;
+ }
+
+ renderTag(component, props, slotEntries, bodyLines, depth) {
+ const pad = INDENT.repeat(depth);
+ const propTexts = [...props.entries()].map(([k, v]) => this.propText(k, v));
+ const slotTexts = slotEntries.map(([key, valueLines]) => ({key, valueLines}));
+ const tag = component.exportName;
+
+ const open = [];
+ const simple = slotTexts.length === 0 && propTexts.join(' ').length <= 60;
+ if (simple) {
+ const attrs = propTexts.length > 0 ? ' ' + propTexts.join(' ') : '';
+ if (bodyLines.length === 0) return [`${pad}<${tag}${attrs} />`];
+ open.push(`${pad}<${tag}${attrs}>`);
+ } else {
+ open.push(`${pad}<${tag}`);
+ for (const text of propTexts) open.push(`${pad}${INDENT}${text}`);
+ for (const {key, valueLines} of slotTexts) {
+ open.push(`${pad}${INDENT}${key}={`);
+ open.push(...valueLines.map(l => `${pad}${INDENT}${INDENT}${l.trimStart() === l ? l : l}`));
+ open.push(`${pad}${INDENT}}`);
+ }
+ if (bodyLines.length === 0) {
+ open.push(`${pad}/>`);
+ return open;
+ }
+ open.push(`${pad}>`);
+ }
+ return [...open, ...bodyLines, `${pad}</${tag}>`];
+ }
+
+ emitSlotValue(slot, _depth) {
+ const value = slot.value;
+ if (value == null) {
+ return [`${INDENT.repeat(0)}null /* TODO(xle): @${slot.key} */`];
+ }
+ if (typeof value === 'string') {
+ const text = this.requireComponent('Text');
+ return [text ? `<${text.exportName}>${value}</${text.exportName}>` : `<>${value}</>`];
+ }
+ if (value.hint) {
+ return [
+ '<>',
+ ...this.emitHint(value.hint, 1).map(l => l.trimStart()).map(l => INDENT + l),
+ '</>',
+ ];
+ }
+ if (value.idref) {
+ return [`null /* TODO(xle): reference #${value.idref} */`];
+ }
+ if (value.subexpr) {
+ const lines = this.emitItems(value.subexpr, 0, {});
+ if (value.subexpr.length > 1) return ['<>', ...lines.map(l => INDENT + l), '</>'];
+ return lines;
+ }
+ return ['null'];
+ }
+
+ emitHint(hint, depth) {
+ const pad = INDENT.repeat(depth);
+ if (hint.block) {
+ const key = hint.block.name;
+ const mod = this.blockModules.get(key) || this.blockModules.get(key.toLowerCase());
+ if (mod) {
+ const name = this.referenceBlock(key, mod);
+ if (name) return [`${pad}<${name} />`];
+ }
+ // Source not available (e.g. browser, or unreadable) → pointer marker.
+ this.todos.push(`reference block ${hint.block.name}`);
+ const flags = hint.flags.length > 0 ? ` (+${hint.flags.join(' +')})` : '';
+ const arg = hint.arg ? `:${hint.arg}` : '';
+ return [
+ `${pad}{/* TODO(xle): content block '${hint.block.name}'${flags}${arg} — scaffold it with: astryx template ${hint.block.name} */}`,
+ ];
+ }
+ this.todos.push(`unresolved hint {${hint.name}}`);
+ return [`${pad}{/* TODO(xle): content '{${hint.name}}' (no matching block) */}`];
+ }
+
+ /**
+ * Register a referenced block (import-mode app component, or splice-mode
+ * template block co-defined once) and return the JSX component name to use.
+ */
+ referenceBlock(key, mod) {
+ if (this.splicedBlocks.has(key)) return this.splicedBlocks.get(key);
+
+ if (mod.mode === 'import') {
+ this.addNamedImport(mod.importPath, mod.componentName);
+ this.componentsUsed.add(mod.componentName);
+ this.splicedBlocks.set(key, mod.componentName);
+ return mod.componentName;
+ }
+
+ // splice mode — prepare from raw source, co-define, hoist imports.
+ const prepared = prepareSpliceModule(mod.source, mod.componentName);
+ if (!prepared) return null;
+ // Avoid name collisions with the generated component or another block.
+ let name = prepared.componentName;
+ if (name === this.componentName || [...this.splicedBlocks.values()].includes(name)) {
+ name = `${name}Block`;
+ }
+ const body = name === prepared.componentName
+ ? prepared.body
+ : prepared.body.replace(
+ new RegExp(`\\bfunction ${prepared.componentName}\\b`),
+ `function ${name}`,
+ );
+ mergeImports(this.imports, prepared.imports);
+ this.blockDefs.push(body);
+ this.componentsUsed.add(name);
+ this.splicedBlocks.set(key, name);
+ return name;
+ }
+
+ routeLayoutChildren(node, props, slotEntries, depth) {
+ const family = {
+ LayoutHeader: 'header',
+ LayoutContent: 'content',
+ LayoutFooter: 'footer',
+ };
+ const assigned = new Set(slotEntries.map(([k]) => k));
+ const loose = [];
+ let panelCount = 0;
+ for (const child of node.children) {
+ const childName = child.bound?.component?.name;
+ let slotName = family[childName];
+ if (childName === 'LayoutPanel') {
+ slotName = panelCount === 0 ? 'start' : 'end';
+ panelCount++;
+ }
+ if (slotName && !assigned.has(slotName)) {
+ assigned.add(slotName);
+ slotEntries.push([slotName, this.emitItems([child], 0, {})]);
+ } else {
+ loose.push(child);
+ }
+ }
+ // Loose children auto-wrap into an implicit LayoutContent slot.
+ if (loose.length > 0 && !assigned.has('content')) {
+ const lc = this.requireComponent('LayoutContent');
+ const inner = this.emitItems(loose, 1, {});
+ slotEntries.push(['content', [`<${lc.exportName}>`, ...inner, `</${lc.exportName}>`]]);
+ } else if (loose.length > 0) {
+ this.todos.push('Layout had extra children but content was already assigned');
+ }
+ void props; void depth;
+ return [];
+ }
+
+ /** Expand groups/repeats into a flat node list (clones carry repeat=null). */
+ flattenItems(items) {
+ const out = [];
+ for (const item of items) {
+ const count = item.repeat || 1;
+ for (let i = 1; i <= count; i++) {
+ const clone = count > 1 ? cloneItem(item) : item;
+ if (count > 1) {
+ clone.repeat = null;
+ substituteCounter(clone, i);
+ }
+ if (clone.kind === 'group') out.push(...this.flattenItems(clone.children));
+ else out.push(clone);
+ }
+ }
+ return out;
+ }
+
+ partitionTableChildren(node) {
+ const flat = this.flattenItems(node.children);
+ const rows = flat.filter(c => c.kind === 'node' && c.bound?.component?.name === 'TableRow');
+ if (rows.length === 0 || rows.length !== flat.length) return node.children;
+ const isHeaderRow = (row) => {
+ const cells = this.flattenItems(row.children);
+ return cells.length > 0 && cells.every(c => c.bound?.component?.name === 'TableHeaderCell');
+ };
+ const headerRows = rows.filter(isHeaderRow);
+ const bodyRows = rows.filter(r => !isHeaderRow(r));
+ const wrap = (name, rowNodes) => {
+ const comp = this.requireComponent(name);
+ const wrapper = {
+ kind: 'node', name, id: null, enumMods: [], payload: null, payload2: null,
+ attrs: [], slots: [], hint: null, repeat: null, selected: false,
+ children: rowNodes, line: node.line, col: node.col,
+ bound: {component: comp, props: new Map(), slots: [], stray: []},
+ };
+ return wrapper;
+ };
+ const out = [];
+ if (headerRows.length > 0) out.push(wrap('TableHeader', headerRows));
+ if (bodyRows.length > 0) out.push(wrap('TableBody', bodyRows));
+ return out;
+ }
+}
+
+/**
+ * Expand a validated document into a complete TSX module.
+ *
+ * @param {{roots: any[], overlays: any[]}} doc
+ * @param {object} registry
+ * @param {{componentName?: string}} [options]
+ * @returns {{code: string, componentsUsed: string[], states: number, todos: string[]}}
+ */
+export function expand(doc, registry, options = {}) {
+ const emitter = new Emitter(registry, options);
+
+ const rootLines = emitter.emitItems(doc.roots, 2, {});
+ const overlayLines = doc.overlays.length > 0
+ ? [
+ `${INDENT.repeat(2)}{/* overlays — wire open state to the matching opens=#id trigger */}`,
+ ...emitter.emitItems(doc.overlays, 2, {}),
+ ]
+ : [];
+
+ const needsFragment = doc.roots.length + (doc.overlays.length > 0 ? 1 : 0) > 1
+ || doc.roots.length > 1
+ || (doc.overlays.length > 0);
+
+ const body = [];
+ if (needsFragment) {
+ body.push(`${INDENT.repeat(1)}return (`, `${INDENT.repeat(2)}<>`);
+ body.push(...[...rootLines, ...overlayLines].map(l => INDENT + l));
+ body.push(`${INDENT.repeat(2)}</>`, `${INDENT.repeat(1)});`);
+ } else {
+ body.push(`${INDENT.repeat(1)}return (`);
+ body.push(...rootLines);
+ body.push(`${INDENT.repeat(1)});`);
+ }
+
+ // useState is just another named import from 'react' so it merges with any
+ // hooks a spliced block brought in (e.g. a Table block's useState).
+ if (emitter.states.length > 0) emitter.addNamedImport('react', 'useState');
+
+ const importLines = [];
+ const sortedImports = [...emitter.imports.entries()].sort(([a], [b]) => a.localeCompare(b));
+ for (const [importPath, entry] of sortedImports) {
+ importLines.push(renderImport(importPath, entry));
+ }
+
+ const stateLines = emitter.states.map(
+ s => `${INDENT}const [${s.name}, ${s.setter}] = useState(${s.initial});`,
+ );
+
+ // Co-defined template blocks live between imports and the page component.
+ const blockSection = emitter.blockDefs.length > 0
+ ? ['', ...emitter.blockDefs.flatMap(b => [b, ''])]
+ : [];
+
+ const code = [
+ `// Generated by \`astryx layout expand\` — this file is the artifact; edit freely.`,
+ ...importLines,
+ ...blockSection,
+ '',
+ `export default function ${emitter.componentName}() {`,
+ ...stateLines,
+ ...body,
+ '}',
+ '',
+ ].join('\n');
+
+ return {
+ code,
+ componentsUsed: [...emitter.componentsUsed].sort(),
+ states: emitter.states.length,
+ todos: emitter.todos,
+ };
+}
diff --git a/packages/cli/src/lib/xle/parse.mjs b/packages/cli/src/lib/xle/parse.mjs
new file mode 100644
index 0000000000..78c15333c3
--- /dev/null
+++ b/packages/cli/src/lib/xle/parse.mjs
@@ -0,0 +1,581 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file XLE/XLO parser — two surfaces, one AST.
+ *
+ * Compact (XLE): A[cp6 @topNav=TN] > L > LC > S[p6] > (C{card-callout}*4) + T
+ * Outline (XLO): indentation for nesting, `slot:` lines, `repeat N:` blocks.
+ *
+ * Both surfaces produce the same AST and share the attribute-token
+ * grammar, so the validator and expander never know which dialect the
+ * author wrote. Whitespace is insignificant in compact form; `^` climb
+ * is rejected with a correction (groups are the documented way).
+ *
+ * @input expression source string
+ * @output parse(source) → {roots, overlays, form}
+ * @position lib/xle — pure (no I/O, no registry); binding happens in validate.mjs
+ */
+
+export class XLEParseError extends Error {
+ constructor(message, line, col) {
+ super(message);
+ this.name = 'XLEParseError';
+ this.line = line;
+ this.col = col;
+ }
+}
+
+/** Keys that expand to full prop names before validation. */
+export const KEY_ALIASES = {
+ p: 'padding', pad: 'padding', g: 'gap', c: 'columns', cols: 'columns',
+ w: 'width', h: 'height', cp: 'contentPadding', mw: 'maxWidth',
+ mh: 'minHeight', rg: 'rowGap', cg: 'columnGap', t: 'type', sz: 'size',
+ v: 'variant', dir: 'direction', dv: 'dividers',
+ // Axis-neutral alignment — resolved per component in validate.mjs.
+ j: '__mainAxis', a: '__crossAxis', justify: '__mainAxis', align: '__crossAxis',
+};
+
+/** Fused shorthand letters (`p6`, `g4`, `cp2`…) — letter must be a KEY_ALIAS. */
+const FUSED = new Set(['p', 'g', 'c', 'w', 'h', 'cp', 'mw', 'mh', 'rg', 'cg']);
+
+export function makeNode(name, line, col) {
+ return {
+ kind: 'node',
+ name,
+ id: null,
+ enumMods: [],
+ payload: null,
+ payload2: null,
+ attrs: [],
+ slots: [],
+ hint: null,
+ repeat: null,
+ selected: false,
+ children: [],
+ line,
+ col,
+ };
+}
+
+function makeGroup(line, col) {
+ return {kind: 'group', repeat: null, children: [], line, col};
+}
+
+// ─── shared low-level helpers ──────────────────────────────────────────────
+
+const isIdentStart = (ch) => /[A-Za-z]/.test(ch);
+const isIdent = (ch) => /[A-Za-z0-9_-]/.test(ch);
+
+/**
+ * Split a string into tokens at depth-0 whitespace, where (), [], {} and
+ * quotes raise depth. Used for attr blocks and outline lines.
+ */
+function tokenize(str, line, startCol) {
+ const tokens = [];
+ let i = 0;
+ while (i < str.length) {
+ while (i < str.length && /\s/.test(str[i])) i++;
+ if (i >= str.length) break;
+ const start = i;
+ let depth = 0;
+ let quote = null;
+ while (i < str.length) {
+ const ch = str[i];
+ if (quote) {
+ if (ch === quote) quote = null;
+ } else if (ch === '"' || ch === "'") {
+ quote = ch;
+ } else if ('([{'.includes(ch)) {
+ depth++;
+ } else if (')]}'.includes(ch)) {
+ depth--;
+ } else if (/\s/.test(ch) && depth === 0) {
+ break;
+ }
+ i++;
+ }
+ if (quote) throw new XLEParseError(`Unterminated ${quote} string`, line, startCol + start + 1);
+ if (depth > 0) throw new XLEParseError('Unbalanced brackets in attribute list', line, startCol + start + 1);
+ tokens.push({text: str.slice(start, i), col: startCol + start + 1});
+ }
+ return tokens;
+}
+
+/** Parse a scalar/object/list attr value string into a JS value. */
+export function parseValue(raw) {
+ const s = raw.trim();
+ if (/^(['"]).*\1$/.test(s)) return s.slice(1, -1);
+ if (/^-?\d+(\.\d+)?$/.test(s)) return Number(s);
+ if (s === 'true') return true;
+ if (s === 'false') return false;
+ if (s.startsWith('#')) return {idref: s.slice(1)};
+ if (s.startsWith('{') && s.endsWith('}')) {
+ const obj = {};
+ for (const part of splitTop(s.slice(1, -1), ',')) {
+ const idx = part.indexOf(':');
+ if (idx === -1) obj[part.trim()] = true;
+ else obj[part.slice(0, idx).trim()] = parseValue(part.slice(idx + 1));
+ }
+ return obj;
+ }
+ if (s.startsWith('[') && s.endsWith(']')) {
+ return splitTop(s.slice(1, -1), ',').map(parseValue);
+ }
+ if (s.includes(',')) return splitTop(s, ',').map(parseValue);
+ return s; // bare ident — enum string
+}
+
+/** Split on a separator at bracket/quote depth 0. */
+function splitTop(str, sep) {
+ const parts = [];
+ let depth = 0;
+ let quote = null;
+ let cur = '';
+ for (const ch of str) {
+ if (quote) {
+ if (ch === quote) quote = null;
+ cur += ch;
+ } else if (ch === '"' || ch === "'") {
+ quote = ch; cur += ch;
+ } else if ('([{'.includes(ch)) {
+ depth++; cur += ch;
+ } else if (')]}'.includes(ch)) {
+ depth--; cur += ch;
+ } else if (ch === sep && depth === 0) {
+ parts.push(cur); cur = '';
+ } else {
+ cur += ch;
+ }
+ }
+ if (cur.trim() !== '') parts.push(cur);
+ return parts.map(p => p.trim()).filter(Boolean);
+}
+
+/** Parse `{name +flag +flag2 :arg}` hint body (without braces). */
+function parseHintBody(body, line, col) {
+ const m = body.trim().match(/^([a-z0-9][a-z0-9-]*)((?:\s*\+[a-z0-9-]+)*)(?:\s*:(.*))?$/);
+ if (!m) {
+ throw new XLEParseError(
+ `'{${body}}' is not a block reference — braces take a kebab-case block name ` +
+ `(e.g. {card-callout}); for text content use a quoted payload: Tx"${body}"`,
+ line, col,
+ );
+ }
+ return {
+ name: m[1],
+ flags: (m[2] || '').split('+').map(f => f.trim()).filter(Boolean),
+ arg: m[3] != null ? m[3].trim() : null,
+ };
+}
+
+/**
+ * Interpret one attribute token. Returns an attr record or mutates node
+ * for special tokens (slots are returned as {kind:'slot'} records too).
+ */
+function parseAttrToken(token, line) {
+ const {text, col} = token;
+
+ if (text.startsWith('@')) {
+ const eq = text.indexOf('=');
+ if (eq === -1) {
+ return {kind: 'slot', key: text.slice(1), value: null, line, col};
+ }
+ const name = text.slice(1, eq);
+ const rest = text.slice(eq + 1);
+ let value;
+ if (rest.startsWith('(') && rest.endsWith(')')) {
+ value = {subexpr: parseCompactSiblings(new CompactStream(rest.slice(1, -1), line, col + eq + 2))};
+ } else if (/^(['"]).*\1$/.test(rest)) {
+ value = rest.slice(1, -1);
+ } else if (rest.startsWith('{') && rest.endsWith('}')) {
+ value = {hint: parseHintBody(rest.slice(1, -1), line, col)};
+ } else if (rest.startsWith('#')) {
+ value = {idref: rest.slice(1)};
+ } else {
+ value = {subexpr: parseCompactSiblings(new CompactStream(rest, line, col + eq + 2))};
+ }
+ return {kind: 'slot', key: name, value, line, col};
+ }
+
+ if (text.startsWith('!') && text.length > 1) {
+ return {kind: 'neg', key: text.slice(1), line, col};
+ }
+
+ // key=value (split at first depth-0 '=')
+ let depth = 0;
+ let quote = null;
+ for (let i = 0; i < text.length; i++) {
+ const ch = text[i];
+ if (quote) { if (ch === quote) quote = null; continue; }
+ if (ch === '"' || ch === "'") quote = ch;
+ else if ('([{'.includes(ch)) depth++;
+ else if (')]}'.includes(ch)) depth--;
+ else if (ch === '=' && depth === 0) {
+ const rawKey = text.slice(0, i);
+ if (!/^[A-Za-z][A-Za-z0-9.]*$/.test(rawKey)) {
+ throw new XLEParseError(`Invalid attribute key '${rawKey}'`, line, col);
+ }
+ return {kind: 'kv', key: rawKey, value: parseValue(text.slice(i + 1)), raw: text, line, col};
+ }
+ }
+
+ // fused shorthand: letters + number (p6, g0.5, cp2)
+ const fused = text.match(/^([a-z]{1,2})(\d+(?:\.\d+)?)$/);
+ if (fused && FUSED.has(fused[1])) {
+ return {kind: 'kv', key: fused[1], value: Number(fused[2]), raw: text, line, col};
+ }
+ // fused object: letters + {…} (c{min:340})
+ const fusedObj = text.match(/^([a-z]{1,2})(\{.*\})$/);
+ if (fusedObj && FUSED.has(fusedObj[1])) {
+ return {kind: 'kv', key: fusedObj[1], value: parseValue(fusedObj[2]), raw: text, line, col};
+ }
+
+ if (/^[A-Za-z][A-Za-z0-9-]*$/.test(text)) {
+ return {kind: 'flag', key: text, line, col};
+ }
+
+ throw new XLEParseError(`Cannot parse attribute '${text}'`, line, col);
+}
+
+// ─── compact (XLE) surface ─────────────────────────────────────────────────
+
+class CompactStream {
+ constructor(src, line = 1, col = 1) {
+ this.src = src;
+ this.i = 0;
+ this.baseLine = line;
+ this.baseCol = col;
+ }
+ pos() {
+ const before = this.src.slice(0, this.i);
+ const lines = before.split('\n');
+ const line = this.baseLine + lines.length - 1;
+ const col = (lines.length === 1 ? this.baseCol : 1) + lines[lines.length - 1].length;
+ return {line, col};
+ }
+ peek(offset = 0) { return this.src[this.i + offset]; }
+ next() { return this.src[this.i++]; }
+ eof() { return this.i >= this.src.length; }
+ skipWs() { while (!this.eof() && /\s/.test(this.peek())) this.i++; }
+ error(message) {
+ const {line, col} = this.pos();
+ throw new XLEParseError(message, line, col);
+ }
+ /** Consume through the matching close bracket; returns inner text. */
+ readBalanced(open, close) {
+ const startPos = this.pos();
+ if (this.peek() !== open) this.error(`Expected '${open}'`);
+ this.next();
+ const start = this.i;
+ let depth = 1;
+ let quote = null;
+ while (!this.eof()) {
+ const ch = this.next();
+ if (quote) { if (ch === quote) quote = null; continue; }
+ if (ch === '"' || ch === "'") quote = ch;
+ else if (ch === open && open !== close) depth++;
+ else if (ch === close) {
+ depth--;
+ if (depth === 0) return this.src.slice(start, this.i - 1);
+ }
+ }
+ throw new XLEParseError(`Unclosed '${open}'`, startPos.line, startPos.col);
+ }
+ readString() {
+ const quote = this.next();
+ const start = this.i;
+ while (!this.eof() && this.peek() !== quote) this.next();
+ if (this.eof()) this.error('Unterminated string');
+ const text = this.src.slice(start, this.i);
+ this.next();
+ return text;
+ }
+}
+
+function parseCompactNode(s) {
+ const {line, col} = s.pos();
+ let name = '';
+ // A term may start with `{block}` — an anonymous block reference with no
+ // wrapping element (e.g. a domain component placed directly in a Grid).
+ if (s.peek() !== '{') {
+ if (!isIdentStart(s.peek())) s.error(`Expected a component name, found '${s.peek() ?? 'end of input'}'`);
+ while (!s.eof() && /[A-Za-z0-9]/.test(s.peek())) name += s.next();
+ }
+ const node = makeNode(name || null, line, col);
+
+ // postfix pieces in any sensible order: #id .mod "payload" [attrs] {hint} *N !
+ for (;;) {
+ const ch = s.peek();
+ if (ch === '#') {
+ s.next();
+ let id = '';
+ while (!s.eof() && isIdent(s.peek())) id += s.next();
+ if (!id) s.error('Expected an id after #');
+ node.id = id;
+ } else if (ch === '.') {
+ s.next();
+ let mod = '';
+ while (!s.eof() && /[a-z0-9-]/.test(s.peek())) mod += s.next();
+ if (!mod) s.error("Expected an enum value after '.'");
+ node.enumMods.push(mod);
+ } else if (ch === '"' || ch === "'") {
+ const text = s.readString();
+ if (node.payload == null) node.payload = text;
+ else node.payload2 = text;
+ } else if (ch === ':' && (s.peek(1) === '"' || s.peek(1) === "'")) {
+ s.next();
+ node.payload2 = s.readString();
+ } else if (ch === '[') {
+ const {line: aLine} = s.pos();
+ const body = s.readBalanced('[', ']');
+ for (const token of tokenize(body, aLine, 0)) {
+ const attr = parseAttrToken(token, aLine);
+ if (attr.kind === 'slot') node.slots.push(attr);
+ else node.attrs.push(attr);
+ }
+ } else if (ch === '{') {
+ const {line: hLine, col: hCol} = s.pos();
+ const body = s.readBalanced('{', '}');
+ node.hint = parseHintBody(body, hLine, hCol);
+ } else if (ch === '*') {
+ s.next();
+ let n = '';
+ while (!s.eof() && /\d/.test(s.peek())) n += s.next();
+ if (!n) s.error("Expected a count after '*'");
+ node.repeat = Number(n);
+ } else if (ch === '!') {
+ s.next();
+ node.selected = true;
+ } else {
+ break;
+ }
+ }
+
+ s.skipWs();
+ if (s.peek() === '>') {
+ s.next();
+ node.children = parseCompactSiblings(s);
+ }
+ return node;
+}
+
+function parseCompactTerm(s) {
+ s.skipWs();
+ if (s.peek() === '(') {
+ const {line, col} = s.pos();
+ const body = s.readBalanced('(', ')');
+ const group = makeGroup(line, col);
+ group.children = parseCompactSiblings(new CompactStream(body, line, col + 1));
+ s.skipWs();
+ if (s.peek() === '*') {
+ s.next();
+ let n = '';
+ while (!s.eof() && /\d/.test(s.peek())) n += s.next();
+ if (!n) s.error("Expected a count after '*'");
+ group.repeat = Number(n);
+ }
+ s.skipWs();
+ if (s.peek() === '>') {
+ s.next();
+ const children = parseCompactSiblings(s);
+ for (const child of group.children) {
+ if (child.kind === 'node') child.children.push(...children.map(structuredCloneNode));
+ }
+ }
+ return group;
+ }
+ return parseCompactNode(s);
+}
+
+function structuredCloneNode(node) {
+ return JSON.parse(JSON.stringify(node));
+}
+
+function parseCompactSiblings(s) {
+ const terms = [];
+ for (;;) {
+ s.skipWs();
+ if (s.eof()) break;
+ if (s.peek() === '^') {
+ s.error("'^' climb-up is not supported — group siblings with (...) instead");
+ }
+ terms.push(parseCompactTerm(s));
+ s.skipWs();
+ if (s.peek() === '^') {
+ s.error("'^' climb-up is not supported — group siblings with (...) instead");
+ }
+ if (s.peek() === '+') { s.next(); continue; }
+ break;
+ }
+ return terms;
+}
+
+export function parseCompact(source) {
+ const parts = source.split(/;;/);
+ const main = new CompactStream(parts[0]);
+ const roots = parseCompactSiblings(main);
+ main.skipWs();
+ if (!main.eof()) main.error(`Unexpected '${main.peek()}'`);
+ const overlays = [];
+ for (const part of parts.slice(1)) {
+ const s = new CompactStream(part);
+ overlays.push(...parseCompactSiblings(s));
+ s.skipWs();
+ if (!s.eof()) s.error(`Unexpected '${s.peek()}'`);
+ }
+ return {roots, overlays, form: 'compact'};
+}
+
+// ─── outline (XLO) surface ─────────────────────────────────────────────────
+
+/** Parse one outline line's node chain: `Layout > LayoutContent pad=0 !scroll`. */
+function parseOutlineChain(text, line) {
+ const segments = splitTop(text, '>');
+ let head = null;
+ let tail = null;
+ for (const segment of segments) {
+ const node = parseOutlineNodeSegment(segment, line);
+ if (!head) head = node;
+ else tail.children.push(node);
+ tail = node;
+ }
+ return {head, tail};
+}
+
+function parseOutlineNodeSegment(segment, line) {
+ const tokens = tokenize(segment, line, 0);
+ if (tokens.length === 0) throw new XLEParseError('Empty node', line, 1);
+ const first = tokens[0];
+ // Anonymous block reference: a line that starts with `{block}`.
+ if (first.text.startsWith('{') && first.text.endsWith('}')) {
+ const node = makeNode(null, line, first.col);
+ node.hint = parseHintBody(first.text.slice(1, -1), line, first.col);
+ for (const token of tokens.slice(1)) {
+ if (/^[x*]\d+$/.test(token.text)) node.repeat = Number(token.text.slice(1));
+ }
+ return node;
+ }
+ const m = first.text.match(/^([A-Za-z][A-Za-z0-9]*)(#[A-Za-z0-9_-]+)?((?:\.[a-z0-9-]+)*)$/);
+ if (!m) {
+ throw new XLEParseError(
+ `Expected a component name, found '${first.text}'`, line, first.col,
+ );
+ }
+ const node = makeNode(m[1], line, first.col);
+ if (m[2]) node.id = m[2].slice(1);
+ if (m[3]) node.enumMods = m[3].split('.').filter(Boolean);
+
+ for (const token of tokens.slice(1)) {
+ const t = token.text;
+ if (/^(['"]).*\1$/.test(t)) {
+ if (node.payload == null) node.payload = t.slice(1, -1);
+ else node.payload2 = t.slice(1, -1);
+ } else if (/^:(['"]).*\1$/.test(t)) {
+ node.payload2 = t.slice(2, -1);
+ } else if (/^[x*]\d+$/.test(t)) {
+ node.repeat = Number(t.slice(1));
+ } else if (t === '!') {
+ node.selected = true;
+ } else if (t.startsWith('{') && t.endsWith('}')) {
+ node.hint = parseHintBody(t.slice(1, -1), line, token.col);
+ } else {
+ const attr = parseAttrToken(token, line);
+ if (attr.kind === 'slot') node.slots.push(attr);
+ else node.attrs.push(attr);
+ }
+ }
+ return node;
+}
+
+export function parseOutline(source) {
+ const roots = [];
+ const overlays = [];
+ // Stack frames: {indent, container: array, node|null}
+ const stack = [{indent: -1, container: roots, node: null}];
+ let inOverlays = false;
+
+ const lines = source.split('\n');
+ for (let li = 0; li < lines.length; li++) {
+ const raw = lines[li];
+ const lineNo = li + 1;
+ if (raw.trim() === '' || raw.trim().startsWith('#') || raw.trim().startsWith('//')) continue;
+ const indent = raw.match(/^[ \t]*/)[0].replace(/\t/g, ' ').length;
+ const text = raw.trim();
+
+ if (text === 'overlays:') {
+ inOverlays = true;
+ stack.length = 1;
+ continue;
+ }
+
+ while (stack.length > 1 && indent <= stack[stack.length - 1].indent) stack.pop();
+ const parent = stack[stack.length - 1];
+ const container = parent === stack[0] && inOverlays ? overlays : parent.container;
+
+ const repeatMatch = text.match(/^repeat\s+(\d+):$/);
+ if (repeatMatch) {
+ const group = makeGroup(lineNo, indent + 1);
+ group.repeat = Number(repeatMatch[1]);
+ container.push(group);
+ stack.push({indent, container: group.children, node: null});
+ continue;
+ }
+
+ // Single `.*` capture (no `\s+(.*)` overlap) keeps this linear — the
+ // inline value, if any, is trimmed in code rather than by the regex.
+ const slotMatch = text.match(/^@?([a-z][A-Za-z0-9]*):(.*)$/);
+ if (slotMatch && !text.startsWith('http')) {
+ if (!parent.node) {
+ throw new XLEParseError(
+ `Slot '${slotMatch[1]}:' has no parent component`, lineNo, indent + 1,
+ );
+ }
+ const slot = {kind: 'slot', key: slotMatch[1], value: {subexpr: []}, line: lineNo, col: indent + 1};
+ parent.node.slots.push(slot);
+ const inline = slotMatch[2].trim();
+ if (inline) {
+ const {head, tail} = parseOutlineChain(inline, lineNo);
+ slot.value.subexpr.push(head);
+ stack.push({indent, container: tail.children, node: tail});
+ } else {
+ stack.push({indent, container: slot.value.subexpr, node: null});
+ }
+ continue;
+ }
+
+ const {head, tail} = parseOutlineChain(text, lineNo);
+ container.push(head);
+ stack.push({indent, container: tail.children, node: tail});
+ }
+
+ return {roots, overlays, form: 'outline'};
+}
+
+// ─── entry point ───────────────────────────────────────────────────────────
+
+/**
+ * Detect which surface the source uses. Multi-line input is outline
+ * unless every line break sits inside an operator chain (trailing
+ * `>`/`+`/`;;` or unclosed brackets), which is multi-line compact.
+ */
+export function detectForm(source) {
+ const lines = source.split('\n').map(l => l.trim()).filter(l => l !== '' && !l.startsWith('#') && !l.startsWith('//'));
+ if (lines.length <= 1) return 'compact';
+ if (lines.some(l => /^(overlays:|repeat\s+\d+:)/.test(l))) return 'outline';
+ for (let i = 0; i < lines.length - 1; i++) {
+ const endsOpen = /[>+(]$/.test(lines[i]) || /;;$/.test(lines[i]);
+ const startsOp = /^[>+)]/.test(lines[i + 1]) || /^;;/.test(lines[i + 1]);
+ if (!endsOpen && !startsOp) return 'outline';
+ }
+ return 'compact';
+}
+
+/**
+ * Parse an XLE/XLO source string.
+ * @param {string} source
+ * @param {{form?: 'compact'|'outline'|'auto'}} [options]
+ */
+export function parse(source, {form = 'auto'} = {}) {
+ const resolved = form === 'auto' ? detectForm(source) : form;
+ return resolved === 'outline' ? parseOutline(source) : parseCompact(source);
+}
diff --git a/packages/cli/src/lib/xle/print.mjs b/packages/cli/src/lib/xle/print.mjs
new file mode 100644
index 0000000000..90c08556c0
--- /dev/null
+++ b/packages/cli/src/lib/xle/print.mjs
@@ -0,0 +1,174 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file XLE canonical printers — AST → compact (XLE) or outline (XLO) text.
+ *
+ * Used by `astryx layout check --form …` so either party (agent or human)
+ * can request the other surface, and by round-trip conformance tests.
+ * Printing is best-effort canonical: spelling variants the lexer
+ * normalized are emitted in canonical form.
+ *
+ * @input parse() AST (binding not required)
+ * @output toCompact(doc) / toOutline(doc)
+ * @position lib/xle — inverse of parse.mjs
+ */
+
+function valueText(value) {
+ if (typeof value === 'string') return /[\s,'"]/.test(value) ? `'${value}'` : value;
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);
+ if (value && value.idref) return `#${value.idref}`;
+ if (Array.isArray(value)) return `[${value.map(valueText).join(',')}]`;
+ if (typeof value === 'object' && value !== null) {
+ return `{${Object.entries(value)
+ .map(([k, v]) => (v === true ? k : `${k}:${valueText(v)}`))
+ .join(',')}}`;
+ }
+ return String(value);
+}
+
+function hintText(hint) {
+ let out = hint.name;
+ for (const flag of hint.flags || []) out += ` +${flag}`;
+ if (hint.arg) out += `:${hint.arg}`;
+ return `{${out}}`;
+}
+
+function attrTokens(node) {
+ const tokens = [];
+ for (const attr of node.attrs) {
+ if (attr.kind === 'kv') tokens.push(`${attr.key}=${valueText(attr.value)}`);
+ else if (attr.kind === 'flag') tokens.push(attr.key);
+ else if (attr.kind === 'neg') tokens.push(`!${attr.key}`);
+ }
+ return tokens;
+}
+
+function slotTokensCompact(node) {
+ return node.slots.map(slot => {
+ if (slot.value == null) return `@${slot.key}`;
+ if (typeof slot.value === 'string') return `@${slot.key}='${slot.value}'`;
+ if (slot.value.hint) return `@${slot.key}=${hintText(slot.value.hint)}`;
+ if (slot.value.idref) return `@${slot.key}=#${slot.value.idref}`;
+ if (slot.value.subexpr) return `@${slot.key}=(${siblingsCompact(slot.value.subexpr)})`;
+ return `@${slot.key}`;
+ });
+}
+
+function nodeCompact(node) {
+ let out = node.name || '';
+ if (node.id) out += `#${node.id}`;
+ for (const mod of node.enumMods) out += `.${mod}`;
+ if (node.payload != null) out += `"${node.payload}"`;
+ if (node.payload2 != null) out += `:"${node.payload2}"`;
+ const attrs = [...attrTokens(node), ...slotTokensCompact(node)];
+ if (attrs.length > 0) out += `[${attrs.join(' ')}]`;
+ if (node.hint) out += hintText(node.hint);
+ if (node.selected) out += '!';
+ if (node.repeat) out += `*${node.repeat}`;
+ if (node.children.length > 0) {
+ const inner = siblingsCompact(node.children);
+ out += node.children.length === 1 ? ` > ${inner}` : ` > ${inner}`;
+ }
+ return out;
+}
+
+function termCompact(item) {
+ if (item.kind === 'group') {
+ let out = `(${siblingsCompact(item.children)})`;
+ if (item.repeat) out += `*${item.repeat}`;
+ return out;
+ }
+ // Multi-sibling children need grouping when this node is itself a sibling.
+ return nodeCompact(item);
+}
+
+function siblingsCompact(items) {
+ return items
+ .map((item, i) => {
+ const text = termCompact(item);
+ // `a > b + c` binds b and c to a; if a itself has a following
+ // sibling, the next `+` would rebind into a's children — wrap any
+ // non-last sibling that opens a `>` chain in a group.
+ const needsGroup =
+ i < items.length - 1 && item.kind === 'node' && item.children.length > 0;
+ return needsGroup ? `(${text})` : text;
+ })
+ .join(' + ');
+}
+
+export function toCompact(doc) {
+ let out = siblingsCompact(doc.roots);
+ for (const overlay of doc.overlays) {
+ out += ` ;; ${termCompact(overlay)}`;
+ }
+ return out;
+}
+
+// ── outline ────────────────────────────────────────────────────────────────
+
+function nodeOutlineLines(node, depth) {
+ const pad = ' '.repeat(depth);
+ let line = node.name || '';
+ if (node.id) line += `#${node.id}`;
+ for (const mod of node.enumMods) line += `.${mod}`;
+ if (node.payload != null) line += ` "${node.payload}"`;
+ if (node.payload2 != null) line += ` :"${node.payload2}"`;
+ const attrs = attrTokens(node);
+ if (attrs.length > 0) line += ' ' + attrs.join(' ');
+ if (node.hint) line += ' ' + hintText(node.hint);
+ if (node.selected) line += ' !';
+ if (node.repeat) line += ` x${node.repeat}`;
+
+ const lines = [pad + line.trimStart()];
+ for (const slot of node.slots) {
+ if (slot.value && slot.value.subexpr) {
+ if (slot.value.subexpr.length === 1 && isSimpleNode(slot.value.subexpr[0])) {
+ const sub = nodeOutlineLines(slot.value.subexpr[0], 0)[0];
+ lines.push(`${pad} ${slot.key}: ${sub}`);
+ // simple = no children, so the single line is complete
+ } else {
+ lines.push(`${pad} ${slot.key}:`);
+ for (const sub of slot.value.subexpr) lines.push(...itemOutlineLines(sub, depth + 2));
+ }
+ } else if (typeof slot.value === 'string') {
+ lines.push(`${pad} ${slot.key}: "${slot.value}"`);
+ } else if (slot.value && slot.value.hint) {
+ lines.push(`${pad} ${slot.key}: ${hintText(slot.value.hint)}`);
+ } else if (slot.value && slot.value.idref) {
+ lines.push(`${pad} ${slot.key}: #${slot.value.idref}`);
+ } else {
+ lines.push(`${pad} ${slot.key}:`);
+ }
+ }
+ for (const child of node.children) lines.push(...itemOutlineLines(child, depth + 1));
+ return lines;
+}
+
+function isSimpleNode(item) {
+ return item.kind === 'node' && item.children.length === 0 && item.slots.length === 0;
+}
+
+function itemOutlineLines(item, depth) {
+ if (item.kind === 'group') {
+ // A repeat-less group exists only to disambiguate compact-form
+ // sibling chains — indentation already does that, so inline it.
+ if (!item.repeat || item.repeat === 1) {
+ return item.children.flatMap(child => itemOutlineLines(child, depth));
+ }
+ const pad = ' '.repeat(depth);
+ const lines = [`${pad}repeat ${item.repeat}:`];
+ for (const child of item.children) lines.push(...itemOutlineLines(child, depth + 1));
+ return lines;
+ }
+ return nodeOutlineLines(item, depth);
+}
+
+export function toOutline(doc) {
+ const lines = [];
+ for (const item of doc.roots) lines.push(...itemOutlineLines(item, 0));
+ if (doc.overlays.length > 0) {
+ lines.push('', 'overlays:');
+ for (const item of doc.overlays) lines.push(...itemOutlineLines(item, 1));
+ }
+ return lines.join('\n');
+}
diff --git a/packages/cli/src/lib/xle/registry-core.mjs b/packages/cli/src/lib/xle/registry-core.mjs
new file mode 100644
index 0000000000..c52a0a708a
--- /dev/null
+++ b/packages/cli/src/lib/xle/registry-core.mjs
@@ -0,0 +1,170 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file XLE registry — pure core (no Node deps).
+ *
+ * The fs-bound builder lives in registry.mjs; everything here is
+ * environment-agnostic so it can run in the browser playground too.
+ * This holds the alias table, enum parsing, the component-entry shape,
+ * name resolution, and the serialize/hydrate pair that lets a Node
+ * build step ship a registry to the browser as plain JSON.
+ *
+ * @input doc.mjs-shaped prop arrays (from registry.mjs) or serialized JSON
+ * @output ALIAS_TABLE, parseEnumValues, toComponentEntry, resolveComponent,
+ * serializeRegistry, hydrateRegistry
+ * @position lib/xle — imported by registry.mjs (Node) and the browser barrel
+ */
+
+/**
+ * Curated alias table (from the XLE research, paste P2376666892 §2).
+ * Single letters reserved for the highest-frequency structural set.
+ * Collision policy: case-only pairs forbidden; HTML mnemonics win the
+ * Table family; form-frequency wins contested pairs (CB, NI).
+ *
+ * Aliases are validated against the discovered registry — an alias whose
+ * component doesn't exist on this branch is silently dropped.
+ */
+export const ALIAS_TABLE = {
+ // Layout core
+ A: 'AppShell', L: 'Layout', LH: 'LayoutHeader', LC: 'LayoutContent',
+ LF: 'LayoutFooter', LP: 'LayoutPanel', V: 'VStack', H: 'HStack',
+ SI: 'StackItem', G: 'Grid', GS: 'GridSpan', S: 'Section', Ctr: 'Center',
+ F: 'FormLayout', D: 'Divider', Tbar: 'Toolbar', AR: 'AspectRatio',
+ // Navigation
+ TN: 'TopNav', TNH: 'TopNavHeading', TNI: 'TopNavItem',
+ SN: 'SideNav', SNI: 'SideNavItem', SNS: 'SideNavSection', SNH: 'SideNavHeading',
+ MN: 'MobileNav', MNT: 'MobileNavToggle',
+ BC: 'Breadcrumbs', BCI: 'BreadcrumbItem',
+ TL: 'TabList', Tab: 'Tab', PG: 'Pagination',
+ SG: 'SegmentedControl', SGI: 'SegmentedControlItem',
+ // Data display
+ T: 'Table', TH: 'TableHeader', TB: 'TableBody', TF: 'TableFooter',
+ TR: 'TableRow', TC: 'TableCell', TD: 'TableCell', THC: 'TableHeaderCell',
+ UL: 'List', LI: 'ListItem', ML: 'MetadataList', MLI: 'MetadataListItem',
+ C: 'Card', CC: 'ClickableCard', ES: 'EmptyState', Bd: 'Badge',
+ SD: 'StatusDot', Av: 'Avatar', AvG: 'AvatarGroup', Tmb: 'Thumbnail',
+ Ts: 'Timestamp', OFL: 'OverflowList', Cs: 'Carousel', It: 'Item',
+ // Forms & inputs
+ Fd: 'Field', IG: 'InputGroup', IGT: 'InputGroupText',
+ TI: 'TextInput', TA: 'TextArea', NI: 'NumberInput',
+ DI: 'DateInput', DR: 'DateRangeInput', DT: 'DateTimeInput', TM: 'TimeInput',
+ FI: 'FileInput', CB: 'CheckboxInput', CL: 'CheckboxList', CLI: 'CheckboxListItem',
+ RL: 'RadioList', RLI: 'RadioListItem', SW: 'Switch', SL: 'Slider',
+ SE: 'Selector', MS: 'MultiSelector', TY: 'Typeahead', Tkz: 'Tokenizer',
+ PS: 'PowerSearch', CAL: 'Calendar',
+ // Overlay & feedback
+ Dlg: 'Dialog', DH: 'DialogHeader', AD: 'AlertDialog',
+ Po: 'Popover', HC: 'HoverCard', Tt: 'Tooltip', Bn: 'Banner', Ov: 'Overlay',
+ CM: 'ContextMenu', DM: 'DropdownMenu', MM: 'MoreMenu', CP: 'CommandPalette',
+ Col: 'Collapsible', ColG: 'CollapsibleGroup',
+ Sp: 'Spinner', PB: 'ProgressBar', Sk: 'Skeleton',
+ // Content & chat
+ Tx: 'Text', Hd: 'Heading', MD: 'Markdown', Cd: 'CodeBlock', BQ: 'Blockquote',
+ K: 'Kbd', Ic: 'Icon', Lk: 'Link', Tk: 'Token',
+ B: 'Button', IB: 'IconButton', BG: 'ButtonGroup', Tg: 'ToggleButton', TgG: 'ToggleButtonGroup',
+ ChL: 'ChatLayout', ChML: 'ChatMessageList', ChM: 'ChatMessage',
+ ChB: 'ChatMessageBubble', ChC: 'ChatComposer', ChCD: 'ChatComposerDrawer',
+ ChS: 'ChatSystemMessage', ChT: 'ChatToolCalls',
+};
+
+/** SpacingStep — the canonical spacing enum (matches the doc.mjs prose). */
+export const SPACING_STEPS = [0, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 8, 10];
+
+/**
+ * Parse enum values from a doc.mjs prop type string.
+ * "'a' | 'b' | 'c'" → ['a','b','c']; "1|2|3" → [1,2,3];
+ * "SpacingStep" → SPACING_STEPS. Mixed/non-enum types → null.
+ */
+export function parseEnumValues(type) {
+ if (!type || typeof type !== 'string') return null;
+ const t = type.trim();
+ if (t === 'SpacingStep' || /^0\|0\.5\|/.test(t.replace(/\s+/g, ''))) {
+ return SPACING_STEPS;
+ }
+ const parts = t.split('|').map(p => p.trim());
+ if (parts.length < 2) return null;
+ const values = [];
+ for (const part of parts) {
+ const str = part.match(/^'([^']*)'$/) || part.match(/^"([^"]*)"$/);
+ if (str) { values.push(str[1]); continue; }
+ if (/^\d+(\.\d+)?$/.test(part)) { values.push(Number(part)); continue; }
+ return null; // union of non-literal types (e.g. number|string) — not an enum
+ }
+ return values;
+}
+
+export function normalizeName(name) {
+ return name.replace(/^XDS/, '');
+}
+
+/**
+ * Index one doc entry's props into the registry component shape.
+ */
+export function toComponentEntry(name, props, dirName, importPath) {
+ const propMap = new Map();
+ for (const p of props || []) {
+ propMap.set(p.name, {
+ name: p.name,
+ type: p.type || '',
+ required: p.required === true,
+ enumValues: parseEnumValues(p.type),
+ isBoolean: (p.type || '').trim() === 'boolean',
+ isFunction: /^\(/.test((p.type || '').trim()),
+ isNode: /ReactNode|ReactElement/.test(p.type || ''),
+ });
+ }
+ return {name, exportName: `XDS${name}`, dirName, importPath, props: propMap};
+}
+
+/**
+ * Resolve a node name (alias, bare name, or XDS-prefixed name) to a
+ * registry component entry, or null.
+ */
+export function resolveComponent(registry, name) {
+ const viaAlias = registry.aliases.get(name);
+ if (viaAlias) return registry.components.get(viaAlias);
+ const bare = normalizeName(name);
+ return registry.components.get(bare) || null;
+}
+
+/**
+ * Serialize a built registry (with Map fields) to a plain JSON-safe object
+ * so a Node build step can ship it to the browser.
+ */
+export function serializeRegistry(registry) {
+ return {
+ components: [...registry.components.values()].map(c => ({
+ name: c.name,
+ exportName: c.exportName,
+ dirName: c.dirName,
+ importPath: c.importPath,
+ undocumented: c.undocumented || false,
+ props: [...c.props.values()],
+ })),
+ aliases: [...registry.aliases.entries()],
+ componentNames: registry.componentNames,
+ };
+}
+
+/**
+ * Hydrate a serialized registry back into the Map-bearing shape that
+ * validate()/expand() expect. Inverse of serializeRegistry.
+ */
+export function hydrateRegistry(json) {
+ const components = new Map();
+ for (const c of json.components) {
+ components.set(c.name, {
+ name: c.name,
+ exportName: c.exportName,
+ dirName: c.dirName,
+ importPath: c.importPath,
+ undocumented: c.undocumented || false,
+ props: new Map(c.props.map(p => [p.name, p])),
+ });
+ }
+ return {
+ components,
+ aliases: new Map(json.aliases),
+ componentNames: json.componentNames || [...components.keys()].sort(),
+ };
+}
diff --git a/packages/cli/src/lib/xle/registry.mjs b/packages/cli/src/lib/xle/registry.mjs
new file mode 100644
index 0000000000..793b38f406
--- /dev/null
+++ b/packages/cli/src/lib/xle/registry.mjs
@@ -0,0 +1,237 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file XLE component registry — built from @astryxdesign/core .doc.mjs metadata.
+ *
+ * Everything the layout language knows about components (valid names,
+ * aliases, props, enums, slots) is derived from the same .doc.mjs files
+ * that power `xds component`, so the notation can never drift from the
+ * branch's actual API. The pure pieces (alias table, enum parsing,
+ * resolution, serialize/hydrate) live in registry-core.mjs so they can
+ * run in the browser; this module adds the fs-bound builder.
+ *
+ * @input packages/core/src/(star)/(star).doc.mjs via component-discovery
+ * @output buildRegistry() → { components, aliases, componentNames }
+ * @position lib/xle — shared by parse/validate/expand; no CLI concerns here
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {findCoreDir} from '../../utils/paths.mjs';
+import {
+ discoverComponents,
+ findComponentReadme,
+ resolveImportPath,
+} from '../component-discovery.mjs';
+import {loadDocs} from '../component-loader.mjs';
+import {
+ ALIAS_TABLE,
+ normalizeName,
+ toComponentEntry,
+} from './registry-core.mjs';
+
+// Re-export the pure surface so existing importers (and tests) keep working.
+export {
+ ALIAS_TABLE,
+ SPACING_STEPS,
+ parseEnumValues,
+ resolveComponent,
+ serializeRegistry,
+ hydrateRegistry,
+} from './registry-core.mjs';
+
+function findDirFor(grouped, member) {
+ for (const [dir, members] of Object.entries(grouped)) {
+ if (members.includes(member)) return dir;
+ }
+ return null;
+}
+
+// Match bare `export {Name}` / `export {Name, Other}` named re-exports in a
+// component directory's index.ts. PascalCase only — hooks (useX), lowercase
+// helpers, and `type` exports are skipped via the caller's filters.
+const NAMED_EXPORT_RE = /export\s*\{([^}]*)\}/g;
+
+/**
+ * Read the PascalCase component names re-exported from a component directory's
+ * `index.ts`. Used to recover structural sub-components that ship without their
+ * own `.doc.mjs` (e.g. TableHeader, TableBody, TableFooter) — the doc-driven
+ * discoverComponents() intentionally skips those, but the layout language still
+ * needs to name and emit them.
+ *
+ * @param {string} coreDir
+ * @param {string} dirName
+ * @returns {string[]} bare PascalCase export names
+ */
+function readDirExportedComponents(coreDir, dirName) {
+ const indexPath = path.join(coreDir, 'src', dirName, 'index.ts');
+ let content;
+ try {
+ content = fs.readFileSync(indexPath, 'utf-8');
+ } catch {
+ return [];
+ }
+ const names = new Set();
+ for (const match of content.matchAll(NAMED_EXPORT_RE)) {
+ for (const raw of match[1].split(',')) {
+ // `Name`, `Name as Alias`, ` type Name ` — keep the exported (left) name,
+ // drop `type` and aliases.
+ const token = raw.trim();
+ if (!token || token.startsWith('type ')) continue;
+ const name = token.split(/\s+as\s+/)[0].trim().replace(/^XDS/, '');
+ // PascalCase components only — skip hooks (useX), lowercase utils, and
+ // non-rendering exports (Context/Provider) that discoverComponents()
+ // also excludes.
+ if (!/^[A-Z][A-Za-z0-9]*$/.test(name)) continue;
+ if (/(?:Context|Provider)$/.test(name)) continue;
+ names.add(name);
+ }
+ }
+ return [...names];
+}
+
+let cachedRegistry = null;
+
+/**
+ * Build (and cache) the registry: every documented component keyed by its
+ * un-prefixed name, plus the validated alias map.
+ *
+ * @param {object} [options]
+ * @param {string} [options.cwd]
+ * @returns {Promise<{components: Map<string, object>, aliases: Map<string, string>, componentNames: string[]}>}
+ */
+export async function buildRegistry({cwd = process.cwd()} = {}) {
+ if (cachedRegistry) return cachedRegistry;
+
+ const coreDir = findCoreDir(cwd);
+ if (!coreDir) {
+ throw new Error('Could not find @astryxdesign/core package — run from an XDS workspace');
+ }
+
+ const components = new Map();
+ const grouped = discoverComponents(coreDir);
+ const dirNames = [...new Set(Object.values(grouped).flat())];
+
+ for (const dirName of dirNames) {
+ const readme = findComponentReadme(coreDir, dirName);
+ if (!readme || !readme.endsWith('.doc.mjs')) continue;
+ let docs;
+ try {
+ docs = await loadDocs(readme, {});
+ } catch {
+ continue; // a malformed doc must not take down the whole language
+ }
+ const importPath = resolveImportPath(coreDir, dirName);
+
+ const register = (rawName, props) => {
+ const name = normalizeName(rawName);
+ const entry = toComponentEntry(name, props, dirName, importPath);
+ const existing = components.get(name);
+ // Some docs list related components with empty prop arrays
+ // (e.g. Layout's references to Card) — prefer the richer entry.
+ if (!existing || entry.props.size > existing.props.size) {
+ components.set(name, entry);
+ }
+ };
+
+ if (docs.props) register(docs.name || dirName, docs.props);
+ for (const sub of docs.components || []) {
+ if (sub?.name) register(sub.name, sub.props);
+ }
+ }
+
+ // Some components are documented in a sibling `<Name>.doc.mjs` inside another
+ // component's dir (e.g. Text/Heading.doc.mjs documents Heading, with its own
+ // props like `level`). The per-dir main-doc read above only sees the bare
+ // `{name: 'Heading'}` cross-reference stub (no props), so without this those
+ // props go missing and valid attrs (e.g. Heading[level=2]) get rejected.
+ // Read every .doc.mjs in each contributing dir and upgrade props, keyed to
+ // each component's own export subpath. Props-only: never adds empty entries.
+ const upgradeFromDoc = (rawName, props, fallbackDir) => {
+ if (!props || props.length === 0) return;
+ const name = normalizeName(rawName);
+ // Prefer the component's own export subpath (Heading → @astryxdesign/core/Heading);
+ // fall back to the dir it was found in, then any existing entry's path.
+ const ip =
+ resolveImportPath(coreDir, name) ||
+ resolveImportPath(coreDir, fallbackDir) ||
+ components.get(name)?.importPath;
+ const entry = toComponentEntry(name, props, name, ip);
+ const existing = components.get(name);
+ if (!existing || entry.props.size > existing.props.size) components.set(name, entry);
+ };
+ for (const dirName of dirNames) {
+ const dirPath = path.join(coreDir, 'src', dirName);
+ let files;
+ try {
+ files = fs.readdirSync(dirPath).filter(f => f.endsWith('.doc.mjs'));
+ } catch {
+ continue;
+ }
+ for (const file of files) {
+ let docs;
+ try {
+ docs = await loadDocs(path.join(dirPath, file), {});
+ } catch {
+ continue;
+ }
+ if (docs.props) upgradeFromDoc(docs.name || file.replace(/\.doc\.mjs$/, ''), docs.props, dirName);
+ for (const sub of docs.components || []) {
+ if (sub?.name && sub.props?.length) upgradeFromDoc(sub.name, sub.props, dirName);
+ }
+ }
+ }
+
+ // Exported components without their own doc entry (e.g. TableHeader,
+ // TableBody) still get minimal registry entries so they can be named in
+ // expressions — the validator warns rather than validates their props.
+ //
+ // Two sources:
+ // 1. Members discovered alongside a documented sibling (legacy path).
+ // 2. Bare PascalCase re-exports in each component dir's index.ts. The
+ // doc-driven discoverComponents() skips doc-less structural pieces
+ // (TableHeader/Body/Footer became bare files with no own .doc.mjs after
+ // the un-prefix migration), so we recover them from the real export
+ // surface here.
+ const registerUndocumented = (name, dirName) => {
+ if (components.has(name)) return;
+ const entry = toComponentEntry(name, [], dirName, resolveImportPath(coreDir, name));
+ entry.undocumented = true;
+ components.set(name, entry);
+ };
+
+ for (const [, members] of Object.entries(grouped)) {
+ for (const member of members) {
+ registerUndocumented(normalizeName(member), findDirFor(grouped, member) || member);
+ }
+ }
+
+ // Walk every component directory (those that contributed at least one
+ // documented component) and backfill its index.ts exports.
+ const docDirs = new Set();
+ for (const c of components.values()) {
+ if (c.dirName) docDirs.add(c.dirName);
+ }
+ for (const dirName of docDirs) {
+ for (const name of readDirExportedComponents(coreDir, dirName)) {
+ registerUndocumented(name, dirName);
+ }
+ }
+
+ const aliases = new Map();
+ for (const [alias, target] of Object.entries(ALIAS_TABLE)) {
+ if (components.has(target)) aliases.set(alias, target);
+ }
+
+ cachedRegistry = {
+ components,
+ aliases,
+ componentNames: [...components.keys()].sort(),
+ };
+ return cachedRegistry;
+}
+
+/** Test seam — drop the module-level cache. */
+export function resetRegistryCache() {
+ cachedRegistry = null;
+}
diff --git a/packages/cli/src/lib/xle/splice.mjs b/packages/cli/src/lib/xle/splice.mjs
new file mode 100644
index 0000000000..64e94fd77f
--- /dev/null
+++ b/packages/cli/src/lib/xle/splice.mjs
@@ -0,0 +1,137 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Block splicing — turn a template block's TSX source into something
+ * the expander can inline.
+ *
+ * A `{hint}` can resolve two ways:
+ * - splice: a template block (not an importable package) is co-defined as a
+ * local component in the generated module and referenced — the block's
+ * imports are hoisted and merged. This is what `astryx template <name>` would
+ * scaffold, inlined.
+ * - import: an app-registered local component (KpiCard, charts, …) is simply
+ * imported from its configured path and referenced. This is the bridge that
+ * lets XLE reach the domain components it's otherwise blind to.
+ *
+ * Pure (no fs): the Node caller reads files; this only transforms strings, so
+ * it stays in the browser barrel.
+ *
+ * @input block TSX source (splice) or a name+importPath (import)
+ * @output prepareSpliceModule / parseImportStatements + import-merge helpers
+ * @position lib/xle — used by expand.mjs; sources gathered in api/layout.mjs
+ */
+
+const IMPORT_RE =
+ /^import\s+(?:(type)\s+)?(?:([A-Za-z_$][\w$]*)\s*,\s*)?(?:\{([^}]*)\}|\*\s+as\s+([A-Za-z_$][\w$]*)|([A-Za-z_$][\w$]*))?\s*(?:from\s*)?['"]([^'"]+)['"]\s*;?/;
+
+/**
+ * Parse the import statements at the top of a module. Handles named, type,
+ * default, namespace, and side-effect imports (incl. simple multiline named
+ * lists). Returns {imports, rest} where rest is the source with those import
+ * lines removed.
+ */
+export function parseImportStatements(source) {
+ const lines = source.split('\n');
+ const imports = [];
+ const kept = [];
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ if (/^\s*import\b/.test(line)) {
+ // Gather a possibly-multiline import up to its terminating quote+;
+ let stmt = line;
+ while (!/['"]\s*;?\s*$/.test(stmt) && i + 1 < lines.length) {
+ i++;
+ stmt += '\n' + lines[i];
+ }
+ const m = stmt.replace(/\s+/g, ' ').match(IMPORT_RE);
+ if (m) {
+ const [, typeKw, defaultWithNamed, named, namespace, bareDefault, src] = m;
+ imports.push({
+ source: src,
+ isType: Boolean(typeKw),
+ default: defaultWithNamed || bareDefault || null,
+ namespace: namespace || null,
+ named: named
+ ? named.split(',').map(s => s.trim()).filter(Boolean)
+ : [],
+ sideEffect: !named && !namespace && !bareDefault && !defaultWithNamed,
+ });
+ continue;
+ }
+ }
+ kept.push(line);
+ }
+ return {imports, rest: kept.join('\n')};
+}
+
+/**
+ * Prepare a template block for inline co-definition.
+ *
+ * Strips the copyright header and `'use client'`, hoists imports, and rewrites
+ * the block's exports into plain module-level declarations so it can live
+ * inside the generated file. Returns null if the block has no default-exported
+ * component to reference (caller falls back to a TODO marker).
+ *
+ * @param {string} source - raw block TSX
+ * @param {string} fallbackName - PascalCase name to use if no export name found
+ * @returns {{componentName: string, imports: object[], body: string} | null}
+ */
+export function prepareSpliceModule(source, fallbackName) {
+ const {imports, rest} = parseImportStatements(source);
+
+ // Determine the component name from the default export.
+ let componentName = fallbackName;
+ const defFn = rest.match(/export\s+default\s+function\s+([A-Za-z_$][\w$]*)/);
+ const defConst = rest.match(/export\s+default\s+([A-Za-z_$][\w$]*)\s*;/);
+ if (defFn) componentName = defFn[1];
+ else if (defConst) componentName = defConst[1];
+ else if (!/export\s+default/.test(rest)) return null;
+
+ let body = rest
+ // drop directive prologues and the copyright comment
+ .replace(/^\s*['"]use client['"];?\s*$/m, '')
+ .replace(/^\/\/.*$/gm, '')
+ // anonymous default → a named function/const we can reference
+ .replace(/export\s+default\s+function\s*\(/, `function ${componentName}(`)
+ .replace(/export\s+default\s+function\s+/, 'function ')
+ // `export default X;` (X already defined above) → nothing
+ .replace(/export\s+default\s+[A-Za-z_$][\w$]*\s*;/, '')
+ // demote remaining named exports to plain declarations
+ .replace(/export\s+(const|function|class|interface|type|enum)\s/g, '$1 ')
+ .trim();
+
+ return {componentName, imports, body};
+}
+
+/**
+ * Merge a parsed import list into an emitter import map.
+ * The map is Map<source, {named:Set, types:Set, default?:string, namespace?:string, sideEffect?:bool}>.
+ */
+export function mergeImports(map, imports) {
+ for (const imp of imports) {
+ if (!map.has(imp.source)) {
+ map.set(imp.source, {named: new Set(), types: new Set(), default: null, namespace: null, sideEffect: false});
+ }
+ const entry = map.get(imp.source);
+ if (imp.sideEffect) entry.sideEffect = true;
+ if (imp.default) entry.default = imp.default;
+ if (imp.namespace) entry.namespace = imp.namespace;
+ for (const n of imp.named) (imp.isType ? entry.types : entry.named).add(n);
+ }
+}
+
+/** Render one merged import entry to a statement string. */
+export function renderImport(source, entry) {
+ if (entry.sideEffect && !entry.default && !entry.namespace && entry.named.size === 0 && entry.types.size === 0) {
+ return `import '${source}';`;
+ }
+ const clauses = [];
+ if (entry.default) clauses.push(entry.default);
+ if (entry.namespace) clauses.push(`* as ${entry.namespace}`);
+ const named = [...entry.named].sort();
+ const types = [...entry.types].sort();
+ // Keep value and type names in one braces group (TS allows inline `type`).
+ const braced = [...named, ...types.map(t => `type ${t}`)];
+ if (braced.length > 0) clauses.push(`{${braced.join(', ')}}`);
+ return `import ${clauses.join(', ')} from '${source}';`;
+}
diff --git a/packages/cli/src/lib/xle/validate.mjs b/packages/cli/src/lib/xle/validate.mjs
new file mode 100644
index 0000000000..c852ffcb3f
--- /dev/null
+++ b/packages/cli/src/lib/xle/validate.mjs
@@ -0,0 +1,356 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file XLE binder/validator — resolves the parsed AST against the
+ * component registry and annotates every node with its bound component
+ * and prop assignments.
+ *
+ * Philosophy (from the XLE research): lenient lexer, strict validator.
+ * Spelling variants normalize silently (p6 ≡ pad=6 ≡ padding=6), but
+ * semantic problems — unknown components, props, enum values, blocks —
+ * are hard errors carrying ranked suggestions, never guesses.
+ *
+ * @input parse() AST + registry (+ block list for {hint} resolution)
+ * @output validate() → {errors, warnings}; nodes gain .bound
+ * @position lib/xle — between parse.mjs and expand.mjs
+ */
+
+import {levenshteinDistance} from '../levenshtein.mjs';
+import {KEY_ALIASES} from './parse.mjs';
+import {resolveComponent} from './registry-core.mjs';
+
+/** Boolean flag synonyms — agent-frequency spellings of isX/hasX props. */
+const FLAG_SYNONYMS = {
+ req: 'isRequired', opt: 'isOptional', dis: 'isDisabled',
+ scroll: 'isScrollable', divider: 'hasDivider', dividers: 'hasDivider',
+ striped: 'isStriped', hover: 'hasHover', clear: 'hasClear',
+ compact: 'isCompact', external: 'isExternalLink', loading: 'isLoading',
+};
+
+/** Props the expander treats as the node's primary text payload, in order. */
+export const PAYLOAD_PROPS = ['label', 'title', 'heading'];
+
+function suggest(input, candidates, max = 4) {
+ const lower = input.toLowerCase();
+ return candidates
+ .map(name => {
+ const candidate = name.toLowerCase();
+ const contains = candidate.includes(lower) || lower.includes(candidate);
+ const distance = levenshteinDistance(lower, candidate);
+ return {name, distance: contains ? Math.min(distance, 1) : distance};
+ })
+ .filter(s => s.distance <= Math.max(2, Math.floor(input.length / 2)))
+ .sort((a, b) => a.distance - b.distance)
+ .slice(0, max)
+ .map(s => s.name);
+}
+
+function normalizeBlockKey(name) {
+ return name.toLowerCase().replace(/[^a-z0-9]/g, '');
+}
+
+/**
+ * Resolve a word to a prop assignment via, in order: synonym table,
+ * exact boolean prop, is/has-prefixed boolean prop, unique enum value.
+ * Returns {prop, value} or null.
+ */
+function resolveWord(component, word) {
+ const synonym = FLAG_SYNONYMS[word];
+ if (synonym && component.props.has(synonym)) {
+ return {prop: synonym, value: true};
+ }
+ const exact = component.props.get(word);
+ if (exact && exact.isBoolean) return {prop: word, value: true};
+ const cap = word[0].toUpperCase() + word.slice(1);
+ for (const prefix of ['is', 'has']) {
+ const pref = component.props.get(prefix + cap);
+ if (pref && pref.isBoolean) return {prop: prefix + cap, value: true};
+ }
+ // Unique enum membership across all enum-typed props.
+ const hits = [];
+ for (const prop of component.props.values()) {
+ if (prop.enumValues && prop.enumValues.includes(word)) hits.push(prop.name);
+ }
+ if (hits.length === 1) return {prop: hits[0], value: word};
+ if (hits.length > 1) return {ambiguous: hits};
+ return null;
+}
+
+/** Map axis-neutral j=/a= keys onto the component's real alignment props. */
+function resolveAxisKey(component, key) {
+ const main = key === '__mainAxis';
+ if (component.name === 'VStack') return main ? 'vAlign' : 'hAlign';
+ if (component.name === 'HStack') return main ? 'hAlign' : 'vAlign';
+ const generic = main ? 'justify' : 'align';
+ if (component.props.has(generic)) return generic;
+ if (component.props.has(main ? 'hAlign' : 'vAlign')) return main ? 'hAlign' : 'vAlign';
+ return generic;
+}
+
+/** Grid's `columns` object shorthand: {min,max,fit|fill} → real keys. */
+function normalizeColumnsObject(value) {
+ if (typeof value !== 'object' || value == null || Array.isArray(value)) return value;
+ const out = {};
+ for (const [k, v] of Object.entries(value)) {
+ if (k === 'min') out.minWidth = v;
+ else if (k === 'fit' || k === 'fill') out.repeat = k;
+ else out[k] = v;
+ }
+ return out;
+}
+
+export class Validation {
+ constructor(registry, blocks, {loose = false} = {}) {
+ this.registry = registry;
+ this.blocks = blocks || [];
+ this.blockIndex = new Map(this.blocks.map(b => [normalizeBlockKey(b.dirName), b]));
+ this.loose = loose;
+ this.errors = [];
+ this.warnings = [];
+ }
+
+ error(node, message, suggestions = []) {
+ this.errors.push({message, line: node.line, col: node.col, suggestions});
+ }
+
+ warn(node, message) {
+ this.warnings.push({message, line: node.line, col: node.col});
+ }
+
+ nameCandidates() {
+ return [...this.registry.aliases.keys(), ...this.registry.componentNames];
+ }
+
+ bindNode(node, parent) {
+ // Anonymous block reference ({block} with no host element).
+ if (!node.name && node.hint) {
+ node.bound = null;
+ this.bindHint(node);
+ for (const child of node.children) this.bindAny(child, node);
+ return;
+ }
+ const component = resolveComponent(this.registry, node.name);
+ if (!component) {
+ this.error(
+ node,
+ `Unknown component or alias '${node.name}'`,
+ suggest(node.name, this.nameCandidates()),
+ );
+ node.bound = null;
+ } else {
+ node.bound = {component, props: new Map(), slots: [], stray: []};
+ this.bindAttrs(node, component);
+ this.bindMods(node, component);
+ this.bindSlots(node, component);
+ this.checkPairings(node, component, parent);
+ }
+ if (node.hint) this.bindHint(node);
+ for (const child of node.children) this.bindAny(child, node);
+ }
+
+ bindAny(item, parent) {
+ if (item.kind === 'group') {
+ for (const child of item.children) this.bindAny(child, parent);
+ } else {
+ this.bindNode(item, parent);
+ }
+ }
+
+ bindAttrs(node, component) {
+ if (component.undocumented) {
+ // No prop metadata for this export — bind raw and tell the author
+ // nothing was checked, rather than rejecting valid props.
+ for (const attr of node.attrs) {
+ if (attr.kind === 'kv') {
+ const key = KEY_ALIASES[attr.key.split('.')[0]] ?? attr.key;
+ node.bound.props.set(key.startsWith('__') ? attr.key : key, attr.value);
+ } else if (attr.kind === 'flag') {
+ node.bound.props.set(attr.key, true);
+ } else if (attr.kind === 'neg') {
+ node.bound.props.set(attr.key, false);
+ }
+ }
+ if (node.attrs.length > 0) {
+ this.warn(node, `${component.name} has no documented props — attrs passed through unvalidated`);
+ }
+ return;
+ }
+ for (const attr of node.attrs) {
+ if (attr.kind === 'kv') {
+ this.bindKv(node, component, attr);
+ } else if (attr.kind === 'flag') {
+ const hit = resolveWord(component, attr.key);
+ if (!hit) {
+ this.error(
+ node,
+ `'${attr.key}' is not a prop, flag, or enum value of ${component.name}`,
+ suggest(attr.key, [...component.props.keys()]),
+ );
+ } else if (hit.ambiguous) {
+ this.error(
+ node,
+ `'${attr.key}' is ambiguous on ${component.name} — it is a value of ${hit.ambiguous.join(' and ')}; use key=value`,
+ );
+ } else {
+ node.bound.props.set(hit.prop, hit.value);
+ }
+ } else if (attr.kind === 'neg') {
+ const hit = resolveWord(component, attr.key);
+ if (!hit || hit.ambiguous || typeof hit.value !== 'boolean') {
+ this.error(
+ node,
+ `'!${attr.key}' does not match a boolean prop of ${component.name}`,
+ suggest(attr.key, [...component.props.keys()].filter(p => component.props.get(p).isBoolean)),
+ );
+ } else {
+ node.bound.props.set(hit.prop, false);
+ }
+ }
+ }
+ }
+
+ bindKv(node, component, attr) {
+ let key = attr.key.split('.')[0];
+ key = KEY_ALIASES[key] ?? key;
+
+ if (key === '__mainAxis' || key === '__crossAxis') {
+ key = resolveAxisKey(component, key);
+ }
+ if (key === 'opens') {
+ // Overlay trigger binding — expander turns this into an onClick TODO.
+ node.bound.props.set('__opens', attr.value);
+ if (!component.props.has('onClick') && !component.props.has('clickAction')) {
+ this.warn(node, `'opens=' on ${component.name}, which has no onClick — emitting a comment only`);
+ }
+ return;
+ }
+
+ const prop = component.props.get(key);
+ if (!prop) {
+ const fallbacks = suggest(key, [...component.props.keys()]);
+ this.error(
+ node,
+ `${component.name} has no prop '${key}'` +
+ (attr.raw && attr.raw !== key ? ` (from '${attr.raw}')` : ''),
+ fallbacks,
+ );
+ return;
+ }
+
+ let value = attr.value;
+ if (key === 'columns') value = normalizeColumnsObject(value);
+
+ if (prop.enumValues && (typeof value === 'string' || typeof value === 'number')) {
+ if (!prop.enumValues.includes(value)) {
+ this.error(
+ node,
+ `${component.name}.${key} must be one of ${prop.enumValues.join(' | ')} — got '${value}'`,
+ typeof value === 'string' ? suggest(String(value), prop.enumValues.map(String)) : [],
+ );
+ return;
+ }
+ }
+ node.bound.props.set(key, value);
+ }
+
+ bindMods(node, component) {
+ for (const mod of node.enumMods) {
+ const hit = resolveWord(component, mod);
+ if (!hit || hit.ambiguous) {
+ const enumPool = [...component.props.values()]
+ .flatMap(p => p.enumValues || [])
+ .map(String);
+ this.error(
+ node,
+ hit?.ambiguous
+ ? `'.${mod}' is ambiguous on ${component.name} (${hit.ambiguous.join(', ')}) — use key=value`
+ : `'.${mod}' does not match an enum value of any ${component.name} prop`,
+ suggest(mod, enumPool),
+ );
+ } else {
+ node.bound.props.set(hit.prop, hit.value);
+ }
+ }
+ }
+
+ bindSlots(node, component) {
+ for (const slot of node.slots) {
+ const prop = component.props.get(slot.key);
+ if (!prop) {
+ this.error(
+ node,
+ `${component.name} has no slot prop '${slot.key}'`,
+ suggest(slot.key, [...component.props.keys()].filter(k => component.props.get(k).isNode)),
+ );
+ continue;
+ }
+ if (!prop.isNode && !prop.isFunction) {
+ this.warn(node, `${component.name}.${slot.key} is typed '${prop.type}' — slot value may not fit`);
+ }
+ if (slot.value && slot.value.subexpr) {
+ for (const sub of slot.value.subexpr) this.bindAny(sub, node);
+ }
+ if (slot.value && slot.value.hint) this.bindHintRef(node, slot.value.hint);
+ node.bound.slots.push(slot);
+ }
+ }
+
+ bindHint(node) {
+ this.bindHintRef(node, node.hint);
+ }
+
+ bindHintRef(node, hint) {
+ const block = this.blockIndex.get(normalizeBlockKey(hint.name));
+ if (block) {
+ hint.block = {name: block.dirName, description: block.description, category: block.category};
+ return;
+ }
+ const nearest = suggest(
+ normalizeBlockKey(hint.name),
+ [...this.blockIndex.keys()],
+ ).map(k => this.blockIndex.get(k).dirName);
+ if (this.loose) {
+ this.warn(node, `Unknown block '{${hint.name}}' — emitting a TODO placeholder (running with --loose)`);
+ } else {
+ this.error(
+ node,
+ `Unknown block '{${hint.name}}' — block hints must name an existing template block`,
+ nearest.length > 0 ? nearest : ['run: astryx template --list --type block'],
+ );
+ }
+ }
+
+ checkPairings(node, component, parent) {
+ const parentName = parent?.bound?.component?.name ?? parent?.name;
+ if (component.name === 'AppShell' && parent) {
+ this.error(node, 'AppShell must be the outermost node');
+ }
+ if (component.name === 'GridSpan' && parentName !== 'Grid') {
+ this.error(node, 'GridSpan is only valid directly under Grid');
+ }
+ if (component.name === 'StackItem' && parentName !== 'VStack' && parentName !== 'HStack') {
+ this.error(node, 'StackItem is only valid directly under VStack/HStack');
+ }
+ }
+}
+
+/**
+ * Validate (and bind) a parsed document in place.
+ *
+ * @param {{roots: any[], overlays: any[]}} doc
+ * @param {object} registry - from buildRegistry()
+ * @param {Array<object>} blocks - from template discovery (dirName et al)
+ * @param {{loose?: boolean}} [options]
+ * @returns {{errors: Array, warnings: Array}}
+ */
+export function validate(doc, registry, blocks, options = {}) {
+ const v = new Validation(registry, blocks, options);
+ for (const item of doc.roots) v.bindAny(item, null);
+ for (const item of doc.overlays) {
+ v.bindAny(item, null);
+ if (item.kind === 'node' && !item.id) {
+ v.warn(item, `Overlay ${item.name} has no #id — triggers cannot reference it`);
+ }
+ }
+ return {errors: v.errors, warnings: v.warnings};
+}
diff --git a/packages/cli/src/lib/xle/xle.test.mjs b/packages/cli/src/lib/xle/xle.test.mjs
new file mode 100644
index 0000000000..e09ca61dc2
--- /dev/null
+++ b/packages/cli/src/lib/xle/xle.test.mjs
@@ -0,0 +1,333 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Unit tests for the XLE/XLO parser, printers, and validator.
+ * Parser/printer tests are registry-free; validator tests use a small
+ * synthetic registry so they don't depend on @xds/core docs.
+ */
+
+import {describe, it, expect} from 'vitest';
+import {parse, parseCompact, parseOutline, detectForm, XLEParseError} from './parse.mjs';
+import {toCompact, toOutline} from './print.mjs';
+import {validate} from './validate.mjs';
+import {parseEnumValues, SPACING_STEPS} from './registry.mjs';
+
+// ─── parser: compact ───────────────────────────────────────────────────────
+
+describe('parseCompact', () => {
+ it('parses child and sibling operators', () => {
+ const doc = parseCompact('A > B + C');
+ expect(doc.roots).toHaveLength(1);
+ expect(doc.roots[0].name).toBe('A');
+ expect(doc.roots[0].children.map(c => c.name)).toEqual(['B', 'C']);
+ });
+
+ it('parses groups with repeat', () => {
+ const doc = parseCompact('V > (C + D)*3');
+ const group = doc.roots[0].children[0];
+ expect(group.kind).toBe('group');
+ expect(group.repeat).toBe(3);
+ expect(group.children.map(c => c.name)).toEqual(['C', 'D']);
+ });
+
+ it('parses node anatomy: id, enum mods, payload, attrs, hint, repeat, selected', () => {
+ const doc = parseCompact('Tab#main.lg"Overview"[divider sz=md]{card-callout}!*2');
+ const node = doc.roots[0];
+ expect(node.id).toBe('main');
+ expect(node.enumMods).toEqual(['lg']);
+ expect(node.payload).toBe('Overview');
+ expect(node.attrs).toEqual([
+ expect.objectContaining({kind: 'flag', key: 'divider'}),
+ expect.objectContaining({kind: 'kv', key: 'sz', value: 'md'}),
+ ]);
+ expect(node.hint.name).toBe('card-callout');
+ expect(node.selected).toBe(true);
+ expect(node.repeat).toBe(2);
+ });
+
+ it('parses fused shorthands, objects, lists, and negation', () => {
+ const doc = parseCompact('G[c{min:340,fit} g4 dv=[top,bottom] !scroll]');
+ const attrs = doc.roots[0].attrs;
+ expect(attrs[0]).toEqual(expect.objectContaining({key: 'c', value: {min: 340, fit: true}}));
+ expect(attrs[1]).toEqual(expect.objectContaining({key: 'g', value: 4}));
+ expect(attrs[2]).toEqual(expect.objectContaining({key: 'dv', value: ['top', 'bottom']}));
+ expect(attrs[3]).toEqual(expect.objectContaining({kind: 'neg', key: 'scroll'}));
+ });
+
+ it('parses slot attrs with nested sub-expressions', () => {
+ const doc = parseCompact('A[@topNav=(TN > TNI"Home" + TNI"Docs") @banner=\'hello\']');
+ const [topNav, banner] = doc.roots[0].slots;
+ expect(topNav.key).toBe('topNav');
+ expect(topNav.value.subexpr[0].name).toBe('TN');
+ expect(topNav.value.subexpr[0].children).toHaveLength(2);
+ expect(banner.value).toBe('hello');
+ });
+
+ it('parses detached overlays after ;;', () => {
+ const doc = parseCompact('V > B"Delete"[opens=#confirm] ;; AD#confirm"Sure?"');
+ expect(doc.roots).toHaveLength(1);
+ expect(doc.overlays).toHaveLength(1);
+ expect(doc.overlays[0].id).toBe('confirm');
+ });
+
+ it('rejects ^ with a correction toward groups', () => {
+ expect(() => parseCompact('A > B ^ C')).toThrow(/group siblings with \(\.\.\.\)/);
+ });
+
+ it('rejects brace content that is not a block name, teaching the payload form', () => {
+ try {
+ parseCompact('C{Total Revenue}');
+ expect.unreachable();
+ } catch (e) {
+ expect(e).toBeInstanceOf(XLEParseError);
+ expect(e.message).toMatch(/not a block reference/);
+ expect(e.message).toMatch(/quoted payload/);
+ }
+ });
+
+ it('reports unterminated constructs with positions', () => {
+ expect(() => parseCompact('V[g6 > C')).toThrow(XLEParseError);
+ expect(() => parseCompact('Tx"unclosed')).toThrow(/Unterminated/);
+ });
+});
+
+// ─── parser: outline ───────────────────────────────────────────────────────
+
+const OUTLINE = `
+AppShell
+ topNav: TN "Acme"
+ Layout > LC !scroll
+ V g=6
+ Tx.lg "Hello"
+ repeat 3:
+ C {card-callout}
+ Tbar "Actions"
+ B "Delete" opens=#confirm
+
+overlays:
+ AD#confirm "Sure?"
+`;
+
+describe('parseOutline', () => {
+ it('parses indentation, slot lines, inline chains, repeats, overlays', () => {
+ const doc = parseOutline(OUTLINE);
+ const shell = doc.roots[0];
+ expect(shell.name).toBe('AppShell');
+ expect(shell.slots[0].key).toBe('topNav');
+ expect(shell.slots[0].value.subexpr[0].payload).toBe('Acme');
+
+ const layout = shell.children[0];
+ expect(layout.name).toBe('Layout');
+ const lc = layout.children[0];
+ expect(lc.name).toBe('LC');
+ expect(lc.attrs[0]).toEqual(expect.objectContaining({kind: 'neg', key: 'scroll'}));
+
+ const v = lc.children[0];
+ expect(v.children[0].enumMods).toEqual(['lg']);
+ const repeat = v.children[1];
+ expect(repeat.kind).toBe('group');
+ expect(repeat.repeat).toBe(3);
+ expect(repeat.children[0].hint.name).toBe('card-callout');
+
+ // Tbar is a sibling of V (child of LC), not swallowed by the repeat block
+ expect(lc.children.map(c => c.name ?? 'group')).toEqual(['V', 'Tbar']);
+ expect(doc.overlays).toHaveLength(1);
+ expect(doc.overlays[0].id).toBe('confirm');
+ });
+
+ it('parses block-form slots', () => {
+ const doc = parseOutline('ChL\n composer:\n ChC\n ChML');
+ const chl = doc.roots[0];
+ expect(chl.slots[0].key).toBe('composer');
+ expect(chl.slots[0].value.subexpr[0].name).toBe('ChC');
+ expect(chl.children.map(c => c.name)).toEqual(['ChML']);
+ });
+
+ it('errors on a slot line with no parent component', () => {
+ expect(() => parseOutline('topNav: TN')).toThrow(/no parent component/);
+ });
+});
+
+// ─── form detection ────────────────────────────────────────────────────────
+
+describe('detectForm', () => {
+ it('single line → compact', () => {
+ expect(detectForm('A > B + C')).toBe('compact');
+ });
+ it('multi-line ending in operators → compact', () => {
+ expect(detectForm('A > B +\n C > D')).toBe('compact');
+ });
+ it('indented multi-line → outline', () => {
+ expect(detectForm('A\n B\n C')).toBe('outline');
+ });
+ it('repeat/overlays markers → outline', () => {
+ expect(detectForm('V\nrepeat 2:\n C')).toBe('outline');
+ });
+});
+
+// ─── printers: round-trips ─────────────────────────────────────────────────
+
+/** Strip positions for structural comparison. */
+function shape(doc) {
+ return JSON.parse(JSON.stringify(doc, (key, value) =>
+ key === 'line' || key === 'col' || key === 'form' || key === 'raw' ? undefined : value));
+}
+
+const ROUND_TRIP_CASES = [
+ 'A > B + C',
+ 'V[g6] > (C{card-callout}*4) + T[striped]',
+ 'Ctr[h=100dvh] > C[w=400 p8] > B.primary"Sign in"',
+ 'A[@topNav=(TN > TNI"Home")] > L > LC[!scroll] > Tx"hi"',
+ 'V > B"Del"[opens=#confirm] ;; AD#confirm"Sure?"',
+ 'TL > Tab"Overview"! + Tab"Activity"',
+];
+
+describe('print round-trips', () => {
+ for (const source of ROUND_TRIP_CASES) {
+ it(`compact → compact: ${source}`, () => {
+ const doc = parse(source, {form: 'compact'});
+ const reparsed = parse(toCompact(doc), {form: 'compact'});
+ expect(shape(reparsed)).toEqual(shape(doc));
+ });
+
+ it(`compact → outline → parse: ${source}`, () => {
+ const doc = parse(source, {form: 'compact'});
+ const outline = toOutline(doc);
+ const reparsed = parse(outline, {form: 'outline'});
+ // Outline flattens repeat-less disambiguation groups — compare the
+ // outline printed from both, which is canonical.
+ expect(toOutline(reparsed)).toEqual(outline);
+ });
+ }
+
+ it('outline → compact → parse → outline is stable', () => {
+ const doc = parseOutline(OUTLINE);
+ const compact = toCompact(doc);
+ const reparsed = parseCompact(compact);
+ expect(toOutline(reparsed)).toEqual(toOutline(doc));
+ });
+});
+
+// ─── validator (synthetic registry) ────────────────────────────────────────
+
+function prop(name, type, required = false) {
+ return {
+ name, type, required,
+ enumValues: parseEnumValues(type),
+ isBoolean: type === 'boolean',
+ isFunction: /^\(/.test(type),
+ isNode: /ReactNode/.test(type),
+ };
+}
+
+function makeTestRegistry() {
+ const make = (name, props) => ({
+ name, exportName: `XDS${name}`, dirName: name, importPath: `@xds/core/${name}`,
+ props: new Map(props.map(p => [p.name, p])),
+ });
+ const components = new Map([
+ ['AppShell', make('AppShell', [prop('contentPadding', 'SpacingStep'), prop('children', 'ReactNode'), prop('topNav', 'ReactNode')])],
+ ['Stack', make('Stack', [prop('gap', 'SpacingStep'), prop('hAlign', "'start' | 'center' | 'end' | 'between'"), prop('vAlign', "'start' | 'center' | 'end'")])],
+ ['Chip', make('Chip', [prop('variant', "'neutral' | 'success' | 'error'"), prop('label', 'string', true)])],
+ ['Box', make('Box', [prop('isScrollable', 'boolean'), prop('children', 'ReactNode')])],
+ ]);
+ const aliases = new Map([['Sh', 'AppShell'], ['St', 'Stack'], ['Ch', 'Chip'], ['Bx', 'Box']]);
+ return {components, aliases, componentNames: [...components.keys()]};
+}
+
+const BLOCKS = [{dirName: 'CardCallout', description: '', category: 'components/Card'}];
+
+describe('validate', () => {
+ const registry = makeTestRegistry();
+
+ it('binds aliases, full names, and XDS-prefixed names identically', () => {
+ for (const name of ['Sh', 'AppShell', 'XDSAppShell']) {
+ const doc = parse(`${name}[cp6]`);
+ const {errors} = validate(doc, registry, BLOCKS);
+ expect(errors).toEqual([]);
+ expect(doc.roots[0].bound.props.get('contentPadding')).toBe(6);
+ }
+ });
+
+ it('rejects unknown components with ranked suggestions', () => {
+ const doc = parse('AppShel');
+ const {errors} = validate(doc, registry, BLOCKS);
+ expect(errors[0].message).toMatch(/Unknown component/);
+ expect(errors[0].suggestions).toContain('AppShell');
+ });
+
+ it('rejects per-component shorthand misuse and suggests the right prop', () => {
+ const doc = parse('Sh[p6]');
+ const {errors} = validate(doc, registry, BLOCKS);
+ expect(errors[0].message).toMatch(/AppShell has no prop 'padding'/);
+ expect(errors[0].suggestions).toContain('contentPadding');
+ });
+
+ it('rejects out-of-enum values, listing the legal set', () => {
+ const doc = parse('St[g7]');
+ const {errors} = validate(doc, registry, BLOCKS);
+ expect(errors[0].message).toMatch(/must be one of 0 \| 0\.5/);
+ });
+
+ it('resolves axis-neutral j= per component axis', () => {
+ const doc = parse('St[j=between]');
+ const {errors} = validate(doc, registry, BLOCKS);
+ expect(errors).toEqual([]);
+ // synthetic Stack has no `justify`, so j= falls back to hAlign
+ expect(doc.roots[0].bound.props.get('hAlign')).toBe('between');
+ });
+
+ it('resolves dot-modifiers against unique enum values, with typo help', () => {
+ const ok = parse('Ch.success"Active"');
+ expect(validate(ok, registry, BLOCKS).errors).toEqual([]);
+ expect(ok.roots[0].bound.props.get('variant')).toBe('success');
+
+ const bad = parse('Ch.sucess"Active"');
+ const {errors} = validate(bad, registry, BLOCKS);
+ expect(errors[0].suggestions).toContain('success');
+ });
+
+ it('resolves negation flags to boolean props', () => {
+ const doc = parse('Bx[!scroll]');
+ expect(validate(doc, registry, BLOCKS).errors).toEqual([]);
+ expect(doc.roots[0].bound.props.get('isScrollable')).toBe(false);
+ });
+
+ it('rejects unknown blocks unless loose', () => {
+ const doc = parse('Bx{nope-not-real}');
+ expect(validate(doc, registry, BLOCKS).errors[0].message).toMatch(/Unknown block/);
+
+ const loose = parse('Bx{nope-not-real}');
+ const result = validate(loose, registry, BLOCKS, {loose: true});
+ expect(result.errors).toEqual([]);
+ expect(result.warnings[0].message).toMatch(/TODO placeholder/);
+ });
+
+ it('resolves block hints case/kebab-insensitively', () => {
+ const doc = parse('Bx{card-callout}');
+ expect(validate(doc, registry, BLOCKS).errors).toEqual([]);
+ expect(doc.roots[0].hint.block.name).toBe('CardCallout');
+ });
+
+ it('enforces structural pairings', () => {
+ const doc = parse('Bx > Sh');
+ const {errors} = validate(doc, registry, BLOCKS);
+ expect(errors[0].message).toMatch(/outermost/);
+ });
+});
+
+// ─── registry helpers ──────────────────────────────────────────────────────
+
+describe('parseEnumValues', () => {
+ it('parses quoted string unions', () => {
+ expect(parseEnumValues("'a' | 'b' | 'c'")).toEqual(['a', 'b', 'c']);
+ });
+ it('parses numeric unions and SpacingStep', () => {
+ expect(parseEnumValues('1|2|3')).toEqual([1, 2, 3]);
+ expect(parseEnumValues('SpacingStep')).toEqual(SPACING_STEPS);
+ });
+ it('returns null for non-enums', () => {
+ expect(parseEnumValues('number | string')).toBeNull();
+ expect(parseEnumValues('boolean')).toBeNull();
+ });
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 46ef0fc842..895917f081 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -189,6 +189,9 @@ importers:
autoprefixer:
specifier: ^10.4.0
version: 10.5.0([email protected])
+ gpt-tokenizer:
+ specifier: ^2.0.0
+ version: 2.9.0
typescript:
specifier: ^6.0.3
version: 6.0.3
@@ -731,6 +734,9 @@ importers:
'@astryxdesign/theme-neutral':
specifier: '*'
version: link:../themes/neutral
+ gpt-tokenizer:
+ specifier: ^2.0.0
+ version: 2.9.0
packages/core:
dependencies:
@@ -4369,6 +4375,9 @@ packages:
resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-YSpexBL/k4bfliAzMrRqn3M6+it02LutVyhVpDeMKrC/O9+pCe/5s8U2hYKa2vFLD5/vHhsKc8sOn/qGqII8Kg==}
+
resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==}
@@ -9625,6 +9634,8 @@ snapshots:
+