brumate 0.0.1 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -72
- package/dist/boot-DN1ZU8Hg.d.ts +37 -0
- package/dist/cli.js +2 -2
- package/dist/{client-DuDTDePF.d.ts → client-DwJInP_a.d.ts} +133 -44
- package/dist/client-routes-DakuM32C.js +94 -0
- package/dist/client-routes-DakuM32C.js.map +1 -0
- package/dist/{cookies-rgIAc8IE.js → cookies-Av5WFmcf.js} +18 -8
- package/dist/cookies-Av5WFmcf.js.map +1 -0
- package/dist/{devtools-Bm8cS7hX.js → devtools-BKjnHrnv.js} +10 -5
- package/dist/devtools-BKjnHrnv.js.map +1 -0
- package/dist/{devtools-panel-CTbDSBBA.js → devtools-panel-AWOn0VK2.js} +23 -26
- package/dist/devtools-panel-AWOn0VK2.js.map +1 -0
- package/dist/{files-D_JUcSU5.js → files-BBLPU9JR.js} +22 -3
- package/dist/{files-D_JUcSU5.js.map → files-BBLPU9JR.js.map} +1 -1
- package/dist/{html-CxWpXngy.js → html-DEeoepg3.js} +47 -10
- package/dist/html-DEeoepg3.js.map +1 -0
- package/dist/{html-DV-Tezgq.d.ts → html-Du8jY2Cc.d.ts} +14 -2
- package/dist/index.d.ts +63 -6
- package/dist/index.js +20 -4
- package/dist/index.js.map +1 -1
- package/dist/{inspect-CGCWfaEx.js → inspect-CRZlO11T.js} +743 -163
- package/dist/inspect-CRZlO11T.js.map +1 -0
- package/dist/loader-Dc9OwY5I.js +101 -0
- package/dist/loader-Dc9OwY5I.js.map +1 -0
- package/dist/{navigate-C5dP89YL.js → navigate-CzLjnoPH.js} +112 -59
- package/dist/navigate-CzLjnoPH.js.map +1 -0
- package/dist/{produce-BjQGMpqL.d.ts → produce-CtZ32UGG.d.ts} +13 -3
- package/dist/{rpc-B86KKjzx.js → rpc-9fSqL_YK.js} +57 -12
- package/dist/rpc-9fSqL_YK.js.map +1 -0
- package/dist/runtime/client.d.ts +4 -4
- package/dist/runtime/client.js +599 -306
- package/dist/runtime/client.js.map +1 -1
- package/dist/runtime/devtools.d.ts +3 -1
- package/dist/runtime/devtools.js +1 -1
- package/dist/runtime/hot.d.ts +1 -1
- package/dist/runtime/hot.js +9 -5
- package/dist/runtime/hot.js.map +1 -1
- package/dist/runtime/html.d.ts +2 -2
- package/dist/runtime/html.js +1 -1
- package/dist/runtime/loader.d.ts +12 -2
- package/dist/runtime/loader.js +3 -1
- package/dist/runtime/server.d.ts +4 -4
- package/dist/runtime/server.js +5 -5
- package/dist/runtime/signals.d.ts +2 -2
- package/dist/runtime/signals.js +5 -5
- package/dist/runtime/signals.js.map +1 -1
- package/dist/runtime/static-loader.d.ts +3 -0
- package/dist/runtime/static-loader.js +1 -0
- package/dist/runtime/testing.d.ts +21 -2
- package/dist/runtime/testing.js +83 -7
- package/dist/runtime/testing.js.map +1 -1
- package/dist/{server-sQCvduOz.d.ts → server-BxqjLUnV.d.ts} +211 -20
- package/dist/{server-CX3JnPCs.js → server-DZsgnPKS.js} +595 -185
- package/dist/server-DZsgnPKS.js.map +1 -0
- package/dist/shared-CWYOd0H3.js +40 -0
- package/dist/shared-CWYOd0H3.js.map +1 -0
- package/dist/static-loader-BcFh4ebX.d.ts +11 -0
- package/dist/static-loader-ClNkHZGn.js +185 -0
- package/dist/static-loader-ClNkHZGn.js.map +1 -0
- package/dist/stream-bgNCMcaA.js +280 -0
- package/dist/stream-bgNCMcaA.js.map +1 -0
- package/dist/vite.d.ts +30 -5
- package/dist/vite.js +501 -62
- package/dist/vite.js.map +1 -1
- package/package.json +7 -2
- package/types.d.ts +5 -0
- package/dist/cookies-rgIAc8IE.js.map +0 -1
- package/dist/devtools-Bm8cS7hX.js.map +0 -1
- package/dist/devtools-panel-CTbDSBBA.js.map +0 -1
- package/dist/html-CxWpXngy.js.map +0 -1
- package/dist/inspect-CGCWfaEx.js.map +0 -1
- package/dist/loader-BUhNqDHw.d.ts +0 -30
- package/dist/loader-py4qu6tQ.js +0 -215
- package/dist/loader-py4qu6tQ.js.map +0 -1
- package/dist/navigate-C5dP89YL.js.map +0 -1
- package/dist/rpc-B86KKjzx.js.map +0 -1
- package/dist/server-CX3JnPCs.js.map +0 -1
- package/dist/shared-BE_oBSDM.js +0 -176
- package/dist/shared-BE_oBSDM.js.map +0 -1
- package/dist/stream-cvhqOzfs.js +0 -145
- package/dist/stream-cvhqOzfs.js.map +0 -1
package/dist/vite.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite.js","names":[],"sources":["../src/dev-error.ts","../src/prerender.ts","../src/report.ts","../src/routes.ts","../src/vite.ts"],"sourcesContent":["// An error while the dev server renders a page, shown in Vite's error overlay.\n\nimport { resolve } from 'node:path';\nimport type { ViteDevServer } from 'vite';\nimport type { Location } from './error.ts';\n\n/** The error that Vite's overlay shows. */\nexport interface ErrorPayload {\n message: string;\n stack: string;\n id?: string;\n frame?: string;\n plugin?: string;\n loc?: { file: string; line: number; column: number };\n}\n\n/** The overlay payload of an error, with the file, line and lines around it for compile errors. */\nexport function errorPayload(error: unknown, root: string = process.cwd()): ErrorPayload {\n const value = error instanceof Error ? error : new Error(String(error));\n const located = value as Error & {\n filename?: string;\n location?: Location;\n frame?: string;\n // Vite adds these to errors of plugins, such as a compile error that `ssrLoadModule` throws.\n loc?: { file?: string; line: number; column: number };\n id?: string;\n plugin?: string;\n };\n const payload: ErrorPayload = {\n message: value.message,\n // A compile error has no useful stack: the message names the file and line.\n stack: located.frame ? '' : (value.stack ?? ''),\n };\n if (located.loc && located.frame) {\n const file = located.loc.file ?? located.id ?? '';\n payload.stack = '';\n payload.id = file;\n payload.plugin = located.plugin;\n payload.frame = located.frame;\n payload.loc = { file, line: located.loc.line, column: located.loc.column };\n } else if (located.filename && located.location) {\n const file = resolve(root, located.filename);\n payload.id = file;\n payload.plugin = 'brumate';\n payload.frame = located.frame;\n payload.loc = { file, line: located.location.line, column: located.location.column };\n }\n return payload;\n}\n\n/**\n * A page that shows an error in Vite's error overlay, for a dev server to\n * answer with when a page fails to render. It loads again when a file changes.\n *\n * ```ts\n * } catch (error) {\n * response.statusCode = 500;\n * response.setHeader('content-type', 'text/html');\n * response.end(errorPage(error, vite));\n * }\n * ```\n */\nexport function errorPage(error: unknown, server?: ViteDevServer): string {\n if (server && error instanceof Error) {\n server.ssrFixStacktrace(error);\n }\n const payload = errorPayload(error, server?.config.root);\n server?.config.logger.error(\n payload.loc ? `${payload.message}\\n${payload.frame}` : String((error as Error)?.stack ?? error),\n );\n // `<` is escaped, so the error cannot end the script.\n const json = JSON.stringify(payload).replace(/</g, '\\\\u003c');\n const base = server?.config.base ?? '/';\n return `<!doctype html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n<script type=\"module\" src=\"${base}@vite/client\"></script>\n</head>\n<body>\n<pre id=\"brumate-error\" style=\"white-space: pre-wrap; font: 14px monospace; padding: 16px\"></pre>\n<script type=\"module\">\nimport { createHotContext } from '${base}@vite/client';\nconst error = ${json};\nconst Overlay = customElements.get('vite-error-overlay');\nif (Overlay) {\n document.body.append(new Overlay(error));\n} else {\n document.getElementById('brumate-error').textContent = [error.message, error.frame, error.stack].filter(Boolean).join('\\\\n\\\\n');\n}\n// A component that updates in place, after a fix, loads the page again.\nconst hot = createHotContext('/@brumate/error');\nhot.on('brumate:update', () => location.reload());\nhot.on('vite:beforeUpdate', () => location.reload());\n</script>\n</body>\n</html>\n`;\n}\n","// Writes the pages of a site as static HTML files after the server build.\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nexport interface PrerenderOptions {\n /** The paths to render first. Defaults to `['/']`. */\n paths?: string[];\n /** Follows links to other pages of the site, and renders them too. Defaults to true. */\n crawl?: boolean;\n /** The output directory of the client build, with its manifest, relative to the root. Defaults to `dist/client`. */\n client?: string;\n /** Markup for the head of every page, from the manifest of the client build. */\n head?: (manifest: Record<string, ManifestChunk>) => string;\n}\n\nexport interface ManifestChunk {\n file: string;\n src?: string;\n isEntry?: boolean;\n}\n\ntype Handle = (request: Request, options: object) => Promise<Response | undefined>;\n\n/** The file of a page: `index.html` in a folder of its path. */\nfunction fileOf(pathname: string): string {\n const clean = pathname.replace(/^\\/+|\\/+$/g, '');\n return clean ? `${clean}/index.html` : 'index.html';\n}\n\n/** The paths of the links in a page that stay on the site, without their query and hash. */\nfunction links(html: string, base: string): string[] {\n const result: string[] = [];\n for (const match of html.matchAll(/<a\\b[^>]*\\bhref=\"([^\"]*)\"/g)) {\n const href = match[1]!.replace(/&/g, '&');\n if (!href.startsWith(base) || href.startsWith('//')) {\n continue;\n }\n const pathname = href.split(/[?#]/)[0]!.slice(base.length - 1) || '/';\n if (!/\\.[a-z0-9]+$/i.test(pathname)) {\n result.push(pathname);\n }\n }\n return result;\n}\n\n/**\n * Renders pages with the route handler of the server build, and writes them\n * into the client build. Returns the paths that it wrote.\n */\nexport async function prerender(\n routes: string,\n root: string,\n base: string,\n options: PrerenderOptions,\n): Promise<string[]> {\n const client = path.resolve(root, options.client ?? 'dist/client');\n const manifest = JSON.parse(\n await readFile(path.join(client, '.vite/manifest.json'), 'utf8'),\n ) as Record<string, ManifestChunk>;\n const entry = Object.values(manifest).find((chunk) => chunk.isEntry);\n if (!entry) {\n throw new Error('The client build has no entry. Build the client before the server.');\n }\n const { handle } = (await import(pathToFileURL(routes).href)) as { handle: Handle };\n const document = {\n head: options.head?.(manifest) ?? '',\n scripts: `<script type=\"module\" async src=\"${base}${entry.file}\"></script>`,\n };\n const queue = [...(options.paths ?? ['/'])];\n const seen = new Set<string>(queue);\n const written: string[] = [];\n while (queue.length > 0) {\n const pathname = queue.shift()!;\n // oxlint-disable-next-line no-await-in-loop -- Pages render one by one, and each can add links.\n const response = await handle(new Request(`http://localhost${pathname}`), document);\n if (!response?.headers.get('content-type')?.includes('text/html') || response.status !== 200) {\n continue;\n }\n // oxlint-disable-next-line no-await-in-loop -- Pages render one by one, and each can add links.\n const html = await response.text();\n const file = path.join(client, fileOf(pathname));\n // oxlint-disable-next-line no-await-in-loop -- Pages render one by one, and each can add links.\n await mkdir(path.dirname(file), { recursive: true });\n // oxlint-disable-next-line no-await-in-loop -- Pages render one by one, and each can add links.\n await writeFile(file, html);\n written.push(pathname);\n if (options.crawl !== false) {\n for (const link of links(html, base)) {\n if (!seen.has(link)) {\n seen.add(link);\n queue.push(link);\n }\n }\n }\n }\n // A static host answers a missing path with 404.html: the error file of the root.\n const missing = await handle(new Request('http://localhost/__brumate_not_found__'), document);\n if (missing?.status === 404 && missing.headers.get('content-type')?.includes('text/html')) {\n await writeFile(path.join(client, '404.html'), await missing.text());\n written.push('404');\n }\n return written;\n}\n","// A report of what the client build ships: what every page loads before its\n// first event, the code that events load, and the most that each route can\n// load. A budget fails the build when a size goes over it.\n\nimport { builtin } from './node.ts';\nimport { parse } from './parser.ts';\nimport { resolveRelative } from './project.ts';\nimport type { RouteFiles } from './routes.ts';\n\n/** A chunk of the client build, as the bundler writes it. */\nexport interface ReportChunk {\n fileName: string;\n code: string;\n isEntry: boolean;\n /** Chunks that this chunk imports statically. */\n imports: string[];\n /** The modules in the chunk. */\n moduleIds: string[];\n}\n\n/** Sizes in bytes, after gzip. */\nexport interface Budget {\n /** What every page loads before its first event. */\n loader?: number;\n /** The most that a route can load after its first event, with the core. */\n route?: number;\n}\n\nexport interface BuildReport {\n /** The entry and its imports, which every page loads. */\n loader: number;\n /** The runtime that the first event loads. */\n core: number;\n /** Each component, with the size of its client code, largest first. */\n components: { file: string; bytes: number }[];\n /** Each route path, with the most it can load after its first event, largest first. */\n routes: { path: string; bytes: number; components: number }[];\n /** The sizes that go over the budget, as sentences. */\n overBudget: string[];\n}\n\n/** The size of a chunk after gzip. Outside Node, the size before it. */\nfunction gzipSize(code: string): number {\n const zlib = builtin('node:zlib');\n return zlib ? zlib.gzipSync(code).length : code.length;\n}\n\n/** The chunk and every chunk that it imports statically. */\nfunction withImports(\n name: string,\n chunks: Map<string, ReportChunk>,\n into = new Set<string>(),\n): Set<string> {\n if (!into.has(name) && chunks.has(name)) {\n into.add(name);\n for (const imported of chunks.get(name)!.imports) {\n withImports(imported, chunks, into);\n }\n }\n return into;\n}\n\n/** The files of the components that a `.brm` file imports. */\nfunction componentImports(file: string, source: string): string[] {\n let parsed;\n try {\n parsed = parse(source, { filename: file });\n } catch {\n return [];\n }\n const result: string[] = [];\n for (const script of [parsed.moduleScript, parsed.instanceScript]) {\n for (const statement of script?.program.body ?? []) {\n if (statement.type === 'ImportDeclaration') {\n const target = resolveRelative(statement.source.value, file);\n if (target) {\n result.push(target);\n }\n }\n }\n }\n return result;\n}\n\n/** Each page path, with its page and the layouts around it. */\nfunction routeEntries(\n node: RouteFiles,\n resolve: (file: string) => string,\n path = '',\n layouts: string[] = [],\n): { path: string; files: string[] }[] {\n const around = node.layout ? [...layouts, resolve(node.layout)] : layouts;\n const result = node.page ? [{ path: path || '/', files: [...around, resolve(node.page)] }] : [];\n for (const [segment, folder] of Object.entries(node.static ?? {})) {\n result.push(...routeEntries(folder, resolve, `${path}/${segment}`, around));\n }\n if (node.dynamic) {\n result.push(\n ...routeEntries(node.dynamic.node, resolve, `${path}/[${node.dynamic.name}]`, around),\n );\n }\n if (node.rest) {\n result.push(...routeEntries(node.rest.node, resolve, `${path}/[...${node.rest.name}]`, around));\n }\n return result;\n}\n\nexport interface ReportInput {\n chunks: ReportChunk[];\n /** The source of each `.brm` file, by absolute path. */\n sources: Map<string, string>;\n /** The route files, and the absolute path of a file in them. */\n routes?: { tree: RouteFiles; resolve: (file: string) => string };\n budget?: Budget;\n}\n\n/** Measures the client build. */\nexport function buildReport({ chunks: list, sources, routes, budget }: ReportInput): BuildReport {\n const chunks = new Map(list.map((chunk) => [chunk.fileName, chunk]));\n const sizes = new Map(list.map((chunk) => [chunk.fileName, gzipSize(chunk.code)]));\n const sum = (names: Iterable<string>): number => {\n let total = 0;\n for (const name of names) {\n total += sizes.get(name) ?? 0;\n }\n return total;\n };\n\n const loaderChunks = new Set<string>();\n for (const chunk of list) {\n if (chunk.isEntry) {\n withImports(chunk.fileName, chunks, loaderChunks);\n }\n }\n const coreChunk = list.find((chunk) =>\n chunk.moduleIds.some((id) => /[\\\\/]runtime[\\\\/]client\\.[jt]s$/.test(id)),\n );\n const coreChunks = coreChunk ? withImports(coreChunk.fileName, chunks) : new Set<string>();\n for (const name of loaderChunks) {\n coreChunks.delete(name);\n }\n\n // The chunks of each component: its entry and its parts, with what they import.\n const byFile = new Map<string, Set<string>>();\n for (const chunk of list) {\n for (const id of chunk.moduleIds) {\n const file = /^(.*\\.brm)\\?brumate-client/.exec(id)?.[1];\n if (file) {\n const set = byFile.get(file) ?? new Set<string>();\n withImports(chunk.fileName, chunks, set);\n byFile.set(file, set);\n }\n }\n }\n for (const set of byFile.values()) {\n for (const name of [...loaderChunks, ...coreChunks]) {\n set.delete(name);\n }\n }\n const components = [...byFile]\n .map(([file, names]) => ({ file, bytes: sum(names) }))\n .toSorted((a, b) => b.bytes - a.bytes);\n\n // A route can load the code of its page, its layouts, and the components that they render.\n const reachable = (files: string[]): Set<string> => {\n const seen = new Set<string>();\n const visit = (file: string): void => {\n if (!seen.has(file)) {\n seen.add(file);\n for (const imported of componentImports(file, sources.get(file) ?? '')) {\n visit(imported);\n }\n }\n };\n files.forEach(visit);\n return seen;\n };\n const routeSizes = (routes ? routeEntries(routes.tree, routes.resolve) : [])\n .map(({ path, files }) => {\n const reached = reachable(files);\n const names = new Set(coreChunks);\n for (const file of reached) {\n for (const name of byFile.get(file) ?? []) {\n names.add(name);\n }\n }\n return { path, bytes: sum(names), components: reached.size };\n })\n .toSorted((a, b) => b.bytes - a.bytes);\n\n const loader = sum(loaderChunks);\n const overBudget: string[] = [];\n if (budget?.loader !== undefined && loader > budget.loader) {\n overBudget.push(\n `The loader is ${formatBytes(loader)}, over the budget of ${formatBytes(budget.loader)}.`,\n );\n }\n for (const route of routeSizes) {\n if (budget?.route !== undefined && route.bytes > budget.route) {\n overBudget.push(\n `The route ${route.path} can load ${formatBytes(route.bytes)}, over the budget of ${formatBytes(budget.route)}.`,\n );\n }\n }\n return { loader, core: sum(coreChunks), components, routes: routeSizes, overBudget };\n}\n\nfunction formatBytes(bytes: number): string {\n return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} kB`;\n}\n\n/** The report as text, with paths relative to `root`. */\nexport function formatBuildReport(report: BuildReport, relative: (file: string) => string): string {\n const lines = [\n 'brumate client report (gzip)',\n ` Every page, before its first event: ${formatBytes(report.loader)}`,\n ` The core, on the first event: ${formatBytes(report.core)}`,\n ];\n if (report.routes.length > 0) {\n lines.push(' The most each route loads after its first event, with the core');\n for (const route of report.routes) {\n lines.push(` ${route.path}: ${formatBytes(route.bytes)} (${route.components} components)`);\n }\n }\n if (report.components.length > 0) {\n lines.push(' Components, largest first');\n for (const component of report.components) {\n lines.push(` ${relative(component.file)}: ${formatBytes(component.bytes)}`);\n }\n }\n return lines.join('\\n');\n}\n","// Builds the route tree of `virtual:brumate/routes` from the files of a routes directory.\n\n/** A folder of routes, with the files as paths. The runtime `RouteNode` has loaders instead. */\nexport interface RouteFiles {\n layout?: string;\n page?: string;\n fallback?: string;\n /** `_error.brm`: renders when a route of the folder throws, or when no route matches. */\n error?: string;\n /** `_loading.brm`: shows while a route of the folder streams in. */\n loading?: string;\n /** `_middleware.ts`: runs before the routes of the folder. */\n middleware?: string;\n /** A `.ts` file that answers requests at its path, such as `api/todos.ts`. */\n endpoint?: string;\n static?: Record<string, RouteFiles>;\n dynamic?: { name: string; node: RouteFiles };\n rest?: { name: string; node: RouteFiles };\n slots?: Record<string, RouteFiles>;\n}\n\nconst DYNAMIC = /^\\[([A-Za-z_$][\\w$]*)\\]$/;\nconst REST = /^\\[\\.\\.\\.([A-Za-z_$][\\w$]*)\\]$/;\n\n/** Returns the folder for a path segment, made if missing. */\nfunction child(node: RouteFiles, segment: string): RouteFiles {\n if (segment.startsWith('@')) {\n node.slots ??= {};\n return (node.slots[segment.slice(1)] ??= {});\n }\n const rest = REST.exec(segment);\n if (rest) {\n node.rest ??= { name: rest[1]!, node: {} };\n return node.rest.node;\n }\n const dynamic = DYNAMIC.exec(segment);\n if (dynamic) {\n if (node.dynamic && node.dynamic.name !== dynamic[1]) {\n throw new Error(`Two dynamic segments in one folder: [${node.dynamic.name}] and ${segment}`);\n }\n node.dynamic ??= { name: dynamic[1]!, node: {} };\n return node.dynamic.node;\n }\n node.static ??= {};\n return (node.static[segment] ??= {});\n}\n\n/**\n * Builds the route tree from paths relative to the routes directory, such as\n * `todos/[id].brm`. `_layout.brm`, `_default.brm`, `_error.brm`,\n * `_loading.brm`, `_middleware.ts` and `index.brm` belong to their folder.\n * Other files starting with `_` are not routes. A `.ts` file is an endpoint.\n */\nexport function routeFiles(paths: string[]): RouteFiles {\n const tree: RouteFiles = {};\n for (const file of paths) {\n const typescript = file.endsWith('.ts');\n const segments = file.replace(/\\.(brm|ts)$/, '').split('/');\n const name = segments.pop()!;\n let node = tree;\n for (const segment of segments) {\n node = child(node, segment);\n }\n if (typescript) {\n if (name === '_middleware') {\n node.middleware = file;\n } else if (name === 'index') {\n node.endpoint = file;\n } else if (!name.startsWith('_')) {\n child(node, name).endpoint = file;\n }\n continue;\n }\n if (name === '_error') {\n node.error = file;\n } else if (name === '_loading') {\n node.loading = file;\n } else if (name === '_layout') {\n node.layout = file;\n } else if (name === '_default') {\n node.fallback = file;\n } else if (name === 'index') {\n node.page = file;\n } else if (!name.startsWith('_')) {\n child(node, name).page = file;\n }\n }\n return tree;\n}\n\n/**\n * Writes a route tree as module code, with an import for each file. `rpc`\n * is the URL prefix of server function calls, for forms that post to one.\n */\nexport function routeModule(\n tree: RouteFiles,\n resolve: (file: string) => string,\n rpc = '/_brumate',\n origins: string[] = [],\n /** In development, errors reach the dev server instead of `_error.brm`. */\n dev = false,\n): string {\n // Static imports, because the server registry of server functions imports every file anyway.\n const imports: string[] = [];\n const load = (file: string): string => {\n const name = `m${imports.length}`;\n imports.push(`import * as ${name} from ${JSON.stringify(resolve(file))};`);\n return `() => Promise.resolve(${name})`;\n };\n const write = (node: RouteFiles): string => {\n const fields: string[] = [];\n for (const key of [\n 'layout',\n 'page',\n 'fallback',\n 'error',\n 'loading',\n 'middleware',\n 'endpoint',\n ] as const) {\n const file = node[key];\n if (file) {\n fields.push(`${key}: ${load(file)}`);\n }\n }\n for (const key of ['static', 'slots'] as const) {\n const children = node[key];\n if (children) {\n const entries = Object.entries(children).map(\n ([name, value]) => `${JSON.stringify(name)}: ${write(value)}`,\n );\n fields.push(`${key}: { ${entries.join(', ')} }`);\n }\n }\n for (const key of ['dynamic', 'rest'] as const) {\n const value = node[key];\n if (value) {\n fields.push(`${key}: { name: ${JSON.stringify(value.name)}, node: ${write(value.node)} }`);\n }\n }\n return `{ ${fields.join(', ')} }`;\n };\n const routes = write(tree);\n return [\n \"import { handleRoute } from 'brumate/server';\",\n // Forms without scripts post to their page, which runs the server function.\n \"import { functions } from 'virtual:brumate/server';\",\n ...imports,\n `export const routes = ${routes};`,\n 'export function handle(request, options) {',\n ` return handleRoute(routes, request, { rpc: ${JSON.stringify(rpc)}, origins: ${JSON.stringify(origins)}, functions${dev ? ', dev: true' : ''}, ...options });`,\n '}',\n ].join('\\n');\n}\n\n/** A path that a request can reach, with the names of its params. */\nexport interface RoutePathInfo {\n /** The path as the route files spell it, such as `/todos/[id]`. */\n path: string;\n params: string[];\n}\n\n/** The paths of the pages and endpoints of a tree. Slots render at the paths of their layout. */\nexport function routePaths(tree: RouteFiles): RoutePathInfo[] {\n const result: RoutePathInfo[] = [];\n const visit = (node: RouteFiles, path: string, params: string[]): void => {\n if (node.page || node.endpoint) {\n result.push({ path: path || '/', params });\n }\n for (const [segment, folder] of Object.entries(node.static ?? {})) {\n visit(folder, `${path}/${segment}`, params);\n }\n if (node.dynamic) {\n visit(node.dynamic.node, `${path}/[${node.dynamic.name}]`, [...params, node.dynamic.name]);\n }\n if (node.rest) {\n visit(node.rest.node, `${path}/[...${node.rest.name}]`, [...params, node.rest.name]);\n }\n };\n visit(tree, '', []);\n return result.toSorted((a, b) => a.path.localeCompare(b.path));\n}\n\n/** A declaration file that adds the paths of a tree to `Routes` of `brumate/routes`. */\nexport function routeTypes(tree: RouteFiles): string {\n const lines = routePaths(tree).map(({ path, params }) => {\n const fields = params.map((name) => `${name}: string`).join('; ');\n // Single quotes, as formatters write them, so a formatted project leaves the file as it is.\n const key = `'${path.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`;\n return ` ${key}: {${fields ? ` ${fields} ` : ''}};`;\n });\n return [\n '// Written by the brumate Vite plugin from the route files. Do not edit.',\n // An export makes this a module, so the block below adds to brumate/routes instead of replacing it.\n 'export {};',\n '',\n \"declare module 'brumate/routes' {\",\n ' interface Routes {',\n ...lines,\n ' }',\n '}',\n '',\n ].join('\\n');\n}\n","import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport path from 'node:path';\nimport { isRunnableDevEnvironment, normalizePath, transformWithOxc } from 'vite';\nimport type { EnvironmentModuleNode, Plugin, ViteDevServer } from 'vite';\nimport { compile } from './compile.ts';\nimport { defaultExclude, findFiles, findServerFiles } from './files.ts';\nimport {\n hasUseServer,\n isScriptFile,\n serverExports,\n serverModule,\n serverStubs,\n} from './server-files.ts';\nimport type { CompileResult } from './compile.ts';\nimport { getLocation } from './error.ts';\nimport { functionId, getComponentName, hash } from './plan.ts';\nimport { analyzeProject } from './project.ts';\nimport type { NavigateOptions } from './runtime/loader.ts';\nimport { formatReport, report, scopeLabel } from './inspect.ts';\nimport { instanceScope, slotIndex } from './codegen/scopes.ts';\nimport { isReactiveModule } from './modules.ts';\nimport { forEachNode } from './project.ts';\nimport { SHARED_QUERY, generateShared } from './shared-module.ts';\nimport { toNodeHeaders } from './runtime/cookies.ts';\nimport { errorPayload } from './dev-error.ts';\nimport { prerender } from './prerender.ts';\nimport type { HotUpdate } from './runtime/hot.ts';\nimport type { SourceMap } from './sourcemap.ts';\nimport { buildReport, formatBuildReport } from './report.ts';\nimport type { Budget, ReportChunk } from './report.ts';\nimport type { PrerenderOptions } from './prerender.ts';\nimport { routeFiles, routeModule, routeTypes } from './routes.ts';\nimport type { RouteFiles } from './routes.ts';\n\nexport interface BrumateOptions {\n /** The URL prefix of server function calls. Defaults to `/_brumate`. */\n rpc?: string;\n /**\n * Other origins that may call server functions, such as\n * `https://app.example.com`. Calls from other sites answer 403.\n */\n origins?: string[];\n /** Directories that are not searched for `.brm` files. Defaults to `node_modules`, `dist` and hidden directories. */\n exclude?: (directory: string) => boolean;\n /** The directory of route files, relative to the root. Defaults to `src/routes`. */\n routes?: string;\n /**\n * The declaration file that gives `href` of `brumate/routes` the paths of\n * the routes, relative to the root. The plugin writes it when the routes\n * change. Defaults to `src/brumate-routes.d.ts`. `false` writes none.\n */\n routeTypes?: string | false;\n /**\n * Loads pages without a full page load when a link is clicked or a form\n * posts. Defaults to true. `{ transition: true }` swaps pages inside a\n * view transition.\n */\n navigate?: boolean | NavigateOptions;\n /**\n * Client parts of a component smaller than this many bytes in all become\n * one module, so its first event loads one file. 0 keeps one module per\n * part. Defaults to 2048.\n */\n merge?: number;\n /**\n * Writes the pages as static HTML files after the server build, for a\n * static host. The client build must run first. `true` renders `/` and\n * the pages that its links lead to.\n */\n prerender?: boolean | PrerenderOptions;\n /**\n * Prints what the client build ships: what every page loads before its\n * first event, the core, the most that each route can load, and each\n * component. Sizes are after gzip.\n */\n report?: boolean;\n /** Fails the client build when a size goes over it, in bytes after gzip. */\n budget?: Budget;\n /** Warns about common accessibility mistakes in markup. Defaults to true. */\n a11y?: boolean;\n /**\n * Shows a button that opens the devtools panel, on the dev server only.\n * The panel shows the scopes of the page, a log of events, and the report\n * of each component. Defaults to true.\n */\n devtools?: boolean;\n}\n\n/** `import 'virtual:brumate/start'` in the client entry starts the loader. */\nconst START = 'virtual:brumate/start';\n/** Exports `load(id)`, which imports the client module of a component. */\nconst MANIFEST = 'virtual:brumate/manifest';\n/** Exports `functions` and `handle(request)` for server function calls. */\nconst SERVER = 'virtual:brumate/server';\n/** Exports `routes` and `handle(request, options)` for the files in the routes directory. */\nconst ROUTES = 'virtual:brumate/routes';\n/** The entry of the server build that prerendering renders with. */\nconst PRERENDER_ENTRY = 'brumate-routes';\n\nconst CLIENT_QUERY = '?brumate-client';\nconst RENDER_QUERY = '?brumate-render';\nconst SERVER_QUERY = '?brumate-server';\n/** Exports `mount` from `brumate/testing`, with the loader of this project's client modules. */\nconst TESTING = 'virtual:brumate/testing';\n/** The dev server answers the devtools panel about a component at this path. */\nconst INSPECT = '/__brumate/inspect';\n\n/** Reads a request body as bytes, so files in form data stay intact. */\nasync function readBody(request: IncomingMessage): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of request) {\n chunks.push(chunk as Buffer);\n }\n return Buffer.concat(chunks);\n}\n\n/** What decides whether an edit of a component can update a page without a reload. */\ninterface Shape {\n /**\n * The parts of the output that a page in the browser depends on: the\n * client entry with its update table, the slots of each scope, and the\n * markup. When they stay the same, the page keeps working with new code.\n */\n layout: string;\n css: string;\n /** The code of the client parts, which the page loads again when it changes. */\n code: string;\n /** The names of the slots of each scope, by its ID in the component. */\n slots: Record<number, string[]>;\n /** The names of the signals, whose values stay when the markup changes. */\n signals: string[];\n}\n\n/** Removes the scripts, styles and event handlers of a file, which leaves the markup of its page. */\nfunction markupOf(result: CompileResult): string {\n const { file } = result;\n const ranges: { start: number; end: number }[] = [\n ...(file.instanceScript ? [file.instanceScript] : []),\n ...(file.moduleScript ? [file.moduleScript] : []),\n ...file.styles,\n ];\n forEachNode(file.children, (node) => {\n if ('body' in node && node.body && 'script' in node.body && node.body.script) {\n ranges.push(node.body.script);\n }\n // The code of an event handler is not in the page, which only names the handler.\n if ('attributes' in node) {\n for (const attribute of node.attributes) {\n if (attribute.kind === 'event') {\n ranges.push(attribute.handler);\n }\n }\n }\n });\n let markup = '';\n let position = 0;\n for (const range of ranges.toSorted((a, b) => a.start - b.start)) {\n markup += file.source.slice(position, range.start);\n position = Math.max(position, range.end);\n }\n return markup + file.source.slice(position);\n}\n\nfunction shapeOf(result: CompileResult): Shape {\n const slots = [...result.plan.scopes.values()].map(\n (layout) => `${layout.scope.id}:${layout.slots.map((slot) => slot.name).join(',')}`,\n );\n const layouts = [...result.plan.scopes.values()];\n return {\n layout: JSON.stringify([result.client, slots, markupOf(result)]),\n css: result.css,\n code: JSON.stringify(result.parts),\n slots: Object.fromEntries(\n layouts.map((layout) => [layout.scope.id, layout.slots.map((slot) => slot.name)]),\n ),\n signals: layouts.flatMap((layout) =>\n layout.slots.filter((slot) => slot.kind === 'signal').map((slot) => slot.name),\n ),\n };\n}\n\n/** The functions of a file of server functions, by their IDs, for a module of it. */\nfunction fileFunctions(\n id: string,\n module: Record<string, unknown>,\n hideNames: boolean,\n): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(module)\n .filter(([, value]) => typeof value === 'function')\n .map(([name, value]) => [functionId(id, name, hideNames), value]),\n );\n}\n\n/** The Vite plugin for `.brm` files. */\nexport default function brumate(options: BrumateOptions = {}): Plugin {\n const rpc = options.rpc ?? '/_brumate';\n const exclude = options.exclude ?? defaultExclude;\n let root = process.cwd();\n let outDir = '';\n let base = '/';\n let isSsrBuild = false;\n let isServe = false;\n /** Component IDs to absolute file paths. */\n const files = new Map<string, string>();\n const compiled = new Map<string, { source: string; result: CompileResult }>();\n /** Files that a component depends on, such as SCSS that it imports or modules that it calls into, with the components. */\n const dependents = new Map<string, Set<string>>();\n /** What the browser has of each component, from its last compile. See `shapeOf`. */\n const shapes = new Map<string, Shape>();\n /** The props that parents can change, by absolute file path. */\n let liveProps = new Map<string, Set<string>>();\n\n // The ID is computed from the path relative to the root, so it is the same on every machine.\n const relative = (file: string): string => normalizePath(path.relative(root, file));\n /** Files of server functions: scripts whose first statement is `'use server'`, by ID. */\n const serverFiles = new Map<string, string>();\n /** The ID of a function that a component imports from a 'use server' file, by a relative path. */\n const serverImport = (importer: string, specifier: string, name: string): string | undefined => {\n if (!specifier.startsWith('.')) {\n return undefined;\n }\n const stem = path.resolve(path.dirname(importer), specifier);\n const found = [\n stem,\n ...['.ts', '.tsx', '.js', '.mjs'].map((extension) => stem + extension),\n ].find(\n (candidate) =>\n isScriptFile(candidate) &&\n existsSync(candidate) &&\n hasUseServer(readFileSync(candidate, 'utf8')),\n );\n return found && functionId(serverFileId(normalizePath(found)), name, !isServe);\n };\n\n const serverFileId = (file: string): string =>\n `${path.basename(file).replace(/\\.[^.]+$/, '')}_${hash(relative(file))}`;\n const componentId = (file: string): string => {\n const filename = relative(file);\n return `${getComponentName(filename)}_${hash(filename)}`;\n };\n\n const scan = async (): Promise<void> => {\n files.clear();\n for (const file of await findFiles(root, exclude)) {\n files.set(componentId(file), file);\n }\n serverFiles.clear();\n for (const file of await findServerFiles(root, exclude)) {\n serverFiles.set(serverFileId(file), file);\n }\n await analyze();\n };\n\n // Props are analyzed across the project, so a change to one file can change the output of others.\n const analyze = async (): Promise<void> => {\n const list = [...files.values()];\n const contents = await Promise.all(list.map((file) => readFile(file, 'utf8')));\n const sources = new Map(list.map((file, index) => [file, contents[index]!]));\n liveProps = analyzeProject(sources);\n compiled.clear();\n };\n\n // The entry, the parts and the render module of a file come from one compile.\n const compileFile = async (file: string): Promise<{ source: string; result: CompileResult }> => {\n const source = await readFile(file, 'utf8');\n let cached = compiled.get(file);\n if (cached?.source !== source) {\n cached = {\n source,\n result: compile(source, {\n filename: relative(file),\n liveProps: liveProps.get(file),\n path: file,\n merge: options.merge ?? 2048,\n a11y: options.a11y,\n // A build does not show the names of server functions in their IDs.\n hideNames: !isServe,\n serverImport: (specifier, name) => serverImport(file, specifier, name),\n }),\n };\n compiled.set(file, cached);\n shapes.set(file, shapeOf(cached.result));\n }\n return cached;\n };\n\n const manifest = (): string => {\n const entries = [...files].map(\n ([id, file]) =>\n ` ${JSON.stringify(id)}: () => import(${JSON.stringify(`${file}${CLIENT_QUERY}`)}),`,\n );\n return [\n 'const modules = {',\n ...entries,\n '};',\n 'export function load(id) {',\n ' const module = modules[id];',\n ' if (!module) {',\n ' throw new Error(`Unknown component \"${id}\"`);',\n ' }',\n ' return module();',\n '}',\n ].join('\\n');\n };\n\n const serverRegistry = (): string => {\n const imports = [...files.values()].map(\n (file, index) => `import * as m${index} from ${JSON.stringify(file)};`,\n );\n const spreads = [...files.values()].map((_, index) => ` ...m${index}.rpc,`);\n // Each exported function of a file of server functions, under the ID that its stub calls.\n const fileImports = [...serverFiles.values()].map(\n (file, index) => `import * as f${index} from ${JSON.stringify(file)};`,\n );\n const fileSpreads = [...serverFiles.entries()].map(([id, file], index) => {\n // The IDs are written here, so a build can hash the names of the functions.\n const names = serverExports(readFileSync(file, 'utf8'), file);\n return names\n .map(\n (name) =>\n ` ${JSON.stringify(functionId(id, name, !isServe))}: f${index}[${JSON.stringify(name)}],`,\n )\n .join('\\n');\n });\n return [\n \"import { handleRequest } from 'brumate/server';\",\n ...imports,\n ...fileImports,\n 'export const functions = {',\n ...spreads,\n ...fileSpreads,\n '};',\n 'export function handle(request) {',\n ` return handleRequest(functions, request, ${JSON.stringify(rpc)}, { origins: ${JSON.stringify(options.origins ?? [])} });`,\n '}',\n ].join('\\n');\n };\n\n const routesDirectory = (): string =>\n normalizePath(path.resolve(root, options.routes ?? 'src/routes'));\n\n /** The route files, from the `.brm` files found and the `.ts` files of the directory. */\n const currentRoutes = (): RouteFiles => {\n const directory = routesDirectory();\n const paths = [...files.values()]\n .filter((file) => file.startsWith(`${directory}/`))\n .map((file) => file.slice(directory.length + 1));\n // Endpoints and middleware are `.ts` files.\n if (existsSync(directory)) {\n for (const entry of readdirSync(directory, { recursive: true, encoding: 'utf8' })) {\n const file = normalizePath(entry);\n if (file.endsWith('.ts') && !file.endsWith('.d.ts')) {\n paths.push(file);\n }\n }\n }\n return routeFiles(paths);\n };\n\n const routeTree = (): string =>\n routeModule(\n currentRoutes(),\n (file) => `${routesDirectory()}/${file}`,\n rpc,\n options.origins,\n isServe,\n );\n\n /** Writes the paths of the routes as types for `href`, when they changed. */\n const writeRouteTypes = (): void => {\n if (options.routeTypes === false || !existsSync(routesDirectory())) {\n return;\n }\n const file = path.resolve(root, options.routeTypes ?? 'src/brumate-routes.d.ts');\n const text = routeTypes(currentRoutes());\n if (!existsSync(file) || readFileSync(file, 'utf8') !== text) {\n writeFileSync(file, text);\n }\n };\n\n /** What the devtools panel shows about a component: its name, its scopes and its report. */\n const inspectComponent = async (id: string): Promise<object | undefined> => {\n const file = files.get(id);\n if (!file) {\n return undefined;\n }\n const { source, result } = await compileFile(file);\n const { plan } = result;\n const scopes: Record<number, { label: string; slots: string[] }> = {};\n for (const layout of plan.scopes.values()) {\n scopes[layout.scope.id] = {\n label: scopeLabel(result.file.source, layout.scope),\n slots: layout.slots.map((slot) => slot.name),\n };\n }\n // The nodes that can change in the browser, with the slot of each value, so the panel\n // can mark a node when its slot is written.\n const nodes = plan.graph.nodes.filter((node) => plan.graph.live.has(node));\n const indexes = new Map(nodes.map((node, index) => [node, index]));\n const graph = {\n nodes: nodes.map((node) => {\n if (node.kind === 'source' || node.kind === 'memo') {\n return {\n kind: node.kind === 'memo' ? 'memo' : node.declaration.kind,\n label: node.declaration.name,\n scope: instanceScope(plan, node.declaration.scope).id,\n slot: slotIndex(plan, node.declaration),\n };\n }\n // Markup has no name, so its place in the file tells nodes apart, such as `insert 9:42`.\n // Code that a module function gave the component has no place in the component's file.\n const at = result.locate(node.site.range.start);\n const where = at.file === undefined ? getLocation(source, at.offset) : undefined;\n return {\n kind: node.kind,\n label: where ? `${node.site.label} ${where.line}:${where.column}` : node.site.label,\n scope: instanceScope(plan, node.site.scope).id,\n };\n }),\n edges: plan.graph.edges\n .filter((edge) => indexes.has(edge.from) && indexes.has(edge.to))\n .map((edge) => [indexes.get(edge.from)!, indexes.get(edge.to)!]),\n };\n const text = formatReport(report(source, result, liveProps.get(file)));\n return { name: plan.name, file: relative(file), scopes, graph, text };\n };\n\n const handleDevRPC = async (\n server: ViteDevServer,\n request: IncomingMessage,\n response: ServerResponse,\n ): Promise<void> => {\n const id = decodeURIComponent((request.url ?? '').slice(rpc.length + 1).split('?')[0]!);\n const owner = id.split('#')[0]!;\n const file = files.get(owner) ?? serverFiles.get(owner);\n if (!file) {\n response.statusCode = 404;\n response.end(`Unknown server function \"${id}\"`);\n return;\n }\n try {\n const module = await server.ssrLoadModule(file);\n const { handleRequest } = await server.ssrLoadModule('brumate/server');\n // The same path as production, so server functions can read the request.\n const webRequest = new Request(new URL(request.url ?? '/', 'http://localhost'), {\n method: 'POST',\n headers: Object.entries(request.headers).flatMap(([name, value]) =>\n value === undefined ? [] : [[name, String(value)] as [string, string]],\n ),\n body: new Uint8Array(await readBody(request)),\n });\n const functions = serverFiles.has(owner)\n ? fileFunctions(owner, module, !isServe)\n : (module.rpc ?? {});\n const answer: Response = await handleRequest(functions, webRequest, rpc, {\n origins: options.origins,\n });\n response.statusCode = answer.status;\n // Each cookie stays apart, as `forEach` would set only the last one.\n for (const [name, value] of Object.entries(toNodeHeaders(answer.headers))) {\n response.setHeader(name, value);\n }\n response.end(await answer.text());\n } catch (error) {\n server.config.logger.error(String((error as Error).stack ?? error));\n response.statusCode = 500;\n response.end(String(error));\n }\n };\n\n /** Updates the page in the browser after a change to a component, or reloads it. */\n async function updateClient(\n file: string,\n server: ViteDevServer,\n timestamp: number,\n ): Promise<[] | undefined> {\n const normalized = normalizePath(file);\n const targets = file.endsWith('.brm') ? [normalized] : [...(dependents.get(normalized) ?? [])];\n if (targets.length === 0) {\n return undefined;\n }\n // A resumed page cannot run a component again. When an edit keeps the markup, the slots\n // and the update table of each changed component, the page keeps its state: new styles\n // replace the old ones, and the next event loads the new code. When the markup changes,\n // the page renders again, and the signals of the component keep their values. A file\n // that does not compile reloads the page, which shows the error.\n const invalidate = (): void => {\n for (const module of server.moduleGraph.idToModuleMap.values()) {\n const id = module.id ?? '';\n if (\n id.includes('.brm') ||\n id === `\\0${MANIFEST}` ||\n id === `\\0${SERVER}` ||\n id === `\\0${ROUTES}`\n ) {\n server.moduleGraph.invalidateModule(module);\n }\n }\n };\n const reload = (): [] => {\n invalidate();\n server.ws.send({ type: 'full-reload' });\n return [];\n };\n await analyze();\n const updates: HotUpdate[] = [];\n for (const target of targets) {\n const before = shapes.get(target);\n let after: Shape;\n try {\n // oxlint-disable-next-line no-await-in-loop -- The first component that cannot update in place reloads the page.\n after = shapeOf((await compileFile(target)).result);\n } catch {\n // The error shows when the page reloads and the module compiles.\n return reload();\n }\n if (!before) {\n return reload();\n }\n const remount = before.layout !== after.layout;\n const id = componentId(target);\n const modules = [\n ...(server.moduleGraph.getModulesByFile(target) ?? []),\n // The shared code of a module of reactive logic that changed.\n ...(target === normalized ? [] : (server.moduleGraph.getModulesByFile(normalized) ?? [])),\n ];\n for (const module of modules) {\n server.moduleGraph.invalidateModule(module, new Set(), timestamp, true);\n }\n const entry = [...(server.moduleGraph.getModulesByFile(target) ?? [])].find((module) =>\n module.id?.endsWith(CLIENT_QUERY),\n );\n updates.push({\n id,\n css: before.css === after.css ? undefined : after.css,\n url: before.code === after.code && !remount ? undefined : entry?.url,\n remount: remount\n ? {\n before: before.slots,\n after: after.slots,\n signals: after.signals.filter((name) => before.signals.includes(name)),\n }\n : undefined,\n });\n }\n if (updates.some((update) => update.remount)) {\n // The server renders the page again with the new markup.\n invalidate();\n }\n server.ws.send({ type: 'custom', event: 'brumate:update', data: { updates, timestamp } });\n return [];\n }\n\n return {\n name: 'brumate',\n enforce: 'pre',\n\n config(config, env) {\n // The server build gets the route handler as an entry of its own, to render the pages with.\n if (!options.prerender || !env.isSsrBuild) {\n return undefined;\n }\n // `--ssr <file>` names the entry, and wins over the input of the config, which can be the client's.\n const ssr = config.build?.ssr;\n const input = typeof ssr === 'string' ? ssr : config.build?.rolldownOptions?.input;\n const entries =\n typeof input === 'string'\n ? { [path.basename(input).replace(/\\.[^.]+$/, '')]: input }\n : Array.isArray(input)\n ? Object.fromEntries(\n input.map((item) => [path.basename(item).replace(/\\.[^.]+$/, ''), item]),\n )\n : { ...(input as Record<string, string> | undefined) };\n return {\n build: { ssr: true, rolldownOptions: { input: { ...entries, [PRERENDER_ENTRY]: ROUTES } } },\n };\n },\n\n configResolved(config) {\n root = config.root;\n isServe = config.command === 'serve';\n outDir = path.resolve(config.root, config.build.outDir);\n base = config.base;\n isSsrBuild = Boolean(config.build.ssr);\n },\n\n async generateBundle(_output, bundle) {\n if (isSsrBuild || (!options.report && !options.budget)) {\n return;\n }\n const chunks: ReportChunk[] = [];\n for (const item of Object.values(bundle)) {\n if (item.type === 'chunk') {\n chunks.push({\n fileName: item.fileName,\n code: item.code,\n isEntry: item.isEntry,\n imports: item.imports,\n moduleIds: item.moduleIds,\n });\n }\n }\n const list = [...files.values()];\n const contents = await Promise.all(list.map((file) => readFile(file, 'utf8')));\n const measured = buildReport({\n chunks,\n sources: new Map(list.map((file, index) => [file, contents[index]!])),\n routes: existsSync(routesDirectory())\n ? { tree: currentRoutes(), resolve: (file) => `${routesDirectory()}/${file}` }\n : undefined,\n budget: options.budget,\n });\n if (options.report) {\n this.info(`\\n${formatBuildReport(measured, relative)}`);\n }\n if (measured.overBudget.length > 0) {\n this.error(measured.overBudget.join('\\n'));\n }\n },\n\n async writeBundle(_output, bundle) {\n if (!options.prerender || !isSsrBuild) {\n return;\n }\n const chunk = Object.values(bundle).find(\n (item) => item.type === 'chunk' && item.isEntry && item.name === PRERENDER_ENTRY,\n );\n if (!chunk) {\n return;\n }\n const settings = options.prerender === true ? {} : options.prerender;\n const written = await prerender(path.join(outDir, chunk.fileName), root, base, settings);\n this.info(`Prerendered ${written.length} pages`);\n },\n\n async buildStart() {\n await scan();\n writeRouteTypes();\n },\n\n resolveId(id) {\n if (id === START || id === MANIFEST || id === SERVER || id === ROUTES || id === TESTING) {\n return `\\0${id}`;\n }\n return undefined;\n },\n\n async load(id, loadOptions) {\n // The browser code of the functions of a module of reactive logic, shared by every call.\n if (id.endsWith(SHARED_QUERY)) {\n const module = id.slice(0, -SHARED_QUERY.length);\n this.addWatchFile(module);\n const { code, map } = generateShared({\n path: module,\n source: await readFile(module, 'utf8'),\n });\n return { code, map: { ...map, sources: [module] } };\n }\n if (id === `\\0${START}`) {\n return [\n \"import { start } from 'brumate/loader';\",\n `import { load } from ${JSON.stringify(MANIFEST)};`,\n // On the dev server, an edit of a component can update the page without a reload.\n ...(isServe\n ? [\n \"import { hotLoad } from 'brumate/hot';\",\n `start({ load: hotLoad(import.meta.hot, load), rpc: ${JSON.stringify(rpc)}, navigate: ${JSON.stringify(options.navigate ?? true)} });`,\n ]\n : [\n `start({ load, rpc: ${JSON.stringify(rpc)}, navigate: ${JSON.stringify(options.navigate ?? true)} });`,\n ]),\n // The devtools listen to the core before it starts. Only the dev server has them.\n ...(isServe && options.devtools !== false\n ? [\n `import('brumate/devtools').then((m) => m.installDevtools(${JSON.stringify(INSPECT)}, ${JSON.stringify(rpc)}));`,\n ]\n : []),\n ].join('\\n');\n }\n if (id === `\\0${MANIFEST}`) {\n return manifest();\n }\n if (id === `\\0${SERVER}`) {\n return serverRegistry();\n }\n if (id === `\\0${ROUTES}`) {\n return routeTree();\n }\n if (id === `\\0${TESTING}`) {\n return [\n \"import { createMount } from 'brumate/testing';\",\n `import { load } from ${JSON.stringify(MANIFEST)};`,\n `export const mount = createMount({ load, rpc: ${JSON.stringify(rpc)} });`,\n ].join('\\n');\n }\n const [file, query] = id.split('?');\n if (!file?.endsWith('.brm')) {\n return undefined;\n }\n // Vite can add its own parameters, such as `import`.\n const params = new URLSearchParams(query);\n const isRender = params.has(RENDER_QUERY.slice(1));\n // A test in a browser environment imports the server version of a component with this query.\n const isServer = params.has(SERVER_QUERY.slice(1));\n const isClient = !isServer && (params.has(CLIENT_QUERY.slice(1)) || !loadOptions?.ssr);\n let output: Awaited<ReturnType<typeof compileFile>>;\n try {\n output = await compileFile(file);\n } catch (error) {\n // The overlay shows the file, the line and the lines around it.\n const { message, frame, loc } = errorPayload(error, root);\n this.error({ message, frame, loc, id: file });\n }\n const { source, result } = output;\n // A stylesheet that the component imports, or a module of reactive logic that it calls into,\n // changes the output of the component.\n for (const dependency of [...result.plan.styles.dependencies, ...result.modules]) {\n const normalized = normalizePath(dependency);\n this.addWatchFile(normalized);\n if (!dependents.has(normalized)) {\n dependents.set(normalized, new Set());\n }\n dependents.get(normalized)!.add(file);\n }\n for (const warning of isClient && !params.has('part') ? result.warnings : []) {\n const { line, column } = getLocation(source, warning.range.start);\n this.warn(`${warning.message} (${relative(file)}:${line}:${column})`);\n }\n const part = params.get('part');\n let code: string;\n let map: SourceMap | undefined;\n if (isRender) {\n code = result.render;\n map = result.maps.render;\n } else if (part) {\n code = result.parts[part] ?? '';\n map = result.maps.parts[part];\n } else if (isServer) {\n // The components that it renders are server versions too. Only import lines change, which have no mappings.\n code = result.server.replace(/(from\\s+(['\"])[^'\"]+\\.brm)\\2/g, `$1${SERVER_QUERY}$2`);\n map = result.maps.server;\n } else {\n code = isClient ? result.client : result.server;\n map = isClient ? result.maps.client : result.maps.server;\n }\n // The map points at the file by its path, so the browser shows it under its own name. Code\n // that came from modules of reactive logic points at them, by their paths too.\n // `transform` below removes the types, and Vite chains the two maps.\n return {\n code,\n map: map && {\n ...map,\n sources: map.sources.map((name, index) => (index === 0 ? file : name)),\n },\n };\n },\n\n async transform(code, id, transformOptions) {\n const [file] = id.split('?');\n // A file of server functions: the browser gets stubs that call the server instead.\n if (file && isScriptFile(file) && hasUseServer(code)) {\n try {\n const fileId = serverFileId(normalizePath(file));\n const stubs = serverStubs(code, file, fileId, !isServe);\n // The server runs the file, with calls while a page renders sharing their results.\n return transformOptions?.ssr\n ? { code: serverModule(code, file, fileId), map: null }\n : { code: stubs, map: null };\n } catch (error) {\n this.error((error as Error).message);\n }\n }\n // The shared module of a module of reactive logic is TypeScript too, under a query\n // that Vite does not strip types for.\n const shared = isReactiveModule(file ?? '') && id.endsWith(SHARED_QUERY);\n if (!file?.endsWith('.brm') && !shared) {\n return undefined;\n }\n const result = await transformWithOxc(code, `${file}.ts`, { lang: 'ts', sourcemap: true });\n return { code: result.code, map: result.map };\n },\n\n configureServer(server) {\n server.watcher.on('all', (event, file) => {\n // A stylesheet that a component imports compiles into that component.\n for (const importer of dependents.get(normalizePath(file)) ?? []) {\n compiled.delete(importer);\n for (const module of server.moduleGraph.getModulesByFile(importer) ?? []) {\n server.moduleGraph.invalidateModule(module);\n }\n }\n // A new or removed endpoint or middleware changes the routes.\n if (\n file.endsWith('.ts') &&\n normalizePath(file).startsWith(`${routesDirectory()}/`) &&\n (event === 'add' || event === 'unlink')\n ) {\n for (const module of server.moduleGraph.idToModuleMap.values()) {\n if (module.id === `\\0${ROUTES}`) {\n server.moduleGraph.invalidateModule(module);\n }\n }\n writeRouteTypes();\n }\n // A file that becomes, or stops being, a file of server functions changes the registry.\n if (isScriptFile(file)) {\n const normalized = normalizePath(file);\n const id = serverFileId(normalized);\n const before = serverFiles.has(id);\n const after =\n event !== 'unlink' && existsSync(file) && hasUseServer(readFileSync(file, 'utf8'));\n if (after) {\n serverFiles.set(id, normalized);\n } else {\n serverFiles.delete(id);\n }\n if (before !== after) {\n for (const module of server.moduleGraph.idToModuleMap.values()) {\n if (module.id === `\\0${SERVER}` || module.id === `\\0${ROUTES}`) {\n server.moduleGraph.invalidateModule(module);\n }\n }\n }\n }\n // A changed component is handled by `handleHotUpdate`, which updates the page in place when it can.\n if (!file.endsWith('.brm') || event === 'change') {\n return;\n }\n void scan()\n .then(writeRouteTypes)\n .then(() => {\n for (const module of server.moduleGraph.idToModuleMap.values()) {\n const id = module.id ?? '';\n if (\n id.includes('.brm') ||\n id === `\\0${MANIFEST}` ||\n id === `\\0${SERVER}` ||\n id === `\\0${ROUTES}`\n ) {\n server.moduleGraph.invalidateModule(module);\n }\n }\n });\n });\n server.middlewares.use((request, response, next) => {\n // When the server code runs in Vite, the plugin answers calls with it. A framework that\n // runs it elsewhere, such as Nitro in a worker, answers them in its own server entry.\n const ssr = server.environments.ssr;\n if (\n request.method === 'POST' &&\n request.url?.startsWith(`${rpc}/`) &&\n ssr &&\n isRunnableDevEnvironment(ssr)\n ) {\n void handleDevRPC(server, request, response);\n return;\n }\n if (request.method === 'GET' && request.url?.startsWith(`${INSPECT}/`)) {\n void inspectComponent(decodeURIComponent(request.url.slice(INSPECT.length + 1)))\n .then((info) => {\n response.statusCode = info ? 200 : 404;\n response.setHeader('content-type', 'application/json');\n response.end(JSON.stringify(info ?? { error: 'Unknown component' }));\n })\n .catch(next);\n return;\n }\n next();\n });\n },\n\n // A server environment that runs apart from Vite, such as Nitro's worker, keeps the code\n // of components it loaded. A change to a component or to a file that one reads, such as\n // a stylesheet, reloads its server code, so the next render uses the new code.\n async hotUpdate({ file, server, timestamp }) {\n const environment = this.environment;\n if (environment.config.consumer === 'client') {\n return updateClient(file, server, timestamp);\n }\n const normalized = normalizePath(file);\n if (!file.endsWith('.brm') && !dependents.has(normalized)) {\n return undefined;\n }\n const invalidated = new Set<EnvironmentModuleNode>();\n for (const module of environment.moduleGraph.idToModuleMap.values()) {\n const id = module.id ?? '';\n if (id.includes('.brm') || id.startsWith('\\0virtual:brumate')) {\n environment.moduleGraph.invalidateModule(module, invalidated, timestamp, true);\n }\n }\n environment.hot.send({ type: 'full-reload' });\n return [];\n },\n };\n}\nexport { errorPage } from './dev-error.ts';\nexport type { ManifestChunk, PrerenderOptions } from './prerender.ts';\nexport type { Budget, BuildReport } from './report.ts';\n"],"mappings":";;;;;;;;;;AAiBA,SAAgB,aAAa,OAAgB,OAAe,QAAQ,IAAI,GAAiB;CACvF,MAAM,QAAQ,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;CACtE,MAAM,UAAU;CAShB,MAAM,UAAwB;EAC5B,SAAS,MAAM;EAEf,OAAO,QAAQ,QAAQ,KAAM,MAAM,SAAS;CAC9C;CACA,IAAI,QAAQ,OAAO,QAAQ,OAAO;EAChC,MAAM,OAAO,QAAQ,IAAI,QAAQ,QAAQ,M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GAEF,MAAM,8BAAc,IAAI,IAA2B;GACnD,KAAK,MAAM,UAAU,YAAY,YAAY,cAAc,OAAO,GAAG;IACnE,MAAM,KAAK,OAAO,MAAM;IACxB,IAAI,GAAG,SAAS,MAAM,KAAK,GAAG,WAAW,mBAAmB,GAC1D,YAAY,YAAY,iBAAiB,QAAQ,aAAa,WAAW,IAAI;GAEjF;GACA,YAAY,IAAI,KAAK,EAAE,MAAM,cAAc,CAAC;GAC5C,OAAO,CAAC;EACV;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"vite.js","names":[],"sources":["../src/packages.ts","../src/dev-error.ts","../src/prerender.ts","../src/report.ts","../src/routes.ts","../src/vite.ts"],"sourcesContent":["// Packages of components. A dependency of the app whose package.json has a\n// `brumate` field ships `.brm` files, `.brm.ts` modules and `'use server'`\n// files as source, and the plugin of the app compiles them with its own files.\n\nimport { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';\nimport path from 'node:path';\n\n/** A dependency of the app that ships `.brm` files. */\nexport interface BrumatePackage {\n /** The name of the package, such as `@acme/ui`. */\n name: string;\n version: string;\n /** The real path of the directory of the package, with forward slashes. */\n root: string;\n /** The directories to search for files, as absolute paths with forward slashes. */\n directories: string[];\n /**\n * The prefix of the names of its files, which their IDs come from: the\n * name of the package, and its version when the app has two versions.\n */\n prefix: string;\n /** True when the package is not inside `node_modules`, such as a workspace package. */\n linked: boolean;\n}\n\ninterface PackageJson {\n name?: string;\n version?: string;\n brumate?: unknown;\n exports?: unknown;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n optionalDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n}\n\nconst toPosix = (file: string): string => file.split(path.sep).join('/');\n\nfunction readJson(file: string): PackageJson | undefined {\n try {\n return JSON.parse(readFileSync(file, 'utf8')) as PackageJson;\n } catch {\n return undefined;\n }\n}\n\n/** The real directory of a package that code in `from` can import, or undefined. */\nexport function findPackageDirectory(name: string, from: string): string | undefined {\n for (let directory = from; ; directory = path.dirname(directory)) {\n const candidate = path.join(directory, 'node_modules', name);\n if (existsSync(path.join(candidate, 'package.json'))) {\n return toPosix(realpathSync(candidate));\n }\n if (path.dirname(directory) === directory) {\n return undefined;\n }\n }\n}\n\n/** The directory of the nearest package.json at or above a directory. */\nfunction packageRoot(directory: string): string | undefined {\n for (let current = directory; ; current = path.dirname(current)) {\n if (existsSync(path.join(current, 'package.json'))) {\n return current;\n }\n if (path.dirname(current) === current) {\n return undefined;\n }\n }\n}\n\n/** The version of the `brumate` field that this version of brumate reads. */\nexport const PACKAGE_FORMAT = 1;\n\n/** The directories that the `brumate` field names, or undefined when the package does not opt in. */\nfunction directoriesOf(root: string, field: unknown, name: string): string[] | undefined {\n if (field === true) {\n return [root];\n }\n if (typeof field === 'object' && field !== null) {\n const { dir, version = PACKAGE_FORMAT } = field as {\n dir?: string | string[];\n version?: number;\n };\n if (version !== PACKAGE_FORMAT) {\n throw new Error(\n `The package ${name} has \"brumate\": { \"version\": ${version} }, but this version of brumate reads version ${PACKAGE_FORMAT}. Install a version of ${name} or of brumate that matches.`,\n );\n }\n if (dir === undefined) {\n return [root];\n }\n return (Array.isArray(dir) ? dir : [dir]).map((item) => toPosix(path.resolve(root, item)));\n }\n return undefined;\n}\n\n/**\n * Finds the dependencies of the app at `root` that ship `.brm` files, and\n * theirs. The app's dependencies come from its package.json: `dependencies`,\n * `devDependencies`, `optionalDependencies` and `peerDependencies`. A package\n * opts in with `\"brumate\": true`, or `\"brumate\": { \"dir\": \"src\" }` to search\n * only that directory. Symbolic links, such as those of pnpm, resolve to the\n * real directory.\n */\nexport function findPackages(root: string): BrumatePackage[] {\n const app = packageRoot(path.resolve(root));\n if (!app) {\n return [];\n }\n const found = new Map<string, Omit<BrumatePackage, 'prefix'>>();\n const visit = (directory: string, json: PackageJson, own: boolean): void => {\n const names = new Set([\n ...Object.keys(json.dependencies ?? {}),\n ...Object.keys(json.optionalDependencies ?? {}),\n ...Object.keys(json.peerDependencies ?? {}),\n // The dev dependencies of a package are its own tools, not part of what it ships.\n ...(own ? Object.keys(json.devDependencies ?? {}) : []),\n ]);\n for (const name of [...names].toSorted()) {\n const real = findPackageDirectory(name, directory);\n if (!real || found.has(real)) {\n continue;\n }\n const dependency = readJson(`${real}/package.json`);\n const directories = dependency && directoriesOf(real, dependency.brumate, name);\n if (!dependency || !directories) {\n continue;\n }\n found.set(real, {\n name: dependency.name ?? name,\n version: dependency.version ?? '0.0.0',\n root: real,\n directories,\n linked: !real.includes('/node_modules/'),\n });\n visit(real, dependency, false);\n }\n };\n visit(app, readJson(path.join(app, 'package.json')) ?? {}, true);\n const list = [...found.values()];\n // Two versions of one package get IDs apart. Copies of one version share theirs, as their files are the same.\n const versions = new Map<string, Set<string>>();\n for (const item of list) {\n versions.set(item.name, (versions.get(item.name) ?? new Set()).add(item.version));\n }\n return list.map((item): BrumatePackage =>\n Object.assign(item, {\n prefix: versions.get(item.name)!.size > 1 ? `${item.name}@${item.version}` : item.name,\n }),\n );\n}\n\n/** The package that a file belongs to, or undefined for a file of the app. */\nexport function packageOf(packages: BrumatePackage[], file: string): BrumatePackage | undefined {\n return packages.find((item) => file.startsWith(`${item.root}/`));\n}\n\n/**\n * The name of a file of a package, which its IDs come from: the prefix of\n * the package and the path of the file in it, such as `@acme/ui/src/Button.brm`.\n * It is the same wherever the package is installed.\n */\nexport function packageFileName(item: BrumatePackage, file: string): string {\n return `${item.prefix}/${file.slice(item.root.length + 1)}`;\n}\n\n/** The name and the subpath of a bare specifier, such as `@acme/ui` and `./Button.brm`. */\nexport function splitSpecifier(specifier: string): { name: string; subpath: string } | undefined {\n if (specifier.startsWith('.') || specifier.startsWith('/') || /^[a-z]+:/i.test(specifier)) {\n return undefined;\n }\n const parts = specifier.split('/');\n const count = specifier.startsWith('@') ? 2 : 1;\n if (parts.length < count || parts.slice(0, count).some((part) => part === '')) {\n return undefined;\n }\n const rest = parts.slice(count).join('/');\n return { name: parts.slice(0, count).join('/'), subpath: rest ? `./${rest}` : '.' };\n}\n\n/** The conditions of `exports` that a `.brm` file or a source module can be under. */\nconst CONDITIONS = new Set(['brumate', 'import', 'module', 'node', 'browser', 'default']);\n\nfunction resolveTarget(target: unknown, star: string): string | undefined {\n if (typeof target === 'string') {\n return target.replaceAll('*', star);\n }\n if (Array.isArray(target)) {\n for (const item of target) {\n const result = resolveTarget(item, star);\n if (result) {\n return result;\n }\n }\n return undefined;\n }\n if (typeof target === 'object' && target !== null) {\n for (const [condition, value] of Object.entries(target)) {\n if (CONDITIONS.has(condition)) {\n const result = resolveTarget(value, star);\n if (result) {\n return result;\n }\n }\n }\n }\n return undefined;\n}\n\n/** Resolves a subpath through the `exports` of a package.json, or undefined if it does not export it. */\nexport function resolveExports(exports: unknown, subpath: string): string | undefined {\n const map =\n typeof exports === 'object' &&\n exports !== null &&\n !Array.isArray(exports) &&\n Object.keys(exports).some((key) => key.startsWith('.'))\n ? (exports as Record<string, unknown>)\n : { '.': exports };\n if (subpath in map) {\n return resolveTarget(map[subpath], '');\n }\n // The pattern with the longest prefix wins, as in Node.\n let best: { key: string; star: string } | undefined;\n for (const key of Object.keys(map)) {\n const index = key.indexOf('*');\n if (index === -1) {\n continue;\n }\n const before = key.slice(0, index);\n const after = key.slice(index + 1);\n if (\n subpath.startsWith(before) &&\n subpath.endsWith(after) &&\n subpath.length >= key.length - 1 &&\n (!best || before.length > best.key.indexOf('*'))\n ) {\n best = { key, star: subpath.slice(before.length, subpath.length - after.length) };\n }\n }\n return best && resolveTarget(map[best.key], best.star);\n}\n\n/**\n * Resolves a bare specifier, such as `@acme/ui/Button.brm`, to the real path\n * of the file, through the `exports` of the package. Returns undefined when\n * it is not a bare specifier or names no file.\n */\nexport function resolvePackageImport(specifier: string, importer: string): string | undefined {\n const split = splitSpecifier(specifier);\n if (!split) {\n return undefined;\n }\n const directory = findPackageDirectory(split.name, path.dirname(importer));\n if (!directory) {\n return undefined;\n }\n const json = readJson(`${directory}/package.json`);\n const target =\n json?.exports === undefined ? split.subpath : resolveExports(json.exports, split.subpath);\n if (!target) {\n return undefined;\n }\n const file = path.resolve(directory, target);\n return existsSync(file) ? toPosix(realpathSync(file)) : undefined;\n}\n\n/** The specifiers that a file imports or exports from, found by a pattern, so it can only find more. */\nexport function importSpecifiers(source: string): string[] {\n const result: string[] = [];\n for (const match of source.matchAll(/(?:\\bfrom|\\bimport\\s*\\(?)\\s*(['\"])([^'\"\\n]+)\\1/g)) {\n result.push(match[2]!);\n }\n return result;\n}\n\n/** The extensions that an import without one can name. */\nconst EXTENSIONS = ['', '.ts', '.tsx', '.js', '.mjs', '/index.ts', '/index.js'];\n\n/**\n * The files of packages that the app reaches: the files of packages that\n * files of the app import, and the files of packages that those import, and\n * so on. Only these become server functions of the app.\n */\nexport function reachableFiles(\n packages: BrumatePackage[],\n appFiles: string[],\n read: (file: string) => string | undefined,\n): Set<string> {\n const reached = new Set<string>();\n const names = new Set(packages.map((item) => item.name));\n const pending: string[] = [];\n const add = (file: string | undefined): void => {\n if (file && !reached.has(file) && packageOf(packages, file)) {\n reached.add(file);\n pending.push(file);\n }\n };\n const resolve = (specifier: string, importer: string): string | undefined => {\n if (specifier.startsWith('.')) {\n const stem = path.resolve(path.dirname(importer), specifier.split('?')[0]!);\n const found = EXTENSIONS.map((extension) => stem + extension).find((candidate) =>\n statSync(candidate, { throwIfNoEntry: false })?.isFile(),\n );\n return found && toPosix(realpathSync(found));\n }\n const name = splitSpecifier(specifier)?.name;\n return name && names.has(name)\n ? resolvePackageImport(specifier.split('?')[0]!, importer)\n : undefined;\n };\n const visit = (file: string, own: boolean): void => {\n const source = read(file);\n if (source === undefined) {\n return;\n }\n for (const specifier of importSpecifiers(source)) {\n // A file of the app reaches a package only by its name.\n if (own && specifier.startsWith('.')) {\n continue;\n }\n try {\n add(resolve(specifier, file));\n } catch {\n // A path that is not a file, such as a directory, reaches nothing.\n }\n }\n };\n for (const file of appFiles) {\n visit(file, true);\n }\n while (pending.length > 0) {\n visit(pending.pop()!, false);\n }\n return reached;\n}\n","// An error while the dev server renders a page, shown in Vite's error overlay.\n\nimport { resolve } from 'node:path';\nimport type { ViteDevServer } from 'vite';\nimport type { Location } from './error.ts';\n\n/** The error that Vite's overlay shows. */\nexport interface ErrorPayload {\n message: string;\n stack: string;\n id?: string;\n frame?: string;\n plugin?: string;\n loc?: { file: string; line: number; column: number };\n}\n\n/** The overlay payload of an error, with the file, line and lines around it for compile errors. */\nexport function errorPayload(error: unknown, root: string = process.cwd()): ErrorPayload {\n const value = error instanceof Error ? error : new Error(String(error));\n const located = value as Error & {\n filename?: string;\n location?: Location;\n frame?: string;\n // Vite adds these to errors of plugins, such as a compile error that `ssrLoadModule` throws.\n loc?: { file?: string; line: number; column: number };\n id?: string;\n plugin?: string;\n };\n const payload: ErrorPayload = {\n message: value.message,\n // A compile error has no useful stack: the message names the file and line.\n stack: located.frame ? '' : (value.stack ?? ''),\n };\n if (located.loc && located.frame) {\n const file = located.loc.file ?? located.id ?? '';\n payload.stack = '';\n payload.id = file;\n payload.plugin = located.plugin;\n payload.frame = located.frame;\n payload.loc = { file, line: located.loc.line, column: located.loc.column };\n } else if (located.filename && located.location) {\n const file = resolve(root, located.filename);\n payload.id = file;\n payload.plugin = 'brumate';\n payload.frame = located.frame;\n payload.loc = { file, line: located.location.line, column: located.location.column };\n }\n return payload;\n}\n\n/**\n * A page that shows an error in Vite's error overlay, for a dev server to\n * answer with when a page fails to render. It loads again when a file changes.\n *\n * ```ts\n * } catch (error) {\n * response.statusCode = 500;\n * response.setHeader('content-type', 'text/html');\n * response.end(errorPage(error, vite));\n * }\n * ```\n */\nexport function errorPage(error: unknown, server?: ViteDevServer): string {\n if (server && error instanceof Error) {\n server.ssrFixStacktrace(error);\n }\n const payload = errorPayload(error, server?.config.root);\n server?.config.logger.error(\n payload.loc ? `${payload.message}\\n${payload.frame}` : String((error as Error)?.stack ?? error),\n );\n // `<` is escaped, so the error cannot end the script.\n const json = JSON.stringify(payload).replace(/</g, '\\\\u003c');\n const base = server?.config.base ?? '/';\n return `<!doctype html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n<script type=\"module\" src=\"${base}@vite/client\"></script>\n</head>\n<body>\n<pre id=\"brumate-error\" style=\"white-space: pre-wrap; font: 14px monospace; padding: 16px\"></pre>\n<script type=\"module\">\nimport { createHotContext } from '${base}@vite/client';\nconst error = ${json};\nconst Overlay = customElements.get('vite-error-overlay');\nif (Overlay) {\n document.body.append(new Overlay(error));\n} else {\n document.getElementById('brumate-error').textContent = [error.message, error.frame, error.stack].filter(Boolean).join('\\\\n\\\\n');\n}\n// A component that updates in place, after a fix, loads the page again.\nconst hot = createHotContext('/@brumate/error');\nhot.on('brumate:update', () => location.reload());\nhot.on('vite:beforeUpdate', () => location.reload());\n</script>\n</body>\n</html>\n`;\n}\n","// Writes the pages of a site as static HTML files after the server build.\nimport { createHash } from 'node:crypto';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nexport interface PrerenderOptions {\n /** The paths to render first. Defaults to `['/']`. */\n paths?: string[];\n /** Follows links to other pages of the site, and renders them too. Defaults to true. */\n crawl?: boolean;\n /** The output directory of the client build, with its manifest, relative to the root. Defaults to `dist/client`. */\n client?: string;\n /** Markup for the head of every page, from the manifest of the client build. */\n head?: (manifest: Record<string, ManifestChunk>) => string;\n}\n\nexport interface ManifestChunk {\n file: string;\n src?: string;\n isEntry?: boolean;\n}\n\n/** A page that the build wrote, in the prerender manifest. */\nexport interface PrerenderedPage {\n /** The file of the page, relative to the client build. */\n file: string;\n /**\n * The hashes of the page's inline scripts, as `sha256-<base64>`, for a\n * Content Security Policy: a prerendered page has no nonce.\n */\n scripts: string[];\n}\n\n/** The prerender manifest, `.brumate/prerender.json` in the client build. */\nexport interface PrerenderManifest {\n /** The pages by path. The error page of a missing path is `404`. */\n pages: Record<string, PrerenderedPage>;\n /** The hashes of the inline scripts of every page, once each. */\n scripts: string[];\n}\n\ntype Handle = (request: Request, options: object) => Promise<Response | undefined>;\n\n/** The file of a page: `index.html` in a folder of its path. */\nfunction fileOf(pathname: string): string {\n const clean = pathname.replace(/^\\/+|\\/+$/g, '');\n return clean ? `${clean}/index.html` : 'index.html';\n}\n\n/** The paths of the links in a page that stay on the site, without their query and hash. */\nfunction links(html: string, base: string): string[] {\n const result: string[] = [];\n for (const match of html.matchAll(/<a\\b[^>]*\\bhref=\"([^\"]*)\"/g)) {\n const href = match[1]!.replace(/&/g, '&');\n if (!href.startsWith(base) || href.startsWith('//')) {\n continue;\n }\n const pathname = href.split(/[?#]/)[0]!.slice(base.length - 1) || '/';\n if (!/\\.[a-z0-9]+$/i.test(pathname)) {\n result.push(pathname);\n }\n }\n return result;\n}\n\n/**\n * Returns the hashes of the inline scripts of a page, as `sha256-<base64>`,\n * in the order of the page. A browser hashes the text between the tags.\n */\nexport function scriptHashes(html: string): string[] {\n const hashes: string[] = [];\n for (const match of html.matchAll(/<script\\b([^>]*)>([^]*?)<\\/script>/gi)) {\n if (/\\ssrc\\s*=/i.test(match[1]!)) {\n continue;\n }\n hashes.push(`sha256-${createHash('sha256').update(match[2]!, 'utf8').digest('base64')}`);\n }\n return hashes;\n}\n\n/**\n * Renders pages with the route handler of the server build, and writes them\n * into the client build. Returns the paths that it wrote.\n */\nexport async function prerender(\n routes: string,\n root: string,\n base: string,\n options: PrerenderOptions,\n): Promise<string[]> {\n const client = path.resolve(root, options.client ?? 'dist/client');\n const manifest = JSON.parse(\n await readFile(path.join(client, '.vite/manifest.json'), 'utf8'),\n ) as Record<string, ManifestChunk>;\n const entry = Object.values(manifest).find((chunk) => chunk.isEntry);\n if (!entry) {\n throw new Error('The client build has no entry. Build the client before the server.');\n }\n const { handle } = (await import(pathToFileURL(routes).href)) as { handle: Handle };\n const document = {\n head: options.head?.(manifest) ?? '',\n scripts: `<script type=\"module\" async src=\"${base}${entry.file}\"></script>`,\n };\n const queue = [...(options.paths ?? ['/'])];\n const seen = new Set<string>(queue);\n const written: string[] = [];\n const pages: Record<string, PrerenderedPage> = {};\n while (queue.length > 0) {\n const pathname = queue.shift()!;\n // oxlint-disable-next-line no-await-in-loop -- Pages render one by one, and each can add links.\n const response = await handle(new Request(`http://localhost${pathname}`), document);\n if (!response?.headers.get('content-type')?.includes('text/html') || response.status !== 200) {\n continue;\n }\n // oxlint-disable-next-line no-await-in-loop -- Pages render one by one, and each can add links.\n const html = await response.text();\n const file = path.join(client, fileOf(pathname));\n // oxlint-disable-next-line no-await-in-loop -- Pages render one by one, and each can add links.\n await mkdir(path.dirname(file), { recursive: true });\n // oxlint-disable-next-line no-await-in-loop -- Pages render one by one, and each can add links.\n await writeFile(file, html);\n written.push(pathname);\n pages[pathname] = { file: fileOf(pathname), scripts: scriptHashes(html) };\n if (options.crawl !== false) {\n for (const link of links(html, base)) {\n if (!seen.has(link)) {\n seen.add(link);\n queue.push(link);\n }\n }\n }\n }\n // A static host answers a missing path with 404.html: the error file of the root.\n const missing = await handle(new Request('http://localhost/__brumate_not_found__'), document);\n if (missing?.status === 404 && missing.headers.get('content-type')?.includes('text/html')) {\n const html = await missing.text();\n await writeFile(path.join(client, '404.html'), html);\n written.push('404');\n pages['404'] = { file: '404.html', scripts: scriptHashes(html) };\n }\n const result: PrerenderManifest = {\n pages,\n scripts: [...new Set(Object.values(pages).flatMap((page) => page.scripts))],\n };\n await mkdir(path.join(client, '.brumate'), { recursive: true });\n await writeFile(\n path.join(client, '.brumate/prerender.json'),\n `${JSON.stringify(result, null, 2)}\\n`,\n );\n return written;\n}\n","// A report of what the client build ships: what every page loads before its\n// first event, the code that events load, and the most that each route can\n// load. A budget fails the build when a size goes over it.\n\nimport { builtin } from './node.ts';\nimport { parse } from './parser.ts';\nimport { resolveRelative } from './project.ts';\nimport type { RouteFiles } from './routes.ts';\n\n/** A chunk of the client build, as the bundler writes it. */\nexport interface ReportChunk {\n fileName: string;\n code: string;\n isEntry: boolean;\n /** Chunks that this chunk imports statically. */\n imports: string[];\n /** The modules in the chunk. */\n moduleIds: string[];\n}\n\n/** Sizes in bytes, after gzip. */\nexport interface Budget {\n /** What every page loads before its first event. */\n loader?: number;\n /** The most that a route can load after its first event, with the core. */\n route?: number;\n}\n\nexport interface BuildReport {\n /** The entry and its imports, which every page loads. */\n loader: number;\n /** The runtime that the first event loads. */\n core: number;\n /** Each component, with the size of its client code, largest first. */\n components: { file: string; bytes: number }[];\n /** Each route path, with the most it can load after its first event, largest first. */\n routes: { path: string; bytes: number; components: number }[];\n /** The sizes that go over the budget, as sentences. */\n overBudget: string[];\n}\n\n/** The size of a chunk after gzip. Outside Node, the size before it. */\nfunction gzipSize(code: string): number {\n const zlib = builtin('node:zlib');\n return zlib ? zlib.gzipSync(code).length : code.length;\n}\n\n/** The chunk and every chunk that it imports statically. */\nfunction withImports(\n name: string,\n chunks: Map<string, ReportChunk>,\n into = new Set<string>(),\n): Set<string> {\n if (!into.has(name) && chunks.has(name)) {\n into.add(name);\n for (const imported of chunks.get(name)!.imports) {\n withImports(imported, chunks, into);\n }\n }\n return into;\n}\n\n/** The files of the components that a `.brm` file imports. */\nfunction componentImports(file: string, source: string): string[] {\n let parsed;\n try {\n parsed = parse(source, { filename: file });\n } catch {\n return [];\n }\n const result: string[] = [];\n for (const script of [parsed.moduleScript, parsed.instanceScript]) {\n for (const statement of script?.program.body ?? []) {\n if (statement.type === 'ImportDeclaration') {\n const target = resolveRelative(statement.source.value, file);\n if (target) {\n result.push(target);\n }\n }\n }\n }\n return result;\n}\n\n/** Each page path, with its page and the layouts around it. */\nfunction routeEntries(\n node: RouteFiles,\n resolve: (file: string) => string,\n path = '',\n layouts: string[] = [],\n): { path: string; files: string[] }[] {\n const around = node.layout ? [...layouts, resolve(node.layout)] : layouts;\n const result = node.page ? [{ path: path || '/', files: [...around, resolve(node.page)] }] : [];\n for (const [segment, folder] of Object.entries(node.static ?? {})) {\n result.push(...routeEntries(folder, resolve, `${path}/${segment}`, around));\n }\n if (node.dynamic) {\n result.push(\n ...routeEntries(node.dynamic.node, resolve, `${path}/[${node.dynamic.name}]`, around),\n );\n }\n if (node.rest) {\n result.push(...routeEntries(node.rest.node, resolve, `${path}/[...${node.rest.name}]`, around));\n }\n return result;\n}\n\nexport interface ReportInput {\n chunks: ReportChunk[];\n /** The source of each `.brm` file, by absolute path. */\n sources: Map<string, string>;\n /** The route files, and the absolute path of a file in them. */\n routes?: { tree: RouteFiles; resolve: (file: string) => string };\n budget?: Budget;\n}\n\n/** Measures the client build. */\nexport function buildReport({ chunks: list, sources, routes, budget }: ReportInput): BuildReport {\n const chunks = new Map(list.map((chunk) => [chunk.fileName, chunk]));\n const sizes = new Map(list.map((chunk) => [chunk.fileName, gzipSize(chunk.code)]));\n const sum = (names: Iterable<string>): number => {\n let total = 0;\n for (const name of names) {\n total += sizes.get(name) ?? 0;\n }\n return total;\n };\n\n const loaderChunks = new Set<string>();\n for (const chunk of list) {\n if (chunk.isEntry) {\n withImports(chunk.fileName, chunks, loaderChunks);\n }\n }\n const coreChunk = list.find((chunk) =>\n chunk.moduleIds.some((id) => /[\\\\/]runtime[\\\\/]client\\.[jt]s$/.test(id)),\n );\n const coreChunks = coreChunk ? withImports(coreChunk.fileName, chunks) : new Set<string>();\n for (const name of loaderChunks) {\n coreChunks.delete(name);\n }\n\n // The chunks of each component: its entry and its parts, with what they import.\n const byFile = new Map<string, Set<string>>();\n for (const chunk of list) {\n for (const id of chunk.moduleIds) {\n const file = /^(.*\\.brm)\\?brumate-client/.exec(id)?.[1];\n if (file) {\n const set = byFile.get(file) ?? new Set<string>();\n withImports(chunk.fileName, chunks, set);\n byFile.set(file, set);\n }\n }\n }\n for (const set of byFile.values()) {\n for (const name of [...loaderChunks, ...coreChunks]) {\n set.delete(name);\n }\n }\n const components = [...byFile]\n .map(([file, names]) => ({ file, bytes: sum(names) }))\n .toSorted((a, b) => b.bytes - a.bytes);\n\n // A route can load the code of its page, its layouts, and the components that they render.\n const reachable = (files: string[]): Set<string> => {\n const seen = new Set<string>();\n const visit = (file: string): void => {\n if (!seen.has(file)) {\n seen.add(file);\n for (const imported of componentImports(file, sources.get(file) ?? '')) {\n visit(imported);\n }\n }\n };\n files.forEach(visit);\n return seen;\n };\n const routeSizes = (routes ? routeEntries(routes.tree, routes.resolve) : [])\n .map(({ path, files }) => {\n const reached = reachable(files);\n const names = new Set(coreChunks);\n for (const file of reached) {\n for (const name of byFile.get(file) ?? []) {\n names.add(name);\n }\n }\n return { path, bytes: sum(names), components: reached.size };\n })\n .toSorted((a, b) => b.bytes - a.bytes);\n\n const loader = sum(loaderChunks);\n const overBudget: string[] = [];\n if (budget?.loader !== undefined && loader > budget.loader) {\n overBudget.push(\n `The loader is ${formatBytes(loader)}, over the budget of ${formatBytes(budget.loader)}.`,\n );\n }\n for (const route of routeSizes) {\n if (budget?.route !== undefined && route.bytes > budget.route) {\n overBudget.push(\n `The route ${route.path} can load ${formatBytes(route.bytes)}, over the budget of ${formatBytes(budget.route)}.`,\n );\n }\n }\n return { loader, core: sum(coreChunks), components, routes: routeSizes, overBudget };\n}\n\nfunction formatBytes(bytes: number): string {\n return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} kB`;\n}\n\n/** The report as text, with paths relative to `root`. */\nexport function formatBuildReport(report: BuildReport, relative: (file: string) => string): string {\n const lines = [\n 'brumate client report (gzip)',\n ` Every page, before its first event: ${formatBytes(report.loader)}`,\n ` The core, on the first event: ${formatBytes(report.core)}`,\n ];\n if (report.routes.length > 0) {\n lines.push(' The most each route loads after its first event, with the core');\n for (const route of report.routes) {\n lines.push(` ${route.path}: ${formatBytes(route.bytes)} (${route.components} components)`);\n }\n }\n if (report.components.length > 0) {\n lines.push(' Components, largest first');\n for (const component of report.components) {\n lines.push(` ${relative(component.file)}: ${formatBytes(component.bytes)}`);\n }\n }\n return lines.join('\\n');\n}\n","// Builds the route tree of `virtual:brumate/routes` from the files of a routes directory.\n\n/** A folder of routes, with the files as paths. The runtime `RouteNode` has loaders instead. */\nexport interface RouteFiles {\n layout?: string;\n page?: string;\n fallback?: string;\n /** `_error.brm`: renders when a route of the folder throws, or when no route matches. */\n error?: string;\n /** `_loading.brm`: shows while a route of the folder streams in. */\n loading?: string;\n /** `_middleware.ts`: runs before the routes of the folder. */\n middleware?: string;\n /** A `.ts` file that answers requests at its path, such as `api/todos.ts`. */\n endpoint?: string;\n static?: Record<string, RouteFiles>;\n dynamic?: { name: string; node: RouteFiles };\n rest?: { name: string; node: RouteFiles };\n slots?: Record<string, RouteFiles>;\n}\n\nconst DYNAMIC = /^\\[([A-Za-z_$][\\w$]*)\\]$/;\nconst REST = /^\\[\\.\\.\\.([A-Za-z_$][\\w$]*)\\]$/;\n\n/** Returns the folder for a path segment, made if missing. */\nfunction child(node: RouteFiles, segment: string): RouteFiles {\n if (segment.startsWith('@')) {\n node.slots ??= {};\n return (node.slots[segment.slice(1)] ??= {});\n }\n const rest = REST.exec(segment);\n if (rest) {\n node.rest ??= { name: rest[1]!, node: {} };\n return node.rest.node;\n }\n const dynamic = DYNAMIC.exec(segment);\n if (dynamic) {\n if (node.dynamic && node.dynamic.name !== dynamic[1]) {\n throw new Error(`Two dynamic segments in one folder: [${node.dynamic.name}] and ${segment}`);\n }\n node.dynamic ??= { name: dynamic[1]!, node: {} };\n return node.dynamic.node;\n }\n node.static ??= {};\n return (node.static[segment] ??= {});\n}\n\n/**\n * Builds the route tree from paths relative to the routes directory, such as\n * `todos/[id].brm`. `_layout.brm`, `_default.brm`, `_error.brm`,\n * `_loading.brm`, `_middleware.ts` and `index.brm` belong to their folder.\n * Other files starting with `_` are not routes. A `.ts` file is an endpoint.\n */\nexport function routeFiles(paths: string[]): RouteFiles {\n const tree: RouteFiles = {};\n for (const file of paths) {\n const typescript = file.endsWith('.ts');\n const segments = file.replace(/\\.(brm|ts)$/, '').split('/');\n const name = segments.pop()!;\n let node = tree;\n for (const segment of segments) {\n node = child(node, segment);\n }\n if (typescript) {\n if (name === '_middleware') {\n node.middleware = file;\n } else if (name === 'index') {\n node.endpoint = file;\n } else if (!name.startsWith('_')) {\n child(node, name).endpoint = file;\n }\n continue;\n }\n if (name === '_error') {\n node.error = file;\n } else if (name === '_loading') {\n node.loading = file;\n } else if (name === '_layout') {\n node.layout = file;\n } else if (name === '_default') {\n node.fallback = file;\n } else if (name === 'index') {\n node.page = file;\n } else if (!name.startsWith('_')) {\n child(node, name).page = file;\n }\n }\n return tree;\n}\n\n/**\n * Writes a route tree as module code, with an import for each file. `rpc`\n * is the URL prefix of server function calls, for forms that post to one.\n */\nexport function routeModule(\n tree: RouteFiles,\n resolve: (file: string) => string,\n rpc = '/_brumate',\n origins: string[] = [],\n /** In development, errors reach the dev server instead of `_error.brm`. */\n dev = false,\n): string {\n // Static imports, because the server registry of server functions imports every file anyway.\n const imports: string[] = [];\n const load = (file: string): string => {\n const name = `m${imports.length}`;\n imports.push(`import * as ${name} from ${JSON.stringify(resolve(file))};`);\n return `() => Promise.resolve(${name})`;\n };\n const write = (node: RouteFiles): string => {\n const fields: string[] = [];\n for (const key of [\n 'layout',\n 'page',\n 'fallback',\n 'error',\n 'loading',\n 'middleware',\n 'endpoint',\n ] as const) {\n const file = node[key];\n if (file) {\n fields.push(`${key}: ${load(file)}`);\n }\n }\n for (const key of ['static', 'slots'] as const) {\n const children = node[key];\n if (children) {\n const entries = Object.entries(children).map(\n ([name, value]) => `${JSON.stringify(name)}: ${write(value)}`,\n );\n fields.push(`${key}: { ${entries.join(', ')} }`);\n }\n }\n for (const key of ['dynamic', 'rest'] as const) {\n const value = node[key];\n if (value) {\n fields.push(`${key}: { name: ${JSON.stringify(value.name)}, node: ${write(value.node)} }`);\n }\n }\n return `{ ${fields.join(', ')} }`;\n };\n const routes = write(tree);\n return [\n \"import { handleRoute } from 'brumate/server';\",\n // Forms without scripts post to their page, which runs the server function.\n \"import { functions } from 'virtual:brumate/server';\",\n ...imports,\n `export const routes = ${routes};`,\n 'export function handle(request, options) {',\n ` return handleRoute(routes, request, { rpc: ${JSON.stringify(rpc)}, origins: ${JSON.stringify(origins)}, functions${dev ? ', dev: true' : ''}, ...options });`,\n '}',\n ].join('\\n');\n}\n\n/** A path that a request can reach, with the names of its params. */\nexport interface RoutePathInfo {\n /** The path as the route files spell it, such as `/todos/[id]`. */\n path: string;\n params: string[];\n}\n\n/** The paths of the pages and endpoints of a tree. Slots render at the paths of their layout. */\nexport function routePaths(tree: RouteFiles): RoutePathInfo[] {\n const result: RoutePathInfo[] = [];\n const visit = (node: RouteFiles, path: string, params: string[]): void => {\n if (node.page || node.endpoint) {\n result.push({ path: path || '/', params });\n }\n for (const [segment, folder] of Object.entries(node.static ?? {})) {\n visit(folder, `${path}/${segment}`, params);\n }\n if (node.dynamic) {\n visit(node.dynamic.node, `${path}/[${node.dynamic.name}]`, [...params, node.dynamic.name]);\n }\n if (node.rest) {\n visit(node.rest.node, `${path}/[...${node.rest.name}]`, [...params, node.rest.name]);\n }\n };\n visit(tree, '', []);\n return result.toSorted((a, b) => a.path.localeCompare(b.path));\n}\n\n/** A declaration file that adds the paths of a tree to `Routes` of `brumate/routes`. */\nexport function routeTypes(tree: RouteFiles): string {\n const lines = routePaths(tree).map(({ path, params }) => {\n const fields = params.map((name) => `${name}: string`).join('; ');\n // Single quotes, as formatters write them, so a formatted project leaves the file as it is.\n const key = `'${path.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`;\n return ` ${key}: {${fields ? ` ${fields} ` : ''}};`;\n });\n return [\n '// Written by the brumate Vite plugin from the route files. Do not edit.',\n // An export makes this a module, so the block below adds to brumate/routes instead of replacing it.\n 'export {};',\n '',\n \"declare module 'brumate/routes' {\",\n ' interface Routes {',\n ...lines,\n ' }',\n '}',\n '',\n ].join('\\n');\n}\n","import { createHash } from 'node:crypto';\nimport { existsSync, readFileSync, readdirSync, realpathSync, writeFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport {\n isRunnableDevEnvironment,\n normalizePath,\n searchForWorkspaceRoot,\n transformWithOxc,\n} from 'vite';\nimport type { EnvironmentModuleNode, Plugin, UserConfig, ViteDevServer } from 'vite';\nimport { compile } from './compile.ts';\nimport { DEFAULT_MERGE } from './codegen/client.ts';\nimport { defaultExclude, findFiles, findScripts, findServerFiles } from './files.ts';\nimport {\n hasUseServer,\n isScriptFile,\n serverExports,\n serverModule,\n serverStubs,\n} from './server-files.ts';\nimport type { CompileResult } from './compile.ts';\nimport { getLocation } from './error.ts';\nimport { functionId, getComponentName, hash } from './plan.ts';\nimport { analyzeProject, resolveRelative } from './project.ts';\nimport {\n findPackages,\n packageFileName,\n packageOf,\n reachableFiles,\n resolvePackageImport,\n splitSpecifier,\n} from './packages.ts';\nimport type { BrumatePackage } from './packages.ts';\nimport type { NavigateOptions } from './runtime/boot.ts';\nimport { formatReport, report, scopeLabel } from './inspect.ts';\nimport { instanceScope, slotIndex } from './codegen/scopes.ts';\nimport { isReactiveModule, resolveFromDisk } from './modules.ts';\nimport { forEachNode } from './project.ts';\nimport { SHARED_QUERY, generateShared } from './shared-module.ts';\nimport { toNodeHeaders } from './runtime/cookies.ts';\nimport { errorPayload } from './dev-error.ts';\nimport { prerender } from './prerender.ts';\nimport type { HotUpdate } from './runtime/hot.ts';\nimport type { SourceMap } from './sourcemap.ts';\nimport { buildReport, formatBuildReport } from './report.ts';\nimport type { Budget, ReportChunk } from './report.ts';\nimport type { PrerenderOptions } from './prerender.ts';\nimport { routeFiles, routeModule, routeTypes } from './routes.ts';\nimport type { RouteFiles } from './routes.ts';\n\nexport interface BrumateOptions {\n /** The URL prefix of server function calls. Defaults to `/_brumate`. */\n rpc?: string;\n /**\n * Other origins that may call server functions, such as\n * `https://app.example.com`. Calls from other sites answer 403.\n */\n origins?: string[];\n /** Directories that are not searched for `.brm` files. Defaults to `node_modules`, `dist` and hidden directories. */\n exclude?: (directory: string) => boolean;\n /** The directory of route files, relative to the root. Defaults to `src/routes`. */\n routes?: string;\n /**\n * The declaration file that gives `href` of `brumate/routes` the paths of\n * the routes, relative to the root. The plugin writes it when the routes\n * change. Defaults to `src/brumate-routes.d.ts`. `false` writes none.\n */\n routeTypes?: string | false;\n /**\n * Loads pages without a full page load when a link is clicked or a form\n * posts. Defaults to true. `{ transition: true }` swaps pages inside a\n * view transition.\n */\n navigate?: boolean | NavigateOptions;\n /**\n * After the page loads, while the browser is idle, the loader loads the\n * core and the code of the handlers of elements in or near the viewport,\n * so the first event needs no request. It skips elements with\n * `prefetch=\"none\"`, and loads nothing when the browser asks to save data\n * or the connection is 2G. Defaults to true.\n */\n preload?: boolean;\n /**\n * Client parts of a component smaller than this many bytes in all, after\n * minifying, become one module, so its first event loads one file. 0\n * keeps one module per part. Defaults to 4096.\n */\n merge?: number;\n /**\n * Writes the pages as static HTML files after the server build, for a\n * static host. The client build must run first. `true` renders `/` and\n * the pages that its links lead to.\n */\n prerender?: boolean | PrerenderOptions;\n /**\n * Prints what the client build ships: what every page loads before its\n * first event, the core, the most that each route can load, and each\n * component. Sizes are after gzip.\n */\n report?: boolean;\n /** Fails the client build when a size goes over it, in bytes after gzip. */\n budget?: Budget;\n /** Warns about common accessibility mistakes in markup. Defaults to true. */\n a11y?: boolean;\n /**\n * Shows a button that opens the devtools panel, on the dev server only.\n * The panel shows the scopes of the page, a log of events, and the report\n * of each component. Defaults to true.\n */\n devtools?: boolean;\n}\n\n/** `import 'virtual:brumate/start'` in the client entry starts the loader. */\nconst START = 'virtual:brumate/start';\n/** Exports `load(id)`, which imports the client module of a component. */\nconst MANIFEST = 'virtual:brumate/manifest';\n/** Exports `functions` and `handle(request)` for server function calls. */\nconst SERVER = 'virtual:brumate/server';\n/** Exports `routes` and `handle(request, options)` for the files in the routes directory. */\nconst ROUTES = 'virtual:brumate/routes';\n/** The entry of the server build that prerendering renders with. */\nconst PRERENDER_ENTRY = 'brumate-routes';\n\nconst CLIENT_QUERY = '?brumate-client';\nconst RENDER_QUERY = '?brumate-render';\nconst SERVER_QUERY = '?brumate-server';\n/** Exports `mount` from `brumate/testing`, with the loader of this project's client modules. */\nconst TESTING = 'virtual:brumate/testing';\n/** The dev server answers the devtools panel about a component at this path. */\nconst INSPECT = '/__brumate/inspect';\n\n/** What tells two lists of packages of components apart. */\nfunction packagesKey(list: BrumatePackage[]): string {\n return JSON.stringify(list.map((item) => [item.prefix, item.root, item.directories]));\n}\n\n/** Skips the `node_modules` and hidden directories of a package of components. */\nfunction packageExclude(directory: string): boolean {\n return directory === 'node_modules' || directory.startsWith('.');\n}\n\n/** Reads a request body as bytes, so files in form data stay intact. */\nasync function readBody(request: IncomingMessage): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of request) {\n chunks.push(chunk as Buffer);\n }\n return Buffer.concat(chunks);\n}\n\n/** What decides whether an edit of a component can update a page without a reload. */\ninterface Shape {\n /**\n * The parts of the output that a page in the browser depends on: the\n * client entry with its update table, the slots of each scope, and the\n * markup. When they stay the same, the page keeps working with new code.\n */\n layout: string;\n css: string;\n /** The code of the client parts, which the page loads again when it changes. */\n code: string;\n /** The names of the slots of each scope, by its ID in the component. */\n slots: Record<number, string[]>;\n /** The names of the signals, whose values stay when the markup changes. */\n signals: string[];\n}\n\n/** Removes the scripts, styles and event handlers of a file, which leaves the markup of its page. */\nfunction markupOf(result: CompileResult): string {\n const { file } = result;\n const ranges: { start: number; end: number }[] = [\n ...(file.instanceScript ? [file.instanceScript] : []),\n ...(file.moduleScript ? [file.moduleScript] : []),\n ...file.styles,\n ];\n forEachNode(file.children, (node) => {\n if ('body' in node && node.body && 'script' in node.body && node.body.script) {\n ranges.push(node.body.script);\n }\n // The code of an event handler is not in the page, which only names the handler.\n if ('attributes' in node) {\n for (const attribute of node.attributes) {\n if (attribute.kind === 'event') {\n ranges.push(attribute.handler);\n }\n }\n }\n });\n let markup = '';\n let position = 0;\n for (const range of ranges.toSorted((a, b) => a.start - b.start)) {\n markup += file.source.slice(position, range.start);\n position = Math.max(position, range.end);\n }\n return markup + file.source.slice(position);\n}\n\nfunction shapeOf(result: CompileResult): Shape {\n const slots = [...result.plan.scopes.values()].map(\n (layout) => `${layout.scope.id}:${layout.slots.map((slot) => slot.name).join(',')}`,\n );\n const layouts = [...result.plan.scopes.values()];\n return {\n layout: JSON.stringify([result.table, slots, markupOf(result)]),\n css: result.css,\n // The entry of a small component holds its code too.\n code: JSON.stringify([result.client, result.parts]),\n slots: Object.fromEntries(\n layouts.map((layout) => [layout.scope.id, layout.slots.map((slot) => slot.name)]),\n ),\n signals: layouts.flatMap((layout) =>\n layout.slots.filter((slot) => slot.kind === 'signal').map((slot) => slot.name),\n ),\n };\n}\n\n/** What Vitest passes to `configureVitest`, the part that this plugin uses. */\ninterface VitestContext {\n defineCacheKeyGenerator?: (generate: () => string) => void;\n experimental_defineCacheKeyGenerator?: (generate: () => string) => void;\n}\n\nlet fingerprint: string | undefined;\n\n/**\n * A hash of the code of this build of brumate. A new build can compile the\n * same `.brm` file to other code, so the hash is part of Vitest's cache key.\n */\nfunction buildFingerprint(): string {\n if (fingerprint === undefined) {\n const digest = createHash('sha1');\n const visit = (directory: string): void => {\n for (const entry of readdirSync(directory, { withFileTypes: true }).toSorted((a, b) =>\n a.name < b.name ? -1 : 1,\n )) {\n const file = path.join(directory, entry.name);\n if (entry.isDirectory()) {\n visit(file);\n } else if (/\\.[jt]s$/.test(entry.name) && !entry.name.endsWith('.d.ts')) {\n digest.update(entry.name).update(readFileSync(file));\n }\n }\n };\n visit(path.dirname(fileURLToPath(import.meta.url)));\n fingerprint = digest.digest('hex').slice(0, 16);\n }\n return fingerprint;\n}\n\n/** The Vite plugin for `.brm` files. */\nexport default function brumate(options: BrumateOptions = {}): Plugin {\n const rpc = options.rpc ?? '/_brumate';\n const exclude = options.exclude ?? defaultExclude;\n let root = process.cwd();\n let outDir = '';\n let base = '/';\n let isSsrBuild = false;\n let isServe = false;\n /** Component IDs to absolute file paths. */\n const files = new Map<string, string>();\n const compiled = new Map<string, { source: string; result: CompileResult }>();\n /** Files that a component depends on, such as SCSS that it imports or modules that it calls into, with the components. */\n const dependents = new Map<string, Set<string>>();\n /** What the browser has of each component, from its last compile. See `shapeOf`. */\n const shapes = new Map<string, Shape>();\n /** The props that parents can change, by absolute file path. */\n let liveProps = new Map<string, Set<string>>();\n\n /** The dependencies of the app that ship `.brm` files. See `packages.ts`. */\n let packages: BrumatePackage[] = [];\n\n // The ID is computed from the path relative to the root, so it is the same on every machine.\n const relative = (file: string): string => normalizePath(path.relative(root, file));\n /**\n * The name of a file, which its IDs come from: its path relative to the root,\n * or for a file of a package, the name of the package and its path in it.\n */\n const nameOf = (file: string): string => {\n let normalized = normalizePath(file);\n let owner = packageOf(packages, normalized);\n // With `resolve.preserveSymlinks`, Vite names a file of a package by its link.\n if (!owner && normalized.includes('/node_modules/') && existsSync(normalized)) {\n normalized = normalizePath(realpathSync(normalized));\n owner = packageOf(packages, normalized);\n }\n return owner ? packageFileName(owner, normalized) : relative(file);\n };\n /** True for a bare specifier that names a package of components. */\n const isPackageSpecifier = (specifier: string): boolean => {\n const name = splitSpecifier(specifier)?.name;\n return name !== undefined && packages.some((item) => item.name === name);\n };\n /** Files of server functions: scripts whose first statement is `'use server'`, by ID. */\n const serverFiles = new Map<string, string>();\n /** The scripts of the app, when it uses packages of components. */\n let appScripts: string[] = [];\n /** The ID of a function that a component imports from a 'use server' file, by a relative path. */\n const serverImport = (importer: string, specifier: string, name: string): string | undefined => {\n // A package of components can export a file of server functions.\n if (!specifier.startsWith('.')) {\n const file = isPackageSpecifier(specifier)\n ? resolvePackageImport(specifier, importer)\n : undefined;\n return file && isScriptFile(file) && hasUseServer(readFileSync(file, 'utf8'))\n ? functionId(serverFileId(file), name, !isServe)\n : undefined;\n }\n const stem = path.resolve(path.dirname(importer), specifier);\n const found = [\n stem,\n ...['.ts', '.tsx', '.js', '.mjs'].map((extension) => stem + extension),\n ].find(\n (candidate) =>\n isScriptFile(candidate) &&\n existsSync(candidate) &&\n hasUseServer(readFileSync(candidate, 'utf8')),\n );\n return found && functionId(serverFileId(normalizePath(found)), name, !isServe);\n };\n\n const serverFileId = (file: string): string =>\n `${path.basename(file).replace(/\\.[^.]+$/, '')}_${hash(nameOf(file))}`;\n const componentId = (file: string): string => {\n const filename = nameOf(file);\n return `${getComponentName(filename)}_${hash(filename)}`;\n };\n\n const scan = async (): Promise<void> => {\n const directories = packages.flatMap((item) =>\n item.directories.filter((directory) => existsSync(directory)),\n );\n // A package inside the root, such as one of a workspace, is found once, as a package.\n const ownFile = (file: string): boolean => !packageOf(packages, file);\n const [own, ownServer, ...found] = await Promise.all([\n findFiles(root, exclude),\n findServerFiles(root, exclude),\n ...directories.flatMap((directory) => [\n findFiles(directory, packageExclude),\n findServerFiles(directory, packageExclude),\n ]),\n ]);\n // The scripts of the app, which can import files of packages.\n appScripts = packages.length > 0 ? (await findScripts(root, exclude)).filter(ownFile) : [];\n files.clear();\n serverFiles.clear();\n for (const file of own!.filter(ownFile)) {\n files.set(componentId(file), file);\n }\n for (const file of ownServer!.filter(ownFile)) {\n serverFiles.set(serverFileId(file), file);\n }\n for (const [index, list] of found.entries()) {\n for (const file of list) {\n if (index % 2 === 0) {\n files.set(componentId(file), file);\n } else {\n serverFiles.set(serverFileId(file), file);\n }\n }\n }\n await analyze();\n };\n\n /**\n * The files of packages that the app reaches through its imports. A server\n * function of a package becomes an endpoint of the app only when the app\n * reaches its file, so installing a package does not expose all of them.\n */\n const reachable = (): Set<string> =>\n reachableFiles(\n packages,\n [...[...files.values()].filter((file) => !packageOf(packages, file)), ...appScripts],\n (file) => {\n try {\n return readFileSync(file, 'utf8');\n } catch {\n return undefined;\n }\n },\n );\n /** The files of packages in the last server registry. */\n let registered = new Set<string>();\n\n /** Resolves a `.brm` file that a component imports: next to it, or from a package of components. */\n const resolveComponent = (specifier: string, importer: string): string | undefined =>\n resolveRelative(specifier, importer) ??\n (specifier.endsWith('.brm') && isPackageSpecifier(specifier)\n ? resolvePackageImport(specifier, importer)\n : undefined);\n\n // Props are analyzed across the project, so a change to one file can change the output of others.\n const analyze = async (): Promise<void> => {\n const list = [...files.values()];\n const contents = await Promise.all(list.map((file) => readFile(file, 'utf8')));\n const sources = new Map(list.map((file, index) => [file, contents[index]!]));\n liveProps = analyzeProject(sources, resolveComponent);\n compiled.clear();\n };\n\n // The entry, the parts and the render module of a file come from one compile.\n const compileFile = async (file: string): Promise<{ source: string; result: CompileResult }> => {\n const source = await readFile(file, 'utf8');\n let cached = compiled.get(file);\n if (cached?.source !== source) {\n cached = {\n source,\n result: compile(source, {\n filename: nameOf(file),\n liveProps: liveProps.get(file),\n path: file,\n merge: options.merge ?? DEFAULT_MERGE,\n a11y: options.a11y,\n // A build does not show the names of server functions in their IDs.\n hideNames: !isServe,\n serverImport: (specifier, name) => serverImport(file, specifier, name),\n // A module of reactive logic can come from a package of components.\n resolveModule: (specifier, importer) => {\n const local = resolveFromDisk(specifier, importer);\n const found =\n local === undefined && isPackageSpecifier(specifier)\n ? resolvePackageImport(specifier, importer)\n : undefined;\n return found ? { path: found, source: readFileSync(found, 'utf8') } : local;\n },\n }),\n };\n compiled.set(file, cached);\n shapes.set(file, shapeOf(cached.result));\n }\n return cached;\n };\n\n const manifest = async (): Promise<string> => {\n const list = [...files];\n // A build leaves out the components that have no client code. The core treats a\n // component that `load` does not know as one with nothing to update. The dev server\n // keeps every component, because an edit can give one client code.\n const needed = await Promise.all(\n list.map(async ([, file]) => isServe || (await compileFile(file)).result.clientCode),\n );\n const kept = list.filter((_, index) => needed[index]);\n const entries = kept.map(\n ([id, file]) =>\n ` ${JSON.stringify(id)}: () => import(${JSON.stringify(`${file}${CLIENT_QUERY}`)}),`,\n );\n return [\n 'const modules = {',\n ...entries,\n '};',\n 'export function load(id) {',\n ...(isServe\n ? [\n ' const module = modules[id];',\n ' if (!module) {',\n ' throw new Error(`Unknown component \"${id}\"`);',\n ' }',\n ' return module();',\n ]\n : [' return modules[id]?.();']),\n '}',\n ].join('\\n');\n };\n\n /**\n * The module of every server function of the app, by ID. With `server`, in\n * a DOM test, it imports the server code of each file, which that\n * environment would give as browser code.\n */\n const serverRegistry = (server = false): string => {\n const query = server ? SERVER_QUERY : '';\n registered = packages.length > 0 ? reachable() : new Set();\n const keep = (file: string): boolean => registered.has(file) || !packageOf(packages, file);\n const components = [...files.values()].filter(keep);\n const imports = components.map(\n (file, index) => `import * as m${index} from ${JSON.stringify(file + query)};`,\n );\n const spreads = components.map((_, index) => ` ...m${index}.rpc,`);\n // Each exported function of a file of server functions, under the ID that its stub calls.\n const functionFiles = [...serverFiles.entries()].filter(([, file]) => keep(file));\n const fileImports = functionFiles.map(\n ([, file], index) => `import * as f${index} from ${JSON.stringify(file + query)};`,\n );\n const fileSpreads = functionFiles.map(([id, file], index) => {\n // The IDs are written here, so a build can hash the names of the functions.\n const names = serverExports(readFileSync(file, 'utf8'), file);\n return names\n .map(\n (name) =>\n ` ${JSON.stringify(functionId(id, name, !isServe))}: f${index}[${JSON.stringify(name)}],`,\n )\n .join('\\n');\n });\n return [\n \"import { handleRequest } from 'brumate/server';\",\n ...imports,\n ...fileImports,\n 'export const functions = {',\n ...spreads,\n ...fileSpreads,\n '};',\n 'export function handle(request) {',\n ` return handleRequest(functions, request, ${JSON.stringify(rpc)}, { origins: ${JSON.stringify(options.origins ?? [])} });`,\n '}',\n ].join('\\n');\n };\n\n const routesDirectory = (): string =>\n normalizePath(path.resolve(root, options.routes ?? 'src/routes'));\n\n /** The route files, from the `.brm` files found and the `.ts` files of the directory. */\n const currentRoutes = (): RouteFiles => {\n const directory = routesDirectory();\n const paths = [...files.values()]\n .filter((file) => file.startsWith(`${directory}/`))\n .map((file) => file.slice(directory.length + 1));\n // Endpoints and middleware are `.ts` files.\n if (existsSync(directory)) {\n for (const entry of readdirSync(directory, { recursive: true, encoding: 'utf8' })) {\n const file = normalizePath(entry);\n if (file.endsWith('.ts') && !file.endsWith('.d.ts')) {\n paths.push(file);\n }\n }\n }\n return routeFiles(paths);\n };\n\n const routeTree = (): string =>\n routeModule(\n currentRoutes(),\n (file) => `${routesDirectory()}/${file}`,\n rpc,\n options.origins,\n isServe,\n );\n\n /** Writes the paths of the routes as types for `href`, when they changed. */\n const writeRouteTypes = (): void => {\n if (options.routeTypes === false || !existsSync(routesDirectory())) {\n return;\n }\n const file = path.resolve(root, options.routeTypes ?? 'src/brumate-routes.d.ts');\n const text = routeTypes(currentRoutes());\n if (!existsSync(file) || readFileSync(file, 'utf8') !== text) {\n writeFileSync(file, text);\n }\n };\n\n /** What the devtools panel shows about a component: its name, its scopes and its report. */\n const inspectComponent = async (id: string): Promise<object | undefined> => {\n const file = files.get(id);\n if (!file) {\n return undefined;\n }\n const { source, result } = await compileFile(file);\n const { plan } = result;\n const scopes: Record<number, { label: string; slots: string[] }> = {};\n for (const layout of plan.scopes.values()) {\n scopes[layout.scope.id] = {\n label: scopeLabel(result.file.source, layout.scope),\n slots: layout.slots.map((slot) => slot.name),\n };\n }\n // The nodes that can change in the browser, with the slot of each value, so the panel\n // can mark a node when its slot is written.\n const nodes = plan.graph.nodes.filter((node) => plan.graph.live.has(node));\n const indexes = new Map(nodes.map((node, index) => [node, index]));\n const graph = {\n nodes: nodes.map((node) => {\n if (node.kind === 'source' || node.kind === 'memo') {\n return {\n kind: node.kind === 'memo' ? 'memo' : node.declaration.kind,\n label: node.declaration.name,\n scope: instanceScope(plan, node.declaration.scope).id,\n slot: slotIndex(plan, node.declaration),\n };\n }\n // Markup has no name, so its place in the file tells nodes apart, such as `insert 9:42`.\n // Code that a module function gave the component has no place in the component's file.\n const at = result.locate(node.site.range.start);\n const where = at.file === undefined ? getLocation(source, at.offset) : undefined;\n return {\n kind: node.kind,\n label: where ? `${node.site.label} ${where.line}:${where.column}` : node.site.label,\n scope: instanceScope(plan, node.site.scope).id,\n };\n }),\n edges: plan.graph.edges\n .filter((edge) => indexes.has(edge.from) && indexes.has(edge.to))\n .map((edge) => [indexes.get(edge.from)!, indexes.get(edge.to)!]),\n };\n const text = formatReport(report(source, result, liveProps.get(file)));\n return { name: plan.name, file: nameOf(file), scopes, graph, text };\n };\n\n const handleDevRPC = async (\n server: ViteDevServer,\n request: IncomingMessage,\n response: ServerResponse,\n ): Promise<void> => {\n const id = decodeURIComponent((request.url ?? '').slice(rpc.length + 1).split('?')[0]!);\n const owner = id.split('#')[0]!;\n const file = files.get(owner) ?? serverFiles.get(owner);\n // A file of a package that the app does not reach has no endpoints, as in production.\n const reached = file && packageOf(packages, file) ? reachable() : undefined;\n if (!file || (reached && !reached.has(file))) {\n response.statusCode = 404;\n response.end(`Unknown server function \"${id}\"`);\n return;\n }\n // The app reached the file after the registry loaded, such as with a new import.\n if (reached && !registered.has(file)) {\n const module = server.moduleGraph.getModuleById(`\\0${SERVER}`);\n if (module) {\n server.moduleGraph.invalidateModule(module);\n }\n }\n try {\n // Every server function of the app, as in production, so `event.refresh` can name a\n // function of another file, such as a component's call that refreshes a 'use server' file.\n const { functions } = await server.ssrLoadModule(SERVER);\n const { handleRequest } = await server.ssrLoadModule('brumate/server');\n // The same path as production, so server functions can read the request.\n const webRequest = new Request(new URL(request.url ?? '/', 'http://localhost'), {\n method: 'POST',\n headers: Object.entries(request.headers).flatMap(([name, value]) =>\n value === undefined ? [] : [[name, String(value)] as [string, string]],\n ),\n body: new Uint8Array(await readBody(request)),\n });\n const answer: Response = await handleRequest(functions, webRequest, rpc, {\n origins: options.origins,\n });\n response.statusCode = answer.status;\n // Each cookie stays apart, as `forEach` would set only the last one.\n for (const [name, value] of Object.entries(toNodeHeaders(answer.headers))) {\n response.setHeader(name, value);\n }\n response.end(await answer.text());\n } catch (error) {\n server.config.logger.error(String((error as Error).stack ?? error));\n response.statusCode = 500;\n response.end(String(error));\n }\n };\n\n /** Updates the page in the browser after a change to a component, or reloads it. */\n async function updateClient(\n file: string,\n server: ViteDevServer,\n timestamp: number,\n ): Promise<[] | undefined> {\n const normalized = normalizePath(file);\n const targets = file.endsWith('.brm') ? [normalized] : [...(dependents.get(normalized) ?? [])];\n if (targets.length === 0) {\n return undefined;\n }\n // A resumed page cannot run a component again. When an edit keeps the markup, the slots\n // and the update table of each changed component, the page keeps its state: new styles\n // replace the old ones, and the next event loads the new code. When the markup changes,\n // the page renders again, and the signals of the component keep their values. A file\n // that does not compile reloads the page, which shows the error.\n const invalidate = (): void => {\n for (const module of server.moduleGraph.idToModuleMap.values()) {\n const id = module.id ?? '';\n if (\n id.includes('.brm') ||\n id === `\\0${MANIFEST}` ||\n id === `\\0${SERVER}` ||\n id === `\\0${ROUTES}`\n ) {\n server.moduleGraph.invalidateModule(module);\n }\n }\n };\n const reload = (): [] => {\n invalidate();\n server.ws.send({ type: 'full-reload' });\n return [];\n };\n await analyze();\n const updates: HotUpdate[] = [];\n for (const target of targets) {\n const before = shapes.get(target);\n let after: Shape;\n try {\n // oxlint-disable-next-line no-await-in-loop -- The first component that cannot update in place reloads the page.\n after = shapeOf((await compileFile(target)).result);\n } catch {\n // The error shows when the page reloads and the module compiles.\n return reload();\n }\n if (!before) {\n return reload();\n }\n const remount = before.layout !== after.layout;\n const id = componentId(target);\n const modules = [\n ...(server.moduleGraph.getModulesByFile(target) ?? []),\n // The shared code of a module of reactive logic that changed.\n ...(target === normalized ? [] : (server.moduleGraph.getModulesByFile(normalized) ?? [])),\n ];\n for (const module of modules) {\n server.moduleGraph.invalidateModule(module, new Set(), timestamp, true);\n }\n const entry = [...(server.moduleGraph.getModulesByFile(target) ?? [])].find((module) =>\n module.id?.endsWith(CLIENT_QUERY),\n );\n updates.push({\n id,\n css: before.css === after.css ? undefined : after.css,\n url: before.code === after.code && !remount ? undefined : entry?.url,\n remount: remount\n ? {\n before: before.slots,\n after: after.slots,\n signals: after.signals.filter((name) => before.signals.includes(name)),\n }\n : undefined,\n });\n }\n if (updates.some((update) => update.remount)) {\n // The server renders the page again with the new markup.\n invalidate();\n }\n server.ws.send({ type: 'custom', event: 'brumate:update', data: { updates, timestamp } });\n return [];\n }\n\n /**\n * The config that packages of components need. Vite must not pre-bundle them,\n * or their `.brm` and `'use server'` files would not reach this plugin, and the\n * server build compiles them instead of importing them from `node_modules`.\n */\n const packageConfig = (config: UserConfig): UserConfig => {\n if (packages.length === 0) {\n return {};\n }\n const names = [...new Set(packages.map((item) => item.name))];\n const result: UserConfig = {\n optimizeDeps: { exclude: names },\n ssr: { noExternal: names },\n // The components of a package and the app share one copy of the runtime.\n resolve: { dedupe: ['brumate'] },\n };\n // The dev server serves files of the workspace. A linked package outside it is allowed too.\n const workspace = normalizePath(searchForWorkspaceRoot(path.resolve(config.root ?? '.')));\n const outside = packages\n .filter((item) => item.root !== workspace && !item.root.startsWith(`${workspace}/`))\n .map((item) => item.root);\n if (outside.length > 0) {\n // A list of allowed directories turns off Vite's own, so it names the workspace too.\n result.server = { fs: { allow: [workspace, ...outside] } };\n }\n return result;\n };\n\n /** The module ID of `brumate/client`, and the chunks of the loader and the core in a client build. */\n let coreModule: string | undefined;\n let loaderChunk: string | undefined;\n let coreChunk: string | undefined;\n\n const plugin: Plugin & { configureVitest(context: VitestContext): void } = {\n name: 'brumate',\n enforce: 'pre',\n\n config(config, env) {\n packages = findPackages(path.resolve(config.root ?? process.cwd()));\n const shared = packageConfig(config);\n if (!env.isSsrBuild) {\n const preload = config.build?.modulePreload;\n if (preload === false) {\n return shared;\n }\n const resolve = typeof preload === 'object' ? preload.resolveDependencies : undefined;\n return {\n ...shared,\n build: {\n modulePreload: {\n // The loader imports the core itself when it imports a component's module, so\n // it needs no list of the chunks to preload with it, which it would ship.\n resolveDependencies(filename, deps, context) {\n const list = resolve ? resolve(filename, deps, context) : deps;\n if (context.hostId !== loaderChunk || !coreChunk) {\n return list;\n }\n const rest = list.filter((dep) => dep !== coreChunk);\n return rest.length === 1 && rest[0] === filename ? [] : rest;\n },\n },\n },\n };\n }\n // The server build gets the route handler as an entry of its own, to render the pages with.\n if (!options.prerender) {\n return shared;\n }\n // `--ssr <file>` names the entry, and wins over the input of the config, which can be the client's.\n const ssr = config.build?.ssr;\n const input = typeof ssr === 'string' ? ssr : config.build?.rolldownOptions?.input;\n const entries =\n typeof input === 'string'\n ? { [path.basename(input).replace(/\\.[^.]+$/, '')]: input }\n : Array.isArray(input)\n ? Object.fromEntries(\n input.map((item) => [path.basename(item).replace(/\\.[^.]+$/, ''), item]),\n )\n : { ...(input as Record<string, string> | undefined) };\n return {\n ...shared,\n build: { ssr: true, rolldownOptions: { input: { ...entries, [PRERENDER_ENTRY]: ROUTES } } },\n };\n },\n\n // Vitest keeps transformed modules between runs. Its cache key does not\n // cover the compiler, so a new build of brumate would reuse old output.\n configureVitest(context: VitestContext) {\n const define =\n context.defineCacheKeyGenerator ?? context.experimental_defineCacheKeyGenerator;\n define?.(buildFingerprint);\n },\n\n configResolved(config) {\n root = config.root;\n isServe = config.command === 'serve';\n outDir = path.resolve(config.root, config.build.outDir);\n base = config.base;\n isSsrBuild = Boolean(config.build.ssr);\n },\n\n async generateBundle(_output, bundle) {\n if (isSsrBuild) {\n return;\n }\n // Vite lists the chunks to preload after this hook, with `resolveDependencies` above.\n loaderChunk = undefined;\n coreChunk = undefined;\n for (const item of Object.values(bundle)) {\n if (item.type !== 'chunk') {\n continue;\n }\n if (item.moduleIds.includes(`\\0${MANIFEST}`)) {\n loaderChunk = item.fileName;\n }\n if (coreModule && item.moduleIds.includes(coreModule)) {\n coreChunk = item.fileName;\n }\n }\n if (!options.report && !options.budget) {\n return;\n }\n const chunks: ReportChunk[] = [];\n for (const item of Object.values(bundle)) {\n if (item.type === 'chunk') {\n chunks.push({\n fileName: item.fileName,\n code: item.code,\n isEntry: item.isEntry,\n imports: item.imports,\n moduleIds: item.moduleIds,\n });\n }\n }\n const list = [...files.values()];\n const contents = await Promise.all(list.map((file) => readFile(file, 'utf8')));\n const measured = buildReport({\n chunks,\n sources: new Map(list.map((file, index) => [file, contents[index]!])),\n routes: existsSync(routesDirectory())\n ? { tree: currentRoutes(), resolve: (file) => `${routesDirectory()}/${file}` }\n : undefined,\n budget: options.budget,\n });\n if (options.report) {\n this.info(`\\n${formatBuildReport(measured, nameOf)}`);\n }\n if (measured.overBudget.length > 0) {\n this.error(measured.overBudget.join('\\n'));\n }\n },\n\n async writeBundle(_output, bundle) {\n if (!options.prerender || !isSsrBuild) {\n return;\n }\n const chunk = Object.values(bundle).find(\n (item) => item.type === 'chunk' && item.isEntry && item.name === PRERENDER_ENTRY,\n );\n if (!chunk) {\n return;\n }\n const settings = options.prerender === true ? {} : options.prerender;\n const written = await prerender(path.join(outDir, chunk.fileName), root, base, settings);\n this.info(`Prerendered ${written.length} pages`);\n },\n\n async buildStart() {\n coreModule = isServe\n ? undefined\n : (await this.resolve('brumate/client', path.join(root, 'index.html')))?.id;\n await scan();\n writeRouteTypes();\n },\n\n async resolveId(id, importer, resolveOptions) {\n if (id === START || id === MANIFEST || id === SERVER || id === ROUTES || id === TESTING) {\n return `\\0${id}`;\n }\n // In a DOM test, the server version of a component, a file of server functions, or the\n // registry imports the server code of a file of server functions, not its stubs. Other\n // modules stay as they are, so the test and the server code share one copy of each.\n if (\n resolveOptions?.ssr ||\n !importer ||\n (!importer.includes(SERVER_QUERY) && importer !== `\\0${SERVER}`) ||\n id.includes(SERVER_QUERY)\n ) {\n return undefined;\n }\n const resolved = await this.resolve(id, importer, { ...resolveOptions, skipSelf: true });\n if (\n !resolved ||\n resolved.external ||\n resolved.id.includes('?') ||\n (resolved.id.includes('/node_modules/') && !packageOf(packages, resolved.id))\n ) {\n return resolved;\n }\n const file = resolved.id;\n return isScriptFile(file) && existsSync(file) && hasUseServer(readFileSync(file, 'utf8'))\n ? { ...resolved, id: `${file}${SERVER_QUERY}` }\n : resolved;\n },\n\n async load(id, loadOptions) {\n // The browser code of the functions of a module of reactive logic, shared by every call.\n if (id.endsWith(SHARED_QUERY)) {\n const module = id.slice(0, -SHARED_QUERY.length);\n this.addWatchFile(module);\n const { code, map } = generateShared({\n path: module,\n source: await readFile(module, 'utf8'),\n });\n return { code, map: { ...map, sources: [module] } };\n }\n if (id === `\\0${START}`) {\n return [\n // Without client navigation, the bundle leaves its code out.\n options.navigate === false\n ? \"import { startWithoutNavigation as start } from 'brumate/static-loader';\"\n : \"import { start } from 'brumate/loader';\",\n `import { load } from ${JSON.stringify(MANIFEST)};`,\n // On the dev server, an edit of a component can update the page without a reload.\n ...(isServe ? [\"import { hotLoad } from 'brumate/hot';\"] : []),\n `start({ load${isServe ? ': hotLoad(import.meta.hot, load)' : ''}, rpc: ${JSON.stringify(rpc)}, navigate: ${JSON.stringify(options.navigate ?? true)}${options.preload === false ? ', preload: false' : ''} });`,\n // The devtools listen to the core before it starts. Only the dev server has them.\n ...(isServe && options.devtools !== false\n ? [\n `import('brumate/devtools').then((m) => m.installDevtools(${JSON.stringify(INSPECT)}, ${JSON.stringify(rpc)}));`,\n ]\n : []),\n ].join('\\n');\n }\n if (id === `\\0${MANIFEST}`) {\n return await manifest();\n }\n if (id === `\\0${SERVER}`) {\n // A DOM test gets the server code of each file too, so its calls can run in the test.\n return serverRegistry(!loadOptions?.ssr);\n }\n if (id === `\\0${ROUTES}`) {\n return routeTree();\n }\n if (id === `\\0${TESTING}`) {\n return [\n \"import { answerCalls as answer, createMount } from 'brumate/testing';\",\n `import { load } from ${JSON.stringify(MANIFEST)};`,\n `export const mount = createMount({ load, rpc: ${JSON.stringify(rpc)} });`,\n // The server code of the app loads on the first call, so a test that makes none skips it.\n 'export function answerCalls(options) {',\n ` return answer(async () => (await import(${JSON.stringify(SERVER)})).functions, { rpc: ${JSON.stringify(rpc)}, ...options });`,\n '}',\n ].join('\\n');\n }\n const [file, query] = id.split('?');\n if (!file?.endsWith('.brm')) {\n return undefined;\n }\n // Vite can add its own parameters, such as `import`.\n const params = new URLSearchParams(query);\n const isRender = params.has(RENDER_QUERY.slice(1));\n // A test in a browser environment imports the server version of a component with this query.\n const isServer = params.has(SERVER_QUERY.slice(1));\n const isClient = !isServer && (params.has(CLIENT_QUERY.slice(1)) || !loadOptions?.ssr);\n let output: Awaited<ReturnType<typeof compileFile>>;\n try {\n output = await compileFile(file);\n } catch (error) {\n // The overlay shows the file, the line and the lines around it.\n const { message, frame, loc } = errorPayload(error, root);\n // The file of a package is not under the root, which `errorPayload` resolves its name against.\n this.error({ message, frame, loc: loc && { ...loc, file }, id: file });\n }\n const { source, result } = output;\n // A stylesheet that the component imports, or a module of reactive logic that it calls into,\n // changes the output of the component.\n for (const dependency of [...result.plan.styles.dependencies, ...result.modules]) {\n const normalized = normalizePath(dependency);\n this.addWatchFile(normalized);\n if (!dependents.has(normalized)) {\n dependents.set(normalized, new Set());\n }\n dependents.get(normalized)!.add(file);\n }\n for (const warning of isClient && !params.has('part') ? result.warnings : []) {\n const { line, column } = getLocation(source, warning.range.start);\n this.warn(`${warning.message} (${nameOf(file)}:${line}:${column})`);\n }\n const part = params.get('part');\n let code: string;\n let map: SourceMap | undefined;\n if (isRender) {\n code = result.render;\n map = result.maps.render;\n } else if (part) {\n code = result.parts[part] ?? '';\n map = result.maps.parts[part];\n } else if (isServer) {\n // The components that it renders are server versions too. Only import lines change, which have no mappings.\n code = result.server.replace(/(from\\s+(['\"])[^'\"]+\\.brm)\\2/g, `$1${SERVER_QUERY}$2`);\n map = result.maps.server;\n } else {\n code = isClient ? result.client : result.server;\n map = isClient ? result.maps.client : result.maps.server;\n }\n // The map points at the file by its path, so the browser shows it under its own name. Code\n // that came from modules of reactive logic points at them, by their paths too.\n // `transform` below removes the types, and Vite chains the two maps.\n return {\n code,\n map: map && {\n ...map,\n sources: map.sources.map((name, index) => (index === 0 ? file : name)),\n },\n };\n },\n\n async transform(code, id, transformOptions) {\n const [file] = id.split('?');\n // A file of server functions: the browser gets stubs that call the server instead.\n if (file && isScriptFile(file) && hasUseServer(code)) {\n try {\n const fileId = serverFileId(normalizePath(file));\n // The server runs the file, with calls while a page renders sharing their results.\n if (transformOptions?.ssr) {\n return { code: serverModule(code, file, fileId), map: null };\n }\n // A DOM test imports the server code with the query, which Vite strips no types for.\n if (id.includes(SERVER_QUERY)) {\n const result = await transformWithOxc(serverModule(code, file, fileId), file, {\n lang: /\\.[cm]?ts$/.test(file) ? 'ts' : file.endsWith('.tsx') ? 'tsx' : 'jsx',\n sourcemap: true,\n });\n return { code: result.code, map: result.map };\n }\n return { code: serverStubs(code, file, fileId, !isServe), map: null };\n } catch (error) {\n this.error((error as Error).message);\n }\n }\n // The shared module of a module of reactive logic is TypeScript too, under a query\n // that Vite does not strip types for.\n const shared = isReactiveModule(file ?? '') && id.endsWith(SHARED_QUERY);\n if (!file?.endsWith('.brm') && !shared) {\n return undefined;\n }\n const result = await transformWithOxc(code, `${file}.ts`, { lang: 'ts', sourcemap: true });\n return { code: result.code, map: result.map };\n },\n\n configureServer(server) {\n // Vite watches the root. An edit of a linked package, such as one of a workspace, updates the page too.\n const linked = packages.filter((item) => item.linked).flatMap((item) => item.directories);\n if (linked.length > 0) {\n server.watcher.add(linked);\n }\n // A change to the dependencies of the app, or to a package's `brumate` field, can change\n // the packages, and with them the config of Vite, so the server restarts.\n const manifests = [\n path.join(root, 'package.json'),\n ...packages.map((item) => `${item.root}/package.json`),\n ].map((file) => normalizePath(file));\n server.watcher.add(manifests);\n server.watcher.on('change', (file) => {\n if (\n manifests.includes(normalizePath(file)) &&\n packagesKey(findPackages(root)) !== packagesKey(packages)\n ) {\n void server.restart();\n }\n });\n server.watcher.on('all', (event, file) => {\n // A stylesheet that a component imports compiles into that component.\n for (const importer of dependents.get(normalizePath(file)) ?? []) {\n compiled.delete(importer);\n for (const module of server.moduleGraph.getModulesByFile(importer) ?? []) {\n server.moduleGraph.invalidateModule(module);\n }\n }\n // A new or removed endpoint or middleware changes the routes.\n if (\n file.endsWith('.ts') &&\n normalizePath(file).startsWith(`${routesDirectory()}/`) &&\n (event === 'add' || event === 'unlink')\n ) {\n for (const module of server.moduleGraph.idToModuleMap.values()) {\n if (module.id === `\\0${ROUTES}`) {\n server.moduleGraph.invalidateModule(module);\n }\n }\n writeRouteTypes();\n }\n // A file that becomes, or stops being, a file of server functions changes the registry.\n if (isScriptFile(file)) {\n const normalized = normalizePath(file);\n if (packages.length > 0 && !packageOf(packages, normalized)) {\n appScripts = appScripts.filter((item) => item !== normalized);\n if (event !== 'unlink') {\n appScripts.push(normalized);\n }\n }\n const id = serverFileId(normalized);\n const before = serverFiles.has(id);\n const after =\n event !== 'unlink' && existsSync(file) && hasUseServer(readFileSync(file, 'utf8'));\n if (after) {\n serverFiles.set(id, normalized);\n } else {\n serverFiles.delete(id);\n }\n if (before !== after) {\n for (const module of server.moduleGraph.idToModuleMap.values()) {\n if (module.id === `\\0${SERVER}` || module.id === `\\0${ROUTES}`) {\n server.moduleGraph.invalidateModule(module);\n }\n }\n }\n }\n // A changed component is handled by `handleHotUpdate`, which updates the page in place when it can.\n if (!file.endsWith('.brm') || event === 'change') {\n return;\n }\n void scan()\n .then(writeRouteTypes)\n .then(() => {\n for (const module of server.moduleGraph.idToModuleMap.values()) {\n const id = module.id ?? '';\n if (\n id.includes('.brm') ||\n id === `\\0${MANIFEST}` ||\n id === `\\0${SERVER}` ||\n id === `\\0${ROUTES}`\n ) {\n server.moduleGraph.invalidateModule(module);\n }\n }\n });\n });\n server.middlewares.use((request, response, next) => {\n // When the server code runs in Vite, the plugin answers calls with it. A framework that\n // runs it elsewhere, such as Nitro in a worker, answers them in its own server entry.\n const ssr = server.environments.ssr;\n if (\n request.method === 'POST' &&\n request.url?.startsWith(`${rpc}/`) &&\n ssr &&\n isRunnableDevEnvironment(ssr)\n ) {\n void handleDevRPC(server, request, response);\n return;\n }\n if (request.method === 'GET' && request.url?.startsWith(`${INSPECT}/`)) {\n void inspectComponent(decodeURIComponent(request.url.slice(INSPECT.length + 1)))\n .then((info) => {\n response.statusCode = info ? 200 : 404;\n response.setHeader('content-type', 'application/json');\n response.end(JSON.stringify(info ?? { error: 'Unknown component' }));\n })\n .catch(next);\n return;\n }\n next();\n });\n },\n\n // A server environment that runs apart from Vite, such as Nitro's worker, keeps the code\n // of components it loaded. A change to a component or to a file that one reads, such as\n // a stylesheet, reloads its server code, so the next render uses the new code.\n async hotUpdate({ file, server, timestamp }) {\n const environment = this.environment;\n if (environment.config.consumer === 'client') {\n return updateClient(file, server, timestamp);\n }\n const normalized = normalizePath(file);\n if (!file.endsWith('.brm') && !dependents.has(normalized)) {\n return undefined;\n }\n const invalidated = new Set<EnvironmentModuleNode>();\n for (const module of environment.moduleGraph.idToModuleMap.values()) {\n const id = module.id ?? '';\n if (id.includes('.brm') || id.startsWith('\\0virtual:brumate')) {\n environment.moduleGraph.invalidateModule(module, invalidated, timestamp, true);\n }\n }\n environment.hot.send({ type: 'full-reload' });\n return [];\n },\n };\n return plugin;\n}\nexport { errorPage } from './dev-error.ts';\nexport type {\n ManifestChunk,\n PrerenderManifest,\n PrerenderOptions,\n PrerenderedPage,\n} from './prerender.ts';\nexport type { Budget, BuildReport } from './report.ts';\n"],"mappings":";;;;;;;;;;AAoCA,MAAM,WAAW,SAAyB,KAAK,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG;AAEvE,SAAS,SAAS,MAAuC;CACvD,IAAI;EACF,OAAO,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;CAC9C,QAAQ;EACN;CACF;AACF;;AAGA,SAAgB,qBAAqB,MAAc,MAAkC;CACnF,KAAK,IAAI,YAAY,OAAQ,YAAY,KAAK,QAAQ,SAAS,GAAG;EAChE,MAAM,YAAY,KAAK,KAAK,WAAW,gBAAgB,IAAI;EAC3D,IAAI,WAAW,KAAK,KAAK,WAAW,cAAc,CAAC,GACjD,OAAO,QAAQ,aAAa,SAAS,CAAC;EAExC,IAAI,KAAK,QAAQ,SAAS,MAAM,WAC9B;CAEJ;AACF;;AAGA,SAAS,YAAY,WAAuC;CAC1D,KAAK,IAAI,UAAU,YAAa,UAAU,KAAK,QAAQ,OAAO,GAAG;EAC/D,IAAI,WAAW,KAAK,KAAK,SAAS,cAAc,CAAC,GAC/C,OAAO;EAET,IAAI,KAAK,QAAQ,OAAO,MAAM,SAC5B;CAEJ;AACF;;AAMA,SAAS,cAAc,MAAc,OAAgB,MAAoC;CACvF,IAAI,UAAU,MACZ,OAAO,CAAC,IAAI;CAEd,IAAI,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json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "brumate",
|
|
3
|
-
"version": "0.0
|
|
3
|
+
"version": "0.1.0",
|
|
4
4
|
"description": "A component language and compiler for resumable web apps",
|
|
5
5
|
"homepage": "https://github.com/lxsmnsyc/brumate",
|
|
6
6
|
"bugs": "https://github.com/lxsmnsyc/brumate/issues",
|
|
@@ -36,6 +36,10 @@
|
|
|
36
36
|
"types": "./dist/runtime/loader.d.ts",
|
|
37
37
|
"default": "./dist/runtime/loader.js"
|
|
38
38
|
},
|
|
39
|
+
"./static-loader": {
|
|
40
|
+
"types": "./dist/runtime/static-loader.d.ts",
|
|
41
|
+
"default": "./dist/runtime/static-loader.js"
|
|
42
|
+
},
|
|
39
43
|
"./vite": {
|
|
40
44
|
"types": "./dist/vite.d.ts",
|
|
41
45
|
"default": "./dist/vite.js"
|
|
@@ -80,7 +84,7 @@
|
|
|
80
84
|
"oxc-parser": "^0.154.0",
|
|
81
85
|
"postcss": "^8.5.31",
|
|
82
86
|
"postcss-selector-parser": "^7.1.6",
|
|
83
|
-
"seroval": "^1.
|
|
87
|
+
"seroval": "^1.7.0"
|
|
84
88
|
},
|
|
85
89
|
"devDependencies": {
|
|
86
90
|
"@oxc-project/types": "^0.154.0",
|
|
@@ -90,6 +94,7 @@
|
|
|
90
94
|
"sass": "^1.105.2",
|
|
91
95
|
"tsdown": "^0.23.1",
|
|
92
96
|
"typescript": "^7.0.2",
|
|
97
|
+
"valibot": "^1.5.0",
|
|
93
98
|
"vite": "^8.3.4",
|
|
94
99
|
"vitest": "^5.0.4"
|
|
95
100
|
},
|
package/types.d.ts
CHANGED
|
@@ -7,6 +7,11 @@ declare module '*.brm?brumate-server' {
|
|
|
7
7
|
|
|
8
8
|
declare module 'virtual:brumate/testing' {
|
|
9
9
|
export const mount: import('brumate/testing').Mount;
|
|
10
|
+
/**
|
|
11
|
+
* Answers the server function calls of the page with the server code of
|
|
12
|
+
* the app, until the returned function restores `fetch`.
|
|
13
|
+
*/
|
|
14
|
+
export function answerCalls(options?: import('brumate/testing').AnswerOptions): () => void;
|
|
10
15
|
}
|
|
11
16
|
|
|
12
17
|
declare module '*.brm' {
|