diff --git a/docs/docs/plugins/design.md b/docs/docs/plugins/design.md index e3dd63599..ac715da65 100644 --- a/docs/docs/plugins/design.md +++ b/docs/docs/plugins/design.md @@ -218,10 +218,10 @@ Each page renders in its own error boundary and posts `appkit:design-ready` once A builder can show a draft while it's still being written, instead of only once it's finished: -- Append the page's source, as it arrives, to `client/src/design/.staging/.tsx` (and the shared mock's to `.staging/mock.ts`). +- Append the page's source, as it arrives, to `client/src/design/.staging/.tsx`. - Show `/design/__stream/`. The dev server keeps the latest renderable version of the staging file under the page's real module (`pages/.tsx`): it closes whatever is still open at the cut (JSX tags, brackets, template literals) and stubs what the page uses that hasn't arrived yet. Components not written yet show a `DraftPlaceholder` skeleton of the right shape. Each version reaches the page as a hot update, so it fills in in place, with no reload and with its state kept. -- Until `mock.ts` exists, the page's `../mock` import is what `.staging/mock.ts` has so far, plus stubs for whatever the page imports from it that isn't there yet. -- When the page type-checks, write it to `pages/.tsx` (and `mock.ts`): the same module then loads from disk. Deleting the staging file starts that draft over. +- A version that imports `../mock` is published only once `mock.ts` exists, so it never shows without its data. What counts is the version as Vite compiles it, under the app's tsconfig. An `import type` compiles away. So does an inline `import { type T }`, unless `verbatimModuleSyntax` is set (as in the AppKit template), which keeps it as an import. So does an early cut that doesn't use the values it imports yet, which is published as usual. Until `mock.ts` exists, the page keeps its last version (or stays pending); the moment it lands, the latest version (or the finished page) is published. So write `mock.ts` first, as soon as it's complete. +- When the page type-checks, write it to `pages/.tsx`: the same module then loads from disk. Deleting the staging file starts that draft over. Every design page, streamed or not, renders through `DesignPage` (from `@databricks/appkit-ui/react/beta`; the plugin adds it, pages don't). It applies the app's theme before the first paint (`?theme=dark` or `?theme=light` on the URL, else the system setting), so a dark page never flashes light. If a render fails mid-stream, it keeps the last good frame on screen instead of a broken page, and holds readiness back until a render succeeds. @@ -231,7 +231,7 @@ A builder showing a page in a frame can read what happened from markers on the p | State | Marker | When | | --- | --- | --- | -| pending | no `[data-design-page]` shell yet, or a shell with none of the markers below | The page hasn't loaded, or it suspended (lazy code, data) and a `Suspense` fallback shows. For `/design/__stream/`: no version is published yet. | +| pending | no `[data-design-page]` shell yet, or a shell with none of the markers below | The page hasn't loaded, or it suspended (lazy code, data) and a `Suspense` fallback shows. For `/design/__stream/`: no version is published yet (a version that imports `../mock` waits for `mock.ts`). | | rendered | `[data-design-page][data-design-rendered]` | The page committed a render without an error (set in an effect after mount). A page that renders an empty element counts: that's its own output. | | last-good | `[data-design-last-good]` inside the shell | A render error once the page has shown: a copy of it as it was on screen when the error came (or, if a `Suspense` fallback had replaced it, as it last showed). No `data-design-rendered`. | | error | `[data-design-error]` inside the shell, with the message | A render error before any good render, or, on a stream page, a published version that fails to load or evaluate (shown at once). No `data-design-rendered`. | @@ -245,6 +245,7 @@ What moves a page between them: | pending | The page renders (an empty page too) | rendered | | pending | It throws while rendering, or (stream) the published version fails to load or evaluate | error | | pending | It suspends | pending, the fallback on screen | +| pending or rendered | (stream) A version imports `../mock` before `mock.ts` exists | unchanged (pending, or the last version); once `mock.ts` lands, the latest version (or the finished page) is published | | pending | (stream) An import fails before any version is out | pending (the server is asked again, in case a publish came before the page listened) | | pending, the fallback on screen | It shows, or throws | rendered, or error (the fallback is never copied) | | rendered (from its first commit) | It or an update throws, at once or later (a timer, data), also in the task it committed in | last-good: the frame on screen, that update's included | diff --git a/packages/appkit/src/plugins/design/stream.ts b/packages/appkit/src/plugins/design/stream.ts index 73a648e49..7e16eaf16 100644 --- a/packages/appkit/src/plugins/design/stream.ts +++ b/packages/appkit/src/plugins/design/stream.ts @@ -3,6 +3,8 @@ * `.staging/.tsx` is served as `pages/.tsx` and hot-swapped in place. */ +import path from "node:path"; + type Frame = | { k: "brace" | "paren" | "bracket" | "tpl" | "tplExpr" | "jsxExpr" } | { k: "tag" | "el"; name: string }; @@ -279,13 +281,7 @@ const MAX_CUTS = 60; export async function renderablePartial( source: string, isValid: IsValid, - { - page = true, - complete = false, - }: { - page?: boolean; - complete?: boolean; - } = {}, + { complete = false }: { complete?: boolean } = {}, ): Promise { const src = stripFence(source); if (complete && (await isValid(src))) return src; @@ -294,67 +290,48 @@ export async function renderablePartial( let end = lines.length - 1; for (let tries = 0; end > 0 && tries < MAX_CUTS; end--, tries++) { const cut = lines.slice(0, end).join("\n"); - if (page && !/export\s+default\b/.test(cut)) return null; + if (!/export\s+default\b/.test(cut)) return null; const closed = closeOpen(cut); if (closed === null) continue; - const code = page ? stubComponents(closed) : closed; + const code = stubComponents(closed); if (await isValid(code)) return code; } return null; } -/** Value names a page imports from `../` (type-only imports excluded). */ -export function mockImports(page: string, mock = "mock"): string[] { - const names: string[] = []; - for (const m of page.matchAll( - /import\s*\{([^}]*)\}\s*from\s*["']\.\.\/([\w-]+?)(?:\.ts)?["']/g, - )) { - if (m[2] !== mock) continue; - for (const spec of m[1].split(",")) { - const s = spec.trim(); - if (!s || s.startsWith("type ")) continue; - names.push(s.split(/\s+as\s+/)[0]); - } - } - return names; -} - -/** Stands in for mock values not written yet: never throws, renders as nothing. */ -const DRAFT_VALUE = `const __draftValue: any = (() => { - const target: any = function () {}; - const value: any = new Proxy(target, { - get: (_t, key) => - key === Symbol.toPrimitive - ? (hint: string) => (hint === "number" ? 0 : "") - : key === Symbol.iterator - ? function* () {} - : key === "then" - ? undefined - : value, - apply: () => value, - construct: () => value, - }); - return value; -})();`; +const MODULE_NODES = new Set([ + "ImportDeclaration", + "ExportNamedDeclaration", + "ExportAllDeclaration", + "ImportExpression", +]); /** - * The partial mock plus a placeholder for each value a page imports from it that - * isn't defined yet (a missing named export would be a SyntaxError). + * Whether a compiled page (the ESTree program of the JS Vite serves for + * `pages/.tsx`, types already stripped) imports `src/design/mock`. * * @internal */ -export function stubMock(mock: string, imported: Iterable): string { - const exported = new Set( - [ - ...mock - .replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, "") - .matchAll(/export\s+(?:const|let|var|function|class|enum)\s+([\w$]+)/g), - ].map((m) => m[1]), - ); - const stubs = [...new Set(imported)].filter((name) => !exported.has(name)); - return stubs.length === 0 - ? mock - : `${mock}\n${DRAFT_VALUE}\n${stubs.map((name) => `export const ${name}: any = __draftValue;`).join("\n")}\n`; +export function importsMock(program: unknown): boolean { + const walk = (node: unknown): boolean => { + if (!node || typeof node !== "object") return false; + if (Array.isArray(node)) return node.some(walk); + const { type, source } = node as { + type?: string; + source?: { value?: unknown }; + }; + if ( + MODULE_NODES.has(type as string) && + typeof source?.value === "string" && + /^\/src\/design\/mock(?:\.[jt]sx?)?$/.test( + path.posix.resolve("/src/design/pages", source.value), + ) + ) { + return true; + } + return Object.values(node).some(walk); + }; + return walk(program); } /** diff --git a/packages/appkit/src/plugins/design/tests/stream-watch.test.ts b/packages/appkit/src/plugins/design/tests/stream-watch.test.ts index b1a24b2e4..ab130dd70 100644 --- a/packages/appkit/src/plugins/design/tests/stream-watch.test.ts +++ b/packages/appkit/src/plugins/design/tests/stream-watch.test.ts @@ -11,17 +11,25 @@ const cwd = process.cwd(); afterEach(() => process.chdir(cwd)); /** The plugin on a fake dev server whose watcher the test drives. */ -function start() { +function start(compilerOptions = {}) { const app = fs.mkdtempSync(path.join(os.tmpdir(), "design-stream-")); const root = path.join(app, "client"); fs.mkdirSync(path.join(root, "src/design/.staging"), { recursive: true }); fs.mkdirSync(path.join(root, "src/design/pages"), { recursive: true }); + // The app's own tsconfig decides what a page imports once compiled. + fs.writeFileSync( + path.join(root, "tsconfig.json"), + JSON.stringify({ compilerOptions }), + ); process.chdir(app); const plugin = designVitePlugin(); (plugin.configResolved as (c: { root: string }) => void)({ root }); const watcher = new EventEmitter(); const sent: { event: string; data: { name: string; done?: boolean } }[] = []; const warn = vi.fn(); + // Modules the browser has loaded, by file, and the ones hot-updated since. + const modules = new Map(); + const reloaded: object[] = []; let handler: Handler | undefined; (plugin.configureServer as (s: unknown) => void)({ config: { root, logger: { warn } }, @@ -30,10 +38,12 @@ function start() { middlewares: { use: (h: Handler) => (handler = h) }, transformIndexHtml: async (_url: string, html: string) => html, moduleGraph: { - getModulesByFile: () => [], + getModulesByFile: (file: string) => modules.get(file) ?? [], getModuleById: async () => undefined, }, - reloadModule: async () => {}, + reloadModule: async (mod: object) => { + reloaded.push(mod); + }, }); /** The HTML of `/design/__stream/`. */ const streamHtml = async (name: string) => { @@ -45,7 +55,34 @@ function start() { ); return html; }; - return { root, watcher, sent, warn, streamHtml }; + /** What the plugin's hotUpdate leaves of Vite's update of `file`. */ + const hotUpdate = (file: string, mods: object[]) => + ( + plugin.hotUpdate as (o: { + type: string; + file: string; + modules: object[]; + read: () => string; + }) => Promise + ).call( + {}, + { + type: "create", + file, + modules: mods, + read: () => fs.readFileSync(file, "utf-8"), + }, + ); + return { + root, + watcher, + sent, + warn, + streamHtml, + modules, + reloaded, + hotUpdate, + }; } type Handler = ( @@ -96,3 +133,155 @@ test("the stream page says whether a version is out, so a failed import isn't ta '
', ); }); + +const TYPES_PAGE = + 'import { type Trip } from "../mock";\n\nexport default function Page() {\n const trip: Trip | null = null;\n return

Trips {String(trip)}

;\n}\n'; +const MOCK_PAGE = + 'import { trips } from "../mock";\n\nexport default function Page() {\n return

{trips.length} trips

;\n}\n'; +const published = ( + sent: { data: { name: string; done?: boolean } }[], + name = "dash", +) => sent.filter((m) => m.data?.name === name); + +test("a page that imports ../mock is published only once mock.ts exists", async () => { + const { root, watcher, sent, streamHtml } = start(); + const staging = path.join(root, "src/design/.staging/dash.tsx"); + fs.writeFileSync(staging, MOCK_PAGE); + watcher.emit("change", staging); + // Type-only imports compile away: it doesn't wait, it's published as before. + const types = path.join(root, "src/design/.staging/types.tsx"); + fs.writeFileSync(types, TYPES_PAGE); + watcher.emit("change", types); + await until(() => sent.some((m) => m.data?.name === "types")); + expect(sent.some((m) => m.data?.name === "types")).toBe(true); + await new Promise((r) => setTimeout(r, 200)); + expect(published(sent)).toEqual([]); + expect(await streamHtml("dash")).toContain('
'); + + const mock = path.join(root, "src/design/mock.ts"); + fs.writeFileSync(mock, "export const trips = [{ id: 1 }];\n"); + watcher.emit("add", mock); + await until(() => published(sent).length > 0); + expect(published(sent)).toMatchObject([ + { event: "appkit:stream", data: { name: "dash" } }, + ]); + expect(await streamHtml("dash")).toContain( + '
', + ); +}); + +test("a finished page waits for mock.ts too, also when its draft was moved in", async () => { + const { root, watcher, sent, streamHtml } = start(); + const staging = path.join(root, "src/design/.staging/dash.tsx"); + fs.writeFileSync(staging, MOCK_PAGE); + watcher.emit("change", staging); + await new Promise((r) => setTimeout(r, 200)); + // Moved in: the staging file goes, the finished page lands. + fs.rmSync(staging); + watcher.emit("unlink", staging); + const page = path.join(root, "src/design/pages/dash.tsx"); + fs.writeFileSync(page, MOCK_PAGE); + watcher.emit("add", page); + await new Promise((r) => setTimeout(r, 200)); + expect(published(sent)).toEqual([]); + expect(await streamHtml("dash")).toContain('
'); + + const mock = path.join(root, "src/design/mock.ts"); + fs.writeFileSync(mock, "export const trips = [{ id: 1 }];\n"); + watcher.emit("add", mock); + await until(() => published(sent).length > 0); + expect(published(sent)).toMatchObject([ + { data: { name: "dash", done: true } }, + ]); + expect(await streamHtml("dash")).toContain( + '
', + ); +}); + +test("with verbatimModuleSyntax, an inline type import keeps ../mock, so the page waits", async () => { + const { root, watcher, sent } = start({ verbatimModuleSyntax: true }); + const staging = path.join(root, "src/design/.staging/dash.tsx"); + fs.writeFileSync(staging, TYPES_PAGE); + watcher.emit("change", staging); + await new Promise((r) => setTimeout(r, 300)); + expect(published(sent)).toEqual([]); + + const mock = path.join(root, "src/design/mock.ts"); + fs.writeFileSync(mock, "export type Trip = { id: number };\n"); + watcher.emit("add", mock); + await until(() => published(sent).length > 0); + expect(published(sent)).toMatchObject([{ data: { name: "dash" } }]); +}); + +test("a finished page shown in an earlier version gets its hot update once mock.ts lands", async () => { + const { root, watcher, sent, modules, reloaded, hotUpdate } = start(); + // An early cut doesn't use the mock yet: its import compiles away, it's published. + const staging = path.join(root, "src/design/.staging/dash.tsx"); + fs.writeFileSync( + staging, + 'import { trips } from "../mock";\n\nexport default function Page() {\n return

Trips

;\n}\n', + ); + watcher.emit("change", staging); + await until(() => published(sent).length > 0); + expect(published(sent)).toHaveLength(1); + + // The browser has that version; the finished page, which uses the mock, lands. + const page = path.join(root, "src/design/pages/dash.tsx"); + const mod = { importers: new Set(), isSelfAccepting: true }; + modules.set(page, [mod]); + fs.writeFileSync(page, MOCK_PAGE); + // Vite's update would fail without mock.ts: it's held, and so is done. + expect(await hotUpdate(page, [mod])).toEqual([]); + watcher.emit("add", page); + await new Promise((r) => setTimeout(r, 200)); + expect(published(sent)).toHaveLength(1); + expect(reloaded).toEqual([]); + + const mock = path.join(root, "src/design/mock.ts"); + fs.writeFileSync(mock, "export const trips = [{ id: 1 }];\n"); + watcher.emit("add", mock); + await until(() => published(sent).length > 1); + expect(reloaded).toEqual([mod]); + expect(published(sent)[1]).toMatchObject({ + data: { name: "dash", done: true }, + }); + // With mock.ts there, Vite's own update of the page goes through. + expect(await hotUpdate(page, [mod])).toBeUndefined(); +}); + +test("a finished page never streamed, first seen by its stream page, is published when mock.ts lands", async () => { + const { root, watcher, sent, streamHtml } = start(); + // No staging draft and no watcher event: only the stream page is opened. + fs.writeFileSync(path.join(root, "src/design/pages/dash.tsx"), MOCK_PAGE); + expect(await streamHtml("dash")).toContain('
'); + + const mock = path.join(root, "src/design/mock.ts"); + fs.writeFileSync(mock, "export const trips = [{ id: 1 }];\n"); + watcher.emit("add", mock); + await until(() => published(sent).length > 0); + expect(published(sent)).toMatchObject([ + { data: { name: "dash", done: true } }, + ]); + expect(await streamHtml("dash")).toContain( + '
', + ); +}); + +test("a finished page first seen as a hot update is updated when mock.ts lands", async () => { + const { root, watcher, sent, modules, reloaded, hotUpdate } = start(); + // A page shown at /design/kpis (never streamed) starts using the mock. + const page = path.join(root, "src/design/pages/kpis.tsx"); + const mod = { importers: new Set([{}]), isSelfAccepting: true }; + modules.set(page, [mod]); + fs.writeFileSync(page, MOCK_PAGE); + expect(await hotUpdate(page, [mod])).toEqual([]); + + const mock = path.join(root, "src/design/mock.ts"); + fs.writeFileSync(mock, "export const trips = [{ id: 1 }];\n"); + watcher.emit("add", mock); + await until(() => published(sent, "kpis").length > 0); + expect(reloaded).toEqual([mod]); + expect(published(sent, "kpis")).toMatchObject([ + { data: { name: "kpis", done: true } }, + ]); +}); diff --git a/packages/appkit/src/plugins/design/tests/stream.test.ts b/packages/appkit/src/plugins/design/tests/stream.test.ts index de815631d..14989dc64 100644 --- a/packages/appkit/src/plugins/design/tests/stream.test.ts +++ b/packages/appkit/src/plugins/design/tests/stream.test.ts @@ -1,12 +1,15 @@ -import { transformWithOxc } from "vite"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { parseAst, transformWithOxc } from "vite"; import { describe, expect, test } from "vitest"; import { closeOpen, - mockImports, + importsMock, placeholderKind, renderablePartial, - stubMock, } from "../stream"; const parses = async (code: string) => { @@ -143,14 +146,45 @@ describe("placeholderKind", () => { }); }); -describe("stubMock", () => { - test("stubs the values a page imports that the mock doesn't export yet", () => { - expect(mockImports(PAGE)).toEqual(["trips"]); - // The contract comment lists trips before it is defined. - const mock = - "export type Trip = { id: number };\n// export const trips: Trip[]\nexport const kpis = {};"; - const code = stubMock(mock, ["trips", "kpis"]); - expect(code).toContain("export const trips: any = __draftValue;"); - expect(code).not.toContain("export const kpis: any"); +describe("importsMock", () => { + // Compiled as Vite serves a page, under a tsconfig without verbatimModuleSyntax. + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "design-mock-")); + fs.writeFileSync(path.join(dir, "tsconfig.json"), "{}"); + const usesMock = async (code: string) => { + const js = await transformWithOxc(code, path.join(dir, "page.tsx"), { + lang: "tsx", + jsx: { runtime: "automatic" }, + }); + return importsMock(parseAst(js.code)); + }; + + test("a value import, re-export, bare or dynamic import of the mock counts", async () => { + for (const code of [ + PAGE, + 'import {\n trips,\n kpis,\n} from "../mock.ts";\nconsole.log(trips, kpis);', + "import * as data from '../mock';\nconsole.log(data);", + 'import mock from "../mock.js";\nconsole.log(mock);', + 'import { trips } /* ; */ from "../mock";\nconsole.log(trips);', + 'export { trips } from "../mock";', + 'import "../mock";', + 'const load = () => import("../mock");\nconsole.log(load);', + 'import { trips } from "/src/design/mock.ts";\nconsole.log(trips);', + ]) { + expect(await usesMock(code), code).toBe(true); + } + }); + + test("type-only imports, strings, comments and other modules don't", async () => { + for (const code of [ + 'import type { Trip } from "../mock";\nlet t: Trip;', + 'import { type Trip } from "../mock";\nlet t: Trip;', + 'export type { Trip } from "../mock";', + 'export default () => "../mock";', + '// import { trips } from "../mock";', + 'import { trips } from "../mocks";\nconsole.log(trips);', + 'import { trips } from "./mock";\nconsole.log(trips);', + ]) { + expect(await usesMock(code), code).toBe(false); + } }); }); diff --git a/packages/appkit/src/plugins/design/vite-plugin.ts b/packages/appkit/src/plugins/design/vite-plugin.ts index ffb2f2c85..f7ba626c6 100644 --- a/packages/appkit/src/plugins/design/vite-plugin.ts +++ b/packages/appkit/src/plugins/design/vite-plugin.ts @@ -4,12 +4,7 @@ import path from "node:path"; import type { Plugin, ViteDevServer } from "vite"; -import { - mockImports, - renderablePartial, - streamHostModule, - stubMock, -} from "./stream"; +import { importsMock, renderablePartial, streamHostModule } from "./stream"; /** Virtual page entry; `.mjs` so plugin-react doesn't inject Fast Refresh into it. */ const ENTRY_PREFIX = "virtual:appkit-design-page:"; @@ -556,8 +551,8 @@ export function designVitePlugin({ >(); let appPath: string | undefined; - // Streamed drafts (.staging/.tsx, .staging/mock.ts): by name, the - // published version and the staging mtime it came from. + // Streamed drafts (.staging/.tsx): by name, the published version and + // the staging mtime it came from. const streams = new Map< string, { @@ -570,12 +565,10 @@ export function designVitePlugin({ last: number; } >(); + // Pages whose latest version waits for mock.ts (kept when its draft is moved in). + const waiting = new Set(); const stagingFile = (name: string) => - path.join( - root, - "src/design/.staging", - name === "mock" ? "mock.ts" : `${name}.tsx`, - ); + path.join(root, "src/design/.staging", `${name}.tsx`); const finalFile = (name: string) => name === "mock" ? path.join(root, "src/design/mock.ts") @@ -585,9 +578,9 @@ export function designVitePlugin({ .relative(path.join(root, "src/design"), file) .split(path.sep) .join("/"); - if (rel === ".staging/mock.ts" || rel === "mock.ts") return "mock"; + if (rel === "mock.ts") return "mock"; const name = /^(?:\.staging|pages)\/([A-Za-z0-9_-]+)\.tsx$/.exec(rel)?.[1]; - return name && !isReservedName(name) ? name : undefined; + return name && name !== "mock" && !isReservedName(name) ? name : undefined; }; const streamCssDir = path.join( projectRoot, @@ -619,23 +612,6 @@ export function designVitePlugin({ ? code : null; }; - /** The mock before mock.ts exists: .staging/mock.ts so far, plus stubs. */ - const mockCode = (): string | null => { - if (fs.existsSync(finalFile("mock"))) return null; - const pages = [...streams.keys()] - .filter((n) => n !== "mock") - .map(streamedCode) - .filter((c): c is string => c !== null); - const mock = fs.existsSync(stagingFile("mock")) - ? (streams.get("mock")?.code ?? null) - : null; - if (mock === null && pages.length === 0) return null; - return stubMock( - mock ?? "", - pages.flatMap((p) => mockImports(p)), - ); - }; - let servedMock: string | null = null; const reloadFile = async (file: string) => { for (const mod of viteServer?.moduleGraph.getModulesByFile(file) ?? []) { // Not imported (page closed): a hot update would reload every page. @@ -643,12 +619,6 @@ export function designVitePlugin({ await viteServer?.reloadModule(mod); } }; - const reloadMock = async () => { - const code = mockCode(); - if (code === servedMock) return; - servedMock = code; - await reloadFile(finalFile("mock")); - }; const reloadCss = async () => { for (const id of streamCssIds) { const mod = await viteServer?.moduleGraph.getModuleById(id); @@ -674,6 +644,52 @@ export function designVitePlugin({ return false; } }; + /** Whether a page, compiled as Vite serves it (its tsconfig applies), imports the mock. */ + const usesMock = async (code: string, file: string) => { + const vite = (await import("vite")) as typeof import("vite") & { + transformWithOxc?: ( + code: string, + file: string, + opts: object, + ) => Promise<{ code: string }>; + }; + try { + const js = vite.transformWithOxc + ? await vite.transformWithOxc(code, file, { + lang: "tsx", + jsx: { runtime: "automatic" }, + }) + : await vite.transformWithEsbuild(code, file, { + loader: "tsx", + jsx: "automatic", + }); + return importsMock(vite.parseAst(js.code)); + } catch { + // It doesn't build: loading it shows that error, with or without the mock. + return false; + } + }; + /** A page using `../mock` before mock.ts exists would render without its data. */ + const waitsForMock = async (code: string, file: string) => + !fs.existsSync(finalFile("mock")) && + (await usesMock(code, file)) && + // Again: it may have landed while compiling. + !fs.existsSync(finalFile("mock")); + /** + * Whether the finished page exists and is published: one that waits for + * mock.ts (streamed or not) is published when it lands. + */ + const finalReady = async (name: string) => { + let code: string; + try { + code = fs.readFileSync(finalFile(name), "utf-8"); + } catch { + return false; + } + if (!(await waitsForMock(code, finalFile(name)))) return true; + waiting.add(name); + return false; + }; /** Publishes the renderable version of a staging file, if it changed. */ const publish = async (name: string) => { const s = streams.get(name); @@ -687,18 +703,22 @@ export function designVitePlugin({ } catch { return; } - const mock = name === "mock"; - const code = await renderablePartial(raw, isValid, { page: !mock }); + const code = await renderablePartial(raw, isValid); if (code === null || code === s.code) return; + // Published once mock.ts lands, not before. + if (await waitsForMock(code, finalFile(name))) { + waiting.add(name); + return; + } + waiting.delete(name); s.code = code; s.last = Date.now(); // Styles first, so the version never shows without its classes. - if (!mock && newTokens(code)) { + if (newTokens(code)) { fs.writeFileSync(path.join(streamCssDir, `${name}.tsx`), code); await reloadCss(); } - if (!mock) await reloadFile(finalFile(name)); - await reloadMock(); + await reloadFile(finalFile(name)); viteServer?.ws.send({ type: "custom", event: "appkit:stream", @@ -750,13 +770,18 @@ export function designVitePlugin({ // Deleted again already (a builder starting the draft over). return; } - if (name !== "mock") { - if (newTokens(code)) { - fs.writeFileSync(path.join(streamCssDir, `${name}.tsx`), code); - await reloadCss(); - } + // Its done event too waits for mock.ts. + if (await waitsForMock(code, file)) { + waiting.add(name); + return; } - await reloadMock(); + const held = waiting.delete(name); + if (newTokens(code)) { + fs.writeFileSync(path.join(streamCssDir, `${name}.tsx`), code); + await reloadCss(); + } + // Its hot update was held too: send it now. + if (held) await reloadFile(file); viteServer?.ws.send({ type: "custom", event: "appkit:stream", @@ -780,7 +805,7 @@ export function designVitePlugin({ resolveId: { // Before Vite's resolver, which can't find a streamed file not on disk yet. order: "pre", - handler(id, importer) { + handler(id) { if ( id.startsWith(ENTRY_PREFIX) || id.startsWith(STREAM_HOST_PREFIX) || @@ -801,13 +826,6 @@ export function designVitePlugin({ ) { return finalFile(page); } - if ( - /^\.\.\/mock(?:\.ts)?$/.test(clean) && - importer?.startsWith(path.join(root, "src/design/pages")) && - mockCode() !== null - ) { - return finalFile("mock"); - } }, }, @@ -837,15 +855,13 @@ export function designVitePlugin({ ? streamHostModule(name) : undefined; } - // A streamed page or mock: its latest renderable version. + // A streamed page: its latest renderable version. const loaded = id.split("?")[0]; const streamed = - loaded === finalFile("mock") - ? mockCode() - : streams.has(path.basename(loaded, ".tsx")) && - loaded === finalFile(path.basename(loaded, ".tsx")) - ? streamedCode(path.basename(loaded, ".tsx")) - : null; + streams.has(path.basename(loaded, ".tsx")) && + loaded === finalFile(path.basename(loaded, ".tsx")) + ? streamedCode(path.basename(loaded, ".tsx")) + : null; if (streamed !== null) return streamed; if (!id.startsWith(`\0${ENTRY_PREFIX}`)) return; if (!id.endsWith(ENTRY_SUFFIX)) return; @@ -857,7 +873,7 @@ export function designVitePlugin({ }, // A deleted draft still in the graph would reload every page. - hotUpdate({ type, file, modules }) { + async hotUpdate({ type, file, modules, read }) { const name = streamName(file); if ( type === "delete" && @@ -871,6 +887,21 @@ export function designVitePlugin({ } return []; } + // A finished page waiting for mock.ts (streamed or not) would fail to + // load, and then lose its update: onFinal sends it once mock.ts lands. + if ( + type !== "delete" && + name && + name !== "mock" && + file === finalFile(name) && + (await waitsForMock( + await Promise.resolve(read()).catch(() => ""), + file, + )) + ) { + waiting.add(name); + return []; + } // Nothing imports it yet: no boundary, Vite would reload every page. if (name && file === finalFile(name)) { const live = modules.filter( @@ -909,8 +940,21 @@ export function designVitePlugin({ `[appkit-design] ${name}: ${String(error)}`, ); if (file === stagingFile(name)) onStagingChange(name).catch(failed); - else if (file === finalFile(name) && streams.has(name)) + else if ( + file === finalFile(name) && + (streams.has(name) || waiting.has(name)) + ) onFinal(name).catch(failed); + // mock.ts is out: publish the versions that waited for it. + if (name === "mock") { + for (const page of [...waiting]) { + onFile( + fs.existsSync(finalFile(page)) + ? finalFile(page) + : stagingFile(page), + ); + } + } }; server.watcher?.on("add", onFile); server.watcher?.on("change", onFile); @@ -960,8 +1004,7 @@ export function designVitePlugin({ if (streamPage && !isReservedName(streamPage)) { // With a version out, a failed import is an error, not still pending. const published = - streamedCode(streamPage) !== null || - fs.existsSync(finalFile(streamPage)); + streamedCode(streamPage) !== null || (await finalReady(streamPage)); const html = await server.transformIndexHtml( req.url ?? pathname, pageHtml(