An open source design system that's fully customizable and agent ready
TypeScript
ci: stage Vite Sandbox alongside Storybook in docsite previews (#6601)
Cindy Zhang29be688a68cc
diff --git a/.github/scripts/generate-pr-comment.js b/.github/scripts/generate-pr-comment.jsindex 354da3755b..6ed004cc48 100644--- a/.github/scripts/generate-pr-comment.js+++ b/.github/scripts/generate-pr-comment.js@@ -203,28 +203,16 @@ if (sandboxUrl) {sandboxSection = `### 🧪 Sandbox Preview**${extLink('View Sandbox for this PR', sandboxUrl)}**-_GitHub Pages may take up to a minute to hydrate after deploy._`;}-// Storybook readiness follows Vercel; Sandbox still follows the source CI's-// trusted Pages publisher. Report their missing states independently.+// Both previews share the exact-head Vercel deployment, never a Pages, canary,+// production, or earlier-head fallback.let previewAvailabilitySection = '';if (previewState) {- const missing = [];- if (!storybookUrl)- missing.push('Storybook is not ready on the exact-head Vercel preview.');- if (!sandboxUrl) {- missing.push(- sourceConclusion === 'success'- ? 'Sandbox was not published for this CI run.'- : `Sandbox is unavailable because CI concluded ${sourceConclusion || 'without a result'}.`,- );- }- if (missing.length > 0) {- previewAvailabilitySection = `> **Preview availability:** ${missing.join(' ')}\n\n`;- }+ if (!storybookUrl || !sandboxUrl)+ previewAvailabilitySection = `> **Preview availability:** Storybook and Sandbox are not both ready on the exact-head Vercel preview.${sourceConclusion && sourceConclusion !== 'success' ? ` CI concluded ${sourceConclusion}.` : ''}\n\n`;}// Build footer with linksdiff --git a/.github/scripts/lib/pr-preview.mjs b/.github/scripts/lib/pr-preview.mjsindex 3665ecb05e..e096a807f9 100644--- a/.github/scripts/lib/pr-preview.mjs+++ b/.github/scripts/lib/pr-preview.mjs@@ -6,7 +6,11 @@ import path from 'node:path';import process from 'node:process';import {fileURLToPath} from 'node:url';-import {resolveVercelPreview} from './vercel-preview.mjs';+import {+ probeVercelPreview,+ resolveVercelPreview,+ waitForPreviewRoutes,+} from './vercel-preview.mjs';export const PR_ANALYSIS_MARKER = '<!-- astryx-pr-analysis -->';export const PREVIEW_RESULT_VERSION = 1;@@ -441,17 +445,13 @@ function previewState(storybook, sandbox) {return 'none';}-function pagesURL(identity, targetPath) {- const [owner, repo] = identity.baseRepository.split('/');- return `https://${owner}.github.io/${repo}/${targetPath}`;-}-+// Both preview links come from one verified exact-head Vercel deployment.+// Pages publication may continue independently, but is never a PR link.function safeCurrentBody({identity,runUrl,message: overrideMessage,previewOrigin,- sandboxPath,}) {const conclusion = identity.sourceConclusion;const message =@@ -459,12 +459,12 @@ function safeCurrentBody({(conclusion === 'success'? 'The current CI run completed, but its trusted analysis is unavailable.': `The current CI run concluded ${conclusion || 'without a result'}. Current analysis is unavailable.`);- const links = [- previewOrigin &&- `[View Storybook for this PR](${previewOrigin}/storybook/)`,- sandboxPath &&- `[View Sandbox for this PR](${pagesURL(identity, sandboxPath)})`,- ].filter(Boolean);+ const links = previewOrigin+ ? [+ `[View Storybook for this PR](${previewOrigin}/storybook/)`,+ `[View Sandbox for this PR](${previewOrigin}/sandbox/)`,+ ]+ : [];const previewMessage = links.length? `\n\n${links.join(' · ')}`: '\n\nThe exact-head preview is not available yet.';@@ -524,6 +524,8 @@ export async function reconcilePrComment({createIfMissing = true,fallbackMessage,lookupPreview = resolveVercelPreview,+ probePreview = probeVercelPreview,+ probeWaitMs = 90_000,generator = GENERATOR,execute = execFileSync,}) {@@ -541,7 +543,7 @@ export async function reconcilePrComment({identity,core,});- const previewOrigin =+ const candidateOrigin =createIfMissing && !identity.draft? await lookupPreview({github,@@ -551,15 +553,29 @@ export async function reconcilePrComment({headSha: identity.headSha,}): null;- const deployment = trustedDeployment({- deploymentResultPath,- identity,- core,- });+ const routesReady =+ candidateOrigin &&+ (await waitForPreviewRoutes(candidateOrigin, {+ probe: probePreview,+ waitMs: probeWaitMs,+ }));+ const previewOrigin =+ routesReady &&+ (await lookupPreview({+ github,+ owner,+ repo,+ prNumber: identity.prNumber,+ headSha: identity.headSha,+ waitMs: 0,+ })) === candidateOrigin+ ? candidateOrigin+ : null;+ // Continue checking the trusted Pages result for stale evidence, but never+ // use Pages as a preview-link fallback.+ trustedDeployment({deploymentResultPath, identity, core});const storybook = previewOrigin !== null;- const sandbox =- !identity.draft && deployment?.targets.sandbox.available === true;- const sandboxPath = sandbox ? deployment.targets.sandbox.path : null;+ const sandbox = storybook;const comments = await allComments(github, owner, repo, identity.prNumber);const botComments = comments.filter(comment => comment.user?.type === 'Bot');const botComment =@@ -603,7 +619,7 @@ export async function reconcilePrComment({]: []),...(storybook ? ['--storybook-url', `${previewOrigin}/storybook/`] : []),- ...(sandbox ? ['--sandbox-url', pagesURL(identity, sandboxPath)] : []),+ ...(sandbox ? ['--sandbox-url', `${previewOrigin}/sandbox/`] : []),'--preview-state',previewState(storybook, sandbox),'--source-conclusion',@@ -625,7 +641,6 @@ export async function reconcilePrComment({runUrl,message: fallbackMessage,previewOrigin,- sandboxPath,});}} else {@@ -634,7 +649,6 @@ export async function reconcilePrComment({runUrl,message: fallbackMessage,previewOrigin,- sandboxPath,});}@@ -646,6 +660,20 @@ export async function reconcilePrComment({repo,expected: expectedIdentity,});+ if (+ previewOrigin &&+ (await lookupPreview({+ github,+ owner,+ repo,+ prNumber: identity.prNumber,+ headSha: identity.headSha,+ waitMs: 0,+ })) !== previewOrigin+ ) {+ core.info('A newer exact-head deployment superseded this preview.');+ return {action: 'none', body: null, identity};+ }if (botComment) {await github.rest.issues.updateComment({owner,@@ -675,6 +703,8 @@ export async function reconcileEarlyPreviewComment({headSha,origin,lookupPreview = resolveVercelPreview,+ probePreview = probeVercelPreview,+ probeWaitMs = 90_000,}) {const currentOrigin = await lookupPreview({github,@@ -684,7 +714,14 @@ export async function reconcileEarlyPreviewComment({headSha,waitMs: 0,});- if (currentOrigin !== origin) return {action: 'none'};+ if (+ currentOrigin !== origin ||+ !(await waitForPreviewRoutes(origin, {+ probe: probePreview,+ waitMs: probeWaitMs,+ }))+ )+ return {action: 'none'};const comments = await allComments(github, owner, repo, prNumber);const existing = comments.find(@@ -692,11 +729,15 @@ export async function reconcileEarlyPreviewComment({comment.user?.type === 'Bot' &&comment.body?.includes(PR_ANALYSIS_MARKER),);- const links = `[View Storybook for this PR](${origin}/storybook/)`;+ const links = `[View Storybook for this PR](${origin}/storybook/) · [View Sandbox for this PR](${origin}/sandbox/)`;const marker = headMarker(headSha);- let body = `## PR Analysis Report\n${PR_ANALYSIS_MARKER}\n${marker}\n\n> **Storybook ready:** Built with this PR's docsite. Sandbox and CI evidence will be added when available.\n\n${links}\n`;+ const legacySandboxURL = `https://${owner}.github.io/${repo}/pr/${prNumber}/sandbox/`;+ let body = `## PR Analysis Report\n${PR_ANALYSIS_MARKER}\n${marker}\n\n> **Previews ready:** Storybook and Sandbox were built with this PR's docsite. CI evidence will be added when available.\n\n${links}\n`;if (existing?.body.includes(marker)) {- if (existing.body.includes(`${origin}/storybook/`)) {+ if (+ existing.body.includes(`${origin}/storybook/`) &&+ existing.body.includes(`${origin}/sandbox/`)+ ) {return {action: 'unchanged'};}const oldOrigins = new Set(@@ -708,12 +749,19 @@ export async function reconcileEarlyPreviewComment({oldOrigins.size === 1 &&existing.body.includes('View Storybook for this PR')) {- // A same-head Vercel redeploy changes only the deployment origin. Keep- // the already-enriched CI, a11y, and canonical visual evidence intact.- body = existing.body.replaceAll([...oldOrigins][0], origin);+ // Same-head redeploy: preserve existing CI/a11y/visual content and+ // change only the exact-head preview URLs.+ body = existing.body+ .replaceAll([...oldOrigins][0], origin)+ .replaceAll(legacySandboxURL, `${origin}/sandbox/`);+ if (!body.includes(`${origin}/sandbox/`)) {+ body = body.replace(+ marker,+ `${marker}\n\n[View Sandbox for this PR](${origin}/sandbox/)`,+ );+ }} else if (!existing.body.includes('View Storybook for this PR')) {- // CI may finish before Vercel. Add the now-ready links without discarding- // current-head analysis or immutable visual evidence from that report.+ // CI may finish before Vercel; add links to the current-head report.body = existing.body.replace(/^> \*\*Preview availability:\*\*[^\n]*\n\n/m, '').replace('The exact-head preview is not available yet.', '')@@ -721,6 +769,12 @@ export async function reconcileEarlyPreviewComment({}}+ // Replace an older same-head Pages Sandbox URL without dropping CI, a11y,+ // or immutable visual evidence in the surrounding report.+ body = body+ .replaceAll(legacySandboxURL, `${origin}/sandbox/`)+ .replace(/^> \*\*Preview availability:\*\*[^\n]*\n\n/m, '');+const {data: current} = await github.rest.pulls.get({owner,repo,@@ -733,6 +787,18 @@ export async function reconcileEarlyPreviewComment({) {return {action: 'none'};}+ if (+ (await lookupPreview({+ github,+ owner,+ repo,+ prNumber,+ headSha,+ waitMs: 0,+ })) !== origin+ ) {+ return {action: 'none'};+ }if (existing) {await github.rest.issues.updateComment({owner,diff --git a/.github/scripts/lib/pr-preview.test.mjs b/.github/scripts/lib/pr-preview.test.mjsindex 938d8fc77e..f2d01545d3 100644--- a/.github/scripts/lib/pr-preview.test.mjs+++ b/.github/scripts/lib/pr-preview.test.mjs@@ -236,6 +236,7 @@ async function reconcile({a11yPath: paths.a11y,deploymentResultPath: paths.deployment,lookupPreview: async () => (previewAvailable ? VERCEL_ORIGIN : null),+ probePreview: async () => true,visualPath: paths.visual,createIfMissing,fallbackMessage,@@ -503,48 +504,34 @@ describe('analysis metadata compatibility', () => {describe('PR comment preview reconciliation', () => {it.each([- ['neither ready', undefined, false, false],- ['Vercel Storybook only', undefined, true, false],- ['Pages Sandbox only', published(identity()), false, true],- ['both independent targets', published(identity()), true, true],+ ['neither ready', undefined, false],+ ['exact-head Vercel ready', undefined, true],+ ['Pages Sandbox only is not proof', published(identity()), false],+ ['Vercel ready with independent Pages result', published(identity()), true],['obsolete Pages Storybook proof',published(identity(), ['storybook']),false,- false,],[- 'Pages failure with ready Storybook',+ 'Pages failure with ready Vercel',createUnavailableDeploymentResult(identity(), 'publisher-failed'),true,- false,],])(- 'shows only validated current targets: %s',- async (_label, deployment, storybookReady, sandboxReady) => {- const {result} = await reconcile({- deployment,- previewAvailable: storybookReady,- });- expect(result.body.includes('View Storybook for this PR')).toBe(- storybookReady,- );- expect(result.body.includes('View Sandbox for this PR')).toBe(- sandboxReady,- );- expect(result.body.includes('> **Preview availability:**')).toBe(- !storybookReady || !sandboxReady,- );- if (storybookReady)+ 'shows both or neither exact-head links: %s',+ async (_label, deployment, ready) => {+ const {result} = await reconcile({deployment, previewAvailable: ready});+ expect(result.body.includes('View Storybook for this PR')).toBe(ready);+ expect(result.body.includes('View Sandbox for this PR')).toBe(ready);+ expect(result.body.includes('> **Preview availability:**')).toBe(!ready);+ if (ready) {expect(result.body).toContain(`${VERCEL_ORIGIN}/storybook/`);- if (sandboxReady)- expect(result.body).toContain(- 'https://facebook.github.io/astryx/pr/5697/sandbox/',- );+ expect(result.body).toContain(`${VERCEL_ORIGIN}/sandbox/`);+ }expect(result.body).not.toContain(- 'https://facebook.github.io/astryx/pr/5697/</a>',+ 'https://facebook.github.io/astryx/pr/5697/sandbox/',);- expect(result.body).not.toContain(`${VERCEL_ORIGIN}/sandbox/`);},);@@ -570,8 +557,7 @@ describe('PR comment preview reconciliation', () => {});expect(result.body).toContain('concluded failure');expect(result.body).toContain(`${VERCEL_ORIGIN}/storybook/`);- expect(result.body).not.toContain('View Sandbox for this PR');- expect(result.body).not.toContain(`${VERCEL_ORIGIN}/sandbox/`);+ expect(result.body).toContain(`${VERCEL_ORIGIN}/sandbox/`);});it('replaces a stale linked comment when failed CI has no analysis artifact', async () => {@@ -642,7 +628,7 @@ describe('PR comment preview reconciliation', () => {});expect(result.body).toContain('trusted analysis is unavailable');- expect(result.body).toContain(+ expect(result.body).not.toContain('https://facebook.github.io/astryx/pr/5697/sandbox/',);expect(result.body).not.toContain('View Storybook for this PR');@@ -664,6 +650,7 @@ describe('PR comment preview reconciliation', () => {serverUrl: 'https://github.com',},visualPath: firstPaths.visual,+ probePreview: async () => true,};await reconcilePrComment({@@ -699,7 +686,7 @@ describe('PR comment preview reconciliation', () => {expect(harness.state.comments[0].body).toContain('View Storybook for this PR',);- expect(harness.state.comments[0].body).not.toContain(+ expect(harness.state.comments[0].body).toContain('View Sandbox for this PR',);expect(harness.state.listedIssues).toEqual([5697, 5697]);@@ -768,6 +755,7 @@ describe('PR comment preview reconciliation', () => {github.rest.pulls.get.mockResolvedValue({data: pull(current)});return VERCEL_ORIGIN;},+ probePreview: async () => true,}),).rejects.toThrow(/head does not match source run/);expect(state.created).toHaveLength(0);@@ -813,13 +801,89 @@ describe('PR comment preview reconciliation', () => {expect(result.action).toBe('created');expect(result.body).toContain(PR_ANALYSIS_MARKER);expect(result.body).toContain(`${VERCEL_ORIGIN}/storybook/`);- expect(result.body).toContain(- 'https://facebook.github.io/astryx/pr/5697/sandbox/',- );+ expect(result.body).toContain(`${VERCEL_ORIGIN}/sandbox/`);expect(state.created[0].issue_number).toBe(5697);expect(state.listedIssues).toEqual([5697]);});+ it('never advertises either link when one preview route probe fails', async () => {+ const value = identity();+ const paths = fixture(value, {deployment: published(value)});+ const {github, state} = githubFixture({value});+ const context = {+ repo: {owner: 'facebook', repo: 'astryx'},+ serverUrl: 'https://github.com',+ };+ const report = await reconcilePrComment({+ github,+ core: {info: vi.fn(), warning: vi.fn()},+ context,+ expectedIdentity: value,+ analysisPath: paths.analysis,+ metadataPath: paths.metadata,+ a11yPath: paths.a11y,+ visualPath: paths.visual,+ lookupPreview: async () => VERCEL_ORIGIN,+ probePreview: async () => false,+ probeWaitMs: 0,+ });+ expect(report.body).not.toContain('View Storybook for this PR');+ expect(report.body).not.toContain('View Sandbox for this PR');+ const early = await reconcileEarlyPreviewComment({+ github,+ owner: 'facebook',+ repo: 'astryx',+ prNumber: value.prNumber,+ headSha: value.headSha,+ origin: VERCEL_ORIGIN,+ lookupPreview: async () => VERCEL_ORIGIN,+ probePreview: async () => false,+ probeWaitMs: 0,+ });+ expect(early.action).toBe('none');+ expect(state.updated).toHaveLength(0);+ });++ it('does not publish an older same-head origin after a newer redeploy starts', async () => {+ const value = identity();+ const paths = fixture(value);+ const {github, state} = githubFixture({value});+ let lookups = 0;+ const lookupPreview = async () => (++lookups === 1 ? VERCEL_ORIGIN : null);+ const report = await reconcilePrComment({+ github,+ core: {info: vi.fn(), warning: vi.fn()},+ context: {+ repo: {owner: 'facebook', repo: 'astryx'},+ serverUrl: 'https://github.com',+ },+ expectedIdentity: value,+ analysisPath: paths.analysis,+ metadataPath: paths.metadata,+ a11yPath: paths.a11y,+ visualPath: paths.visual,+ lookupPreview,+ probePreview: async () => true,+ });+ expect(report.body).not.toContain('View Storybook for this PR');+ expect(report.body).not.toContain('View Sandbox for this PR');+ expect(state.created).toHaveLength(1);++ let earlyLookups = 0;+ const early = await reconcileEarlyPreviewComment({+ github,+ owner: 'facebook',+ repo: 'astryx',+ prNumber: value.prNumber,+ headSha: value.headSha,+ origin: VERCEL_ORIGIN,+ lookupPreview: async () => (++earlyLookups === 1 ? VERCEL_ORIGIN : null),+ probePreview: async () => true,+ });+ expect(early.action).toBe('none');+ expect(state.updated).toHaveLength(0);+ });+it('posts preview links before CI and later enriches the same report', async () => {const value = identity();const paths = fixture(value, {deployment: published(value)});@@ -833,10 +897,11 @@ describe('PR comment preview reconciliation', () => {headSha: value.headSha,origin: VERCEL_ORIGIN,lookupPreview: async () => VERCEL_ORIGIN,+ probePreview: async () => true,});expect((await early()).action).toBe('created');expect(state.comments[0].body).toContain(`${VERCEL_ORIGIN}/storybook/`);- expect(state.comments[0].body).not.toContain('View Sandbox for this PR');+ expect(state.comments[0].body).toContain('View Sandbox for this PR');expect(state.comments[0].body).not.toContain('Modified Components');expect((await early()).action).toBe('unchanged');expect(state.created).toHaveLength(1);@@ -855,14 +920,13 @@ describe('PR comment preview reconciliation', () => {deploymentResultPath: paths.deployment,visualPath: paths.visual,lookupPreview: async () => VERCEL_ORIGIN,+ probePreview: async () => true,});expect(enriched.action).toBe('updated');expect(state.comments).toHaveLength(1);expect(state.comments[0].body).toContain('Modified Components');expect(state.comments[0].body).toContain(`${VERCEL_ORIGIN}/storybook/`);- expect(state.comments[0].body).toContain(- 'https://facebook.github.io/astryx/pr/5697/sandbox/',- );+ expect(state.comments[0].body).toContain(`${VERCEL_ORIGIN}/sandbox/`);});it('adds a late preview without discarding same-head CI and visual evidence', async () => {@@ -882,14 +946,49 @@ describe('PR comment preview reconciliation', () => {headSha: value.headSha,origin: VERCEL_ORIGIN,lookupPreview: async () => VERCEL_ORIGIN,+ probePreview: async () => true,});expect(early.action).toBe('updated');expect(state.comments[0].body).toContain('Modified Components');expect(state.comments[0].body).not.toContain('Preview availability');expect(state.comments[0].body).toContain(`${VERCEL_ORIGIN}/storybook/`);- expect(state.comments[0].body).toContain(- 'https://facebook.github.io/astryx/pr/5697/sandbox/',- );+ expect(state.comments[0].body).toContain(`${VERCEL_ORIGIN}/sandbox/`);+ });++ it('replaces a same-head Pages fallback without duplicating its Sandbox link', async () => {+ const value = identity();+ const oldOrigin = VERCEL_ORIGIN;+ const nextOrigin = 'https://astryx-atz4b1yim-fbopensource.vercel.app';+ const legacySandbox = 'https://facebook.github.io/astryx/pr/5697/sandbox/';+ const evidence = 'CI, a11y and visual evidence remains here';+ const {github, state} = githubFixture({+ value,+ comments: [+ {+ id: 777,+ user: {type: 'Bot'},+ body: `## PR Analysis Report\n${PR_ANALYSIS_MARKER}\n<!-- astryx-pr-head:${value.headSha} -->\n\n[View Storybook for this PR](${oldOrigin}/storybook/) · [View Sandbox for this PR](${legacySandbox})\n\n${evidence}`,+ },+ ],+ });+ const result = await reconcileEarlyPreviewComment({+ github,+ owner: 'facebook',+ repo: 'astryx',+ prNumber: value.prNumber,+ headSha: value.headSha,+ origin: nextOrigin,+ lookupPreview: async () => nextOrigin,+ probePreview: async () => true,+ });+ expect(result.action).toBe('updated');+ expect(state.comments[0].body).toContain(evidence);+ expect(state.comments[0].body).toContain(`${nextOrigin}/storybook/`);+ expect(state.comments[0].body).toContain(`${nextOrigin}/sandbox/`);+ expect(state.comments[0].body).not.toContain(legacySandbox);+ expect(+ state.comments[0].body.match(/View Sandbox for this PR/g),+ ).toHaveLength(1);});it('refreshes a same-head redeployment without losing CI, a11y, or visual evidence', async () => {@@ -913,6 +1012,7 @@ describe('PR comment preview reconciliation', () => {headSha: value.headSha,origin: nextOrigin,lookupPreview: async () => nextOrigin,+ probePreview: async () => true,});expect(result.action).toBe('updated');expect(state.comments).toHaveLength(1);@@ -920,10 +1020,7 @@ describe('PR comment preview reconciliation', () => {expect(state.comments[0].body).toContain('Accessibility Audit');expect(state.comments[0].body).toContain(visualEvidence);expect(state.comments[0].body).toContain(`${nextOrigin}/storybook/`);- expect(state.comments[0].body).toContain(- 'https://facebook.github.io/astryx/pr/5697/sandbox/',- );- expect(state.comments[0].body).not.toContain(`${nextOrigin}/sandbox/`);+ expect(state.comments[0].body).toContain(`${nextOrigin}/sandbox/`);expect(state.comments[0].body).not.toContain(VERCEL_ORIGIN);expect(prior).toContain(VERCEL_ORIGIN);});@@ -942,6 +1039,7 @@ describe('PR comment preview reconciliation', () => {headSha: HEAD,origin: VERCEL_ORIGIN,lookupPreview: async () => VERCEL_ORIGIN,+ probePreview: async () => true,});expect(result.action).toBe('none');expect(state.created).toHaveLength(0);diff --git a/.github/scripts/lib/vercel-preview.mjs b/.github/scripts/lib/vercel-preview.mjsindex 2730c1bd22..3a489088b5 100644--- a/.github/scripts/lib/vercel-preview.mjs+++ b/.github/scripts/lib/vercel-preview.mjs@@ -38,12 +38,68 @@ export function previewOrigin(deployment, status, headSha) {}}+export async function probeVercelPreview(origin, fetchRoute = fetch) {+ // Check both static apps and a real Sandbox deep link before publishing any+ // PR link. A redirect (including an auth/login redirect) or Next's 404 page+ // cannot count as ready. The origin has already passed previewOrigin().+ const routes = [+ '/storybook/',+ '/storybook/iframe.html',+ '/sandbox/',+ '/sandbox/pages/component-scores/',+ ];+ try {+ const responses = await Promise.all(+ routes.map(route =>+ fetchRoute(`${origin}${route}`, {+ redirect: 'manual',+ signal: AbortSignal.timeout(12000),+ }),+ ),+ );+ return responses.every(+ response =>+ response.status === 200 &&+ response.headers.get('content-type')?.includes('text/html'),+ );+ } catch {+ return false;+ }+}++export async function waitForPreviewRoutes(+ origin,+ {+ probe = probeVercelPreview,+ waitMs = 90_000,+ pollMs = 5_000,+ now = Date.now,+ sleep = ms => new Promise(resolve => setTimeout(resolve, ms)),+ } = {},+) {+ // Vercel can report deployment success shortly before every static route+ // reaches the edge. Retry within this bounded window instead of dropping the+ // one deployment_status event on a transient 404.+ const deadline = now() + waitMs;+ while (true) {+ try {+ if (await probe(origin)) return true;+ } catch {+ // A failed network probe is not evidence of a ready preview.+ }+ if (now() >= deadline) return false;+ await sleep(Math.min(pollMs, deadline - now()));+ }+}+export async function resolveVercelDeploymentEvent({github,owner,repo,deployment,status,+ probePreview = probeVercelPreview,+ probeWaitMs = 90_000,}) {const origin = previewOrigin(deployment, status, deployment?.sha);if (!origin) return null;@@ -73,7 +129,36 @@ export async function resolveVercelDeploymentEvent({headSha: deployment.sha,waitMs: 0,});- if (currentOrigin !== origin) return null;+ if (+ currentOrigin !== origin ||+ !(await waitForPreviewRoutes(origin, {+ probe: probePreview,+ waitMs: probeWaitMs,+ }))+ )+ return null;+ const {data: current} = await github.rest.pulls.get({+ owner,+ repo,+ pull_number: prNumber,+ });+ if (+ current.state !== 'open' ||+ current.draft ||+ current.head?.sha !== deployment.sha+ )+ return null;+ // A newer deployment for this *same head* may have started while we waited+ // for edge routes. Never promote an older successful origin over it.+ const latestOrigin = await resolveVercelPreview({+ github,+ owner,+ repo,+ prNumber,+ headSha: deployment.sha,+ waitMs: 0,+ });+ if (latestOrigin !== origin) return null;return {prNumber, headSha: deployment.sha, origin};}diff --git a/.github/scripts/lib/vercel-preview.test.mjs b/.github/scripts/lib/vercel-preview.test.mjsindex e6f697d682..17e79a2f6e 100644--- a/.github/scripts/lib/vercel-preview.test.mjs+++ b/.github/scripts/lib/vercel-preview.test.mjs@@ -4,8 +4,10 @@ import {describe, expect, it, vi} from 'vitest';import {previewOrigin,+ probeVercelPreview,resolveVercelDeploymentEvent,resolveVercelPreview,+ waitForPreviewRoutes,} from './vercel-preview.mjs';const SHA = 'a'.repeat(40);@@ -68,6 +70,119 @@ function resolve(github, options = {}) {}describe('exact-head Vercel preview', () => {+ it('probes both static apps, iframe and a Sandbox deep link; rejects redirects and 404s', async () => {+ const paths = [];+ const fetchRoute = vi.fn(async (url, options) => {+ paths.push(new URL(url).pathname);+ expect(options.redirect).toBe('manual');+ return {+ status: 200,+ headers: new Headers({'content-type': 'text/html; charset=utf-8'}),+ };+ });+ expect(await probeVercelPreview(ORIGIN, fetchRoute)).toBe(true);+ expect(paths).toEqual([+ '/storybook/',+ '/storybook/iframe.html',+ '/sandbox/',+ '/sandbox/pages/component-scores/',+ ]);+ fetchRoute.mockImplementationOnce(async () => ({+ status: 308,+ headers: new Headers(),+ }));+ expect(await probeVercelPreview(ORIGIN, fetchRoute)).toBe(false);+ fetchRoute.mockImplementationOnce(async () => {+ throw new Error('network unavailable');+ });+ expect(await probeVercelPreview(ORIGIN, fetchRoute)).toBe(false);+ });++ it('retries transient route failures within a bounded window', async () => {+ let time = 0;+ const probe = vi+ .fn()+ .mockResolvedValueOnce(false)+ .mockResolvedValueOnce(false)+ .mockResolvedValueOnce(true);+ const sleep = vi.fn(async ms => {+ time += ms;+ });+ expect(+ await waitForPreviewRoutes(ORIGIN, {+ probe,+ waitMs: 20,+ pollMs: 5,+ now: () => time,+ sleep,+ }),+ ).toBe(true);+ expect(probe).toHaveBeenCalledTimes(3);+ expect(sleep).toHaveBeenCalledTimes(2);+ expect(+ await waitForPreviewRoutes(ORIGIN, {+ probe: async () => false,+ waitMs: 0,+ }),+ ).toBe(false);+ });++ it('refuses a successful status if either static tree is not actually ready', async () => {+ const github = fixture();+ const deployment = {+ id: 7,+ sha: SHA,+ environment: 'Preview',+ creator: {login: 'vercel[bot]'},+ };+ const status = {state: 'success', environment_url: ORIGIN};+ expect(+ await resolveVercelDeploymentEvent({+ github,+ owner: 'facebook',+ repo: 'astryx',+ deployment,+ status,+ probePreview: async () => false,+ probeWaitMs: 0,+ }),+ ).toBeNull();+ });++ it('refuses an old origin if a newer same-head deployment begins during route probes', async () => {+ const github = fixture();+ const deployment = {+ id: 7,+ sha: SHA,+ environment: 'Preview',+ creator: {login: 'vercel[bot]'},+ };+ const newer = {...deployment, id: 8};+ github.rest.repos.listDeploymentStatuses.mockImplementation(+ async ({deployment_id}) => ({+ data:+ deployment_id === 8+ ? [{state: 'pending', environment_url: ORIGIN}]+ : [{state: 'success', environment_url: ORIGIN}],+ }),+ );+ expect(+ await resolveVercelDeploymentEvent({+ github,+ owner: 'facebook',+ repo: 'astryx',+ deployment,+ status: {state: 'success', environment_url: ORIGIN},+ probePreview: async () => {+ github.rest.repos.listDeployments.mockResolvedValue({+ data: [newer, deployment],+ });+ return true;+ },+ }),+ ).toBeNull();+ });+it('only accepts a successful Vercel Preview deployment for the exact SHA', () => {const deployment = {sha: SHA,@@ -219,6 +334,7 @@ describe('exact-head Vercel preview', () => {repo: 'astryx',deployment,status,+ probePreview: async () => true,}),).toEqual({prNumber: 123, headSha: SHA, origin: ORIGIN});expect(github.paginate).toHaveBeenCalledWith(github.rest.pulls.list, {@@ -274,6 +390,7 @@ describe('exact-head Vercel preview', () => {repo: 'astryx',deployment,status,+ probePreview: async () => true,}),).toBeNull();}diff --git a/.github/scripts/visual-gate/workflow-concurrency.test.mjs b/.github/scripts/visual-gate/workflow-concurrency.test.mjsindex a6cf936b4f..f4edb7e680 100644--- a/.github/scripts/visual-gate/workflow-concurrency.test.mjs+++ b/.github/scripts/visual-gate/workflow-concurrency.test.mjs@@ -1,5 +1,13 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file Guard PR reporting, preview staging, and remaining Pages writers.+ * @input Workflow definitions plus the docsite builder and PR reconciler.+ * @output Node tests that keep exact-head Vercel links and visual evidence+ * separate from the remaining Pages publisher until its migration is proven.+ * @position Repository workflow contract tests.+ */+import {execFileSync} from 'node:child_process';import fs from 'node:fs';import os from 'node:os';@@ -147,7 +155,7 @@ describe('PR report and deployment workflow contracts', () => {);});- it('hosts only Storybook on Vercel and preserves Sandbox Pages publication', () => {+ it('stages both static apps on Vercel while retaining separate Pages publication', () => {const config = JSON.parse(fs.readFileSync(path.join(ROOT, 'apps/docsite/vercel.json'), 'utf8'),);@@ -162,8 +170,18 @@ describe('PR report and deployment workflow contracts', () => {'utf8',);expect(builder).toContain("deploymentEnv !== 'preview'");- expect(builder).toContain('buildStorybookPreview(deploymentEnv, root');- expect(builder).not.toContain("'@astryxdesign/sandbox'");+ expect(builder).toContain('buildPreviews(deploymentEnv, root');+ expect(builder).toContain("'@astryxdesign/storybook'");+ expect(builder).toContain("'@astryxdesign/sandbox'");+ expect(builder).toContain("SANDBOX_BASE_PATH: '/sandbox'");+ expect(builder).toContain('fs.rmSync(storybookDestination');+ expect(builder).toContain('fs.rmSync(sandboxDestination');+ const routing = fs.readFileSync(+ path.join(ROOT, 'apps/docsite/next.config.mjs'),+ 'utf8',+ );+ expect(routing).toContain("source: '/sandbox/:path+'");+ expect(routing).toContain("destination: '/sandbox/:path+/index.html'");const comment = workflow('pr-comment.yml');expect(comment).toContain('uses: ./.github/workflows/deploy-preview.yml');expect(comment).toContain('preview-deployment-');@@ -190,7 +208,8 @@ describe('PR report and deployment workflow contracts', () => {);expect(reconciler).toContain('resolveVercelPreview');expect(reconciler).toContain('`${previewOrigin}/storybook/`');- expect(reconciler).toContain('pagesURL(identity, sandboxPath)');+ expect(reconciler).toContain('`${previewOrigin}/sandbox/`');+ expect(reconciler).not.toContain('pagesURL(identity, sandboxPath)');});it('defers full-tree cleanup and retains required visual evidence and stable-site writers', () => {diff --git a/.github/workflows/pr-comment.yml b/.github/workflows/pr-comment.ymlindex 81d51780f5..d2e57873ae 100644--- a/.github/workflows/pr-comment.yml+++ b/.github/workflows/pr-comment.yml@@ -10,9 +10,9 @@# drift between a fork path and a same-repo path.## Safety: resolves scope and PR identity from the GitHub API. Privileged jobs-# check out only trusted default-branch code. The Storybook URL is resolved-# from GitHub's exact-head Vercel deployment, while Sandbox Pages proof comes-# from the validated source CI artifact. PR artifacts remain static data.+# check out only trusted default-branch code. Both preview URLs are resolved+# from one exact-head Vercel deployment after route probes; the Pages result+# remains a separate source-CI artifact, never a preview-link fallback.name: PR Comment@@ -298,8 +298,8 @@ jobs:concurrency:group: pr-report-${{ needs.resolve.outputs.pr_number }}cancel-in-progress: false- # Sandbox Pages publication settles before CI evidence reconciliation;- # Storybook links come from the exact-head Vercel deployment independently.+ # Pages publication may continue independently, but only the exact-head+ # Vercel deployment can supply either Storybook or Sandbox PR links.if: >-always() &&github.event.action == 'completed' &&diff --git a/apps/docsite/.gitignore b/apps/docsite/.gitignoreindex db289ee722..3b7cdf4ff8 100644--- a/apps/docsite/.gitignore+++ b/apps/docsite/.gitignore@@ -13,8 +13,9 @@ public/playground-types.jsonpublic/monaco/public/vendor/-# Vercel stages the built Storybook beside preview/canary docs, never in source control.+# Vercel stages both static previews beside preview/canary docs, never in source control.public/storybook/+public/sandbox/# Auto-generated by `astryx theme build` (pnpm build:theme). The theme source# lives at src/themes/astryxTheme.ts; the built JS/CSS/d.ts files arediff --git a/apps/docsite/next.config.mjs b/apps/docsite/next.config.mjsindex 3b66ee7c5e..844386f5de 100644--- a/apps/docsite/next.config.mjs+++ b/apps/docsite/next.config.mjs@@ -2,8 +2,8 @@/*** @file Configure the docsite's routes, response headers, and theme resolution.- * @input Next.js build configuration and staged Storybook static export.- * @output Docsite routes plus preview-only Storybook HTML at /storybook/.+ * @input Next.js build configuration and staged preview-only static exports.+ * @output Docsite routes plus Storybook and Sandbox at /storybook/ and /sandbox/.* @position Next.js configuration for the existing Vercel docsite deployment.*/@@ -13,15 +13,31 @@ import {resolve} from 'node:path';/** @type {import('next').NextConfig} */const nextConfig = {cacheComponents: true,+ // Sandbox exports trailing-slash directories; Next's automatic slash+ // redirect runs before rewrites. Only preview/canary needs to preserve+ // those URLs. Production docs keep their existing canonical redirects.+ skipTrailingSlashRedirect: process.env.VERCEL_ENV === 'preview',// A dynamic route segment can't carry a static extension, so the public// plaintext URL /blog/<slug>.txt is served by the /blog/txt/[slug] handler.- // Storybook's exported index.html is a static file, not a Next.js route.- // Its other files are served directly from public/ before this rewrite.+ // Static files (including Storybook's iframe and Sandbox's JS/CSS, embeds+ // and template assets) take precedence over afterFiles rewrites. A missing+ // Sandbox path maps only to its own absent index.html, never to the root.async rewrites() {- return [- {source: '/blog/:slug.txt', destination: '/blog/txt/:slug'},- {source: '/storybook', destination: '/storybook/index.html'},- ];+ return {+ afterFiles: [+ {source: '/blog/:slug.txt', destination: '/blog/txt/:slug'},+ {source: '/storybook', destination: '/storybook/index.html'},+ ...(process.env.VERCEL_ENV === 'preview'+ ? [+ {source: '/sandbox', destination: '/sandbox/index.html'},+ {+ source: '/sandbox/:path+',+ destination: '/sandbox/:path+/index.html',+ },+ ]+ : []),+ ],+ };},// The playground preview evaluates user-authored code, so it is the one// route that must never be embeddable by another site and never a loader ofdiff --git a/apps/docsite/scripts/build-previews.mjs b/apps/docsite/scripts/build-previews.mjsindex 02b44acb96..73ddfee9b1 100644--- a/apps/docsite/scripts/build-previews.mjs+++ b/apps/docsite/scripts/build-previews.mjs@@ -1,9 +1,9 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file Build and stage Storybook in the existing Vercel docsite preview.- * @input VERCEL_ENV and the Storybook static build.- * @output apps/docsite/public/storybook only in preview/canary deployments.+ * @file Build and stage Storybook and Vite Sandbox in the existing Vercel docsite preview.+ * @input VERCEL_ENV, Storybook static build, and Sandbox Vite static build.+ * @output apps/docsite/public/{storybook,sandbox} only in preview/canary deployments.* @position Build-time staging before the docsite Next.js build; CI retains its own visual artifact.*/@@ -39,19 +39,27 @@ function indexPath(directory) {return path.join(directory, 'index.html');}-export function buildStorybookPreview(deploymentEnv, root, run = execFileSync) {- const destination = path.join(root, 'apps/docsite/public/storybook');- if (deploymentEnv !== 'preview') {- // Release docs must never package an earlier cached preview.- fs.rmSync(destination, {recursive: true, force: true});- return;+export function stageSandbox(source, destination) {+ for (const relative of ['index.html', '404.html', '404/index.html']) {+ const file = path.join(source, relative);+ if (!fs.existsSync(file) || !fs.statSync(file).isFile()) {+ throw new Error(`Sandbox build has no ${relative}: ${file}`);+ }}+ // The Vite export already uses /sandbox/ for JS, CSS, template assets and+ // fullscreen embeds. Copy the physical tree unchanged: missing paths must+ // stay missing rather than falling through to an SPA shell.+ fs.rmSync(destination, {recursive: true, force: true});+ fs.cpSync(source, destination, {recursive: true});+}+function runPreviewBuild(run, root, name, args, env = process.env) {try {- const output = run('pnpm', ['-F', '@astryxdesign/storybook', 'build'], {+ const output = run('pnpm', args, {cwd: root,encoding: 'utf8',maxBuffer: 64 * 1024 * 1024,+ env,});if (output) process.stdout.write(output);} catch (error) {@@ -60,11 +68,43 @@ export function buildStorybookPreview(deploymentEnv, root, run = execFileSync) {.join('\n').slice(-12000);throw new Error(- `Storybook preview build failed:\n${detail || error.message}`,- {cause: error},+ `${name} preview build failed:\n${detail || error.message}`,+ {+ cause: error,+ },);}- stageStorybook(path.join(root, 'apps/storybook/dist'), destination);+}++export function buildPreviews(deploymentEnv, root, run = execFileSync) {+ const publicDir = path.join(root, 'apps/docsite/public');+ const storybookDestination = path.join(publicDir, 'storybook');+ const sandboxDestination = path.join(publicDir, 'sandbox');+ if (deploymentEnv !== 'preview') {+ // Release docs must never package an earlier cached preview.+ fs.rmSync(storybookDestination, {recursive: true, force: true});+ fs.rmSync(sandboxDestination, {recursive: true, force: true});+ return;+ }++ // Remove cached previews before either build: a failed build must not leave+ // an older static tree that the subsequent Next build could accidentally ship.+ fs.rmSync(storybookDestination, {recursive: true, force: true});+ fs.rmSync(sandboxDestination, {recursive: true, force: true});+ runPreviewBuild(run, root, 'Storybook', [+ '-F',+ '@astryxdesign/storybook',+ 'build',+ ]);+ runPreviewBuild(+ run,+ root,+ 'Sandbox',+ ['-F', '@astryxdesign/sandbox', 'build'],+ {...process.env, SANDBOX_BASE_PATH: '/sandbox'},+ );+ stageStorybook(path.join(root, 'apps/storybook/dist'), storybookDestination);+ stageSandbox(path.join(root, 'apps/sandbox/out'), sandboxDestination);}if (@@ -75,5 +115,5 @@ if (path.dirname(fileURLToPath(import.meta.url)),'../../..',);- buildStorybookPreview(process.env.VERCEL_ENV, root);+ buildPreviews(process.env.VERCEL_ENV, root);}diff --git a/apps/docsite/scripts/build-previews.test.mjs b/apps/docsite/scripts/build-previews.test.mjsindex 5acb9c0c7f..e886a07f6a 100644--- a/apps/docsite/scripts/build-previews.test.mjs+++ b/apps/docsite/scripts/build-previews.test.mjs@@ -6,34 +6,57 @@ import os from 'node:os';import path from 'node:path';import {afterEach, test} from 'node:test';-import {buildStorybookPreview, stageStorybook} from './build-previews.mjs';+import {+ buildPreviews,+ stageSandbox,+ stageStorybook,+} from './build-previews.mjs';const roots = [];function fixture() {- const root = fs.mkdtempSync(- path.join(os.tmpdir(), 'astryx-storybook-preview-'),- );+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-static-preview-'));roots.push(root);- const source = path.join(root, 'apps/storybook/dist');- const destination = path.join(root, 'apps/docsite/public/storybook');- fs.mkdirSync(path.join(source, 'assets'), {recursive: true});+ const storybook = path.join(root, 'apps/storybook/dist');+ const sandbox = path.join(root, 'apps/sandbox/out');+ const publicDir = path.join(root, 'apps/docsite/public');+ fs.mkdirSync(path.join(storybook, 'assets'), {recursive: true});fs.writeFileSync(- path.join(source, 'index.html'),+ path.join(storybook, 'index.html'),'<html><head></head><body>Storybook</body></html>',);- fs.writeFileSync(path.join(source, 'assets/manager.js'), 'manager bytes');- return {root, source, destination};+ fs.writeFileSync(path.join(storybook, 'assets/manager.js'), 'manager bytes');+ for (const dir of [+ '',+ '404',+ 'pages/motion-lab/bugs',+ 'templates/login-sso',+ ]) {+ fs.mkdirSync(path.join(sandbox, dir), {recursive: true});+ fs.writeFileSync(path.join(sandbox, dir, 'index.html'), `<p>${dir}</p>`);+ }+ fs.writeFileSync(path.join(sandbox, '404.html'), 'not found');+ fs.mkdirSync(path.join(sandbox, 'assets'), {recursive: true});+ fs.mkdirSync(path.join(sandbox, 'template-assets'), {recursive: true});+ fs.writeFileSync(path.join(sandbox, 'assets/app.js'), 'app');+ fs.writeFileSync(path.join(sandbox, 'assets/app.css'), 'styles');+ fs.writeFileSync(path.join(sandbox, 'template-assets/logo.svg'), '<svg/>');+ fs.writeFileSync(+ path.join(sandbox, 'templates/login-sso/embed.html'),+ 'embed',+ );+ return {root, storybook, sandbox, publicDir};}afterEach(() => {for (const root of roots.splice(0))fs.rmSync(root, {recursive: true, force: true});});-test('stages a complete Storybook under a stable /storybook/ asset base', () => {- const {source, destination} = fixture();+test('stages complete Storybook under a stable /storybook/ asset base', () => {+ const {storybook, publicDir} = fixture();+ const destination = path.join(publicDir, 'storybook');fs.mkdirSync(destination, {recursive: true});fs.writeFileSync(path.join(destination, 'stale.js'), 'old');- stageStorybook(source, destination);+ stageStorybook(storybook, destination);assert.match(fs.readFileSync(path.join(destination, 'index.html'), 'utf8'),/<base href="\/storybook\/" \/>/,@@ -45,17 +68,55 @@ test('stages a complete Storybook under a stable /storybook/ asset base', () =>assert.equal(fs.existsSync(path.join(destination, 'stale.js')), false);});-test('rejects an incomplete or incompatible export before touching staged bytes', () => {- const {source, destination} = fixture();+test('stages physical Sandbox routes, embeds and assets without a fallback', () => {+ const {sandbox, publicDir} = fixture();+ const destination = path.join(publicDir, 'sandbox');fs.mkdirSync(destination, {recursive: true});- fs.writeFileSync(path.join(destination, 'index.html'), 'old');- for (const html of [null, 'not HTML', '<head><base href="/other/"></head>']) {- if (html === null) fs.rmSync(path.join(source, 'index.html'));- else fs.writeFileSync(path.join(source, 'index.html'), html);- assert.throws(- () => stageStorybook(source, destination),- /Storybook (?:build has no index.html|index.html must have a head)/,+ fs.writeFileSync(path.join(destination, 'stale.html'), 'old');+ stageSandbox(sandbox, destination);+ for (const relative of [+ 'index.html',+ '404.html',+ '404/index.html',+ 'pages/motion-lab/bugs/index.html',+ 'templates/login-sso/embed.html',+ 'template-assets/logo.svg',+ 'assets/app.js',+ 'assets/app.css',+ ]) {+ assert.equal(+ fs.readFileSync(path.join(destination, relative), 'utf8'),+ fs.readFileSync(path.join(sandbox, relative), 'utf8'),);+ }+ assert.equal(fs.existsSync(path.join(destination, 'stale.html')), false);+ assert.equal(+ fs.existsSync(path.join(destination, 'unknown/index.html')),+ false,+ );+});++test('rejects incomplete exports before touching staged bytes', () => {+ const {storybook, sandbox, publicDir} = fixture();+ for (const [source, stage, missing, message] of [+ [+ storybook,+ stageStorybook,+ 'index.html',+ /Storybook build has no index.html/,+ ],+ [+ sandbox,+ stageSandbox,+ '404/index.html',+ /Sandbox build has no 404\/index.html/,+ ],+ ]) {+ const destination = path.join(publicDir, 'staged');+ fs.mkdirSync(destination, {recursive: true});+ fs.writeFileSync(path.join(destination, 'index.html'), 'old');+ fs.rmSync(path.join(source, missing));+ assert.throws(() => stage(source, destination), message);assert.equal(fs.readFileSync(path.join(destination, 'index.html'), 'utf8'),'old',@@ -63,35 +124,71 @@ test('rejects an incomplete or incompatible export before touching staged bytes'}});-test('only preview/canary Vercel builds create the Storybook route', () => {- const {root, destination} = fixture();+test('only preview/canary builds create either static tree', () => {+ const {root, publicDir} = fixture();const calls = [];- buildStorybookPreview('preview', root, (command, args, options) => {+ buildPreviews('preview', root, (command, args, options) => {calls.push({command, args, options});});assert.deepEqual(calls.map(({command, args}) => [command, args]),- [['pnpm', ['-F', '@astryxdesign/storybook', 'build']]],+ [+ ['pnpm', ['-F', '@astryxdesign/storybook', 'build']],+ ['pnpm', ['-F', '@astryxdesign/sandbox', 'build']],+ ],);- assert.equal(fs.existsSync(path.join(destination, 'index.html')), true);+ assert.equal(calls[1].options.env.SANDBOX_BASE_PATH, '/sandbox');+ for (const name of ['storybook', 'sandbox'])+ assert.equal(fs.existsSync(path.join(publicDir, name, 'index.html')), true);for (const env of ['production', 'development', undefined]) {- buildStorybookPreview(env, root, () => {+ buildPreviews(env, root, () => {throw new Error('should not run');});- assert.equal(fs.existsSync(destination), false);+ for (const name of ['storybook', 'sandbox'])+ assert.equal(fs.existsSync(path.join(publicDir, name)), false);+ }+});++test('Next keeps generated Sandbox route rewrites preview-only and never uses a catch-all', async () => {+ const configPath = path.resolve(import.meta.dirname, '../next.config.mjs');+ const previous = process.env.VERCEL_ENV;+ try {+ process.env.VERCEL_ENV = 'preview';+ const {default: preview} = await import(`${configPath}?preview`);+ assert.equal(preview.skipTrailingSlashRedirect, true);+ assert.deepEqual((await preview.rewrites()).afterFiles.slice(-2), [+ {source: '/sandbox', destination: '/sandbox/index.html'},+ {source: '/sandbox/:path+', destination: '/sandbox/:path+/index.html'},+ ]);+ process.env.VERCEL_ENV = 'production';+ const {default: production} = await import(`${configPath}?production`);+ assert.equal(production.skipTrailingSlashRedirect, false);+ assert.equal(+ (await production.rewrites()).afterFiles.some(rule =>+ rule.source.startsWith('/sandbox'),+ ),+ false,+ );+ } finally {+ if (previous === undefined) delete process.env.VERCEL_ENV;+ else process.env.VERCEL_ENV = previous;}});-test('reports captured build output on a failed Storybook build', () => {- const {root} = fixture();+test('failed preview builds do not leave cached static trees', () => {+ const {root, publicDir} = fixture();+ buildPreviews('preview', root, () => {});assert.throws(() =>- buildStorybookPreview('preview', root, () => {- throw Object.assign(new Error('command failed'), {- stdout: 'building',- stderr: 'failed to compile',- });+ buildPreviews('preview', root, (_command, args) => {+ if (args[1] === '@astryxdesign/sandbox')+ throw Object.assign(new Error('command failed'), {+ stdout: 'building',+ stderr: 'failed to compile',+ });}),- /Storybook preview build failed:\nbuilding\nfailed to compile/,+ /Sandbox preview build failed:\nbuilding\nfailed to compile/,);+ for (const name of ['storybook', 'sandbox'])+ assert.equal(fs.existsSync(path.join(publicDir, name)), false);});