An open source design system that's fully customizable and agent ready
TypeScript
feat(docsite): document published packages on prod, workspace on canary + PR previews (#3858)
Cindy Zhange009fdd371eb
diff --git a/apps/docsite/README.md b/apps/docsite/README.mdindex 4e963d48da..ce182b1af3 100644--- a/apps/docsite/README.md+++ b/apps/docsite/README.md@@ -51,6 +51,40 @@ This means:- No hand-maintained arrays of component names; use `componentRegistry`- No `if (pkg === '@astryxdesign/core')` switches; let the pipeline classify packages+## Versioned Content: latest vs canary++The docsite ships one codebase deployed from `main`, but the data pipeline can+read package docs from two different sources depending on the build **target**.+The two targets mirror the two npm dist-tags the packages publish under:++| Target | npm dist-tag | Reads package docs from | Deploys |+| -------- | ------------ | ---------------------------------- | -------------------------------------- |+| `latest` | `@latest` | the last **published** npm release | production (`astryx.atmeta.com`) |+| `canary` | `@canary` | the live monorepo (`main`, WIP) | the canary site + **every PR preview** |++The target is derived from Vercel's `VERCEL_ENV`: the production deploy is+`latest`; preview deploys (the `main` canary site and all PR previews) and local+dev are `canary`. `scripts/resolve-content-root.mjs` maps the target to the+filesystem root the pipeline reads from — for `latest` it downloads the+published package tarballs from npm (their `src/` ships the `.doc.mjs` the+pipeline needs); for `canary` it reads the live workspace. Only the documented+**data** is version-pinned — CLI template demos are live-rendered React and+always resolve `@astryxdesign/core` from the bundled workspace version.++> **⚠️ Contributor gotcha: library changes don't show on the production site+> until they're released.** Production (`astryx.atmeta.com`) documents the last+> **published** release. If you add a component, change a prop, or update docs+> and merge to `main`, those changes will **not** appear in production until the+> next release publishes to npm. To see your merged change in a deployed site,+> use the **canary** site or any **PR preview** (both read `main`) — or the+> "Canary docs" link in the footer. The canary banner links back to+> production.++**Local dev is unaffected.** `pnpm dev` has no `VERCEL_ENV`, so it defaults to+`canary` and reads the live workspace — your local changes show up as expected.+To preview the `latest` view locally, run the pipeline with+`DOCSITE_TARGET=latest` (needs network to fetch the published tarballs).+## Adding a New Theme1. Create the theme package under `packages/themes/<name>/`diff --git a/apps/docsite/scripts/generate-data.mjs b/apps/docsite/scripts/generate-data.mjsindex bb1b679ae7..622028cbb1 100644--- a/apps/docsite/scripts/generate-data.mjs+++ b/apps/docsite/scripts/generate-data.mjs@@ -22,12 +22,29 @@import * as fs from 'node:fs';import * as path from 'node:path';import {fileURLToPath, pathToFileURL} from 'node:url';+import {resolveContentRoot} from './resolve-content-root.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));const DOCSITE_ROOT = path.resolve(__dirname, '..');const REPO_ROOT = path.resolve(DOCSITE_ROOT, '..', '..');const OUT_DIR = path.join(DOCSITE_ROOT, 'src', 'generated');-const CLI_ROOT = path.join(REPO_ROOT, 'packages', 'cli');++// Which version of the packages supplies the documented DATA (component+// .doc.mjs, package.json versions, READMEs). `canary` (and every PR preview)+// reads the live workspace; `latest` (production) reads the published release.+// CLI_ROOT is deliberately NOT pinned — template demos are live-rendered React+// against the bundled core, so they always come from the workspace.+const {+ target: DOCSITE_TARGET,+ contentRoot: CONTENT_ROOT,+ cliRoot: CLI_ROOT,+} = resolveContentRoot();++console.log(+ `Docsite content target: ${DOCSITE_TARGET} (reading package docs from ${+ path.relative(REPO_ROOT, CONTENT_ROOT) || '.'+ })`,+);fs.mkdirSync(OUT_DIR, {recursive: true});@@ -191,7 +208,7 @@ function findDocFilesRecursive(dir) {* Falls back to the package name when no explicit export is found.*/function resolveImportPathForPkg(pkgDir, directory) {- const pkgJsonPath = path.join(REPO_ROOT, pkgDir, 'package.json');+ const pkgJsonPath = path.join(CONTENT_ROOT, pkgDir, 'package.json');if (!fs.existsSync(pkgJsonPath)) return null;const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8'));if (pkg.exports && pkg.exports[`./${directory}`]) {@@ -209,7 +226,7 @@ function resolveImportPathForPkg(pkgDir, directory) {* Skips apps/* and internal/* — only surfaces packages/*.*/function discoverPackageDirs() {- const rootPkg = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, 'package.json'), 'utf-8'));+ const rootPkg = JSON.parse(fs.readFileSync(path.join(CONTENT_ROOT, 'package.json'), 'utf-8'));const workspaces = rootPkg.workspaces || [];const dirs = [];@@ -219,7 +236,7 @@ function discoverPackageDirs() {// Expand glob: packages/* or packages/themes/*const base = pattern.replace('/*', '');- const baseDir = path.join(REPO_ROOT, base);+ const baseDir = path.join(CONTENT_ROOT, base);if (!fs.existsSync(baseDir)) continue;for (const entry of fs.readdirSync(baseDir, {withFileTypes: true})) {@@ -245,7 +262,7 @@ function generatePackageRegistry() {const packages = packageDirs.map(dir => {- const pkgPath = path.join(REPO_ROOT, dir, 'package.json');+ const pkgPath = path.join(CONTENT_ROOT, dir, 'package.json');const raw = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));// Skip private packages@@ -254,13 +271,13 @@ function generatePackageRegistry() {// Skip packages not installed in the docsiteif (docsiteDeps[raw.name] == null) return null;- const hasReadme = fs.existsSync(path.join(REPO_ROOT, dir, 'README.md'));- const hasChangelog = fs.existsSync(path.join(REPO_ROOT, dir, 'CHANGELOG.md'));+ const hasReadme = fs.existsSync(path.join(CONTENT_ROOT, dir, 'README.md'));+ const hasChangelog = fs.existsSync(path.join(CONTENT_ROOT, dir, 'CHANGELOG.md'));const readme = hasReadme- ? fs.readFileSync(path.join(REPO_ROOT, dir, 'README.md'), 'utf-8')+ ? fs.readFileSync(path.join(CONTENT_ROOT, dir, 'README.md'), 'utf-8'): null;const changelog = hasChangelog- ? fs.readFileSync(path.join(REPO_ROOT, dir, 'CHANGELOG.md'), 'utf-8')+ ? fs.readFileSync(path.join(CONTENT_ROOT, dir, 'CHANGELOG.md'), 'utf-8'): null;return {name: raw.name,@@ -321,9 +338,9 @@ async function generateComponentRegistry() {const componentPackages = [];for (const dir of packageDirs) {- const srcDir = path.join(REPO_ROOT, dir, 'src');+ const srcDir = path.join(CONTENT_ROOT, dir, 'src');if (!fs.existsSync(srcDir)) continue;- const pkgJson = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, dir, 'package.json'), 'utf-8'));+ const pkgJson = JSON.parse(fs.readFileSync(path.join(CONTENT_ROOT, dir, 'package.json'), 'utf-8'));const allDocFiles = findDocFilesRecursive(srcDir);if (allDocFiles.length > 0) {componentPackages.push({name: pkgJson.name, srcDir, dir});diff --git a/apps/docsite/scripts/resolve-content-root.mjs b/apps/docsite/scripts/resolve-content-root.mjsnew file mode 100644index 0000000000..82c209ecb4--- /dev/null+++ b/apps/docsite/scripts/resolve-content-root.mjs@@ -0,0 +1,253 @@+#!/usr/bin/env node+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file resolve-content-root.mjs+ *+ * Resolves the CONTENT ROOT the docsite data pipeline reads package+ * documentation from (component .doc.mjs prop tables, package.json versions,+ * READMEs, CHANGELOGs).+ *+ * The docsite CODE is always the current checkout. What varies per deploy is+ * *which version of the @astryxdesign/* packages* supplies that documentation:+ *+ * canary → the live monorepo workspace (REPO_ROOT). Documents main / WIP.+ * Used for the canary deploy AND every PR preview.+ * latest → the last PUBLISHED release on npm. Documents exactly what+ * `npm install` gives a consumer today. Used for production.+ *+ * Target selection (no manual config in the common case):+ * - Explicit override: DOCSITE_TARGET=latest|canary always wins.+ * - Otherwise derived from Vercel's VERCEL_ENV: `production` → latest,+ * everything else (preview, development, unset) → canary.+ *+ * How `latest` sources are materialized: the version is read live from npm+ * (`npm view @astryxdesign/core version`) so it always tracks the current+ * published release with nothing to hand-maintain. Each docsite @astryxdesign/*+ * dependency's published tarball is downloaded and unpacked into a cache dir+ * laid out like the monorepo, so generate-data.mjs's workspace discovery works+ * unchanged. The published tarballs ship `src/` (see each package's+ * package.json "files"), so the .doc.mjs docs the pipeline reads are present.+ *+ * This module is the SINGLE place that maps a target to a filesystem root.+ * generate-data.mjs consumes CONTENT_ROOT from here; every generated registry+ * keeps its exact shape, so no consuming page code changes.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {execFileSync} from 'node:child_process';+import * as os from 'node:os';+import {fileURLToPath} from 'node:url';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const DOCSITE_ROOT = path.resolve(__dirname, '..');+const REPO_ROOT = path.resolve(DOCSITE_ROOT, '..', '..');++/** The npm dist-tag whose version `latest` documents. */+const PUBLISHED_DIST_TAG = 'latest';+/** Package whose published version defines the release the docsite pins to. */+const VERSION_SOURCE_PKG = '@astryxdesign/core';++function run(cmd, args, opts = {}) {+ return execFileSync(cmd, args, {encoding: 'utf-8', ...opts});+}++/**+ * Resolve the build target. Explicit DOCSITE_TARGET wins; otherwise derive from+ * VERCEL_ENV (production → latest, else canary).+ */+export function getTarget() {+ const explicit = (process.env.DOCSITE_TARGET || '').trim();+ if (explicit) {+ if (explicit !== 'canary' && explicit !== 'latest') {+ throw new Error(+ `Invalid DOCSITE_TARGET="${explicit}". Expected "canary" or "latest".`,+ );+ }+ return explicit;+ }+ return process.env.VERCEL_ENV === 'production' ? 'latest' : 'canary';+}++/**+ * The docsite's @astryxdesign/* dependencies that are documented on the+ * `latest` (production) site: the ones actually published to the stable npm+ * `latest` dist-tag. Mapped to the monorepo-relative dir each occupies (so the+ * materialized cache mirrors REPO_ROOT's layout — themes under+ * packages/themes/<name>, everything else under packages/<name>).+ *+ * Packages that never reach the stable tag are EXCLUDED from `latest`:+ * - `private` packages, and+ * - `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.)+ */+function latestPublishablePackages() {+ const pkg = JSON.parse(+ fs.readFileSync(path.join(DOCSITE_ROOT, 'package.json'), 'utf-8'),+ );+ 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};+ })+ .filter(({dir}) => {+ // Read the package's own workspace manifest for its publish flags. Same+ // rule release.yml uses for the stable `latest` tag.+ 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 manifest.private !== true && manifest.astryx?.canaryOnly !== true;+ });+}++/** Latest published version of the version-source package, read live from npm. */+function latestPublishedVersion() {+ const out = run(+ 'npm',+ [+ 'view',+ `${VERSION_SOURCE_PKG}@${PUBLISHED_DIST_TAG}`,+ 'version',+ '--json',+ ],+ {maxBuffer: 8 * 1024 * 1024},+ ).trim();+ // `npm view … version` prints a bare quoted string for a single match.+ const version = JSON.parse(out);+ if (typeof version !== 'string' || !version) {+ throw new Error(+ `Could not resolve a published version for ${VERSION_SOURCE_PKG}@${PUBLISHED_DIST_TAG}.`,+ );+ }+ return version;+}++/**+ * Materialize the published package sources for `latest` into a cache dir by+ * downloading each package's PUBLISHED TARBALL from npm.+ *+ * Layout produced (mirrors a real monorepo release so generate-data.mjs's+ * workspace discovery works unchanged):+ * <cache>/package.json — synthetic root (workspaces globs)+ * <cache>/packages/core/… — @astryxdesign/core tarball+ * <cache>/packages/themes/<name>/… — @astryxdesign/theme-<name> tarballs+ */+function materializeFromNpm(version, packages) {+ const cacheRoot = path.join(DOCSITE_ROOT, '.content-cache', `npm-${version}`);+ const stamp = path.join(cacheRoot, '.stamp');+ const stampValue = `npm-${version}:${packages+ .map(p => p.name)+ .sort()+ .join(',')}`;+ if (+ fs.existsSync(stamp) &&+ fs.readFileSync(stamp, 'utf-8').trim() === stampValue+ ) {+ return cacheRoot;+ }+ fs.rmSync(cacheRoot, {recursive: true, force: true});+ fs.mkdirSync(cacheRoot, {recursive: true});++ // Synthetic root package.json so discoverPackageDirs() expands the same+ // workspace globs it would in the real monorepo.+ fs.writeFileSync(+ path.join(cacheRoot, 'package.json'),+ JSON.stringify(+ {+ name: 'astryx-pinned-content',+ private: true,+ version,+ workspaces: ['packages/*', 'packages/themes/*'],+ },+ null,+ 2,+ ),+ );++ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-pin-'));+ try {+ for (const {name, dir} of packages) {+ const spec = `${name}@${version}`;+ // `npm pack` downloads the exact published tarball and prints its+ // filename; --pack-destination keeps it out of the cwd.+ //+ // Run it from the tmp dir (OUTSIDE the repo), NOT from the workspace: the+ // root package.json declares `devEngines.packageManager: pnpm`, which+ // 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 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]);+ }+ } finally {+ fs.rmSync(tmp, {recursive: true, force: true});+ }++ fs.writeFileSync(stamp, stampValue);+ return cacheRoot;+}++/**+ * Returns {target, contentRoot, cliRoot, version} for the current target.+ * contentRoot mirrors REPO_ROOT layout (has packages/* and package.json).+ */+export function resolveContentRoot() {+ const target = getTarget();++ if (target === 'canary') {+ return {+ target,+ contentRoot: REPO_ROOT,+ cliRoot: path.join(REPO_ROOT, 'packages', 'cli'),+ version: null,+ };+ }++ // latest+ const version = latestPublishedVersion();+ const packages = latestPublishablePackages();+ const contentRoot = materializeFromNpm(version, packages);+ return {+ target,+ // DATA (component .doc.mjs prop tables, package.json versions, READMEs) is+ // read from the published release — that's the point of `latest`.+ contentRoot,+ // EXECUTABLE content (CLI templates: showcases, examples, blocks, pages,+ // long-form docs) is LIVE-RENDERED as React and always resolves+ // @astryxdesign/core from node_modules — i.e. the version the docsite+ // bundles. Pinning it would make a stale release's demo use API the bundled+ // core no longer exposes, breaking render AND typecheck. So it always comes+ // from the real workspace; only the documented DATA is pinned.+ cliRoot: path.join(REPO_ROOT, 'packages', 'cli'),+ version,+ };+}++// CLI usage: `node resolve-content-root.mjs` prints the resolution as JSON.+if (import.meta.url === `file://${process.argv[1]}`) {+ const r = resolveContentRoot();+ process.stdout.write(JSON.stringify(r, null, 2) + '\n');+}diff --git a/apps/docsite/src/app/(site)/layout.tsx b/apps/docsite/src/app/(site)/layout.tsxindex 24b2b06e7e..b56f541884 100644--- a/apps/docsite/src/app/(site)/layout.tsx+++ b/apps/docsite/src/app/(site)/layout.tsx@@ -2,6 +2,8 @@import {AppShell} from '@astryxdesign/core/AppShell';import {SharedTopNav} from '../../components/SharedTopNav';+import {CanaryBanner} from '../../components/CanaryBanner';+import {CURRENT_TARGET} from '../../lib/docsVersions';import {SiteFooter} from '../../components/SiteFooter';import {getCopyrightYear} from '../../lib/copyrightYear';import styles from './layout.module.css';@@ -18,6 +20,7 @@ export default async function MarketingLayout({variant="surface"height="auto"mobileNav={false}+ banner={CURRENT_TARGET === 'canary' ? <CanaryBanner /> : undefined}topNav={<SharedTopNav />}><div className={styles.shell}><div className={styles.main}>{children}</div>diff --git a/apps/docsite/src/app/blog/layout.tsx b/apps/docsite/src/app/blog/layout.tsxindex 42f8df939c..b5f2e82e87 100644--- a/apps/docsite/src/app/blog/layout.tsx+++ b/apps/docsite/src/app/blog/layout.tsx@@ -8,6 +8,8 @@import {AppShell} from '@astryxdesign/core/AppShell';import {SharedTopNav} from '../../components/SharedTopNav';+import {CanaryBanner} from '../../components/CanaryBanner';+import {CURRENT_TARGET} from '../../lib/docsVersions';import {SiteFooter} from '../../components/SiteFooter';import {getCopyrightYear} from '../../lib/copyrightYear';@@ -23,6 +25,7 @@ export default async function BlogLayout({variant="surface"height="auto"mobileNav={false}+ banner={CURRENT_TARGET === 'canary' ? <CanaryBanner /> : undefined}topNav={<SharedTopNav />}>{children}<SiteFooter year={year} />diff --git a/apps/docsite/src/app/not-found.tsx b/apps/docsite/src/app/not-found.tsxindex 76a7598238..f4ebf82373 100644--- a/apps/docsite/src/app/not-found.tsx+++ b/apps/docsite/src/app/not-found.tsx@@ -5,6 +5,8 @@ import {Center} from '@astryxdesign/core/Center';import {VStack} from '@astryxdesign/core/Layout';import {Heading, Text} from '@astryxdesign/core/Text';import {SharedTopNav} from '../components/SharedTopNav';+import {CanaryBanner} from '../components/CanaryBanner';+import {CURRENT_TARGET} from '../lib/docsVersions';import {SiteFooter} from '../components/SiteFooter';import {getCopyrightYear} from '../lib/copyrightYear';import styles from './not-found.module.css';@@ -17,6 +19,7 @@ export default async function NotFound() {variant="surface"height="fill"mobileNav={false}+ banner={CURRENT_TARGET === 'canary' ? <CanaryBanner /> : undefined}topNav={<SharedTopNav />}><div className={styles.shell}><div className={styles.content}>diff --git a/apps/docsite/src/components/CanaryBanner.tsx b/apps/docsite/src/components/CanaryBanner.tsxnew file mode 100644index 0000000000..54af6e7a08--- /dev/null+++ b/apps/docsite/src/components/CanaryBanner.tsx@@ -0,0 +1,49 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {usePathname} from 'next/navigation';+import {Banner} from '@astryxdesign/core/Banner';+import {Button} from '@astryxdesign/core/Button';+import {CURRENT_TARGET, DOCS_VERSIONS, urlForTarget} from '../lib/docsVersions';++/**+ * Full-width notice shown ONLY on canary builds (the `main` deploy and every PR+ * preview), warning readers that they are viewing unreleased, work-in-progress+ * documentation whose components and props may not exist in the published+ * package yet. Links to the same page on the stable site.+ *+ * Rendered via AppShell's `banner` slot; callers gate the slot on+ * `CURRENT_TARGET === 'canary'` so production renders no banner region at all+ * (AppShell keys the region off `isRenderable`, and a bare `<CanaryBanner />`+ * element always counts as renderable even when it would return `null`). The+ * internal target guard is a belt-and-suspenders fallback.+ */+export function CanaryBanner() {+ const pathname = usePathname();++ if (CURRENT_TARGET !== 'canary') {+ return null;+ }++ const stableHref = urlForTarget('latest', pathname);+ const stableLabel = DOCS_VERSIONS.latest.label;++ return (+ <Banner+ container="section"+ status="warning"+ title="You're viewing unreleased docs (Canary)"+ description="This documents the canary release from main. Some components and props shown here may not exist in the latest published package yet — they ship on the @canary npm tag until the next stable release."+ endContent={+ stableHref ? (+ <Button+ label={`View ${stableLabel}`}+ variant="secondary"+ href={stableHref}+ />+ ) : undefined+ }+ />+ );+}diff --git a/apps/docsite/src/components/DocsShell.tsx b/apps/docsite/src/components/DocsShell.tsxindex 289d99f537..01aad7e73a 100644--- a/apps/docsite/src/components/DocsShell.tsx+++ b/apps/docsite/src/components/DocsShell.tsx@@ -9,6 +9,8 @@ import {AppShell} from '@astryxdesign/core/AppShell';import {SideNav, SideNavItem, SideNavSection} from '@astryxdesign/core/SideNav';import {TextInput} from '@astryxdesign/core/TextInput';import {SharedTopNav} from './SharedTopNav';+import {CanaryBanner} from './CanaryBanner';+import {CURRENT_TARGET} from '../lib/docsVersions';import type {PackageMeta} from '../generated/packageRegistry';import type {DocTopic} from '../generated/docsRegistry';import type {GroupedEntry} from '../generated/groupedComponentRegistry';@@ -33,11 +35,7 @@ const foundationsSort = (a: DocTopic, b: DocTopic) => {// ── Shell ──────────────────────────────────────────────────────────────-export function DocsShell({- children,- packages,- docTopics,-}: DocsShellProps) {+export function DocsShell({children, packages, docTopics}: DocsShellProps) {const pathname = usePathname();const [componentQuery, setComponentQuery] = useState('');@@ -110,6 +108,7 @@ export function DocsShell({<AppShellvariant="surface"height="auto"+ banner={CURRENT_TARGET === 'canary' ? <CanaryBanner /> : undefined}topNav={<SharedTopNav />}sideNav={<SideNav topContent={isOnComponentsRoute ? componentSearch : undefined}>diff --git a/apps/docsite/src/components/DocsVersionFooterLink.tsx b/apps/docsite/src/components/DocsVersionFooterLink.tsxnew file mode 100644index 0000000000..599470784f--- /dev/null+++ b/apps/docsite/src/components/DocsVersionFooterLink.tsx@@ -0,0 +1,35 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {usePathname} from 'next/navigation';+import {Link} from '@astryxdesign/core/Link';+import {CURRENT_TARGET, DOCS_VERSIONS, urlForTarget} from '../lib/docsVersions';+import type {DocsTarget} from '../lib/docsVersions';++/**+ * Footer link to the sibling content line: from the Latest (production) site+ * over to the Canary docs, or back again. This is the low-key, persistent way+ * to reach Canary from production; on Canary the prominent CanaryBanner carries+ * the primary link back to Latest.+ *+ * Renders nothing when there is no distinct sibling to link to (e.g. a local+ * build where the destination resolves to the current origin).+ */+export function DocsVersionFooterLink() {+ const pathname = usePathname();+ const other: DocsTarget = CURRENT_TARGET === 'latest' ? 'canary' : 'latest';+ const href = urlForTarget(other, pathname);++ if (href == null) {+ return null;+ }++ const label = `${DOCS_VERSIONS[other].label} docs`;++ return (+ <Link href={href} type="supporting" color="secondary" isStandalone>+ {label}+ </Link>+ );+}diff --git a/apps/docsite/src/components/SiteFooter.tsx b/apps/docsite/src/components/SiteFooter.tsxindex a2b455e93e..0948205c1a 100644--- a/apps/docsite/src/components/SiteFooter.tsx+++ b/apps/docsite/src/components/SiteFooter.tsx@@ -11,6 +11,7 @@ import {Grid, GridSpan} from '@astryxdesign/core/Grid';import {Divider} from '@astryxdesign/core/Divider';import {Section} from '@astryxdesign/core/Section';import {useAppShellMobile} from '@astryxdesign/core/AppShell';+import {DocsVersionFooterLink} from './DocsVersionFooterLink';import {GITHUB_REPO,DISCORD_URL,@@ -103,6 +104,7 @@ function NavLinks() {{item.label}</Link>))}+ <DocsVersionFooterLink /></>);}diff --git a/apps/docsite/src/lib/docsVersions.ts b/apps/docsite/src/lib/docsVersions.tsnew file mode 100644index 0000000000..8a7e9a40f9--- /dev/null+++ b/apps/docsite/src/lib/docsVersions.ts@@ -0,0 +1,82 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Version-line wiring for the docsite.+ *+ * The docsite ships as ONE codebase deployed from `main`. Which content line a+ * given deploy documents is decided at build time by the deploy target:+ *+ * - `latest` — the last published release (what `npm install` gives you+ * today). The canonical, default site. Production only.+ * - `canary` — the live monorepo `main` (unreleased, WIP). The canary deploy+ * AND every PR preview.+ *+ * The build-time data pipeline reads package docs from the matching source (see+ * scripts/resolve-content-root.mjs); this module is the client-side counterpart+ * that tells the banner + footer link which line they're on and where the other+ * one lives.+ *+ * Target is derived from Vercel's environment: the production deploy is+ * `latest`; preview (the `main` deploy and every PR preview) and local dev are+ * `canary`. Reading `NEXT_PUBLIC_VERCEL_ENV` (Vercel's build-time system var,+ * exposed to the client bundle) keeps this a single source of truth with the+ * pipeline, with no generated file to keep in sync.+ */++export type DocsTarget = 'latest' | 'canary';++/**+ * Absolute URLs of the two deploys, used to cross-link between them. Configured+ * per Vercel project; the defaults match the current production + canary hosts+ * so the links work even if the env vars are ever unset.+ */+const LATEST_URL =+ process.env.NEXT_PUBLIC_DOCS_LATEST_URL ?? 'https://astryx.atmeta.com';+const CANARY_URL =+ process.env.NEXT_PUBLIC_DOCS_CANARY_URL ?? 'https://astryx-canary.vercel.app';++export interface DocsVersionInfo {+ target: DocsTarget;+ /** Human-readable label. */+ label: string;+ /** Absolute base URL of that deploy. */+ baseUrl: string;+}++export const DOCS_VERSIONS: Record<DocsTarget, DocsVersionInfo> = {+ latest: {target: 'latest', label: 'Latest', baseUrl: LATEST_URL},+ canary: {target: 'canary', label: 'Canary', baseUrl: CANARY_URL},+};++/**+ * The target this build was produced for. Production → `latest`; every other+ * environment (preview = the `main` deploy + PR previews, development) →+ * `canary`. An explicit `NEXT_PUBLIC_DOCS_TARGET` overrides, mirroring the+ * pipeline's `DOCSITE_TARGET` override for local testing.+ */+export const CURRENT_TARGET: DocsTarget =+ process.env.NEXT_PUBLIC_DOCS_TARGET === 'latest'+ ? 'latest'+ : process.env.NEXT_PUBLIC_DOCS_TARGET === 'canary'+ ? 'canary'+ : process.env.NEXT_PUBLIC_VERCEL_ENV === 'production'+ ? 'latest'+ : 'canary';++/**+ * URL of the same logical page on the other version's deploy. Both deploys+ * serve identical routes at their own origin, so we just swap the base URL and+ * keep the path. Returns null when there is no distinct sibling to link to+ * (e.g. a local build with both URLs pointing at the same origin).+ */+export function urlForTarget(target: DocsTarget, path: string): string | null {+ if (target === CURRENT_TARGET) {+ return null;+ }+ const base = DOCS_VERSIONS[target].baseUrl.replace(/\/$/, '');+ if (!base) {+ return null;+ }+ const suffix = path.startsWith('/') ? path : `/${path}`;+ return `${base}${suffix}`;+}