An open source design system that's fully customizable and agent ready
TypeScript
feat(docsite): document stable integration packages on the production site (#7393)
Cindy Zhang9e09cec496fd
diff --git a/apps/docsite/README.md b/apps/docsite/README.mdindex 9a02abb1a5..81ed43dd9b 100644--- a/apps/docsite/README.md+++ b/apps/docsite/README.md@@ -117,18 +117,28 @@ them. Check the theme's `## Fonts` section for the specific Google Fonts URL.1. Create the package under `packages/<name>/`2. Add `"@astryxdesign/<name>": "*"` to `apps/docsite/package.json` dependencies-3. For a canary-only component package, set `astryx.canaryOnly: true` in its- `package.json`, add `astryx.integration.mjs` with `components: './src'`,- include that file in the package's `files`, and list the package in- `apps/docsite/astryx.config.mjs`. Keep optional showcase blocks in the- package too and expose their directory through the integration's `templates`- field; the docsite retrieves them through the CLI template API.+3. For a component package other than Core, add `astryx.integration.mjs` with+ `components: './src'`, include that file (and `src`) in the package's+ `files`, and list the package in `apps/docsite/astryx.config.mjs`. Keep+ optional showcase blocks in the package too and expose their directory+ through the integration's `templates` field; the docsite retrieves them+ through the CLI template API. A package that publishes only canaries also+ sets `astryx.canaryOnly: true` in its `package.json`. A package that+ publishes stable releases joins the Changesets `fixed` group in+ `.changeset/config.json` so it versions with Core: the production snapshot+ fetches every documented package at Core's published version, and a stable+ integration on its own version would fail production builds as a partly+ published release.4. Run `pnpm generate`The package appears in the sidebar, the libraries section, and gets its own`/docs/<name>` detail page. If the package contains `.doc.mjs` files,its components are extracted into `componentRegistry.ts` as well. Canary-onlypackages and components appear only on canary builds and carry a flask icon.+A configured package that is a stable release (neither `private` nor+`astryx.canaryOnly`) is documented on the production site too, from its+published tarball, starting with its first stable release+(`scripts/resolve-content-root.mjs`).## Adding a Blog Postdiff --git a/apps/docsite/astryx.config.mjs b/apps/docsite/astryx.config.mjsindex 05330da3f7..b29817834a 100644--- a/apps/docsite/astryx.config.mjs+++ b/apps/docsite/astryx.config.mjs@@ -1,8 +1,10 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * Astryx CLI integrations documented by the canary site.- * Production uses published stable packages and never loads this catalog.+ * Astryx CLI integrations the docsite documents. The canary site documents+ * every package here from the workspace. Production documents the ones that+ * are stable releases, from their published tarballs, and never loads a+ * canary-only package (src/lib/integrationTargets.mjs).*/export default {integrations: [diff --git a/apps/docsite/scripts/generate-data.mjs b/apps/docsite/scripts/generate-data.mjsindex 4b93e424c8..58db50a79b 100644--- a/apps/docsite/scripts/generate-data.mjs+++ b/apps/docsite/scripts/generate-data.mjs@@ -24,7 +24,10 @@ import * as path from 'node:path';import {execFileSync} from 'node:child_process';import {createRequire} from 'node:module';import {fileURLToPath, pathToFileURL} from 'node:url';-import {resolveContentRoot} from './resolve-content-root.mjs';+import {+ admittedStableIntegration,+ resolveContentRoot,+} from './resolve-content-root.mjs';import {GUIDE_NAMESPACE_PAGES,GUIDE_PAGE_NAMESPACES,@@ -38,7 +41,10 @@ import {template as queryTemplates,} from '@astryxdesign/cli/api';import docsiteConfig from '../astryx.config.mjs';-import {integrationContentEnabled} from '../src/lib/integrationTargets.mjs';+import {+ integrationContentEnabled,+ integrationPackagesForTarget,+} from '../src/lib/integrationTargets.mjs';import {expandWorkspaceDirs} from '../../../scripts/lib/workspace-globs.mjs';import {projectThemingDoc} from './lib/theming-doc.mjs';import {collectBlogImages} from './lib/blog-images.mjs';@@ -98,16 +104,34 @@ function writeRegistry(filename, content) {}/**- * Ask the CLI for the component packages configured by this docsite. The- * integration list is canary-only: stable production content comes from the- * published package snapshot and never loads workspace integrations.+ * The integration packages this build documents. Canary documents every+ * configured integration and asks the CLI to confirm each one is installed.+ * `latest` documents only the configured integrations that are stable+ * releases present in the published content snapshot+ * (src/lib/integrationTargets.mjs); their component docs are read from the+ * snapshot like Core's, so no workspace discovery runs.+ *+ * The admitted list is written to src/generated/integrationPackages.json so+ * generate-scope.mjs and generate-playground-types.mjs document the same+ * packages without resolving the content snapshot again.*/function discoverConfiguredComponentPackages() {- // Same gate as generate-scope.mjs (src/lib/integrationTargets.mjs): only the- // canary target ever loads workspace integration packages.- if (!integrationContentEnabled(DOCSITE_TARGET)) {+ const admitted = integrationPackagesForTarget(+ DOCSITE_TARGET,+ docsiteConfig,+ admittedStableIntegration(CONTENT_ROOT),+ );+ fs.writeFileSync(+ path.join(OUT_DIR, 'integrationPackages.json'),+ JSON.stringify({target: DOCSITE_TARGET, packages: admitted}, null, 2) ++ '\n',+ );+ if (admitted.length === 0) {return new Set();}+ if (!integrationContentEnabled(DOCSITE_TARGET)) {+ return new Set(admitted);+ }const output = execFileSync(process.execPath,@@ -1495,7 +1519,10 @@ async function generateBlockRegistry() {});}- if (integrationContentEnabled(DOCSITE_TARGET)) {+ // Showcase blocks are executable content: like Core's CLI templates they are+ // live-rendered from the workspace install (see resolve-content-root.mjs),+ // filtered to the integration packages this build documents.+ if (CONFIGURED_COMPONENT_PACKAGES.size > 0) {const templateList = await queryTemplates(undefined, {list: true,type: 'block',diff --git a/apps/docsite/scripts/generate-playground-types.mjs b/apps/docsite/scripts/generate-playground-types.mjsindex 76d73ed4f1..255b35cc45 100644--- a/apps/docsite/scripts/generate-playground-types.mjs+++ b/apps/docsite/scripts/generate-playground-types.mjs@@ -3,7 +3,7 @@/*** Generates a JSON bundle of @astryxdesign/core, React, StyleX, icon,- * Recharts, and canary integration-package declarations for the playground's+ * Recharts, and integration-package declarations for the playground's* Monaco editor.* Output: public/playground-types.json*@@ -24,9 +24,8 @@ import {import {createRequire} from 'node:module';import {join, dirname, relative} from 'node:path';import {fileURLToPath} from 'node:url';-import docsiteConfig from '../astryx.config.mjs';import {getTarget} from './resolve-content-root.mjs';-import {integrationPackagesForTarget} from '../src/lib/integrationTargets.mjs';+import {readAdmittedIntegrationPackages} from '../src/lib/integrationTargets.mjs';// Resolves from this script, so docsite's own dependencies are found wherever// the installer put them. Throws if one is missing, rather than emitting a@@ -310,15 +309,19 @@ function buildThemeTypes() {return files;}-// Integration packages the canary preview scope exposes (the same shared gate-// generate-scope.mjs uses, so production declares none). Declared as shorthand-// ambient modules: imports resolve, typed as `any`, so the editor shows no-// unresolved-module error on code that renders. Like the theme packages, their-// dist is not built in CI's docsite-test job, so real declarations are left-// for a follow-up.+// Integration packages the preview scope exposes: the list generate-data.mjs+// admitted for this target (every configured integration on canary; on latest+// the ones that are stable releases), the same list generate-scope.mjs maps.+// Declared as shorthand ambient modules: imports resolve, typed as `any`, so+// the editor shows no unresolved-module error on code that renders. Like the+// theme packages, their dist is not built in CI's docsite-test job, so real+// declarations are left for a follow-up.function buildIntegrationTypes() {const files = {};- for (const pkg of integrationPackagesForTarget(getTarget(), docsiteConfig)) {+ for (const pkg of readAdmittedIntegrationPackages(+ join(root, 'src/generated'),+ getTarget(),+ )) {files[pkg] = {'index.d.ts': `declare module '${pkg}';\n`};}return files;diff --git a/apps/docsite/scripts/generate-scope.mjs b/apps/docsite/scripts/generate-scope.mjsindex 64800cdae6..1920dee461 100644--- a/apps/docsite/scripts/generate-scope.mjs+++ b/apps/docsite/scripts/generate-scope.mjs@@ -4,8 +4,10 @@/*** Generates apps/docsite/src/generated/playground-scope.ts*- * Maps Core exports and configured canary integrations into the preview iframe.- * @input Core package exports, docsite integrations, and the content target+ * Maps Core exports and the integration packages this build documents into+ * the preview iframe.+ * @input Core package exports, the admitted integration packages recorded by+ * generate-data.mjs, and the content target* @output The runtime module scope used by copyable Playground examples* @position Build-time companion to component and block registry generation* This runs as part of `pnpm generate` (before dev/build) so new components@@ -17,19 +19,19 @@import {readFileSync, writeFileSync, mkdirSync} from 'node:fs';import {dirname, resolve} from 'node:path';import {fileURLToPath} from 'node:url';-import docsiteConfig from '../astryx.config.mjs';import {getTarget} from './resolve-content-root.mjs';-import {integrationPackagesForTarget} from '../src/lib/integrationTargets.mjs';+import {readAdmittedIntegrationPackages} from '../src/lib/integrationTargets.mjs';const __dirname = dirname(fileURLToPath(import.meta.url));const ROOT = resolve(__dirname, '..');const CORE_PKG = resolve(ROOT, '../../packages/core/package.json');const OUT = resolve(ROOT, 'src/generated/playground-scope.ts');-// Shared with generate-data.mjs so the canary-only admission rule for-// integration packages cannot drift between the two generators.-const integrationPackages = integrationPackagesForTarget(+// The packages generate-data.mjs admitted for this target (canary: every+// configured integration; latest: the stable releases in its content+// snapshot), so the scope and the registries describe the same packages.+const integrationPackages = readAdmittedIntegrationPackages(+ resolve(ROOT, 'src/generated'),getTarget(),- docsiteConfig,);const HEADER = `// Copyright (c) Meta Platforms, Inc. and affiliates.diff --git a/apps/docsite/scripts/resolve-content-root.mjs b/apps/docsite/scripts/resolve-content-root.mjsindex bccfde3b68..747a856796 100644--- a/apps/docsite/scripts/resolve-content-root.mjs+++ b/apps/docsite/scripts/resolve-content-root.mjs@@ -39,6 +39,7 @@ import * as path from 'node:path';import {execFileSync} from 'node:child_process';import * as os from 'node:os';import {fileURLToPath} from 'node:url';+import {isStableRelease} from '../src/lib/integrationTargets.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));const DOCSITE_ROOT = path.resolve(__dirname, '..');@@ -82,8 +83,9 @@ export function getTarget() {* - `astryx.canaryOnly` packages (e.g. @astryxdesign/charts, @astryxdesign/lab)* — these publish only as canaries, so no stable version exists to document.* This mirrors the publishable predicate in .github/workflows/release.yml's- * stable-publish step, so production documents exactly the stable release set.- * (On canary these still appear, sourced from the workspace like everything else.)+ * stable-publish step (`isStableRelease`), so production documents exactly the+ * stable release set. (On canary these still appear, sourced from the+ * workspace like everything else.)*/function latestPublishablePackages() {const pkg = JSON.parse(@@ -92,13 +94,7 @@ function latestPublishablePackages() {const deps = {...pkg.dependencies, ...pkg.devDependencies};return Object.keys(deps).filter(name => name.startsWith('@astryxdesign/'))- .map(name => {- const short = name.slice('@astryxdesign/'.length);- const dir = short.startsWith('theme-')- ? path.join('packages', 'themes', short.slice('theme-'.length))- : path.join('packages', short);- return {name, dir};- })+ .map(name => ({name, dir: packageDirFor(name)})).filter(({dir}) => {// Read the package's own workspace manifest for its publish flags. Same// rule release.yml uses for the stable `latest` tag.@@ -107,10 +103,46 @@ function latestPublishablePackages() {return false;}const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));- return manifest.private !== true && manifest.astryx?.canaryOnly !== true;+ return isStableRelease(manifest);});}+/** Monorepo-relative directory of a documented @astryxdesign/* package. */+function packageDirFor(name) {+ const short = name.slice('@astryxdesign/'.length);+ return short.startsWith('theme-')+ ? path.join('packages', 'themes', short.slice('theme-'.length))+ : path.join('packages', short);+}++/**+ * The `latest` admission predicate for configured integration packages (see+ * src/lib/integrationTargets.mjs): a configured package is admitted when its+ * workspace manifest is a stable release AND the materialized content+ * snapshot holds it. The second half matters between a package's promotion+ * and its first stable publish: the package is publishable, but no tarball+ * exists at the documented version yet, so `latest` keeps documenting the+ * release that is actually on npm.+ *+ * @param {string} contentRoot the resolved `latest` content root+ * @returns {(name: string) => boolean}+ */+export function admittedStableIntegration(contentRoot) {+ return name => {+ if (typeof name !== 'string' || !name.startsWith('@astryxdesign/')) {+ return false;+ }+ const dir = packageDirFor(name);+ const manifestPath = path.join(REPO_ROOT, dir, 'package.json');+ if (!fs.existsSync(manifestPath)) return false;+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));+ return (+ isStableRelease(manifest) &&+ fs.existsSync(path.join(contentRoot, dir, 'package.json'))+ );+ };+}+/** Latest published version of the version-source package, read live from npm. */function latestPublishedVersion() {const out = run(@@ -143,20 +175,31 @@ function latestPublishedVersion() {* <cache>/package.json — synthetic private root manifest* <cache>/packages/core/… — @astryxdesign/core tarball* <cache>/packages/themes/<name>/… — @astryxdesign/theme-<name> tarballs+ *+ * `exec` runs npm and tar (tests inject a fake); `cacheDir` is where the+ * version caches live.*/-function materializeFromNpm(version, packages) {- const cacheRoot = path.join(DOCSITE_ROOT, '.content-cache', `npm-${version}`);+export function materializeFromNpm(+ version,+ packages,+ {exec = run, cacheDir = path.join(DOCSITE_ROOT, '.content-cache')} = {},+) {+ const cacheRoot = path.join(cacheDir, `npm-${version}`);const stamp = path.join(cacheRoot, '.stamp');- // v2: layout is declared by a synthetic pnpm-workspace.yaml (not a- // package.json `workspaces` array) — bump invalidates caches from the- // pre-#3752 layout, which the new discovery can't read.- const stampValue = `v2:npm-${version}:${packages- .map(p => p.name)- .sort()- .join(',')}`;+ // The stamp names the packages the cache actually holds. It is reused only+ // when it names every expected package, so a cache built while a package+ // awaited its first stable release (see below) is rebuilt on the next run+ // instead of keeping that gap.+ // v3: the stamp lists materialized packages, not expected ones. v2 declared+ // the layout through a synthetic pnpm-workspace.yaml (pre-#3752 caches+ // cannot be read by the new discovery).+ const expectedStamp = stampFor(+ version,+ packages.map(p => p.name),+ );if (fs.existsSync(stamp) &&- fs.readFileSync(stamp, 'utf-8').trim() === stampValue+ fs.readFileSync(stamp, 'utf-8').trim() === expectedStamp) {return cacheRoot;}@@ -169,7 +212,7 @@ function materializeFromNpm(version, packages) {// and a minimal package.json marks the cache root as a private package.fs.writeFileSync(path.join(cacheRoot, 'pnpm-workspace.yaml'),- ["packages:", " - 'packages/*'", " - 'packages/themes/*'", ''].join('\n'),+ ['packages:', " - 'packages/*'", " - 'packages/themes/*'", ''].join('\n'),);fs.writeFileSync(path.join(cacheRoot, 'package.json'),@@ -184,6 +227,7 @@ function materializeFromNpm(version, packages) {),);+ const materialized = [];const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-pin-'));try {for (const {name, dir} of packages) {@@ -196,29 +240,98 @@ function materializeFromNpm(version, packages) {// makes npm hard-error EBADDEVENGINES if it discovers that manifest by// walking up from the cwd. The tmp dir has no package.json, so npm skips// the engine guard. (COREPACK_ENABLE_STRICT=0 as belt-and-suspenders.)- const out = run(- 'npm',- ['pack', spec, '--pack-destination', tmp, '--json'],- {- cwd: tmp,- maxBuffer: 256 * 1024 * 1024,- env: {...process.env, COREPACK_ENABLE_STRICT: '0'},- },- );+ const out = packPublished(spec, tmp, exec);+ if (out == null) {+ // No tarball at the documented version. For a package that has+ // never had a stable release this is the gap between its promotion+ // and the next cut: `latest` documents what is on npm, and the+ // package appears once that cut publishes it. For a package with a+ // stable release behind it, the release itself is only partly+ // published, and the build fails as before.+ const prior = latestStableVersion(name, exec);+ if (prior != null) {+ throw new Error(+ `${spec} is not on npm, but ${name} already has stable release ${prior}: ` ++ 'the documented release is only partly published.',+ );+ }+ console.log(+ ` ${spec} is not on npm yet; ${name} joins latest after its first stable release`,+ );+ continue;+ }const tgz = path.join(tmp, JSON.parse(out)[0].filename);const dest = path.join(cacheRoot, dir);fs.mkdirSync(dest, {recursive: true});// npm tarballs wrap everything under a top-level "package/" dir.- run('tar', ['-x', '-z', '-f', tgz, '--strip-components=1', '-C', dest]);+ exec('tar', ['-x', '-z', '-f', tgz, '--strip-components=1', '-C', dest]);+ materialized.push(name);}} finally {fs.rmSync(tmp, {recursive: true, force: true});}- fs.writeFileSync(stamp, stampValue);+ fs.writeFileSync(stamp, stampFor(version, materialized));return cacheRoot;}+function stampFor(version, names) {+ return `v3:npm-${version}:${[...names].sort().join(',')}`;+}++/**+ * Whether an npm error is "no such package or version": E404 for a package+ * that is not on npm at all, ETARGET for a published package without the+ * requested version (`npm pack` reports the latter as "No matching version").+ */+function isNotFound(error) {+ return /\b(?:E404|ETARGET)\b/.test(String(error?.stderr ?? error));+}++/**+ * Download `spec`'s published tarball into `tmp` and return npm's JSON+ * report, or null when no such version is published. Any other failure+ * propagates.+ */+function packPublished(spec, tmp, exec) {+ try {+ return exec('npm', ['pack', spec, '--pack-destination', tmp, '--json'], {+ cwd: tmp,+ maxBuffer: 256 * 1024 * 1024,+ // stderr is read from the error, not inherited, so an expected E404+ // does not print as a failure in the build log.+ stdio: ['ignore', 'pipe', 'pipe'],+ env: {...process.env, COREPACK_ENABLE_STRICT: '0'},+ });+ } catch (error) {+ if (isNotFound(error)) return null;+ throw error;+ }+}++/**+ * The version on `name`'s stable npm dist-tag, or null when the package has+ * never had a stable release: it is not on npm at all, or its `latest` tag+ * still points at a prerelease placeholder (the bootstrap publish that+ * reserves a package name before its first real release).+ */+export function latestStableVersion(name, exec = run) {+ let out;+ try {+ out = exec('npm', ['view', name, 'dist-tags', '--json'], {+ maxBuffer: 8 * 1024 * 1024,+ stdio: ['ignore', 'pipe', 'pipe'],+ env: {...process.env, COREPACK_ENABLE_STRICT: '0'},+ });+ } catch (error) {+ if (isNotFound(error)) return null;+ throw error;+ }+ const latest = JSON.parse(out)?.[PUBLISHED_DIST_TAG];+ if (typeof latest !== 'string' || latest.includes('-')) return null;+ return latest;+}+/*** Returns {target, contentRoot, cliRoot, version} for the current target.* contentRoot mirrors REPO_ROOT layout (has packages/* and pnpm-workspace.yaml).diff --git a/apps/docsite/src/__tests__/data-extraction.test.ts b/apps/docsite/src/__tests__/data-extraction.test.tsindex dae1aad7f4..8941516f5b 100644--- a/apps/docsite/src/__tests__/data-extraction.test.ts+++ b/apps/docsite/src/__tests__/data-extraction.test.ts@@ -51,7 +51,24 @@ const COMPONENT_REGISTRY_SOURCE = fs.readFileSync(COMPONENT_REGISTRY_PATH,'utf-8',);-const CONFIGURED_CANARY_PACKAGES = new Set(docsiteConfig.integrations);+const CONFIGURED_INTEGRATION_PACKAGES = new Set(docsiteConfig.integrations);++/** The workspace manifest of a configured integration package. */+function integrationManifest(name: string): {+ private?: boolean;+ astryx?: {canaryOnly?: boolean};+} {+ const entry = packages.find(pkg => pkg.name === name);+ if (!entry) {+ throw new Error(`${name} is missing from packageRegistry`);+ }+ return JSON.parse(+ fs.readFileSync(+ path.join(REPO_ROOT, entry.packagePath, 'package.json'),+ 'utf-8',+ ),+ );+}function findFiles(dir: string, predicate: (filePath: string) => boolean) {const files: string[] = [];@@ -132,8 +149,12 @@ describe('packageRegistry', () => {expect(names).not.toContain('@astryxdesign/theme-chocolate');expect(names).not.toContain('@astryxdesign/theme-daily');expect(names).not.toContain('@astryxdesign/build');+ // Every canary-only package is a configured integration; a configured+ // integration that is a stable release (no `astryx.canaryOnly`) is not.expect(packages.filter(pkg => pkg.canaryOnly).map(pkg => pkg.name)).toEqual(- [...CONFIGURED_CANARY_PACKAGES].sort(),+ [...CONFIGURED_INTEGRATION_PACKAGES]+ .filter(name => integrationManifest(name).astryx?.canaryOnly === true)+ .sort(),);expect(packages.length).toBeGreaterThanOrEqual(9);});@@ -263,14 +284,18 @@ describe('componentRegistry', () => {'VegaChart',]);+ // Components of a canary-only integration are not ready; components of a+ // configured integration that is a stable release are, like Core's.for (const packageName of ['@astryxdesign/lab','@astryxdesign/charts','@astryxdesign/richtext','@astryxdesign/vega',]) {+ const isReady =+ integrationManifest(packageName).astryx?.canaryOnly !== true;expect(- components[packageName].every(comp => !comp.isReady),+ components[packageName].every(comp => comp.isReady === isReady),packageName,).toBe(true);}diff --git a/apps/docsite/src/__tests__/integration-targets.test.ts b/apps/docsite/src/__tests__/integration-targets.test.tsindex cf82bbb924..e72e1a6f03 100644--- a/apps/docsite/src/__tests__/integration-targets.test.ts+++ b/apps/docsite/src/__tests__/integration-targets.test.ts@@ -3,27 +3,31 @@/*** @file Integration-content target gating tests.*- * The production (`latest`) docsite must contain ZERO integration content:- * the configured integration packages (@astryxdesign/lab et al.) are- * canary-only (spec:AST-017). generate-data.mjs and generate-scope.mjs share- * one admission gate (src/lib/integrationTargets.mjs); this file unit-tests- * that gate for every target and pins the canary-side invariants that make- * the exclusion provable from the generated artifacts.+ * The production (`latest`) docsite documents a configured integration+ * package only when it is a stable release; a canary-only package+ * (@astryxdesign/lab et al., spec:AST-017) never reaches production.+ * generate-data.mjs applies that rule once (src/lib/integrationTargets.mjs)+ * and the other generators read its result; this file unit-tests the rule+ * for every target and pins the canary-side invariants that make the+ * exclusion provable from the generated artifacts.*- * @input The shared integration target gate, docsite config, and the+ * @input The shared integration admission rule, docsite config, and the* canary-generated registries- * @output Regression coverage for production exclusion of integration content+ * @output Regression coverage for which integration content each target admits* @position Build-time docsite target verification* Run: pnpm -F @astryxdesign/docsite test*/import * as fs from 'node:fs';+import * as os from 'node:os';import * as path from 'node:path';import {describe, expect, it} from 'vitest';import docsiteConfig from '../../astryx.config.mjs';import {integrationContentEnabled,integrationPackagesForTarget,+ isStableRelease,+ readAdmittedIntegrationPackages,} from '../lib/integrationTargets.mjs';import {blocks} from '../generated/blockRegistry';import {components} from '../generated/componentRegistry';@@ -43,10 +47,55 @@ describe('integration target gate', () => {);});- it('returns no packages on latest regardless of configuration', () => {+ it('returns no packages on latest without a stability predicate', () => {expect(integrationPackagesForTarget('latest', docsiteConfig)).toEqual([]);});+ it('admits only the configured packages the predicate calls stable, in order, on latest', () => {+ const config = {+ integrations: ['@astryxdesign/a', '@astryxdesign/b', '@astryxdesign/c'],+ };+ expect(+ integrationPackagesForTarget('latest', config, name =>+ ['@astryxdesign/c', '@astryxdesign/a'].includes(name),+ ),+ ).toEqual(['@astryxdesign/a', '@astryxdesign/c']);+ // Canary ignores the predicate: every configured package is admitted.+ expect(integrationPackagesForTarget('canary', config, () => false)).toEqual(+ config.integrations,+ );+ });++ it('reads back the admitted list generate-data.mjs recorded, for the same target', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-admitted-'));+ try {+ expect(() => readAdmittedIntegrationPackages(dir, 'canary')).toThrow(+ /run scripts\/generate-data\.mjs first/,+ );+ fs.writeFileSync(+ path.join(dir, 'integrationPackages.json'),+ JSON.stringify({target: 'latest', packages: ['@astryxdesign/a']}),+ );+ expect(readAdmittedIntegrationPackages(dir, 'latest')).toEqual([+ '@astryxdesign/a',+ ]);+ expect(() => readAdmittedIntegrationPackages(dir, 'canary')).toThrow(+ /generated for target "latest"/,+ );+ } finally {+ fs.rmSync(dir, {recursive: true, force: true});+ }+ });++ it('calls a manifest stable only without private or canaryOnly', () => {+ expect(isStableRelease({})).toBe(true);+ expect(isStableRelease({private: true})).toBe(false);+ expect(isStableRelease({astryx: {canaryOnly: true}})).toBe(false);+ expect(isStableRelease({private: false, astryx: {canaryOnly: false}})).toBe(+ true,+ );+ });+it('tolerates a config without an integrations list', () => {expect(integrationPackagesForTarget('canary', {})).toEqual([]);expect(integrationPackagesForTarget('canary', undefined)).toEqual([]);@@ -77,32 +126,42 @@ describe('production-exclusion invariants (asserted on canary artifacts)', () =>}});- it('marks every configured integration canary-only or private, so the latest content snapshot can never materialize it', () => {+ it('admits a configured integration on latest only when it is a stable release', () => {// resolve-content-root.mjs materializes the `latest` content root from the// packages published to the stable npm tag, excluding `private` and- // `astryx.canaryOnly` manifests (mirroring release.yml). As long as every- // configured integration carries one of those flags, the production data- // pipeline cannot even see its sources. Revisit this invariant before ever- // configuring a stable package as a docsite integration.- for (const name of docsiteConfig.integrations) {+ // `astryx.canaryOnly` manifests (mirroring release.yml). The admission rule+ // uses the same predicate, so a canary-only integration can never reach+ // the production data pipeline, and a configured package that is a stable+ // release is documented there once its first stable release is published.+ const manifestOf = (name: string) => {const registryEntry = packages.find(pkg => pkg.name === name);// Present on canary (documented at all) …expect(registryEntry,`${name} missing from canary packageRegistry`,).toBeDefined();- const manifest = JSON.parse(+ return JSON.parse(fs.readFileSync(path.join(REPO_ROOT, registryEntry!.packagePath, 'package.json'),'utf-8',),);+ };+ const admitted = new Set(+ integrationPackagesForTarget('latest', docsiteConfig, name =>+ isStableRelease(manifestOf(name)),+ ),+ );+ for (const name of docsiteConfig.integrations) {+ const manifest = manifestOf(name);const excludedFromStable =manifest.private === true || manifest.astryx?.canaryOnly === true;expect(- excludedFromStable,- `${name} is neither private nor astryx.canaryOnly — it would be eligible for the latest content snapshot`,- ).toBe(true);+ admitted.has(name),+ excludedFromStable+ ? `${name} is private or astryx.canaryOnly and must stay off latest`+ : `${name} is a stable release and belongs on latest`,+ ).toBe(!excludedFromStable);}});diff --git a/apps/docsite/src/__tests__/resolve-content-root.test.ts b/apps/docsite/src/__tests__/resolve-content-root.test.tsindex 343abfb85c..14cc3b2356 100644--- a/apps/docsite/src/__tests__/resolve-content-root.test.ts+++ b/apps/docsite/src/__tests__/resolve-content-root.test.ts@@ -9,14 +9,28 @@* for CI lanes and local runs. Deployments rely on VERCEL_ENV alone (canary* site = preview, production → latest) and never set the override.*- * @input DOCSITE_TARGET / VERCEL_ENV environment combinations- * @output Regression coverage for the target-selection contract+ * Also covers the `latest` content snapshot: which packages it materializes+ * from npm, when a missing tarball is the gap before a package's first stable+ * release and when it is a partly published release that fails the build, and+ * that a cache built with a gap is not reused.+ *+ * @input DOCSITE_TARGET / VERCEL_ENV environment combinations; a fake npm/tar+ * runner for the snapshot+ * @output Regression coverage for the target-selection and snapshot contracts* @position Build-time docsite target verification* Run: pnpm -F @astryxdesign/docsite test*/+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';import {afterEach, beforeEach, describe, expect, it} from 'vitest';-import {getTarget} from '../../scripts/resolve-content-root.mjs';+import {+ admittedStableIntegration,+ getTarget,+ latestStableVersion,+ materializeFromNpm,+} from '../../scripts/resolve-content-root.mjs';const ENV_KEYS = ['DOCSITE_TARGET', 'VERCEL_ENV'] as const;const saved: Partial<Record<(typeof ENV_KEYS)[number], string | undefined>> =@@ -88,3 +102,221 @@ describe('getTarget', () => {expect(() => getTarget()).toThrow(/Invalid DOCSITE_TARGET="bogus"/);});});++/**+ * A fake `exec` for the snapshot: `npm pack` succeeds for the specs in+ * `published` (writing a placeholder tarball), fails E404 for the rest;+ * `npm view <name> dist-tags` answers from `distTags` (E404 when absent);+ * `tar` extracts by writing a package.json into the destination.+ */+function fakeNpm({+ published,+ distTags,+}: {+ published: string[];+ distTags: Record<string, Record<string, string>>;+}) {+ const calls: string[][] = [];+ // What npm really reports: ETARGET for a published package without the+ // requested version, E404 for a package that is not on npm at all.+ const noSuchVersion = (spec: string) =>+ Object.assign(new Error(`Command failed: npm pack ${spec}`), {+ stderr: `npm error code ETARGET\nnpm error notarget No matching version found for ${spec}.\n`,+ });+ const notFound = (what: string) =>+ Object.assign(new Error(`Command failed: npm view ${what}`), {+ stderr: `npm error code E404\nnpm error 404 Not Found - ${what}\n`,+ });+ const exec = (cmd: string, args: string[], opts: {cwd?: string} = {}) => {+ calls.push([cmd, ...args]);+ if (cmd === 'npm' && args[0] === 'pack') {+ const spec = args[1];+ if (!published.includes(spec)) {+ throw noSuchVersion(spec);+ }+ const filename = `${spec.replace(/[@/]/g, '-')}.tgz`;+ fs.writeFileSync(path.join(opts.cwd!, filename), '');+ return JSON.stringify([{filename}]);+ }+ if (cmd === 'npm' && args[0] === 'view') {+ const tags = distTags[args[1]];+ if (tags == null) {+ throw notFound(args[1]);+ }+ return JSON.stringify(tags);+ }+ if (cmd === 'tar') {+ const dest = args[args.indexOf('-C') + 1];+ fs.mkdirSync(dest, {recursive: true});+ fs.writeFileSync(path.join(dest, 'package.json'), '{}');+ return '';+ }+ throw new Error(`unexpected command: ${cmd} ${args.join(' ')}`);+ };+ return {exec, calls};+}++describe('materializeFromNpm', () => {+ const core = {name: '@astryxdesign/core', dir: 'packages/core'};+ const neutral = {+ name: '@astryxdesign/theme-neutral',+ dir: 'packages/themes/neutral',+ };+ const richtext = {name: '@astryxdesign/richtext', dir: 'packages/richtext'};+ let cacheDir: string;++ beforeEach(() => {+ cacheDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-snapshot-'));+ });++ afterEach(() => {+ fs.rmSync(cacheDir, {recursive: true, force: true});+ });++ it('skips a package that has never had a stable release and leaves it out of the stamp', () => {+ const npm = fakeNpm({+ published: ['@astryxdesign/[email protected]'],+ distTags: {+ '@astryxdesign/core': {latest: '0.7.0'},+ // The bootstrap publish that reserves the name: a prerelease on+ // `latest`, no stable release yet.+ '@astryxdesign/richtext': {+ latest: '0.0.0-bootstrap.0',+ canary: '0.7.0-canary.abc1234',+ },+ },+ });+ const root = materializeFromNpm('0.7.0', [core, richtext], {+ exec: npm.exec,+ cacheDir,+ });++ expect(fs.existsSync(path.join(root, 'packages/core/package.json'))).toBe(+ true,+ );+ expect(fs.existsSync(path.join(root, 'packages/richtext'))).toBe(false);+ expect(fs.readFileSync(path.join(root, '.stamp'), 'utf-8')).toBe(+ 'v3:npm-0.7.0:@astryxdesign/core',+ );++ // A cache with a gap is rebuilt on the next run, so the package appears+ // as soon as it is published; a complete cache is reused as is.+ const before = npm.calls.length;+ materializeFromNpm('0.7.0', [core, richtext], {exec: npm.exec, cacheDir});+ expect(npm.calls.length).toBeGreaterThan(before);+ const complete = fakeNpm({+ published: ['@astryxdesign/[email protected]'],+ distTags: {'@astryxdesign/core': {latest: '0.7.0'}},+ });+ materializeFromNpm('0.7.0', [core], {exec: complete.exec, cacheDir});+ const afterComplete = complete.calls.length;+ materializeFromNpm('0.7.0', [core], {exec: complete.exec, cacheDir});+ expect(complete.calls.length).toBe(afterComplete);+ });++ it('fails when a package with a stable release behind it is missing at the documented version', () => {+ // Core is published at 0.7.0 but the theme is still at 0.6.8: the release+ // is only partly published, which must fail the build, not document a+ // production site without the theme.+ const npm = fakeNpm({+ published: ['@astryxdesign/[email protected]'],+ distTags: {+ '@astryxdesign/core': {latest: '0.7.0'},+ '@astryxdesign/theme-neutral': {latest: '0.6.8'},+ },+ });+ expect(() =>+ materializeFromNpm('0.7.0', [core, neutral], {exec: npm.exec, cacheDir}),+ ).toThrow(+ /@astryxdesign\/theme-neutral@0\.7\.0 is not on npm, but @astryxdesign\/theme-neutral already has stable release 0\.6\.8/,+ );+ expect(fs.existsSync(path.join(cacheDir, 'npm-0.7.0', '.stamp'))).toBe(+ false,+ );+ });++ it('propagates npm failures other than a missing version', () => {+ // execFileSync appends the captured stderr to the message.+ const exec = () => {+ throw Object.assign(+ new Error('Command failed: npm pack\nnpm error code ETIMEDOUT'),+ {stderr: 'npm error code ETIMEDOUT\n'},+ );+ };+ expect(() => materializeFromNpm('0.7.0', [core], {exec, cacheDir})).toThrow(+ /ETIMEDOUT/,+ );+ });+});++describe('latestStableVersion', () => {+ it('reads the stable dist-tag', () => {+ const {exec} = fakeNpm({+ published: [],+ distTags: {'@astryxdesign/core': {latest: '0.6.8', canary: '0.7.0-c'}},+ });+ expect(latestStableVersion('@astryxdesign/core', exec)).toBe('0.6.8');+ });++ it('treats a prerelease on latest, or no package at all, as no stable release', () => {+ const {exec} = fakeNpm({+ published: [],+ distTags: {'@astryxdesign/richtext': {latest: '0.0.0-bootstrap.0'}},+ });+ expect(latestStableVersion('@astryxdesign/richtext', exec)).toBeNull();+ expect(+ latestStableVersion('@astryxdesign/never-published', exec),+ ).toBeNull();+ });+});++describe('admittedStableIntegration', () => {+ let contentRoot: string;++ beforeEach(() => {+ contentRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-content-'));+ });++ afterEach(() => {+ fs.rmSync(contentRoot, {recursive: true, force: true});+ });++ it('admits a stable package only once the content snapshot holds it', () => {+ // Core is a stable release in the workspace. Before its tarball is in+ // the snapshot (a promoted package awaiting its first stable publish)+ // it is not admitted, so its workspace showcase blocks and playground+ // scope stay off `latest` along with its component docs; once the+ // snapshot holds it, it is.+ const admitted = admittedStableIntegration(contentRoot);+ expect(admitted('@astryxdesign/core')).toBe(false);++ fs.mkdirSync(path.join(contentRoot, 'packages/core'), {recursive: true});+ fs.writeFileSync(+ path.join(contentRoot, 'packages/core/package.json'),+ '{"name":"@astryxdesign/core"}',+ );+ expect(admitted('@astryxdesign/core')).toBe(true);+ });++ it('never admits a canary-only package, a theme dir mismatch, or a non-Astryx name', () => {+ const admitted = admittedStableIntegration(contentRoot);+ // @astryxdesign/lab is astryx.canaryOnly in the workspace: a snapshot+ // entry alone cannot admit it.+ fs.mkdirSync(path.join(contentRoot, 'packages/lab'), {recursive: true});+ fs.writeFileSync(+ path.join(contentRoot, 'packages/lab/package.json'),+ '{"name":"@astryxdesign/lab"}',+ );+ expect(admitted('@astryxdesign/lab')).toBe(false);+ // Themes live under packages/themes/<name>, so the plain dir does not count.+ fs.mkdirSync(path.join(contentRoot, 'packages/theme-neutral'), {+ recursive: true,+ });+ fs.writeFileSync(+ path.join(contentRoot, 'packages/theme-neutral/package.json'),+ '{}',+ );+ expect(admitted('@astryxdesign/theme-neutral')).toBe(false);+ expect(admitted('react')).toBe(false);+ });+});diff --git a/apps/docsite/src/__tests__/search-palette.test.ts b/apps/docsite/src/__tests__/search-palette.test.tsindex 7dcc7c8f28..552d9abb23 100644--- a/apps/docsite/src/__tests__/search-palette.test.ts+++ b/apps/docsite/src/__tests__/search-palette.test.ts@@ -97,12 +97,14 @@ describe('SearchPalette data', () => {?.entries.every(entry => entry.isReady),).toBe(true);- expect(canaryCategories.map(category => category.displayName)).toEqual([- 'Charts',- 'Lab',- 'Rich Text',- 'Vega',- ]);+ // One canary category per canary-only package with components; a+ // configured integration that is a stable release joins the ready view.+ expect(canaryCategories.map(category => category.displayName)).toEqual(+ packages+ .filter(pkg => pkg.canaryOnly && components[pkg.name]?.length)+ .map(pkg => pkg.displayName)+ .sort((a, b) => a.localeCompare(b)),+ );const chartEntries = canaryCategories.flatMap(category =>category.componentItems.flatMap(item =>item.type === 'entry' || item.label !== 'Charts' ? [] : item.entries,diff --git a/apps/docsite/src/lib/integrationTargets.mjs b/apps/docsite/src/lib/integrationTargets.mjsindex 1d9730e541..b5a4702064 100644--- a/apps/docsite/src/lib/integrationTargets.mjs+++ b/apps/docsite/src/lib/integrationTargets.mjs@@ -3,26 +3,49 @@/*** @file integrationTargets.mjs*- * Single decision point for whether a docsite content target admits workspace- * integration packages (their component docs, runnable blocks, and playground- * scope modules).+ * Single decision point for which workspace integration packages a docsite+ * content target admits (their component docs, runnable blocks, and+ * playground scope modules).*- * @input A resolved docsite target ('canary' | 'latest') and the docsite- * astryx.config- * @output Whether integration content is admitted, and the admitted package- * names in configuration order- * @position Shared by scripts/generate-data.mjs, scripts/generate-scope.mjs and- * scripts/generate-playground-types.mjs so the production-exclusion rule- * cannot drift between generators. The- * production (`latest`) site must contain zero integration content — the- * configured packages are canary-only (e.g. @astryxdesign/lab, spec:AST-017).+ * @input A resolved docsite target ('canary' | 'latest'), the docsite+ * astryx.config, and — for `latest` — a predicate saying which configured+ * packages are stable releases+ * @output The admitted package names in configuration order+ * @position scripts/generate-data.mjs applies the rule and records the+ * admitted list in src/generated/integrationPackages.json;+ * scripts/generate-scope.mjs and scripts/generate-playground-types.mjs read+ * that record (`readAdmittedIntegrationPackages`) so the three generators+ * document one set of packages from one content snapshot. Canary admits+ * every configured integration. The+ * production (`latest`) site admits only the configured integrations that+ * are stable releases: packages whose manifest carries neither `private`+ * nor `astryx.canaryOnly`, the same predicate release.yml uses for the+ * stable npm tag and resolve-content-root.mjs uses to materialize the+ * `latest` content snapshot. Canary-only packages (e.g. @astryxdesign/lab,+ * spec:AST-017) therefore never reach production.* Unit-tested directly in src/__tests__/integration-targets.test.ts.*/+import * as fs from 'node:fs';+import * as path from 'node:path';++/**+ * Whether a package manifest describes a stable release: one the release+ * workflow publishes to the stable npm tag. Mirrors the publishable predicate+ * in .github/workflows/release.yml and resolve-content-root.mjs.+ *+ * @param {{private?: unknown, astryx?: {canaryOnly?: unknown}}} manifest+ * @returns {boolean}+ */+export function isStableRelease(manifest) {+ return manifest?.private !== true && manifest?.astryx?.canaryOnly !== true;+}+/**- * Integration content (workspace packages beyond @astryxdesign/core) is only- * ever admitted on the canary target. `latest` documents the published stable- * release, which never includes canary-only packages.+ * Whether `target` admits every configured integration without looking at+ * the package. Only canary does: `latest` documents the published stable+ * release, so it admits a configured integration only when that package is a+ * stable release (see {@link integrationPackagesForTarget}).** @param {string} target resolved docsite target ('canary' | 'latest')* @returns {boolean}@@ -37,11 +60,55 @@ export function integrationContentEnabled(target) {* later-wins across scope entries, so a later-configured package owns a* shared export name).*+ * On canary every configured package is admitted. On `latest` a configured+ * package is admitted only when `isStablePackage(name)` says it is a stable+ * release; without a predicate, `latest` admits nothing, which keeps the+ * production exclusion the default for every caller that has no manifest to+ * consult.+ ** @param {string} target resolved docsite target ('canary' | 'latest')* @param {{integrations?: unknown}} [config] the docsite astryx.config module- * @returns {string[]} admitted package names; empty off-canary+ * @param {(name: string) => boolean} [isStablePackage] whether a configured+ * package is a stable release (publishable to the stable npm tag)+ * @returns {string[]} admitted package names+ */+export function integrationPackagesForTarget(+ target,+ config,+ isStablePackage = () => false,+) {+ const configured = Array.isArray(config?.integrations)+ ? [...config.integrations]+ : [];+ if (integrationContentEnabled(target)) return configured;+ if (target !== 'latest') return [];+ return configured.filter(name => isStablePackage(name) === true);+}++/**+ * The integration packages generate-data.mjs admitted for this build, read+ * back from src/generated/integrationPackages.json. Later generators use+ * this instead of applying the rule again, which on `latest` would resolve+ * (and, while a promoted package awaits its first stable release,+ * re-download) the content snapshot once per generator.+ *+ * @param {string} generatedDir the docsite's src/generated directory+ * @param {string} target the target this generator resolved, for the+ * consistency check+ * @returns {string[]} admitted package names in configuration order*/-export function integrationPackagesForTarget(target, config) {- if (!integrationContentEnabled(target)) return [];- return Array.isArray(config?.integrations) ? [...config.integrations] : [];+export function readAdmittedIntegrationPackages(generatedDir, target) {+ const file = path.join(generatedDir, 'integrationPackages.json');+ if (!fs.existsSync(file)) {+ throw new Error(+ `${file} is missing: run scripts/generate-data.mjs first (pnpm generate runs the generators in order).`,+ );+ }+ const record = JSON.parse(fs.readFileSync(file, 'utf-8'));+ if (record.target !== target) {+ throw new Error(+ `${file} was generated for target "${record.target}", but this run resolves "${target}": rerun pnpm generate.`,+ );+ }+ return Array.isArray(record.packages) ? [...record.packages] : [];}