Skip to content

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

TypeScript

docs(cli): minimal exports recipe for integration block templates (#4041)

EJ Hammondab5a429142f4
diff --git a/.changeset/integration-block-exports-recipe.md b/.changeset/integration-block-exports-recipe.md
new file mode 100644
index 0000000000..49cdca05e8
--- /dev/null
+++ b/.changeset/integration-block-exports-recipe.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[docs] Document the minimal `package.json#exports` recipe an integration needs so its block templates are importable by a bundler-resolution consumer and type-check under `moduleResolution: bundler`: `"./templates/*.tsx": "./templates/*.tsx"` plus an extensionful `import('@acme/widgets/templates/…/…Showcase.tsx')`. Adds `packages/cli/docs/integration-authoring.md` and a fixture test proving the recipe against the repo's own `tsc` and `esbuild`.
+
+@ejhammond
diff --git a/packages/cli/docs/integration-authoring.md b/packages/cli/docs/integration-authoring.md
new file mode 100644
index 0000000000..103140313e
--- /dev/null
+++ b/packages/cli/docs/integration-authoring.md
@@ -0,0 +1,105 @@
+# Authoring an Astryx Integration
+
+> **Status:** working notes. This should eventually move to the public wiki
+> alongside the rest of the integration-authoring guidance; it lives here for
+> now so it ships and is versioned with the CLI.
+
+An **Integration** is an npm package that contributes components, templates, and/or
+codemods to a consumer's design-system workflow. Consumers install the 3rd party
+package, add a line to their astryx.config file:
+
+```js
+import {createConfig} from '@astryxdesign/cli/config';
+
+export default createConfig({
+ integrations: ['@acme/astryx-widgets'],
+ ...
+});
+```
+
+Then the integration's components and templates will be surfaced alongside Astryx
+components in the Astryx CLI.
+
+```sh
+astryx component AcmeCarousel --props
+astryx component --list --package @acme/astryx-widgets
+```
+
+## The Integration File
+
+In order to register your package as an Astryx Integration, create an
+`astryx.integration.{ts,mjs,js}` file as a sibling to your `package.json`. This file
+tells Astryx where to find your components, templates, codemods, etc.
+
+```js
+// astryx.integration.{ts,mjs,js}
+import {createIntegration} from '@astryxdesign/cli/integration';
+
+export default createIntegration({
+ components: './components',
+ templates: './templates',
+ codemods: './codemods',
+ issuesUrl: 'https://github.com/acme/widgets/issues',
+});
+```
+
+## Components
+
+Your components themselves may be exported from your library as you see fit (consumers
+will still import them from your package) but Astryx CLI will look for a .doc.{ts,mjs,js}
+file with the same stem e.g. `AcmeCarousel.tsx` and `AcmeCarousel.doc.ts`.
+
+```js
+// AcmeCarousel.doc.ts
+import {createComponentDoc} from '@astryxdesign/cli/doc';
+
+export default createComponentDoc({
+ name: 'AcmeCarousel',
+ description: '...',
+ ...
+});
+```
+
+## Templates
+
+Templates are typically not exported from the package directly, but instead accessed
+via the Astryx CLI. Consumers can look through your templates and materialize them
+into their apps.
+
+You define a template with the `createPageTemplate` (for full pages) or `createBlockTemplate`
+(for smaller chunks). e.g. `AcmeLandingPage.tsx`, `AcmeLandingPage.template.ts`
+
+```js
+// AcmeLandingPage.template.ts
+import {createPageTemplate} from '@astryxdesign/cli/template';
+
+export default createPageTemplate({
+ ...
+});
+```
+
+Note that, since the CLI needs access to the template source code, you need to make sure
+that it is included in your published package. This will also allow us to render previews
+of templates in the future by bundling your template into a doc site build.
+
+Typically, this is done via the package.json `exports` key.
+
+```jsonc
+{
+ "exports": {
+ // ...
+ "./templates/*.tsx": "./templates/*.tsx",
+ },
+}
+```
+
+In order to verify that it's working, you can test importing the template component like this:
+
+```ts
+import('@acme/astryx-widgets/templates/AcmeLandingPage.tsx');
+```
+
+Import **with the `.tsx` extension** — an extensionless specifier won't resolve
+under `moduleResolution: bundler`. The extensionful `"./templates/*.tsx"` export
+above is what lets that import type-check without consumers enabling
+`allowImportingTsExtensions`.
diff --git a/packages/cli/src/api/integration-block-exports.test.mjs b/packages/cli/src/api/integration-block-exports.test.mjs
new file mode 100644
index 0000000000..a3242b1adb
--- /dev/null
+++ b/packages/cli/src/api/integration-block-exports.test.mjs
@@ -0,0 +1,240 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Proves the minimal `exports` recipe an integration package needs so a
+ * bundler-resolution consumer can `import()` its block templates AND type-check
+ * them under `moduleResolution: bundler`.
+ *
+ * Integration packages in this ecosystem ship TypeScript SOURCE — their block
+ * templates are `.tsx` files with no compiled `.d.ts`. A later feature renders
+ * showcase previews by a REAL dynamic `import()` of a block's `.tsx` source
+ * (e.g. `import('@acme/widgets/templates/Gauge/GaugeShowcase.tsx')`) instead of
+ * eval'ing source text. For that import to resolve, the integration's
+ * `package.json#exports` map must GATE the deep path.
+ *
+ * These tests stand up a throwaway `@acme/widgets` fixture and drive the two
+ * gates that matter with the repo's own toolchain:
+ * 1. `tsc --noEmit` under `moduleResolution: bundler` (the consumer profile
+ * used by the Next.js example apps — NO `allowImportingTsExtensions`).
+ * 2. `esbuild --bundle` (a real bundler resolving + loading the deep import).
+ *
+ * CANONICAL RECIPE (see integration-authoring.md):
+ * exports: { "./templates/*.tsx": "./templates/*.tsx" }
+ * import: import('@acme/widgets/templates/<Name>/<Name>Showcase.tsx') // WITH .tsx
+ *
+ * The negative controls lock in WHY the extension is required: a bare
+ * `./templates/*` export with an extensionless import fails to type-check under
+ * bundler resolution (TS cannot infer the `.tsx` extension for a deep
+ * specifier), and an extensionless import fails to bundle.
+ */
+
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {createRequire} from 'node:module';
+import {execFileSync} from 'node:child_process';
+
+const require = createRequire(import.meta.url);
+
+/** Resolve the workspace tsc/esbuild binaries; null if unavailable. */
+function resolveBin(spec) {
+ try {
+ return require.resolve(spec);
+ } catch {
+ return null;
+ }
+}
+const TSC_BIN = resolveBin('typescript/bin/tsc');
+const ESBUILD_BIN = resolveBin('esbuild/bin/esbuild');
+
+let tmpDir;
+
+/**
+ * Build an @acme/widgets fixture: a block template (`.template.ts` doc +
+ * same-stem `.tsx` source) under `templates/`, plus an astryx.integration
+ * manifest, plus a caller-supplied `exports` map.
+ * @param {Record<string, string> | undefined} exportsMap
+ */
+function makeWidgets(exportsMap) {
+ const pkgDir = path.join(tmpDir, 'node_modules', '@acme', 'widgets');
+ const blockDir = path.join(pkgDir, 'templates', 'Gauge');
+ fs.mkdirSync(blockDir, {recursive: true});
+
+ const pkg = {name: '@acme/widgets', version: '2.0.0', type: 'module'};
+ if (exportsMap) pkg.exports = exportsMap;
+ fs.writeFileSync(
+ path.join(pkgDir, 'package.json'),
+ JSON.stringify(pkg, null, 2),
+ );
+ fs.writeFileSync(
+ path.join(pkgDir, 'astryx.integration.mjs'),
+ `export default { templates: './templates' };\n`,
+ );
+ // The template-spec doc (canonical `.template.*` family).
+ fs.writeFileSync(
+ path.join(blockDir, 'GaugeShowcase.template.ts'),
+ `export default { name: 'Gauge showcase', description: 'A gauge.' };\n`,
+ );
+ // The same-stem `.tsx` SOURCE that a preview will dynamically import().
+ // Returns a plain value so the fixture type-checks without React types.
+ fs.writeFileSync(
+ path.join(blockDir, 'GaugeShowcase.tsx'),
+ `const GaugeShowcase = (): string => 'gauge-showcase';\n` +
+ `export default GaugeShowcase;\n`,
+ );
+ return pkgDir;
+}
+
+/** Write a consumer that dynamically imports the given specifier. */
+function writeConsumer(specifier) {
+ fs.writeFileSync(
+ path.join(tmpDir, 'consumer.ts'),
+ `const load = () => import('${specifier}');\nexport default load;\n`,
+ );
+}
+
+/**
+ * The realistic consumer tsconfig: matches the repo's Next.js example apps
+ * (`moduleResolution: bundler`, `noEmit`, and deliberately NO
+ * `allowImportingTsExtensions`).
+ */
+function writeTsconfig() {
+ fs.writeFileSync(
+ path.join(tmpDir, 'tsconfig.json'),
+ JSON.stringify(
+ {
+ compilerOptions: {
+ target: 'ES2022',
+ lib: ['ES2022', 'DOM', 'DOM.Iterable'],
+ module: 'ESNext',
+ moduleResolution: 'bundler',
+ jsx: 'react-jsx',
+ strict: true,
+ skipLibCheck: true,
+ esModuleInterop: true,
+ noEmit: true,
+ isolatedModules: true,
+ },
+ include: ['consumer.ts'],
+ },
+ null,
+ 2,
+ ),
+ );
+}
+
+/** @returns {{ok: boolean, out: string}} */
+function runTsc() {
+ try {
+ execFileSync(process.execPath, [TSC_BIN, '--noEmit', '-p', 'tsconfig.json'], {
+ cwd: tmpDir,
+ stdio: 'pipe',
+ });
+ return {ok: true, out: ''};
+ } catch (e) {
+ return {ok: false, out: `${e.stdout ?? ''}${e.stderr ?? ''}`};
+ }
+}
+
+/** @returns {{ok: boolean, out: string}} */
+function runEsbuild() {
+ try {
+ // esbuild's bin is a native executable (not a node script), so invoke it
+ // directly rather than through process.execPath.
+ execFileSync(
+ ESBUILD_BIN,
+ [
+ 'consumer.ts',
+ '--bundle',
+ '--format=esm',
+ '--loader:.tsx=tsx',
+ '--outfile=/dev/null',
+ '--log-level=error',
+ ],
+ {cwd: tmpDir, stdio: 'pipe'},
+ );
+ return {ok: true, out: ''};
+ } catch (e) {
+ return {ok: false, out: `${e.stdout ?? ''}${e.stderr ?? ''}`};
+ }
+}
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-block-exports-'));
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: 'consumer', private: true, type: 'module'}),
+ );
+ writeTsconfig();
+});
+
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+const CANONICAL = 'import(@acme/widgets/templates/Gauge/GaugeShowcase.tsx)';
+const SPEC = '@acme/widgets/templates/Gauge/GaugeShowcase.tsx';
+
+describe('integration block-template exports recipe', () => {
+ it.runIf(TSC_BIN != null)(
+ `CANONICAL: exports {"./templates/*.tsx"} + ${CANONICAL} type-checks under bundler resolution`,
+ () => {
+ makeWidgets({'./templates/*.tsx': './templates/*.tsx'});
+ writeConsumer(SPEC);
+ const {ok, out} = runTsc();
+ expect(out).toBe('');
+ expect(ok).toBe(true);
+ },
+ 30_000,
+ );
+
+ it.runIf(ESBUILD_BIN != null)(
+ `CANONICAL: the same import resolves + bundles with a real bundler`,
+ () => {
+ makeWidgets({'./templates/*.tsx': './templates/*.tsx'});
+ writeConsumer(SPEC);
+ const {ok, out} = runEsbuild();
+ expect(out).toBe('');
+ expect(ok).toBe(true);
+ },
+ 30_000,
+ );
+
+ it.runIf(TSC_BIN != null)(
+ 'NEGATIVE: an extensionless import does NOT type-check (TS cannot infer .tsx)',
+ () => {
+ makeWidgets({'./templates/*.tsx': './templates/*.tsx'});
+ writeConsumer('@acme/widgets/templates/Gauge/GaugeShowcase');
+ const {ok, out} = runTsc();
+ expect(ok).toBe(false);
+ expect(out).toContain('TS2307');
+ },
+ 30_000,
+ );
+
+ it.runIf(TSC_BIN != null)(
+ 'NEGATIVE: a bare "./templates/*" export (no .tsx entry) does NOT type-check the .tsx import',
+ () => {
+ // Only a bare mapping — the extensionful subpath is not exported.
+ makeWidgets({'./templates/*': './templates/*'});
+ writeConsumer(SPEC);
+ const {ok, out} = runTsc();
+ expect(ok).toBe(false);
+ // Bare export forces the TS5097 opt-in requirement (allowImportingTsExtensions).
+ expect(out).toContain('TS5097');
+ },
+ 30_000,
+ );
+
+ it.runIf(ESBUILD_BIN != null)(
+ 'NEGATIVE: an extensionless import does NOT bundle against the .tsx-only export',
+ () => {
+ makeWidgets({'./templates/*.tsx': './templates/*.tsx'});
+ writeConsumer('@acme/widgets/templates/Gauge/GaugeShowcase');
+ const {ok} = runEsbuild();
+ expect(ok).toBe(false);
+ },
+ 30_000,
+ );
+});