brumate 0.4.0 → 0.4.2

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.
Files changed (62) hide show
  1. package/dist/{boot-DLlRmD9z.d.ts → boot-D3NjfyUX.d.ts} +2 -2
  2. package/dist/cli.js +2 -2
  3. package/dist/{client-BvDsC6Qr.js → client-Cwr2AfP4.js} +133 -35
  4. package/dist/client-Cwr2AfP4.js.map +1 -0
  5. package/dist/{client-DBwL2wKQ.d.ts → client-DNva05jp.d.ts} +20 -7
  6. package/dist/{defer-CKWZLv2K.js → defer-CxjvJXD_.js} +2 -2
  7. package/dist/{defer-CKWZLv2K.js.map → defer-CxjvJXD_.js.map} +1 -1
  8. package/dist/{devtools-4uTPwR_v.js → devtools-BdB_9WB8.js} +4 -4
  9. package/dist/{devtools-4uTPwR_v.js.map → devtools-BdB_9WB8.js.map} +1 -1
  10. package/dist/{devtools-panel-Be9pxYgv.js → devtools-panel-Bp6LE4nM.js} +2 -2
  11. package/dist/{devtools-panel-Be9pxYgv.js.map → devtools-panel-Bp6LE4nM.js.map} +1 -1
  12. package/dist/{files-WW4RlajL.js → files-BzVNgGOL.js} +2 -2
  13. package/dist/{files-WW4RlajL.js.map → files-BzVNgGOL.js.map} +1 -1
  14. package/dist/{html-BtKRyi7g.js → html-t1JpkODI.js} +15 -7
  15. package/dist/html-t1JpkODI.js.map +1 -0
  16. package/dist/index.d.ts +7 -1
  17. package/dist/index.js +1 -1
  18. package/dist/{inspect-Y6y4uNZp.js → inspect-DaZtoKgg.js} +290 -70
  19. package/dist/inspect-DaZtoKgg.js.map +1 -0
  20. package/dist/{loader-BjKGJzLN.js → loader-BX8uIUav.js} +2 -2
  21. package/dist/{loader-BjKGJzLN.js.map → loader-BX8uIUav.js.map} +1 -1
  22. package/dist/produce-CLABZ8k2.d.ts +11 -0
  23. package/dist/{produce-B7X9ori9.js → produce-DS-dQaUX.js} +5 -3
  24. package/dist/produce-DS-dQaUX.js.map +1 -0
  25. package/dist/{rpc-Q-XkLwFh.js → rpc-t5M5dqs9.js} +3 -3
  26. package/dist/{rpc-Q-XkLwFh.js.map → rpc-t5M5dqs9.js.map} +1 -1
  27. package/dist/runtime/client.d.ts +4 -4
  28. package/dist/runtime/client.js +4 -4
  29. package/dist/runtime/devtools.d.ts +2 -2
  30. package/dist/runtime/devtools.js +1 -1
  31. package/dist/runtime/hot.d.ts +1 -1
  32. package/dist/runtime/html.d.ts +2 -2
  33. package/dist/runtime/html.js +1 -1
  34. package/dist/runtime/loader.d.ts +2 -2
  35. package/dist/runtime/loader.js +2 -2
  36. package/dist/runtime/server.d.ts +3 -3
  37. package/dist/runtime/server.js +3 -3
  38. package/dist/runtime/static-loader.d.ts +2 -2
  39. package/dist/runtime/static-loader.js +1 -1
  40. package/dist/runtime/testing.d.ts +2 -2
  41. package/dist/runtime/testing.js +2 -2
  42. package/dist/{server-BvPIg9pT.d.ts → server-BXMH3Z9T.d.ts} +23 -3
  43. package/dist/{server-DjyOVJtJ.js → server-C6c-GXF4.js} +54 -16
  44. package/dist/server-C6c-GXF4.js.map +1 -0
  45. package/dist/shared-CzbnWkVA.d.ts +255 -0
  46. package/dist/{static-loader-BGgdp_Y5.d.ts → static-loader-BiUaZaag.d.ts} +2 -2
  47. package/dist/{static-loader-BZR17hSw.js → static-loader-CqQRu-p9.js} +4 -3
  48. package/dist/{static-loader-BZR17hSw.js.map → static-loader-CqQRu-p9.js.map} +1 -1
  49. package/dist/{stream-BP5AVmg5.js → stream-CqhuQJwK.js} +4 -4
  50. package/dist/stream-CqhuQJwK.js.map +1 -0
  51. package/dist/vite.d.ts +1 -1
  52. package/dist/vite.js +72 -12
  53. package/dist/vite.js.map +1 -1
  54. package/package.json +1 -1
  55. package/dist/client-BvDsC6Qr.js.map +0 -1
  56. package/dist/html-BtKRyi7g.js.map +0 -1
  57. package/dist/html-Bw9Qwu6F.d.ts +0 -107
  58. package/dist/inspect-Y6y4uNZp.js.map +0 -1
  59. package/dist/produce-B7X9ori9.js.map +0 -1
  60. package/dist/produce-DIgHBVwL.d.ts +0 -148
  61. package/dist/server-DjyOVJtJ.js.map +0 -1
  62. package/dist/stream-BP5AVmg5.js.map +0 -1
package/dist/vite.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"vite.js","names":["viteVersion","parseComponent","viteVersion"],"sources":["../src/env-file.ts","../src/features.ts","../src/builds.ts","../src/version.ts","../src/dev-error.ts","../src/workbench-page.ts","../src/workbench.ts","../src/prerender.ts","../src/report.ts","../src/routes.ts","../src/vite.ts"],"sourcesContent":["// The file of environment variables, `src/env.ts`, which calls `defineEnv`\n// from `brumate/env` with the schemas of the server and the public\n// variables. The compiler reads which variables are server values, and the\n// Vite plugin writes the copy of the file that the browser gets: without the\n// server schemas, and with the values of the public variables.\n\nimport { parseSync } from 'oxc-parser';\nimport type { oxc } from './oxc.ts';\n\n/** The name of the function that declares the variables. */\nconst DEFINE = 'defineEnv';\n\nexport interface EnvFile {\n /** The names of the server variables. */\n server: string[];\n /** The names of the public variables. */\n public: string[];\n /** The range of the `server: { … }` property, with its comma, or undefined without one. */\n serverRange?: { start: number; end: number };\n /** The end of the first argument of `defineEnv`, where the options go. */\n schemaEnd: number;\n /** True if the call has options already. */\n hasOptions: boolean;\n}\n\n/** The names of the properties of an object literal. Other keys throw. */\nfunction readKeys(node: oxc.Node, group: string, filename: string): string[] {\n if (node.type !== 'ObjectExpression') {\n throw new Error(\n `The ${group} variables of ${filename} must be an object literal, so the compiler can read their names`,\n );\n }\n const keys: string[] = [];\n for (const property of node.properties) {\n if (property.type === 'Property' && !property.computed) {\n keys.push(\n property.key.type === 'Identifier'\n ? property.key.name\n : String((property.key as { value?: unknown }).value),\n );\n continue;\n }\n throw new Error(\n `The ${group} variables of ${filename} must be plain properties, so the compiler can read their names`,\n );\n }\n return keys;\n}\n\n/** Finds the `defineEnv` call of the file. */\nfunction findCall(program: oxc.Program): oxc.CallExpression | undefined {\n let found: oxc.CallExpression | undefined;\n function visit(node: unknown): void {\n if (found || typeof node !== 'object' || node === null) {\n return;\n }\n const value = node as oxc.Node & { callee?: oxc.Node & { name?: string } };\n if (value.type === 'CallExpression' && value.callee?.name === DEFINE) {\n found = value as oxc.CallExpression;\n return;\n }\n for (const child of Object.values(value)) {\n if (Array.isArray(child)) {\n for (const item of child) {\n visit(item);\n }\n } else if (typeof child === 'object') {\n visit(child);\n }\n }\n }\n visit(program);\n return found;\n}\n\n/**\n * Reads the variables that a file of environment variables declares. The\n * schemas are written in the call, as object literals, so their names can\n * be read without running the file.\n */\nexport function parseEnvFile(source: string, filename: string): EnvFile {\n const { program, errors } = parseSync(filename, source, { lang: 'ts' });\n if (errors[0]) {\n throw new Error(`${errors[0].message} (${filename})`);\n }\n const call = findCall(program);\n const schema = call?.arguments[0];\n if (!call || schema?.type !== 'ObjectExpression') {\n throw new Error(\n `${filename} must call ${DEFINE} with an object literal of server and public variables`,\n );\n }\n const result: EnvFile = {\n server: [],\n public: [],\n schemaEnd: schema.end,\n hasOptions: call.arguments.length > 1,\n };\n for (const [index, property] of schema.properties.entries()) {\n if (property.type !== 'Property' || property.computed || property.key.type !== 'Identifier') {\n throw new Error(`${DEFINE} in ${filename} takes server and public variables only`);\n }\n const group = property.key.name;\n if (group !== 'server' && group !== 'public') {\n throw new Error(`${DEFINE} in ${filename} takes server and public variables, not ${group}`);\n }\n result[group] = readKeys(property.value, group, filename);\n if (group === 'server') {\n // The property with its comma, so the browser's copy stays valid code.\n const next = schema.properties[index + 1];\n const comma = source.indexOf(',', property.end);\n let end = property.end;\n if (next) {\n end = next.start;\n } else if (comma !== -1 && comma < schema.end) {\n end = comma + 1;\n }\n result.serverRange = { start: property.start, end };\n }\n }\n return result;\n}\n\n/**\n * The copy of the file that the browser gets: the server schemas are gone,\n * and the values of the public variables, read when the build or the dev\n * server ran, are the source of the call. The public schemas check them in\n * the browser, as the server's do on the server.\n */\nexport function clientEnvModule(\n source: string,\n filename: string,\n values: Record<string, string | undefined>,\n): string {\n const file = parseEnvFile(source, filename);\n if (file.hasOptions) {\n throw new Error(\n `${DEFINE} in ${filename} takes no options, because the Vite plugin writes the values of the browser`,\n );\n }\n const given: Record<string, string> = {};\n for (const name of file.public) {\n const value = values[name];\n if (value !== undefined) {\n given[name] = value;\n }\n }\n const edits: { start: number; end: number; text: string }[] = [\n { start: file.schemaEnd, end: file.schemaEnd, text: `, { source: ${JSON.stringify(given)} }` },\n ];\n if (file.serverRange) {\n edits.push({ ...file.serverRange, text: '' });\n }\n let result = '';\n let position = 0;\n for (const edit of edits.toSorted((a, b) => a.start - b.start)) {\n result += source.slice(position, edit.start) + edit.text;\n position = edit.end;\n }\n return result + source.slice(position);\n}\n","// The features of the core that a compiled component uses. The Vite plugin turns off, in the\n// client build of an app, the features that none of its components use. See\n// `runtime/features.ts`.\nimport type { CompileResult } from './compile.ts';\n\nexport interface Features {\n /** Children that the browser renders with an export of their own. */\n children: boolean;\n /** `#template` values that the browser calls. */\n templates: boolean;\n /** `<title>` elements in markup. */\n titles: boolean;\n /** `$bind` that a component passes to another. */\n bindings: boolean;\n /** Markup that comes after the page: `#loading`, `#defer` and lists that stream. */\n lateMarkup: boolean;\n /** `$client` callbacks and `#defer` blocks. */\n blocks: boolean;\n /** Handlers of the window or the document. */\n listeners: boolean;\n /** Forms of an `$action`. */\n actions: boolean;\n /** Markup that the browser renders as HTML, not as a clone of a template. */\n clientHTML: boolean;\n}\n\n/** No feature at all, which a build that has no component uses. */\nexport function noFeatures(): Features {\n return {\n children: false,\n templates: false,\n titles: false,\n bindings: false,\n lateMarkup: false,\n blocks: false,\n listeners: false,\n actions: false,\n clientHTML: false,\n };\n}\n\n/** Every feature, for a build that compiles components in the browser. */\nexport function allFeatures(): Features {\n const all = noFeatures();\n for (const name of Object.keys(all) as (keyof Features)[]) {\n all[name] = true;\n }\n return all;\n}\n\n/** The features of the core that a compiled component uses. */\nexport function getFeatures(result: CompileResult): Features {\n const client = [result.client, result.render, ...Object.values(result.parts)].join('\\n');\n // A `#client` body has no markup on the server, so its titles, listeners and forms are only in\n // the code of the browser.\n const all = `${result.server}\\n${client}`;\n return {\n // The server sends a reference to the export that renders them, or the browser makes them.\n children: result.plan.childrenRenders.size > 0 || /\\$\\$b\\.children\\(/.test(client),\n // A template that the browser can call has an export of its own, `t` and a number.\n templates: /\\bexport (?:const|function) t\\d+\\b/.test(client),\n titles: /\\bb-t\\b/.test(all),\n bindings: /\\$\\$b\\.binding\\(/.test(all),\n lateMarkup: /\\$\\$ctx\\.(?:boundary|defer|deferBlock)\\(|\\bgather\\(/.test(result.server),\n blocks: /\\bb-(?:client|defer)\\b/.test(all),\n listeners: /\\bb-listen\\b/.test(all),\n actions: /\\$\\$b\\.action\\(/.test(all),\n // A render function that gives HTML. One with no markup gives an empty string.\n clientHTML: /\\breturn \\$\\$html;/.test(client),\n };\n}\n\n/** The features of several components together. */\nexport function joinFeatures(all: Features[]): Features {\n const joined = noFeatures();\n for (const features of all) {\n joined.children ||= features.children;\n joined.templates ||= features.templates;\n joined.titles ||= features.titles;\n joined.bindings ||= features.bindings;\n joined.lateMarkup ||= features.lateMarkup;\n joined.blocks ||= features.blocks;\n joined.listeners ||= features.listeners;\n joined.actions ||= features.actions;\n joined.clientHTML ||= features.clientHTML;\n }\n return joined;\n}\n\n/** The names of the globals of `runtime/features.ts`, by feature. */\nconst GLOBALS: Record<keyof Features, string> = {\n children: '__BRUMATE_HAS_CHILDREN__',\n templates: '__BRUMATE_HAS_TEMPLATES__',\n titles: '__BRUMATE_HAS_TITLES__',\n bindings: '__BRUMATE_HAS_BINDINGS__',\n lateMarkup: '__BRUMATE_HAS_LATE_MARKUP__',\n blocks: '__BRUMATE_HAS_BLOCKS__',\n listeners: '__BRUMATE_HAS_LISTENERS__',\n actions: '__BRUMATE_HAS_ACTIONS__',\n clientHTML: '__BRUMATE_HAS_CLIENT_HTML__',\n};\n\n/** True for code that reads a feature, such as the core. */\nexport function readsFeatures(code: string): boolean {\n return code.includes('__BRUMATE_HAS_');\n}\n\n/** The code with each feature written in as `true` or `false`. */\nexport function writeFeatures(code: string, features: Features): string {\n let result = code;\n for (const [name, global] of Object.entries(GLOBALS)) {\n // The TypeScript source declares each global, and the declaration stays.\n result = result.replace(\n new RegExp(`(?<!declare const )\\\\b${global}\\\\b`, 'g'),\n String(features[name as keyof Features]),\n );\n }\n return result;\n}\n","// The builds of the client, for skew protection. Each build has an ID, which\n// the client build writes to `.brumate/build.json` and the server build\n// reads. `.brumate/builds.json` lists the last builds with their files, so\n// the files of earlier builds can stay for the pages that are still open,\n// and go when they are old enough.\n\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\n\n/** The file in the client build that names its build. */\nexport const BUILD_FILE = '.brumate/build.json';\n/** The file in the client build that lists the builds whose files are in it. */\nexport const BUILDS_FILE = '.brumate/builds.json';\n\ninterface BuildEntry {\n id: string;\n /** When the build ran, as milliseconds since the epoch. */\n at: number;\n /** The files that the build wrote, relative to the output directory. */\n files: string[];\n}\n\n/** The directory of the client build, from the root and the prerender options. */\nexport function clientBuildDirectory(\n root: string,\n prerender: boolean | { client?: string } | undefined,\n): string {\n const client = typeof prerender === 'object' ? prerender.client : undefined;\n return path.resolve(root, client ?? 'dist/client');\n}\n\n/** The ID of the build in a client build directory, or undefined without one. */\nexport function readBuildId(directory: string): string | undefined {\n const file = path.join(directory, BUILD_FILE);\n if (!existsSync(file)) {\n return undefined;\n }\n try {\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as { build?: unknown };\n return typeof parsed.build === 'string' ? parsed.build : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Writes the ID of a build to its client output, adds the build to the list\n * of builds, and removes the files of builds older than the `keep` builds\n * before this one, unless a kept build wrote the same file. Returns the IDs\n * of the builds whose files went.\n */\nexport function pruneBuilds(\n directory: string,\n id: string,\n files: string[],\n keep: number,\n now: number = Date.now(),\n): string[] {\n const list = path.join(directory, BUILDS_FILE);\n let builds: BuildEntry[] = [];\n if (existsSync(list)) {\n try {\n builds = (JSON.parse(readFileSync(list, 'utf8')) as { builds?: BuildEntry[] }).builds ?? [];\n } catch {\n builds = [];\n }\n }\n const others: BuildEntry[] = [];\n for (const build of builds) {\n if (build.id !== id) {\n others.push(build);\n }\n }\n builds = others;\n builds.push({ id, at: now, files });\n builds.sort((a, b) => a.at - b.at);\n const kept = builds.slice(Math.max(0, builds.length - 1 - keep));\n const dropped = builds.slice(0, builds.length - kept.length);\n const keptFiles = new Set<string>();\n for (const build of kept) {\n for (const file of build.files) {\n keptFiles.add(file);\n }\n }\n for (const build of dropped) {\n for (const file of build.files) {\n if (!keptFiles.has(file)) {\n rmSync(path.join(directory, file), { force: true });\n }\n }\n }\n mkdirSync(path.join(directory, '.brumate'), { recursive: true });\n writeFileSync(path.join(directory, BUILD_FILE), `${JSON.stringify({ build: id })}\\n`);\n writeFileSync(list, `${JSON.stringify({ builds: kept }, null, 2)}\\n`);\n const droppedIds: string[] = [];\n for (const build of dropped) {\n droppedIds.push(build.id);\n }\n return droppedIds;\n}\n","import { readFileSync } from 'node:fs';\n\n/** The version of brumate, which the devtools show. `package.json` is next to `src` and `dist`. */\nexport const BRUMATE_VERSION: string = (\n JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as {\n version: string;\n }\n).version;\n","// An error while the dev server renders a page, shown in Vite's error overlay.\n\nimport { resolve } from 'node:path';\nimport { version as viteVersion } from 'vite';\nimport type { ViteDevServer } from 'vite';\nimport { BRUMATE_VERSION } from './version.ts';\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 const meta = JSON.stringify({ version: BRUMATE_VERSION, vite: viteVersion });\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};\n// The Errors tab of the devtools shows the error with its code. Vite's overlay is the fallback.\ntry {\n const devtools = await import('${base}@id/brumate/devtools');\n devtools.reportError(devtools.installDevtools(undefined, undefined, ${meta}), error, 'server');\n} catch {\n const Overlay = customElements.get('vite-error-overlay');\n if (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}\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","import { LOGO } from './runtime/logo.ts';\n\n// The page of the workbench in the dev server. The sidebar lists the components that depend\n// only on their props, and apart the ones that need more, with why. The canvas renders the\n// picked component in a frame, on the server and resumed in the browser, as a page does, and\n// the panel on the right has the controls of its props. The colors are those of the devtools.\n\n/** The HTML of the workbench page. `base` is the path of the workbench, such as `/__brumate/workbench`. */\nexport function workbenchPage(base: string): string {\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Workbench · brumate</title>\n<link rel=\"icon\" type=\"image/svg+xml\" href=\"data:image/svg+xml,${encodeURIComponent(LOGO.replace('<svg ', '<svg xmlns=\"http://www.w3.org/2000/svg\" '))}\">\n<style>\n :root {\n --bg: #121113; --surface: #19181a; --raised: #222023; --hover: #2a282c; --line: #2f2c31;\n --text: #ece8e4; --dim: #a39a92; --faint: #6f6862; --accent: #ee7a3e; --accent-soft: #ee7a3e22;\n --blue: #7cb7ff; --purple: #c49bff; --green: #7fd99a; --yellow: #ffd166; --red: #ff7a7a;\n --mono: ui-monospace, SFMono-Regular, Menlo, monospace;\n color-scheme: dark;\n }\n * { box-sizing: border-box; }\n [hidden] { display: none !important; }\n html, body { height: 100%; }\n body {\n margin: 0; display: grid; grid-template-columns: 260px minmax(0, 1fr) 300px;\n background: var(--bg); color: var(--text); font: 13px/1.45 system-ui, -apple-system, sans-serif;\n }\n body.no-props { grid-template-columns: 260px minmax(0, 1fr); }\n body.no-props #props { display: none; }\n button, input, select, textarea { font: inherit; color: inherit; }\n button:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible {\n outline: 2px solid var(--accent); outline-offset: 1px;\n }\n .mono { font-family: var(--mono); }\n\n /* Sidebar */\n #sidebar { display: flex; flex-direction: column; min-height: 0; border-right: 1px solid var(--line); background: var(--surface); }\n .brand { display: flex; align-items: center; gap: 10px; padding: 16px 16px 12px; }\n .brand .logo { display: block; width: 22px; height: 22px; }\n .brand strong { font-size: 14px; }\n .brand span { margin-left: auto; color: var(--faint); font-size: 12px; }\n .search { margin: 0 12px 8px; position: relative; }\n .search input {\n width: 100%; padding: 7px 10px 7px 30px; border: 1px solid var(--line); border-radius: 8px;\n background: var(--bg);\n }\n .search svg { position: absolute; left: 10px; top: 50%; transform: translateY(-50%); color: var(--faint); }\n #tree { flex: 1; overflow: auto; padding: 4px 8px 16px; }\n .group { margin-top: 10px; }\n .group-head {\n display: flex; align-items: center; gap: 6px; padding: 4px 8px; color: var(--faint);\n font-size: 11px; font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase;\n }\n .group-head .count { margin-left: auto; font-weight: 500; }\n .item {\n display: flex; align-items: center; gap: 8px; width: 100%; padding: 6px 8px; border: 0; border-radius: 6px;\n background: none; text-align: left; cursor: pointer;\n }\n .item:hover { background: var(--hover); }\n .item[aria-current=\"true\"] { background: var(--accent-soft); box-shadow: inset 2px 0 0 var(--accent); }\n .item[aria-current=\"true\"] .label { color: #ffb48a; font-weight: 600; }\n .item .glyph { flex: none; width: 16px; height: 16px; color: var(--faint); }\n .item[aria-current=\"true\"] .glyph { color: var(--accent); }\n .item .label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n .item .meta { margin-left: auto; color: var(--faint); font-size: 11px; white-space: nowrap; }\n .env .item .label { color: var(--dim); }\n .env .group-head { cursor: pointer; }\n .env .group-head .chev { transition: transform 0.15s; }\n .env.closed .group-head .chev { transform: rotate(-90deg); }\n .env.closed .items { display: none; }\n .kinds { display: flex; gap: 3px; margin-left: auto; }\n .dot { width: 7px; height: 7px; border-radius: 50%; }\n .note { padding: 6px 8px; color: var(--faint); font-size: 12px; }\n\n /* Kinds of needs */\n .k-server { --k: var(--blue); } .k-request { --k: var(--purple); } .k-route { --k: var(--green); }\n .k-action { --k: var(--red); } .k-defer { --k: var(--accent); }\n .k-dynamic { --k: var(--dim); } .k-component { --k: var(--faint); }\n .dot { background: var(--k); }\n .tag {\n display: inline-flex; align-items: center; gap: 6px; padding: 2px 8px; border-radius: 999px;\n background: color-mix(in srgb, var(--k) 16%, transparent); color: var(--k); font-size: 11px; font-weight: 600;\n }\n\n /* Canvas */\n #main { display: grid; grid-template-rows: auto minmax(0, 1fr); min-width: 0; }\n .toolbar {\n display: flex; align-items: center; gap: 10px; min-height: 52px; padding: 8px 16px;\n border-bottom: 1px solid var(--line); background: var(--surface);\n }\n .title { display: flex; align-items: baseline; gap: 10px; min-width: 0; }\n .title h1 { margin: 0; font-size: 15px; font-weight: 650; white-space: nowrap; }\n .title button { padding: 0; border: 0; background: none; color: var(--faint); font: 12px var(--mono); cursor: pointer;\n overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n .title button:hover { color: var(--blue); text-decoration: underline; }\n .tools { display: flex; align-items: center; gap: 6px; margin-left: auto; }\n .segment { display: flex; padding: 2px; border: 1px solid var(--line); border-radius: 8px; background: var(--bg); }\n .segment button, .tool {\n display: grid; place-items: center; height: 26px; min-width: 28px; padding: 0 8px; border: 0; border-radius: 6px;\n background: none; color: var(--dim); cursor: pointer;\n }\n .segment button[aria-pressed=\"true\"] { background: var(--raised); color: var(--text); }\n .tool { border: 1px solid var(--line); background: var(--bg); }\n .tool:hover, .segment button:hover { color: var(--text); }\n .canvas { position: relative; display: grid; place-items: center; overflow: auto; padding: 24px; }\n .canvas.dots { background: radial-gradient(circle, #ffffff14 1px, transparent 1px) 0 0 / 16px 16px, var(--bg); }\n .canvas.light { background: #f4f1ec; }\n .canvas.dark { background: #0b0a0b; }\n .device {\n width: 100%; height: 100%; border: 1px solid var(--line); border-radius: 10px; overflow: hidden;\n background: #fff; box-shadow: 0 12px 40px #0006; transition: width 0.2s, height 0.2s;\n }\n .device iframe { display: block; width: 100%; height: 100%; border: 0; background: #fff; }\n .size { position: absolute; right: 16px; bottom: 10px; color: var(--faint); font: 11px var(--mono); }\n\n /* Cards on the canvas: the start, and a component that needs the environment */\n .card {\n width: min(520px, 100%); padding: 24px 26px; border: 1px solid var(--line); border-radius: 14px; background: var(--surface);\n }\n .card .eyebrow { color: var(--accent); font-size: 12px; font-weight: 600; }\n .card h2 { margin: 6px 0 8px; font-size: 18px; }\n .card p { margin: 0 0 14px; color: var(--dim); }\n .needs { display: grid; gap: 8px; margin: 0 0 16px; padding: 0; list-style: none; }\n .needs li { display: grid; grid-template-columns: auto 1fr; gap: 4px 12px; align-items: baseline;\n padding: 10px 12px; border-radius: 10px; background: var(--raised); }\n .needs .what { font-family: var(--mono); }\n .needs .via { grid-column: 2; color: var(--faint); font-size: 12px; }\n .hint { padding: 10px 12px; border-left: 2px solid var(--accent); border-radius: 0 8px 8px 0; background: var(--accent-soft);\n color: var(--dim); font-size: 12px; }\n .hint code { color: #ffb48a; }\n .stats { display: flex; gap: 18px; margin-top: 4px; }\n .stats div { color: var(--faint); font-size: 12px; }\n .stats strong { display: block; color: var(--text); font-size: 22px; font-weight: 650; }\n\n /* Props */\n #props { display: flex; flex-direction: column; min-height: 0; border-left: 1px solid var(--line); background: var(--surface); }\n .panel-head { display: flex; align-items: center; gap: 8px; min-height: 52px; padding: 8px 16px; border-bottom: 1px solid var(--line); }\n .panel-head h2 { margin: 0; font-size: 13px; }\n .panel-head button { margin-left: auto; }\n #controls { flex: 1; overflow: auto; padding: 8px 0; }\n .prop { padding: 10px 16px; border-bottom: 1px solid #ffffff08; }\n .prop-head { display: flex; align-items: center; gap: 6px; margin-bottom: 6px; }\n .prop-head .name { color: #ffc28f; font-family: var(--mono); }\n .prop-head .req { color: var(--accent); }\n .prop-head .type { margin-left: auto; color: var(--faint); font: 11px var(--mono); }\n .prop-head .reset { padding: 0 4px; border: 0; background: none; color: var(--faint); cursor: pointer; visibility: hidden; }\n .prop.changed .reset { visibility: visible; }\n .prop-head .reset:hover { color: var(--text); }\n .prop input[type=\"text\"], .prop input[type=\"number\"], .prop select, .prop textarea {\n width: 100%; padding: 6px 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--bg);\n }\n .prop textarea { min-height: 76px; resize: vertical; font: 12px/1.5 var(--mono); }\n .prop .invalid { border-color: var(--red); }\n .error { margin-top: 4px; color: var(--red); font-size: 11px; }\n .switch { position: relative; display: inline-flex; align-items: center; gap: 8px; cursor: pointer; color: var(--dim); }\n .switch input { position: absolute; opacity: 0; }\n .switch span { width: 30px; height: 18px; border-radius: 999px; background: var(--raised); border: 1px solid var(--line); position: relative; transition: background 0.15s; }\n .switch span::after { content: ''; position: absolute; top: 2px; left: 2px; width: 12px; height: 12px; border-radius: 50%; background: var(--dim); transition: transform 0.15s; }\n .switch input:checked + span { background: var(--accent); border-color: var(--accent); }\n .switch input:checked + span::after { transform: translateX(12px); background: #fff; }\n .switch input:focus-visible + span { outline: 2px solid var(--accent); outline-offset: 1px; }\n .choices { display: flex; flex-wrap: wrap; gap: 4px; }\n .choices button { padding: 3px 9px; border: 1px solid var(--line); border-radius: 6px; background: var(--bg); color: var(--dim); cursor: pointer; font: 12px var(--mono); }\n .choices button[aria-pressed=\"true\"] { border-color: var(--accent); background: var(--accent-soft); color: #ffb48a; }\n .empty-props { padding: 16px; color: var(--faint); }\n .stories { padding: 12px 16px; border-bottom: 1px solid var(--line); }\n .stories-head { margin-bottom: 8px; color: var(--faint); font-size: 11px; font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase; }\n .stories .choices button { font-family: inherit; }\n .stories-error { color: var(--red); font-size: 12px; }\n .footer { padding: 10px 16px; border-top: 1px solid var(--line); color: var(--faint); font-size: 11px; }\n</style>\n</head>\n<body class=\"no-props\">\n<aside id=\"sidebar\">\n <div class=\"brand\"><span class=\"logo\">${LOGO}</span><strong>Workbench</strong><span id=\"total\"></span></div>\n <label class=\"search\">\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\"><circle cx=\"7\" cy=\"7\" r=\"5\" stroke=\"currentColor\" stroke-width=\"1.5\"/><path d=\"m11 11 3 3\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\"/></svg>\n <input id=\"filter\" type=\"search\" placeholder=\"Find a component\" aria-label=\"Find a component\">\n </label>\n <nav id=\"tree\" aria-label=\"Components\"></nav>\n</aside>\n<main id=\"main\">\n <div class=\"toolbar\">\n <div class=\"title\"><h1 id=\"name\">Workbench</h1><button id=\"file\" type=\"button\" title=\"Open in your editor\" hidden></button></div>\n <div class=\"tools\" id=\"tools\" hidden>\n <div class=\"segment\" role=\"group\" aria-label=\"Width\">\n <button type=\"button\" data-width=\"\" aria-pressed=\"true\" title=\"Fill the canvas\">Fill</button>\n <button type=\"button\" data-width=\"390\" title=\"Phone, 390 px\">390</button>\n <button type=\"button\" data-width=\"768\" title=\"Tablet, 768 px\">768</button>\n <button type=\"button\" data-width=\"1280\" title=\"Desktop, 1280 px\">1280</button>\n </div>\n <div class=\"segment\" role=\"group\" aria-label=\"Background\">\n <button type=\"button\" data-canvas=\"dots\" aria-pressed=\"true\" title=\"Dots\">Dots</button>\n <button type=\"button\" data-canvas=\"light\" title=\"Light\">Light</button>\n <button type=\"button\" data-canvas=\"dark\" title=\"Dark\">Dark</button>\n </div>\n <button class=\"tool\" id=\"reload\" type=\"button\" title=\"Render again\">\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\"><path d=\"M13.5 8a5.5 5.5 0 1 1-1.6-3.9M13.5 2.5v3h-3\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>\n </button>\n <a class=\"tool\" id=\"open\" target=\"_blank\" title=\"Open alone in a new tab\">\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\"><path d=\"M9 3h4v4M13 3 7.5 8.5M12 9.5V13H3V4h3.5\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>\n </a>\n </div>\n </div>\n <div class=\"canvas dots\" id=\"canvas\"></div>\n</main>\n<aside id=\"props\">\n <div class=\"panel-head\"><h2>Props</h2><button class=\"tool\" id=\"resetAll\" type=\"button\" title=\"Reset every prop\">Reset</button></div>\n <div id=\"stories\" class=\"stories\" hidden></div>\n <div id=\"controls\"></div>\n <div class=\"footer\">From the type of <span class=\"mono\">$props&lt;T&gt;()</span>. Function props have no control.</div>\n</aside>\n<script type=\"module\">\nconst base = ${JSON.stringify(base)};\nconst $ = (id) => document.getElementById(id);\nconst make = (tag, props = {}, ...children) => {\n const node = document.createElement(tag);\n for (const [key, value] of Object.entries(props)) {\n if (key === 'class') node.className = value;\n else if (key.startsWith('on')) node.addEventListener(key.slice(2), value);\n else if (value !== undefined && value !== false) node.setAttribute(key, value === true ? '' : value);\n }\n node.append(...children.filter((child) => child !== undefined && child !== null));\n return node;\n};\nconst svg = (markup) => {\n const holder = document.createElement('span');\n holder.innerHTML = markup;\n return holder.firstChild;\n};\nconst COMPONENT = '<svg class=\"glyph\" viewBox=\"0 0 16 16\" fill=\"none\"><rect x=\"2.5\" y=\"2.5\" width=\"11\" height=\"11\" rx=\"3\" stroke=\"currentColor\" stroke-width=\"1.4\"/><path d=\"M5.5 8h5\" stroke=\"currentColor\" stroke-width=\"1.4\" stroke-linecap=\"round\"/></svg>';\nconst LOCKED = '<svg class=\"glyph\" viewBox=\"0 0 16 16\" fill=\"none\"><rect x=\"3\" y=\"7\" width=\"10\" height=\"7\" rx=\"2\" stroke=\"currentColor\" stroke-width=\"1.4\"/><path d=\"M5.5 7V5a2.5 2.5 0 0 1 5 0v2\" stroke=\"currentColor\" stroke-width=\"1.4\"/></svg>';\nconst FOLDER = '<svg width=\"12\" height=\"12\" viewBox=\"0 0 16 16\" fill=\"none\"><path d=\"M2 4.5A1.5 1.5 0 0 1 3.5 3h3l1.5 1.5h4.5A1.5 1.5 0 0 1 14 6v5.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 11.5z\" stroke=\"currentColor\" stroke-width=\"1.4\"/></svg>';\nconst CHEVRON = '<svg class=\"chev\" width=\"10\" height=\"10\" viewBox=\"0 0 16 16\" fill=\"none\"><path d=\"m4 6 4 4 4-4\" stroke=\"currentColor\" stroke-width=\"1.6\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>';\n\n// What each kind of need is, in words, for the tags and the card.\nconst KINDS = {\n server: ['Server', 'calls the server function'],\n request: ['Request', 'reads the request with'],\n route: ['Route', 'reads the route with'],\n action: ['Action', 'has the form action'],\n defer: ['Defer', 'has a block that the server renders later:'],\n dynamic: ['Dynamic tag', 'renders a dynamic tag'],\n component: ['Unknown', 'renders a component that the workbench cannot find:'],\n};\nconst TYPES = { text: 'string', number: 'number', boolean: 'boolean', json: 'JSON' };\n\nconst components = await (await fetch(base + '/components')).json();\nconst ready = components.filter((component) => component.selfContained);\nconst others = components.filter((component) => !component.selfContained);\nlet current;\n// The story of the component that is picked, whose props start the controls.\nlet story;\nlet values = {};\nlet start = {};\nlet timer;\nlet width = '';\nlet envOpen = false;\n\nfunction frameUrl() {\n return base + '/frame?file=' + encodeURIComponent(current.file) + '&props=' + encodeURIComponent(JSON.stringify(values));\n}\n\nfunction render() {\n const url = frameUrl();\n $('open').href = url;\n let frame = $('canvas').querySelector('iframe');\n if (!frame) {\n frame = make('iframe', { title: current.name });\n $('canvas').replaceChildren(make('div', { class: 'device', id: 'device' }, frame), make('div', { class: 'size', id: 'size' }));\n applyWidth();\n }\n frame.src = url;\n}\n\nfunction later() {\n clearTimeout(timer);\n timer = setTimeout(render, 200);\n}\n\nfunction applyWidth() {\n const device = $('device');\n if (!device) return;\n device.style.width = width ? width + 'px' : '100%';\n device.style.maxWidth = '100%';\n $('size').textContent = width ? width + ' px' : '';\n}\n\nfunction set(name, value) {\n if (value === undefined) delete values[name];\n else values[name] = value;\n for (const row of $('controls').querySelectorAll('.prop')) {\n row.classList.toggle('changed', JSON.stringify(values[row.dataset.name]) !== JSON.stringify(start[row.dataset.name]));\n }\n later();\n}\n\nfunction input(spec) {\n const value = values[spec.name];\n if (spec.kind === 'boolean') {\n const box = make('input', { type: 'checkbox', onchange: () => set(spec.name, box.checked) });\n box.checked = Boolean(value);\n return make('label', { class: 'switch' }, box, make('span'), spec.name);\n }\n if (spec.kind === 'choice') {\n const options = spec.optional ? [undefined, ...spec.options] : spec.options;\n if (options.length <= 5) {\n const group = make('div', { class: 'choices', role: 'group', 'aria-label': spec.name });\n for (const option of options) {\n const button = make('button', {\n type: 'button',\n 'aria-pressed': String(option === value),\n onclick: () => {\n for (const other of group.children) other.setAttribute('aria-pressed', String(other === button));\n set(spec.name, option);\n },\n }, option === undefined ? 'none' : String(option));\n group.append(button);\n }\n return group;\n }\n const select = make('select', { 'aria-label': spec.name, onchange: () => set(spec.name, options[select.selectedIndex]) });\n for (const option of options) select.append(make('option', {}, option === undefined ? 'none' : String(option)));\n select.selectedIndex = Math.max(0, options.indexOf(value));\n return select;\n }\n if (spec.kind === 'json') {\n const area = make('textarea', { spellcheck: 'false', 'aria-label': spec.name });\n const error = make('div', { class: 'error', hidden: true });\n area.value = value === undefined ? '' : JSON.stringify(value, null, 2);\n area.addEventListener('input', () => {\n if (area.value.trim() === '') {\n area.classList.remove('invalid');\n error.hidden = true;\n set(spec.name, undefined);\n return;\n }\n try {\n const parsed = JSON.parse(area.value);\n area.classList.remove('invalid');\n error.hidden = true;\n set(spec.name, parsed);\n } catch (problem) {\n area.classList.add('invalid');\n error.hidden = false;\n error.textContent = String(problem.message ?? problem);\n }\n });\n return make('div', {}, area, error);\n }\n const field = make('input', {\n type: spec.kind === 'number' ? 'number' : 'text',\n 'aria-label': spec.name,\n placeholder: spec.optional ? 'undefined' : '',\n oninput: () => set(spec.name, field.value === '' ? undefined : spec.kind === 'number' ? Number(field.value) : field.value),\n });\n field.value = value === undefined ? '' : String(value);\n return field;\n}\n\nfunction typeOf(spec) {\n if (spec.kind === 'choice') return spec.options.map((option) => JSON.stringify(option)).join(' | ');\n return TYPES[spec.kind];\n}\n\nfunction stories() {\n const box = $('stories');\n box.replaceChildren();\n box.hidden = !current.stories?.length && !current.storiesError;\n if (current.storiesError) {\n box.append(make('div', { class: 'stories-error' }, 'The stories do not load: ' + current.storiesError));\n return;\n }\n if (!current.stories?.length) return;\n box.append(make('div', { class: 'stories-head' }, 'Stories'));\n const list = make('div', { class: 'choices' });\n for (const item of [{ name: 'Default', props: {} }, ...current.stories]) {\n list.append(make('button', {\n type: 'button',\n 'aria-pressed': String((story?.name ?? 'Default') === item.name),\n onclick: () => pickStory(item.name === 'Default' ? undefined : item),\n }, item.name));\n }\n box.append(list);\n}\n\n/** Starts the controls from the props of a story, or from the defaults without one. */\nfunction pickStory(next) {\n story = next;\n start = { ...initial(current), ...(next?.props ?? {}) };\n values = structuredClone(start);\n history.replaceState(null, '', '#' + current.file + (next ? '@' + next.name : ''));\n stories();\n controls();\n render();\n}\n\nfunction controls() {\n const box = $('controls');\n box.replaceChildren();\n if (current.unreadProps) {\n box.append(make('div', { class: 'empty-props' }, 'The workbench cannot read the type of the props, such as a type that the file imports. Declare it in the file to get controls.'));\n return;\n }\n if (!current.controls.length) {\n box.append(make('div', { class: 'empty-props' }, 'This component takes no props that the workbench can set.'));\n return;\n }\n for (const spec of current.controls) {\n const reset = make('button', { class: 'reset', type: 'button', title: 'Reset', onclick: () => {\n set(spec.name, start[spec.name]);\n controls();\n } }, '↺');\n box.append(make('div', { class: 'prop', 'data-name': spec.name },\n make('div', { class: 'prop-head' },\n make('span', { class: 'name' }, spec.name),\n spec.optional ? undefined : make('span', { class: 'req', title: 'Required' }, '*'),\n reset,\n make('span', { class: 'type', title: typeOf(spec) }, typeOf(spec).length > 28 ? 'union' : typeOf(spec))),\n input(spec)));\n }\n}\n\nfunction initial(component) {\n const props = {};\n for (const spec of component.controls) {\n if (spec.default !== undefined) props[spec.name] = spec.default;\n // A required prop gets a value, so the component renders at once.\n else if (!spec.optional) {\n props[spec.name] =\n spec.kind === 'text' ? spec.name\n : spec.kind === 'number' ? 0\n : spec.kind === 'boolean' ? false\n : spec.kind === 'choice' ? spec.options[0]\n : (spec.empty ?? null);\n }\n }\n return props;\n}\n\nfunction title(component) {\n $('name').textContent = component ? component.name : 'Workbench';\n $('file').hidden = !component;\n if (component) $('file').textContent = component.label ?? component.file;\n}\n\nfunction select(component) {\n current = component;\n for (const item of $('tree').querySelectorAll('.item')) item.setAttribute('aria-current', String(item.dataset.file === component.file));\n title(component);\n history.replaceState(null, '', '#' + component.file);\n if (!component.selfContained) {\n document.body.classList.add('no-props');\n $('tools').hidden = true;\n explain(component);\n return;\n }\n document.body.classList.remove('no-props');\n $('tools').hidden = false;\n $('canvas').replaceChildren();\n pickStory(undefined);\n}\n\nfunction explain(component) {\n const list = make('ul', { class: 'needs' });\n for (const need of component.needs) {\n const [label, words] = KINDS[need.kind] ?? [need.kind, ''];\n list.append(make('li', {},\n make('span', { class: 'tag k-' + need.kind }, label),\n make('span', {}, words + ' ', make('span', { class: 'what' }, need.name)),\n need.via ? make('span', { class: 'via' }, 'through ' + need.via) : undefined));\n }\n const hint = make('div', { class: 'hint' });\n hint.append('Test it in a page: ', make('code', {}, 'visit()'), ' from ', make('code', {}, 'brumate/testing'),\n ', or an end-to-end test. Its parts that depend only on their props show here.');\n $('canvas').replaceChildren(make('div', { class: 'card' },\n make('div', { class: 'eyebrow' }, 'Needs the environment'),\n make('h2', {}, component.name + ' needs more than its props'),\n make('p', {}, 'The workbench renders a component with nothing around it: no request, no route, no server data and no providers. This one needs:'),\n list, hint));\n}\n\nfunction welcome() {\n const stats = make('div', { class: 'stats' },\n make('div', {}, make('strong', {}, String(ready.length)), 'can show here'),\n make('div', {}, make('strong', {}, String(others.length)), 'need the environment'));\n $('canvas').replaceChildren(make('div', { class: 'card' },\n make('div', { class: 'eyebrow' }, 'Workbench'),\n make('h2', {}, 'Pick a component'),\n make('p', {}, 'Each component renders on the server with the props that you set, and resumes in the browser, as it does in a page.'),\n stats));\n}\n\nfunction item(component) {\n const kinds = [...new Set(component.needs.map((need) => need.kind))];\n return make('button', {\n class: 'item', type: 'button', 'data-file': component.file,\n 'aria-current': String(component === current),\n title: component.file,\n onclick: () => select(component),\n },\n svg(component.selfContained ? COMPONENT : LOCKED),\n make('span', { class: 'label' }, component.name),\n component.selfContained\n ? make('span', { class: 'meta' }, component.stories?.length\n ? component.stories.length + (component.stories.length === 1 ? ' story' : ' stories')\n : component.controls.length ? component.controls.length + (component.controls.length === 1 ? ' prop' : ' props') : '')\n : make('span', { class: 'kinds' }, ...kinds.map((kind) => make('span', { class: 'dot k-' + kind, title: KINDS[kind]?.[0] ?? kind }))));\n}\n\nfunction tree() {\n const query = $('filter').value.trim().toLowerCase();\n const match = (component) => !query || component.name.toLowerCase().includes(query) || component.file.toLowerCase().includes(query);\n const box = $('tree');\n box.replaceChildren();\n const folders = new Map();\n for (const component of ready.filter(match)) {\n const folder = component.group || '.';\n if (!folders.has(folder)) folders.set(folder, []);\n folders.get(folder).push(component);\n }\n for (const [folder, items] of [...folders].sort(([a], [b]) => a.localeCompare(b))) {\n box.append(make('div', { class: 'group' },\n make('div', { class: 'group-head' }, svg(FOLDER), folder, make('span', { class: 'count' }, String(items.length))),\n ...items.map(item)));\n }\n if (!folders.size) box.append(make('div', { class: 'note' }, query ? 'No component matches.' : 'No component depends only on its props.'));\n const shown = others.filter(match);\n if (shown.length) {\n const group = make('div', { class: 'group env' + (envOpen || query ? '' : ' closed') });\n const head = make('div', { class: 'group-head', role: 'button', tabindex: '0', 'aria-expanded': String(envOpen || Boolean(query)) },\n svg(CHEVRON), 'Needs the environment', make('span', { class: 'count' }, String(shown.length)));\n const toggle = () => {\n envOpen = group.classList.toggle('closed') === false;\n head.setAttribute('aria-expanded', String(envOpen));\n };\n head.addEventListener('click', toggle);\n head.addEventListener('keydown', (event) => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); toggle(); } });\n group.append(head, make('div', { class: 'items' }, ...shown.map(item)));\n box.append(group);\n }\n}\n\n$('total').textContent = components.length + ' components';\n$('filter').addEventListener('input', tree);\n$('file').addEventListener('click', () => {\n if (current) fetch('/__open-in-editor?file=' + encodeURIComponent(current.file));\n});\n$('reload').addEventListener('click', render);\n$('resetAll').addEventListener('click', () => {\n values = structuredClone(start);\n controls();\n render();\n});\nfor (const button of document.querySelectorAll('[data-width]')) {\n button.addEventListener('click', () => {\n width = button.dataset.width;\n for (const other of document.querySelectorAll('[data-width]')) other.setAttribute('aria-pressed', String(other === button));\n applyWidth();\n });\n}\nfor (const button of document.querySelectorAll('[data-canvas]')) {\n button.addEventListener('click', () => {\n $('canvas').className = 'canvas ' + button.dataset.canvas;\n for (const other of document.querySelectorAll('[data-canvas]')) other.setAttribute('aria-pressed', String(other === button));\n });\n}\n// The hash names the component, so a link or the back button can pick one.\nfunction fromHash() {\n // The hash is the file, and the name of a story after \\`@\\`.\n const [chosen, storyName] = decodeURIComponent(location.hash.slice(1)).split('@');\n const found = components.find((component) => component.file === chosen);\n if (!found) {\n welcome();\n return;\n }\n const named = found.stories?.find((item) => item.name === storyName);\n if (found === current && named === story) return;\n if (!found.selfContained && !envOpen) {\n envOpen = true;\n tree();\n }\n if (found !== current) select(found);\n if (found.selfContained && named !== story) pickStory(named);\n}\ntree();\nfromHash();\naddEventListener('hashchange', fromHash);\n</script>\n</body>\n</html>`;\n}\n","// Classifies the components of a project by what they depend on, so the workbench lists only\n// the ones that it can show: those that depend on their props, their own state and nothing\n// else. A context counts as neither, since a component without a provider reads its default.\n// A component that calls the server, or reads the request or the route, fits an end-to-end\n// test better. A component needs what the components it renders need.\n\nimport { analyze } from './analyze.ts';\nimport type { Markup, SFCFile } from './ast.ts';\nimport { resolveMacros, walk } from './macros.ts';\nimport type { oxc } from './oxc.ts';\nimport { parse } from './parser.ts';\nimport { forEachNode, importSource, resolveRelative } from './project.ts';\nimport type { Resolve } from './project.ts';\n\nexport type NeedKind =\n /** A server function: one of a `'use server'` file, or one that the component declares. */\n | 'server'\n /** The request, through an import of `brumate/server`, such as `getEvent`. */\n | 'request'\n /** The route, through `$route` or `$navigation`. */\n | 'route'\n /** A form action of `$action`. */\n | 'action'\n /** A `#defer` block, whose body the server renders later. */\n | 'defer'\n /** A dynamic tag without an element to fall back to, which can render any component. */\n | 'dynamic'\n /** A component that the analysis cannot find, such as one of a package that is not a `.brm` file. */\n | 'component';\n\nexport interface Need {\n kind: NeedKind;\n /** What the need is about: the name of a function, an import, a block or a component. */\n name: string;\n /** For a need of a component that this one renders, the file of that component, which can have it from a component that it renders. */\n via?: string;\n}\n\nexport interface Classification {\n /** True when the component depends only on its props and its own state. */\n selfContained: boolean;\n needs: Need[];\n}\n\nexport interface ClassifyOptions {\n /** Resolves the import of a component to its file. */\n resolve?: Resolve;\n /** True for an import of a function of a `'use server'` file. */\n serverImport?: (file: string, specifier: string, name: string) => boolean;\n}\n\n/** True for a string literal, such as `'button'`. */\nfunction isElementName(node: oxc.Node | undefined): boolean {\n return node?.type === 'Literal' && typeof node.value === 'string';\n}\n\n/** The props that destructure with an element name as their default, such as `as = 'button'`. */\nfunction elementDefaults(file: SFCFile): Set<string> {\n const names = new Set<string>();\n for (const statement of file.instanceScript?.program.body ?? []) {\n if (statement.type !== 'VariableDeclaration') {\n continue;\n }\n for (const declarator of statement.declarations) {\n const call = declarator.init;\n if (\n call?.type !== 'CallExpression' ||\n call.callee.type !== 'Identifier' ||\n call.callee.name !== '$props' ||\n declarator.id.type !== 'ObjectPattern'\n ) {\n continue;\n }\n for (const property of declarator.id.properties) {\n if (\n property.type === 'Property' &&\n property.value.type === 'AssignmentPattern' &&\n property.value.left.type === 'Identifier' &&\n isElementName(property.value.right)\n ) {\n names.add(property.value.left.name);\n }\n }\n }\n }\n return names;\n}\n\n/**\n * True for the tag of a dynamic tag that renders an element when the caller gives none: a\n * string, `as ?? 'button'`, or a prop with an element as its default. A part such as a button\n * that takes `as` depends only on its props this way.\n */\nfunction hasElementDefault(tag: oxc.Node, defaults: Set<string>): boolean {\n if (isElementName(tag)) {\n return true;\n }\n if (tag.type === 'Identifier') {\n return defaults.has(tag.name);\n }\n if (tag.type === 'LogicalExpression' && (tag.operator === '??' || tag.operator === '||')) {\n return isElementName(tag.right) || hasElementDefault(tag.right, defaults);\n }\n if (tag.type === 'ConditionalExpression') {\n return (\n hasElementDefault(tag.consequent, defaults) && hasElementDefault(tag.alternate, defaults)\n );\n }\n return tag.type === 'ParenthesizedExpression' && hasElementDefault(tag.expression, defaults);\n}\n\n/** The needs of one file, without those of the components that it renders. */\nfunction ownNeeds(file: SFCFile, options: ClassifyOptions): Need[] {\n const needs: Need[] = [];\n const model = analyze(file);\n for (const declaration of model.declarations) {\n if (declaration.kind === 'server-function') {\n needs.push({ kind: 'server', name: declaration.name });\n } else if (declaration.kind === 'action') {\n needs.push({ kind: 'action', name: declaration.name });\n } else if (declaration.imported) {\n const { source, name } = declaration.imported;\n if (source === 'brumate/server') {\n needs.push({ kind: 'request', name });\n } else if (options.serverImport?.(file.filename, source, name)) {\n needs.push({ kind: 'server', name });\n }\n }\n }\n // The namespace imports, by the start of their name, since the analysis declares one without\n // its module. It resolves each name by its scope, so a read of `api` counts only when it is\n // the import, and a name in a type, a property or a shadowing parameter does not count.\n const namespaces = new Map<number, string>();\n for (const script of [file.moduleScript, file.instanceScript]) {\n for (const statement of script?.program.body ?? []) {\n if (statement.type !== 'ImportDeclaration' || statement.importKind === 'type') {\n continue;\n }\n for (const specifier of statement.specifiers) {\n if (specifier.type === 'ImportNamespaceSpecifier') {\n namespaces.set(specifier.local.start, statement.source.value);\n }\n }\n }\n }\n for (const declaration of model.declarations) {\n const source = namespaces.get(declaration.range.start);\n if (declaration.kind !== 'import' || source === undefined || declaration.reads.length === 0) {\n continue;\n }\n const name = `* as ${declaration.name}`;\n if (source === 'brumate/server') {\n needs.push({ kind: 'request', name });\n } else if (options.serverImport?.(file.filename, source, '*')) {\n needs.push({ kind: 'server', name });\n }\n }\n // `$route` and `$navigation` read the route of the page, which the workbench does not have.\n // A call inside a function, such as a handler, runs later, if at all, so only the others\n // count. The scripts and the expressions of the markup have positions in the file, so one\n // range check finds the functions around a call.\n const functions: oxc.Node[] = [];\n const calls: oxc.CallExpression[] = [];\n walk(\n [file.moduleScript?.program, file.instanceScript?.program, file.children, file.templates],\n (node) => {\n if (\n node.type === 'ArrowFunctionExpression' ||\n node.type === 'FunctionExpression' ||\n node.type === 'FunctionDeclaration'\n ) {\n functions.push(node);\n } else if (\n node.type === 'CallExpression' &&\n node.callee.type === 'Identifier' &&\n (node.callee.name === '$route' || node.callee.name === '$navigation')\n ) {\n calls.push(node);\n }\n },\n );\n for (const call of calls) {\n let inside = false;\n for (const fn of functions) {\n if (fn.start <= call.start && call.end <= fn.end) {\n inside = true;\n break;\n }\n }\n if (!inside) {\n needs.push({ kind: 'route', name: (call.callee as oxc.IdentifierReference).name });\n }\n }\n const defaults = elementDefaults(file);\n function visit(node: Markup): void {\n if (node.kind === 'defer') {\n needs.push({ kind: 'defer', name: '#defer' });\n } else if (node.kind === 'dynamic' && !hasElementDefault(node.tag.ast, defaults)) {\n needs.push({ kind: 'dynamic', name: '<{…}>' });\n }\n }\n forEachNode(file.children, visit);\n for (const template of file.templates) {\n forEachNode(template.body.children, visit);\n }\n return needs;\n}\n\n/** The import specifiers of the components that a file renders. */\nfunction renderedComponents(file: SFCFile): Set<string> {\n const sources = new Set<string>();\n function visit(node: Markup): void {\n if (node.kind === 'component') {\n const source = importSource(file, node.name.split('.')[0]!);\n if (source) {\n sources.add(source);\n }\n }\n }\n forEachNode(file.children, visit);\n for (const template of file.templates) {\n forEachNode(template.body.children, visit);\n }\n return sources;\n}\n\nfunction key(need: Need): string {\n return `${need.kind}:${need.name}`;\n}\n\n/**\n * Classifies every component of a project, by file. A file that does not parse or analyze is\n * not classified, because the workbench could not render it either.\n */\nexport function classifyComponents(\n files: Map<string, string>,\n options: ClassifyOptions = {},\n): Map<string, Classification> {\n const resolve = options.resolve ?? resolveRelative;\n const needs = new Map<string, Map<string, Need>>();\n const children = new Map<string, string[]>();\n for (const [filename, source] of files) {\n let file: SFCFile;\n let own: Need[];\n try {\n file = parse(source, { filename });\n own = ownNeeds(file, options);\n } catch {\n continue;\n }\n const map = new Map<string, Need>();\n for (const need of own) {\n map.set(key(need), need);\n }\n const found: string[] = [];\n for (const specifier of renderedComponents(file)) {\n const target = resolve(specifier, filename);\n if (target !== undefined && files.has(target)) {\n found.push(target);\n } else if (specifier.endsWith('.brm')) {\n map.set(`component:${specifier}`, { kind: 'component', name: specifier });\n }\n }\n needs.set(filename, map);\n children.set(filename, found);\n }\n // A component needs what the components that it renders need. Each round can only add needs,\n // so this ends, also for a component that renders itself.\n for (let changed = true; changed;) {\n changed = false;\n for (const [filename, map] of needs) {\n for (const child of children.get(filename)!) {\n for (const need of needs.get(child)?.values() ?? []) {\n const id = key(need);\n if (!map.has(id)) {\n map.set(id, { ...need, via: child });\n changed = true;\n }\n }\n }\n }\n }\n const result = new Map<string, Classification>();\n for (const [filename, map] of needs) {\n const list = [...map.values()];\n result.set(filename, { selfContained: list.length === 0, needs: list });\n }\n return result;\n}\n\n/** The input of a control, by the type of its prop. */\nexport type ControlInput =\n | { kind: 'text'; default?: string }\n | { kind: 'number'; default?: number }\n | { kind: 'boolean'; default?: boolean }\n | { kind: 'choice'; options: (string | number)[]; default?: string | number }\n | {\n kind: 'json';\n default?: unknown;\n /** The value to start a required prop with: `[]` for an array type, `{}` for an object type. */\n empty?: unknown[] | Record<string, never>;\n };\n\n/** A control of the workbench for one prop of a component. */\nexport type Control = { name: string; optional: boolean } & ControlInput;\n\n/** The interface or type alias of the scripts that has this name. */\nfunction localType(name: string, file: SFCFile): oxc.Node | undefined {\n for (const script of [file.moduleScript, file.instanceScript]) {\n for (let statement of script?.program.body ?? []) {\n if (statement.type === 'ExportNamedDeclaration' && statement.declaration) {\n statement = statement.declaration;\n }\n if (\n (statement.type === 'TSInterfaceDeclaration' ||\n statement.type === 'TSTypeAliasDeclaration') &&\n statement.id.name === name\n ) {\n return statement;\n }\n }\n }\n return undefined;\n}\n\ntype Member = { optional?: boolean };\n\n/**\n * The name of a property or a method of a type, or undefined for a computed one or a signature\n * without a name. A method replaces a prop of the same name that its interface extends.\n */\nfunction memberName(member: oxc.Node): string | undefined {\n if (\n (member.type !== 'TSPropertySignature' && member.type !== 'TSMethodSignature') ||\n member.computed\n ) {\n return undefined;\n }\n return member.key.type === 'Identifier'\n ? member.key.name\n : String((member.key as { value?: unknown }).value);\n}\n\n/**\n * The members of the type of `$props<T>()`: a literal, an interface or alias of the scripts and\n * what it extends, an intersection of those, or `Partial` of one. Undefined for a type that the\n * workbench cannot read, such as one that the file imports.\n */\n/**\n * Merges lists of members by name. A later member takes the place of an earlier one with the\n * same name. With `required`, as for an intersection, the prop is required when any list\n * requires it.\n */\nfunction mergeMembers(lists: oxc.Node[][], required: boolean): oxc.Node[] {\n // A member without a name, such as a method, gets a key that no name can equal.\n const byName = new Map<string | symbol, oxc.Node>();\n for (const list of lists) {\n for (const member of list) {\n const id = memberName(member) ?? Symbol('member');\n const before = byName.get(id);\n byName.set(\n id,\n required && before && !((before as Member).optional && (member as Member).optional)\n ? ({ ...member, optional: false } as oxc.Node)\n : member,\n );\n }\n }\n return [...byName.values()];\n}\n\nfunction propsMembers(\n type: oxc.Node,\n file: SFCFile,\n seen = new Set<string>(),\n // The members of each named type, so a type that many branches reach is read once.\n known = new Map<string, oxc.Node[] | undefined>(),\n): oxc.Node[] | undefined {\n if (type.type === 'TSTypeLiteral') {\n return type.members;\n }\n if (type.type === 'TSIntersectionType') {\n const lists: oxc.Node[][] = [];\n for (const item of type.types) {\n const found = propsMembers(item, file, seen, known);\n if (!found) {\n return undefined;\n }\n lists.push(found);\n }\n return mergeMembers(lists, true);\n }\n if (type.type !== 'TSTypeReference' || type.typeName.type !== 'Identifier') {\n return undefined;\n }\n const name = type.typeName.name;\n const argument = type.typeArguments?.params[0];\n if (name !== 'Partial' && type.typeArguments) {\n // The workbench does not put the arguments of a generic type in its members.\n return undefined;\n }\n if (name === 'Partial' && argument) {\n const members = propsMembers(argument, file, seen, known);\n if (!members) {\n return undefined;\n }\n const optional: oxc.Node[] = [];\n for (const member of members) {\n optional.push({ ...member, optional: true } as oxc.Node);\n }\n return optional;\n }\n if (known.has(name)) {\n return known.get(name);\n }\n const declaration = seen.has(name) ? undefined : localType(name, file);\n if (!declaration || (declaration as { typeParameters?: unknown }).typeParameters) {\n return undefined;\n }\n // The types on the way here, which a type that refers to itself would reach again.\n const path = new Set(seen).add(name);\n let members: oxc.Node[] | undefined;\n if (declaration.type === 'TSTypeAliasDeclaration') {\n members = propsMembers(declaration.typeAnnotation, file, path, known);\n } else if (declaration.type === 'TSInterfaceDeclaration') {\n const lists: oxc.Node[][] = [];\n let readable = true;\n for (const heritage of declaration.extends ?? []) {\n const found =\n heritage.expression.type === 'Identifier'\n ? propsMembers(\n {\n type: 'TSTypeReference',\n typeName: heritage.expression,\n typeArguments: heritage.typeArguments,\n } as oxc.Node,\n file,\n path,\n known,\n )\n : undefined;\n if (!found) {\n readable = false;\n break;\n }\n lists.push(found);\n }\n // A member of the interface replaces one that it extends with the same name.\n members = readable ? mergeMembers([...lists, declaration.body.body], false) : undefined;\n }\n known.set(name, members);\n return members;\n}\n\n/** The value of a literal default, such as `'info'` in `{ tone = 'info' }`. */\nfunction literalValue(node: oxc.Node): unknown {\n if (node.type === 'Literal') {\n return node.value;\n }\n if (node.type === 'TemplateLiteral' && node.expressions.length === 0) {\n return node.quasis[0]?.value.cooked;\n }\n if (\n node.type === 'UnaryExpression' &&\n node.operator === '-' &&\n node.argument.type === 'Literal'\n ) {\n return -Number(node.argument.value);\n }\n return undefined;\n}\n\n/** The control for a type, or undefined for a function, which the workbench cannot make. */\nfunction getControl(\n type: oxc.Node | undefined,\n file: SFCFile,\n seen = new Set<string>(),\n): ControlInput | undefined {\n if (!type) {\n return { kind: 'json' };\n }\n // `Bindable<T>` is a `T` that a parent can bind.\n if (\n type.type === 'TSTypeReference' &&\n type.typeName.type === 'Identifier' &&\n type.typeName.name === 'Bindable' &&\n type.typeArguments?.params[0]\n ) {\n return getControl(type.typeArguments.params[0], file, seen);\n }\n switch (type.type) {\n case 'TSStringKeyword':\n return { kind: 'text' };\n case 'TSNumberKeyword':\n return { kind: 'number' };\n case 'TSBooleanKeyword':\n return { kind: 'boolean' };\n case 'TSFunctionType':\n case 'TSConstructorType':\n return undefined;\n case 'TSParenthesizedType':\n return getControl(type.typeAnnotation, file, seen);\n case 'TSArrayType':\n case 'TSTupleType':\n return { kind: 'json', empty: [] };\n case 'TSTypeLiteral':\n return { kind: 'json', empty: {} };\n case 'TSTypeReference':\n if (type.typeName.type === 'Identifier') {\n if (type.typeName.name === 'Array' || type.typeName.name === 'ReadonlyArray') {\n return { kind: 'json', empty: [] };\n }\n if (type.typeName.name === 'Record') {\n return { kind: 'json', empty: {} };\n }\n // An interface is an object, and an alias has the control of its type.\n const name = type.typeName.name;\n const declaration = seen.has(name) ? undefined : localType(name, file);\n if (declaration?.type === 'TSInterfaceDeclaration') {\n return { kind: 'json', empty: {} };\n }\n if (declaration?.type === 'TSTypeAliasDeclaration') {\n return getControl(declaration.typeAnnotation, file, new Set(seen).add(name));\n }\n }\n return { kind: 'json' };\n case 'TSUnionType': {\n const types: oxc.Node[] = [];\n for (const item of type.types as oxc.Node[]) {\n if (item.type !== 'TSUndefinedKeyword' && item.type !== 'TSNullKeyword') {\n types.push(item);\n }\n }\n const options: (string | number)[] = [];\n for (const item of types) {\n const value = item.type === 'TSLiteralType' ? literalValue(item.literal) : undefined;\n if (typeof value !== 'string' && typeof value !== 'number') {\n return types.length === 1 ? getControl(types[0], file, seen) : { kind: 'json' };\n }\n options.push(value);\n }\n return { kind: 'choice', options };\n }\n default:\n return { kind: 'json' };\n }\n}\n\n/**\n * The controls for the props of a component, from the type of `$props<T>()` and the defaults\n * of its destructuring. A prop whose type is a function, such as a handler, has none. Undefined\n * when the workbench cannot read the type, such as one that the file imports.\n */\nexport function propControls(file: SFCFile): Control[] | undefined {\n // A renamed import, such as `$props as props`, is read as `$props`.\n resolveMacros(file);\n for (const statement of file.instanceScript?.program.body ?? []) {\n if (statement.type !== 'VariableDeclaration') {\n continue;\n }\n for (const declarator of statement.declarations) {\n const call = declarator.init;\n if (\n call?.type !== 'CallExpression' ||\n call.callee.type !== 'Identifier' ||\n call.callee.name !== '$props'\n ) {\n continue;\n }\n const defaults = new Map<string, unknown>();\n if (declarator.id.type === 'ObjectPattern') {\n for (const property of declarator.id.properties) {\n if (\n property.type === 'Property' &&\n property.key.type === 'Identifier' &&\n property.value.type === 'AssignmentPattern'\n ) {\n defaults.set(property.key.name, literalValue(property.value.right));\n }\n }\n }\n const type = (call as { typeArguments?: { params: oxc.Node[] } }).typeArguments?.params[0];\n const members = type ? propsMembers(type, file) : [];\n if (!members) {\n return undefined;\n }\n // A later member with the same name, as of an interface over what it extends, wins, in\n // the place of the first.\n const byName = new Map<string, Control>();\n for (const member of members) {\n const name = memberName(member);\n if (name === undefined || member.type !== 'TSPropertySignature') {\n continue;\n }\n // The children of a part are text in the workbench, whatever their type says.\n const control =\n name === 'children'\n ? { kind: 'text' as const }\n : getControl(member.typeAnnotation?.typeAnnotation, file);\n if (!control) {\n byName.delete(name);\n continue;\n }\n const value = defaults.get(name);\n byName.set(name, {\n name,\n optional: member.optional,\n ...control,\n ...(value === undefined ? {} : { default: value }),\n } as Control);\n }\n return [...byName.values()];\n }\n }\n return [];\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 getPageFile(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(/&amp;/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 let entry: ManifestChunk | undefined;\n for (const chunk of Object.values(manifest)) {\n if (chunk.isEntry) {\n entry = chunk;\n break;\n }\n }\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 // Every page renders from one place, with no client, so rate limits do not count.\n prerender: true,\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, getPageFile(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: getPageFile(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 scripts = new Set<string>();\n for (const page of Object.values(pages)) {\n for (const script of page.scripts) {\n scripts.add(script);\n }\n }\n const result: PrerenderManifest = { pages, scripts: [...scripts] };\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, the code of\n// each component, and what each route loads. A budget fails the build when a\n// 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 /** The size of each module in the chunk, before minifying and gzip. */\n modules?: Record<string, number>;\n}\n\n/** Sizes in bytes, after gzip. */\nexport interface Budget {\n /** The loader, which every page loads. */\n loader?: number;\n /** What a route loads, with the core. */\n route?: number;\n /** The client code of one component. */\n component?: number;\n}\n\nexport interface BuildReport {\n /** The entry and its imports, which every page loads. */\n loader: number;\n /** The runtime, which every page loads when it starts. */\n core: number;\n /**\n * Each component, with the size of its client code, largest first. A chunk that holds several\n * components, such as the bundle of a page, counts for each by the size of its modules.\n */\n components: { file: string; bytes: number }[];\n /** Each route path, with what it loads besides the loader, 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 /** A file as the messages show it. Defaults to the path. */\n relative?: (file: string) => string;\n}\n\n/** Measures the client build. */\nexport function buildReport({\n chunks: list,\n sources,\n routes,\n budget,\n relative = (file) => file,\n}: ReportInput): BuildReport {\n const chunks = new Map<string, (typeof list)[number]>();\n const sizes = new Map<string, number>();\n for (const chunk of list) {\n chunks.set(chunk.fileName, chunk);\n sizes.set(chunk.fileName, gzipSize(chunk.code));\n }\n function 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 let coreChunk: (typeof list)[number] | undefined;\n for (const chunk of list) {\n let isCore = false;\n for (const id of chunk.moduleIds) {\n if (/[\\\\/]runtime[\\\\/]client\\.[jt]s$/.test(id)) {\n isCore = true;\n break;\n }\n }\n if (isCore) {\n coreChunk = chunk;\n break;\n }\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: those that hold its entry and its parts, with what they\n // import. Its size is its share of each chunk that holds its modules.\n const byFile = new Map<string, Set<string>>();\n const shares = new Map<string, number>();\n const everyPage = new Set([...loaderChunks, ...coreChunks]);\n for (const chunk of list) {\n const owned = new Map<string, number>();\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 owned.set(file, (owned.get(file) ?? 0) + (chunk.modules?.[id] ?? 1));\n }\n }\n let total = chunk.moduleIds.length;\n if (chunk.modules) {\n total = 0;\n for (const bytes of Object.values(chunk.modules)) {\n total += bytes;\n }\n }\n for (const [file, bytes] of owned) {\n const share = total > 0 ? ((sizes.get(chunk.fileName) ?? 0) * bytes) / total : 0;\n shares.set(file, (shares.get(file) ?? 0) + share);\n }\n }\n for (const set of byFile.values()) {\n for (const name of everyPage) {\n set.delete(name);\n }\n }\n const components: { file: string; bytes: number }[] = [];\n for (const [file, bytes] of shares) {\n components.push({ file, bytes: Math.round(bytes) });\n }\n components.sort((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 function reachable(files: string[]): Set<string> {\n const seen = new Set<string>();\n function 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 for (const file of files) {\n visit(file);\n }\n return seen;\n }\n const routeSizes: { path: string; bytes: number; components: number }[] = [];\n for (const { path, files } of routes ? routeEntries(routes.tree, routes.resolve) : []) {\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 routeSizes.push({ path, bytes: sum(names), components: reached.size });\n }\n routeSizes.sort((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 for (const component of components) {\n if (budget?.component !== undefined && component.bytes > budget.component) {\n overBudget.push(\n `The component ${relative(component.file)} ships ${formatBytes(component.bytes)}, over the budget of ${formatBytes(budget.component)}.`,\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 ` The loader, on every page: ${formatBytes(report.loader)}`,\n ` The core, when the page starts: ${formatBytes(report.core)}`,\n ];\n if (report.routes.length > 0) {\n lines.push(' What each route loads when it starts, 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 * `middleware` is the path of the entry middleware, which runs for every\n * request, when the app has 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 middleware?: string,\n /** The ID of the build, for skew protection. */\n build?: string,\n /** The modules that every page loads early, from the client build. */\n hints: string[] = [],\n /** The chunks of the bundle of each root component, by ID, from the client build. */\n bundleHints: Record<string, string[]> = {},\n): string {\n // Static imports in a build, because the server registry of server functions imports every\n // file anyway. In development, a route loads when a request needs it, so a file that does not\n // compile breaks only its own pages.\n const imports: string[] = [];\n function load(file: string): string {\n if (dev) {\n return `() => import(${JSON.stringify(resolve(file))})`;\n }\n const name = `m${imports.length}`;\n imports.push(`import * as ${name} from ${JSON.stringify(resolve(file))};`);\n return `() => Promise.resolve(${name})`;\n }\n function 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: string[] = [];\n for (const [name, value] of Object.entries(children)) {\n entries.push(`${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, fileMiddleware } from 'virtual:brumate/server';\",\n ...(middleware ? [`import middleware from ${JSON.stringify(middleware)};`] : []),\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, fileMiddleware${middleware ? ', middleware' : ''}${dev ? ', dev: true' : ''}${build === undefined ? '' : `, build: ${JSON.stringify(build)}`}${hints.length > 0 ? `, hints: ${JSON.stringify(hints)}` : ''}${Object.keys(bundleHints).length > 0 ? `, bundleHints: ${JSON.stringify(bundleHints)}` : ''}, ...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 function 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: string[] = [];\n for (const { path, params } of routePaths(tree)) {\n const names: string[] = [];\n for (const name of params) {\n names.push(`${name}: string`);\n }\n const fields = names.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 lines.push(` ${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 { parseSync } from 'oxc-parser';\nimport type { Site } from './model.ts';\nimport type { oxc } from './oxc.ts';\nimport { existsSync, readFileSync, readdirSync, realpathSync, writeFileSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } 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 isFileLoadingAllowed,\n transformWithOxc,\n version as viteVersion,\n} from 'vite';\nimport type { EnvironmentModuleNode, Plugin, UserConfig, ViteDevServer } from 'vite';\nimport { entryClasses } from './captures.ts';\nimport { refreshedNames } from './refreshes.ts';\nimport { compile } from './compile.ts';\nimport { DEFAULT_MERGE } from './codegen/client.ts';\nimport { defaultExclude, findFiles, findScripts, findServerFiles } from './files.ts';\nimport { clientEnvModule, parseEnvFile } from './env-file.ts';\nimport {\n findPackageServerFile,\n hasServerMiddleware,\n hasUseServer,\n isScriptFile,\n serverExports,\n serverModule,\n serverStubs,\n} from './server-files.ts';\nimport type { CompileOptions, CompileResult } from './compile.ts';\nimport { getLocation } from './error.ts';\nimport { functionId, getComponentName, hash } from './plan.ts';\nimport { analyzeProject, importedComponents, resolveRelative } from './project.ts';\nimport {\n allFeatures,\n getFeatures,\n joinFeatures,\n readsFeatures,\n writeFeatures,\n} from './features.ts';\nimport type { Features } from './features.ts';\nimport { BUILD_FILE, clientBuildDirectory, pruneBuilds, readBuildId } from './builds.ts';\nimport {\n findPackages,\n packageFileName,\n findPackage,\n reachableFiles,\n resolveComponentPackage,\n} from './packages.ts';\nimport type { BrumatePackage } from './packages.ts';\nimport type { NavigateOptions } from './runtime/boot.ts';\nimport { anchorLabel, 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 { originalPosition } from './sourcemap.ts';\nimport { toNodeHeaders } from './runtime/cookies.ts';\nimport { errorPage, errorPayload } from './dev-error.ts';\nimport type { renderToStream as RenderToStream } from './runtime/server.ts';\nimport { workbenchPage } from './workbench-page.ts';\nimport { classifyComponents, propControls } from './workbench.ts';\nimport { parse as parseComponent } from './parser.ts';\nimport { BRUMATE_VERSION } from './version.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 entry middleware, relative to the root. Its default export runs for\n * every request: pages, endpoints, server function calls, form posts and\n * `#defer` bodies. Defaults to `src/middleware.ts` when the file exists.\n * `false` runs none.\n */\n middleware?: string | false;\n /**\n * The serial entry, relative to the root. It exports `plugins` for values\n * of the app, such as a class, and the options of the serializer that it\n * changes. The server and the browser load it. Defaults to `src/serial.ts`\n * when the file exists. `false` uses none.\n */\n serial?: string | false;\n /**\n * The file of environment variables, relative to the root, which calls\n * `defineEnv` from `brumate/env`. The server checks them when it starts,\n * and the browser gets the file without the server variables. Defaults\n * to `src/env.ts` when the file exists. `false` uses none.\n */\n env?: string | false;\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 * The features of the core that the client build keeps. By default it leaves out the code of\n * those that no component of the build uses, such as `#template` values that the browser\n * calls. `'all'` keeps every feature, for an app that compiles components in the browser.\n */\n features?: 'used' | 'all';\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 * Skew protection: a page that was open before a deploy keeps working.\n * Each build has an ID, which the page carries and sends with its calls.\n * A call to a function that is gone, or a page of another build, makes\n * the browser load the page in full. The client build writes its ID to\n * `.brumate/build.json`, and the server build reads it, so build the\n * client first. `BRUMATE_BUILD` in the environment names the ID for both.\n *\n * `keep` is how many earlier builds keep their files in the client\n * output, so a page that is open still finds the code of its handlers\n * after a deploy. The build then does not empty the output directory, and\n * removes the files of older builds itself. Defaults to 0, which empties\n * it as Vite does.\n */\n skew?: { keep?: number };\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. */\n/** How many files a build reads or compiles at once, so a large project does not run out of file handles. */\nconst BATCH = 32;\n\n/** Runs `run` for each item, one batch at a time. */\nasync function inBatches<T, R>(list: T[], run: (item: T) => Promise<R>): Promise<R[]> {\n const results: R[] = [];\n for (let start = 0; start < list.length; start += BATCH) {\n const batch: Promise<R>[] = [];\n for (const item of list.slice(start, start + BATCH)) {\n batch.push(run(item));\n }\n // oxlint-disable-next-line no-await-in-loop -- Each batch waits for the one before, to bound open files.\n results.push(...(await Promise.all(batch)));\n }\n return results;\n}\n\nconst START = 'virtual:brumate/start';\n/** Exports `load(id)`, which imports the client module of a component. */\nconst MANIFEST = 'virtual:brumate/manifest';\n/** `virtual:brumate/bundle/<id>` imports the client modules of a root component and those it renders. */\nconst BUNDLE = 'virtual:brumate/bundle/';\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 modules that every page loads early, in the client build. See `hints` of `handleRoute`. */\nconst HINTS_FILE = '.brumate/hints.json';\n/** The dev server answers the devtools panel about a component at this path. */\nconst INSPECT = '/__brumate/inspect';\n/** Maps a position of a module that the browser ran to its source, for the Errors tab. */\nconst POSITION = '/__brumate/position';\n/** The dev server sends the source of a file for the Errors tab of the devtools at this path. */\nconst SOURCE = '/__brumate/source';\n/** The workbench of the dev server, which shows the components that depend only on their props. */\nconst WORKBENCH = '/__brumate/workbench';\n\n/** What tells two lists of packages of components apart. */\nfunction packagesKey(list: BrumatePackage[]): string {\n const rows: unknown[][] = [];\n for (const item of list) {\n rows.push([item.prefix, item.root, item.directories]);\n }\n return JSON.stringify(rows);\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 getMarkup(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 getShape(result: CompileResult): Shape {\n const labels: string[] = [];\n const slots: Record<number, string[]> = {};\n const signals: string[] = [];\n for (const layout of result.plan.scopes.values()) {\n const names: string[] = [];\n for (const slot of layout.slots) {\n names.push(slot.name);\n if (slot.kind === 'signal') {\n signals.push(slot.name);\n }\n }\n labels.push(`${layout.scope.id}:${names.join(',')}`);\n slots[layout.scope.id] = names;\n }\n return {\n layout: JSON.stringify([result.table, labels, getMarkup(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,\n signals,\n };\n}\n\n/** What Vitest passes to `configureVitest`, the part that this plugin uses. */\ninterface VitestContext {\n defineCacheKeyGenerator?: (generate: CacheKeyGenerator) => void;\n experimental_defineCacheKeyGenerator?: (generate: CacheKeyGenerator) => void;\n}\n\n/** Makes a part of Vitest's cache key of a module, or returns false to keep it out of the cache. */\ntype CacheKeyGenerator = (context: { id: string }) => string | false;\n\n/**\n * The cache key of a module for Vitest: the hash of this build of brumate. A component is never\n * cached, because its code depends on other files, such as the `.brm.ts` modules that it calls\n * and the props that other components pass it. A key of its own source would go stale.\n */\nfunction cacheKey({ id }: { id: string }): string | false {\n return id.split('?')[0]!.endsWith('.brm') ? false : buildFingerprint();\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 function 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 /** The entry middleware, when the app has one. */\n function middlewareFile(): string | undefined {\n if (options.middleware === false) {\n return undefined;\n }\n const file = normalizePath(path.resolve(root, options.middleware ?? 'src/middleware.ts'));\n if (!existsSync(file)) {\n if (options.middleware !== undefined) {\n throw new Error(`The middleware file ${options.middleware} does not exist`);\n }\n return undefined;\n }\n return file;\n }\n /** The serial entry, when the app has one. */\n function serialFile(): string | undefined {\n if (options.serial === false) {\n return undefined;\n }\n const file = normalizePath(path.resolve(root, options.serial ?? 'src/serial.ts'));\n if (!existsSync(file)) {\n if (options.serial !== undefined) {\n throw new Error(`The serial entry ${options.serial} does not exist`);\n }\n return undefined;\n }\n return file;\n }\n /** The classes that the plugins of the serial entry send, read from its `instanceof` checks. */\n let serialRead: { source: string; classes: string[] } | undefined;\n function serialClasses(): string[] {\n const file = serialFile();\n if (!file) {\n return [];\n }\n const source = readFileSync(file, 'utf8');\n if (serialRead?.source !== source) {\n const { program } = parseSync(file, source, { lang: 'ts' });\n serialRead = { source, classes: entryClasses(program as oxc.Node) };\n }\n return serialRead.classes;\n }\n /** The lines that give the server the serial entry, before anything is written or read. */\n function serialImports(): string[] {\n const file = serialFile();\n return file\n ? [\n `import * as $$serial from ${JSON.stringify(file)};`,\n \"import { useSerialEntry } from 'brumate/server';\",\n 'useSerialEntry($$serial);',\n ]\n : [];\n }\n /** The file of environment variables, when the app has one. */\n function envFile(): string | undefined {\n if (options.env === false) {\n return undefined;\n }\n const file = normalizePath(path.resolve(root, options.env ?? 'src/env.ts'));\n if (!existsSync(file)) {\n if (options.env !== undefined) {\n throw new Error(`The env file ${options.env} does not exist`);\n }\n return undefined;\n }\n return file;\n }\n /** The names of the server variables, read from the env file, by its source. */\n let envKeys: { source: string; server: string[] } | undefined;\n function serverEnvKeys(): string[] | undefined {\n const file = envFile();\n if (!file) {\n return undefined;\n }\n const source = readFileSync(file, 'utf8');\n if (envKeys?.source !== source) {\n envKeys = { source, server: parseEnvFile(source, file).server };\n }\n return envKeys.server;\n }\n const exclude = options.exclude ?? defaultExclude;\n let root = process.cwd();\n let outDir = '';\n /** The ID of the build, for skew protection. Undefined on the dev server. */\n let buildId: string | undefined;\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 `getShape`. */\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 /** The names of the server functions that the app refreshes, or undefined before the first scan. */\n let refreshed: Set<string> | undefined;\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 function relative(file: string): string {\n return normalizePath(path.relative(root, file));\n }\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 function getFileName(file: string): string {\n let normalized = normalizePath(file);\n let owner = findPackage(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 = findPackage(packages, normalized);\n }\n return owner ? packageFileName(owner, normalized) : relative(file);\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 function 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 = findPackageServerFile(packages, importer, specifier);\n return file ? functionId(serverFileId(file), name, !isServe) : undefined;\n }\n const stem = path.resolve(path.dirname(importer), specifier);\n const candidates = [stem];\n for (const extension of ['.ts', '.tsx', '.js', '.mjs']) {\n candidates.push(stem + extension);\n }\n let found: string | undefined;\n for (const candidate of candidates) {\n if (\n isScriptFile(candidate) &&\n existsSync(candidate) &&\n hasUseServer(readFileSync(candidate, 'utf8'))\n ) {\n found = candidate;\n break;\n }\n }\n return found && functionId(serverFileId(normalizePath(found)), name, !isServe);\n }\n\n function serverFileId(file: string): string {\n return `${path.basename(file).replace(/\\.[^.]+$/, '')}_${hash(getFileName(file))}`;\n }\n function componentId(file: string): string {\n const filename = getFileName(file);\n return `${getComponentName(filename)}_${hash(filename)}`;\n }\n\n async function scan(): Promise<void> {\n const directories: string[] = [];\n for (const item of packages) {\n for (const directory of item.directories) {\n if (existsSync(directory)) {\n directories.push(directory);\n }\n }\n }\n // A package inside the root, such as one of a workspace, is found once, as a package.\n function ownFile(file: string): boolean {\n return !findPackage(packages, file);\n }\n const searches = [findFiles(root, exclude), findServerFiles(root, exclude)];\n for (const directory of directories) {\n searches.push(\n findFiles(directory, packageExclude),\n findServerFiles(directory, packageExclude),\n );\n }\n const [own, ownServer, ...found] = await Promise.all(searches);\n // The scripts of the app, which can import files of packages.\n // The list is assigned once, after the search, so a lookup during the search sees the last one.\n const scripts: string[] = [];\n if (packages.length > 0) {\n for (const file of await findScripts(root, exclude)) {\n if (ownFile(file)) {\n scripts.push(file);\n }\n }\n }\n appScripts = scripts;\n files.clear();\n serverFiles.clear();\n for (const file of own!) {\n if (ownFile(file)) {\n files.set(componentId(file), file);\n }\n }\n for (const file of ownServer!) {\n if (ownFile(file)) {\n serverFiles.set(serverFileId(file), file);\n }\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 try {\n await analyze();\n } finally {\n // A list of the workbench made while the scan ran has the files from before it.\n workbenchList = undefined;\n }\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 function reachable(): Set<string> {\n const roots: string[] = [];\n for (const file of files.values()) {\n if (!findPackage(packages, file)) {\n roots.push(file);\n }\n }\n return reachableFiles(packages, [...roots, ...appScripts], (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 function resolveComponent(specifier: string, importer: string): string | undefined {\n return (\n resolveRelative(specifier, importer) ??\n (specifier.endsWith('.brm')\n ? resolveComponentPackage(packages, specifier, importer)\n : undefined)\n );\n }\n\n // Props are analyzed across the project, so a change to one file can change the output of others.\n async function analyze(): Promise<void> {\n const list = [...files.values()];\n const contents = await inBatches(list, (file) => readFile(file, 'utf8'));\n const sources = new Map<string, string>();\n for (const [index, file] of list.entries()) {\n sources.set(file, contents[index]!);\n }\n liveProps = analyzeProject(sources, resolveComponent);\n // The server functions that the app refreshes, from its components and its scripts.\n const scripts = await findScripts(root, exclude);\n const scriptSources = await inBatches(\n [...new Set([...scripts, ...serverFiles.values()])],\n (file) => readFile(file, 'utf8').catch(() => ''),\n );\n refreshed = refreshedNames([...contents, ...scriptSources]);\n compiled.clear();\n }\n\n /** The features of the core that the components of the build use, once for each build. */\n let builtFeatures: Promise<Features> | undefined;\n /** The files that `builtFeatures` counted, and the features it found. */\n let counted = new Set<string>();\n let knownFeatures: Features | undefined;\n /** The components that the client build loaded. */\n const loadedComponents = new Set<string>();\n function buildFeatures(): Promise<Features> {\n return (builtFeatures ??= (async () => {\n const seen = new Set<string>();\n const all: Features[] = [];\n // The files of the scan, and the components they import from outside it, such as a file\n // of a sibling folder or of a package with no `brumate` field.\n async function visit(file: string): Promise<void> {\n if (seen.has(file)) {\n return;\n }\n seen.add(file);\n const { result } = await compileFile(file);\n all.push(getFeatures(result));\n const imported: string[] = [];\n for (const specifier of importedComponents(result.file)) {\n const target = resolveComponent(specifier, file);\n if (target !== undefined && existsSync(target)) {\n imported.push(target);\n }\n }\n await inBatches(imported, visit);\n }\n await inBatches([...files.values()], visit);\n const features = joinFeatures(all);\n // Client navigation inserts the pages that it loads, and a route with `_loading.brm`\n // streams its body after the page.\n let loading = false;\n for (const file of seen) {\n if (path.basename(file) === '_loading.brm') {\n loading = true;\n break;\n }\n }\n features.lateMarkup ||= options.navigate !== false || loading;\n counted = seen;\n knownFeatures = features;\n return features;\n })());\n }\n\n /** The options of the compile of a file. */\n function compileOptions(file: string): CompileOptions {\n return {\n filename: getFileName(file),\n liveProps: liveProps.get(file),\n refreshed,\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 sendableClasses: serialClasses(),\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 ? resolveComponentPackage(packages, specifier, importer) : undefined;\n return found ? { path: found, source: readFileSync(found, 'utf8') } : local;\n },\n };\n }\n\n // The entry, the parts and the render module of a file come from one compile.\n async function compileFile(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 = { source, result: compile(source, compileOptions(file)) };\n compiled.set(file, cached);\n shapes.set(file, getShape(cached.result));\n }\n return cached;\n }\n\n /** The compiles whose imports were checked for the env file. */\n const envChecked = new WeakSet<CompileResult>();\n /**\n * Compiles a component again with the server variables of the env file,\n * when one of its imports resolves to it, by any specifier, such as an\n * alias. The compile fails when code that runs in the browser reads one.\n */\n async function checkEnvReads(\n file: string,\n { source, result }: { source: string; result: CompileResult },\n resolve: (specifier: string, importer: string) => Promise<{ id: string } | null>,\n ): Promise<void> {\n const env = envFile();\n if (!env || envChecked.has(result)) {\n return;\n }\n const specifiers = new Set<string>();\n for (const declaration of result.plan.graph.model.declarations) {\n if (declaration.imported) {\n specifiers.add(declaration.imported.source);\n }\n }\n const pending: Promise<string | undefined>[] = [];\n for (const specifier of specifiers) {\n pending.push(\n (async () => {\n const found = await resolve(specifier, file);\n return found?.id.split('?')[0] === env ? specifier : undefined;\n })(),\n );\n }\n const imports = new Set<string>();\n for (const specifier of await Promise.all(pending)) {\n if (specifier !== undefined) {\n imports.add(specifier);\n }\n }\n if (imports.size > 0) {\n const server = serverEnvKeys() ?? [];\n compile(source, {\n ...compileOptions(file),\n envImport: (specifier) => (imports.has(specifier) ? server : undefined),\n });\n }\n envChecked.add(result);\n }\n\n /** The components that a component imports, by file. */\n async function componentImports(file: string): Promise<string[]> {\n const { result } = await compileFile(file);\n const found: string[] = [];\n for (const declaration of result.plan.graph.model.declarations) {\n const source = declaration.imported?.source;\n const target = source?.endsWith('.brm') ? resolveComponent(source, file) : undefined;\n if (target !== undefined) {\n found.push(target);\n }\n }\n return found;\n }\n\n /**\n * The bundles of a build: for each component that no other component imports, such as a\n * route or a page, the components with client code that it can render. The page loads the\n * bundles of its roots at once, as one chunk each, so its code comes in one request.\n * Components that only import each other get a bundle too.\n */\n async function bundles(kept: Set<string>): Promise<Map<string, string[]>> {\n const imports = new Map<string, string[]>();\n await inBatches([...files.values()], async (file) => {\n try {\n imports.set(file, await componentImports(file));\n } catch {\n imports.set(file, []);\n }\n });\n const imported = new Set<string>();\n for (const targets of imports.values()) {\n for (const target of targets) {\n imported.add(target);\n }\n }\n const result = new Map<string, string[]>();\n // The components that a bundle holds so far.\n const reached = new Set<string>();\n function addRoot(id: string, file: string): void {\n const seen = new Set<string>();\n function walk(current: string): void {\n if (seen.has(current)) {\n return;\n }\n seen.add(current);\n reached.add(current);\n for (const next of imports.get(current) ?? []) {\n walk(next);\n }\n }\n walk(file);\n const members: string[] = [];\n for (const member of seen) {\n if (kept.has(member)) {\n members.push(member);\n }\n }\n if (members.length > 0) {\n result.set(id, members);\n }\n }\n for (const [id, file] of files) {\n if (!imported.has(file)) {\n addRoot(id, file);\n }\n }\n // Components that import each other, with no other component that imports them, have no\n // root of their own, so the first of them is the root of their bundle.\n for (const [id, file] of files) {\n if (!reached.has(file) && kept.has(file)) {\n addRoot(id, file);\n }\n }\n return result;\n }\n\n /** The ID of each component file. */\n function findComponentId(file: string): string | undefined {\n for (const [id, other] of files) {\n if (other === file) {\n return id;\n }\n }\n return undefined;\n }\n\n /** A bundle module: the client modules of a root component and of those it renders. */\n async function bundleModule(root: string): Promise<string> {\n const list = [...files];\n const needed = await inBatches(\n list,\n async ([, file]) => (await compileFile(file)).result.clientCode,\n );\n const kept = new Set<string>();\n for (const [index, [, file]] of list.entries()) {\n if (needed[index]) {\n kept.add(file);\n }\n }\n const members = (await bundles(kept)).get(root) ?? [];\n // Each module is a plain object of its exports. A namespace object, from `import * as`,\n // would make the bundler write a getter for each export.\n const imports: string[] = [];\n const objects: string[] = [];\n for (const [index, file] of members.entries()) {\n const { result } = await compileFile(file);\n const codes = [result.client];\n for (const [name, code] of Object.entries(result.parts)) {\n if (name !== 'shared') {\n codes.push(code);\n }\n }\n const names = exportNames(codes);\n const aliased: string[] = [];\n const fields: string[] = [];\n for (const name of names) {\n aliased.push(`${name} as $$c${index}_${name}`);\n fields.push(`${name}: $$c${index}_${name}`);\n }\n imports.push(\n `import { ${aliased.join(', ')} } from ${JSON.stringify(`${file}${CLIENT_QUERY}`)};`,\n );\n objects.push(` ${JSON.stringify(findComponentId(file))}: { ${fields.join(', ')} },`);\n }\n return [...imports, 'export const modules = {', ...objects, '};'].join('\\n');\n }\n\n async function manifest(): 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 inBatches(\n list,\n async ([, file]) => isServe || (await compileFile(file)).result.clientCode,\n );\n const kept: [string, string][] = [];\n for (const [index, entry] of list.entries()) {\n if (needed[index]) {\n kept.push(entry);\n }\n }\n if (!isServe) {\n // A build loads code by bundles of roots, so each component's code is in the chunk of\n // the page instead of a chunk of its own.\n const keptFiles = new Set<string>();\n for (const [, file] of kept) {\n keptFiles.add(file);\n }\n const groups = await bundles(keptFiles);\n const owners = new Map<string, string>();\n for (const [root, members] of groups) {\n for (const member of members) {\n const id = findComponentId(member);\n if (id !== undefined && !owners.has(id)) {\n owners.set(id, root);\n }\n }\n }\n const bundleLines: string[] = [];\n for (const root of groups.keys()) {\n bundleLines.push(\n ` ${JSON.stringify(root)}: () => import(${JSON.stringify(`${BUNDLE}${root}`)}),`,\n );\n }\n return [\n 'const bundles = {',\n ...bundleLines,\n '};',\n `const owners = ${JSON.stringify(Object.fromEntries(owners))};`,\n 'const loaded = new Map();',\n 'const pending = new Map();',\n '/** Loads the bundle of a root component of the page. Undefined for a component that is not a root. */',\n 'export function loadBundle(root) {',\n ' let promise = pending.get(root);',\n ' if (!promise && bundles[root]) {',\n ' promise = bundles[root]().then((bundle) => {',\n ' for (const [id, module] of Object.entries(bundle.modules)) {',\n ' loaded.set(id, module);',\n ' }',\n ' });',\n ' pending.set(root, promise);',\n ' promise.catch(() => pending.delete(root));',\n ' }',\n ' return promise;',\n '}',\n '/** The client module of a component, from the bundles of the page, or else from a bundle that holds it. */',\n 'export function load(id) {',\n ' if (loaded.has(id)) {',\n ' return Promise.resolve(loaded.get(id));',\n ' }',\n ' const waiting = [...pending.values()];',\n ' const owner = () => (loaded.has(id) || !owners[id] ? loaded.get(id) : loadBundle(owners[id]).then(() => loaded.get(id)));',\n ' return waiting.length > 0 ? Promise.allSettled(waiting).then(owner) : owners[id] ? owner() : undefined;',\n '}',\n ].join('\\n');\n }\n const entries: string[] = [];\n for (const [id, file] of kept) {\n entries.push(\n ` ${JSON.stringify(id)}: () => import(${JSON.stringify(`${file}${CLIENT_QUERY}`)}),`,\n );\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 function serverRegistry(server = false): string {\n const query = server ? SERVER_QUERY : '';\n registered = packages.length > 0 ? reachable() : new Set();\n function keep(file: string): boolean {\n return registered.has(file) || !findPackage(packages, file);\n }\n const components: string[] = [];\n for (const file of files.values()) {\n if (keep(file)) {\n components.push(file);\n }\n }\n // In development, a file that does not compile leaves out its functions, and the pages that\n // import it show its error, so the other pages still work.\n function importAll(prefix: string, list: string[]): string[] {\n if (!isServe) {\n const lines: string[] = [];\n for (const [index, file] of list.entries()) {\n lines.push(`import * as ${prefix}${index} from ${JSON.stringify(file + query)};`);\n }\n return lines;\n }\n if (list.length === 0) {\n return [];\n }\n const loads: string[] = [];\n const names: string[] = [];\n for (const [index, file] of list.entries()) {\n loads.push(`import(${JSON.stringify(file + query)})`);\n names.push(`${prefix}${index}`);\n }\n return [\n `const [${names.join(', ')}] = (await Promise.allSettled([${loads.join(', ')}])).map((result) => (result.status === 'fulfilled' ? result.value : {}));`,\n ];\n }\n const imports = importAll('m', components);\n const spreads: string[] = [];\n for (const index of components.keys()) {\n spreads.push(` ...m${index}.rpc,`);\n }\n // Each exported function of a file of server functions, under the ID that its stub calls.\n const functionFiles: [string, string][] = [];\n for (const entry of serverFiles) {\n if (keep(entry[1])) {\n functionFiles.push(entry);\n }\n }\n const functionPaths: string[] = [];\n for (const [, file] of functionFiles) {\n functionPaths.push(file);\n }\n const fileImports = importAll('f', functionPaths);\n // The middleware of a file runs before each of its functions.\n const guards: string[] = [];\n const fileSpreads: string[] = [];\n for (const [index, [id, file]] of functionFiles.entries()) {\n // The IDs are written here, so a build can hash the names of the functions.\n const source = readFileSync(file, 'utf8');\n const names = serverExports(source, file);\n const guarded = hasServerMiddleware(source, file);\n const lines: string[] = [];\n for (const name of names) {\n const key = JSON.stringify(functionId(id, name, !isServe));\n if (guarded) {\n guards.push(` ${key}: f${index}.middleware,`);\n }\n lines.push(` ${key}: f${index}[${JSON.stringify(name)}],`);\n }\n fileSpreads.push(lines.join('\\n'));\n }\n const env = envFile();\n const entry = middlewareFile();\n return [\n // The variables are checked when the server starts, before anything else loads.\n ...(env ? [`import ${JSON.stringify(env)};`] : []),\n ...serialImports(),\n \"import { handleRequest } from 'brumate/server';\",\n ...(entry ? [`import middleware from ${JSON.stringify(entry)};`] : []),\n ...imports,\n ...fileImports,\n 'export const functions = {',\n ...spreads,\n ...fileSpreads,\n '};',\n 'export const fileMiddleware = {',\n ...guards,\n '};',\n 'export function handle(request, options) {',\n ` return handleRequest(functions, request, ${JSON.stringify(rpc)}, { origins: ${JSON.stringify(options.origins ?? [])}, ${entry ? 'middleware, ' : ''}fileMiddleware${buildId === undefined ? '' : `, build: ${JSON.stringify(buildId)}`}, ...options });`,\n '}',\n ].join('\\n');\n }\n\n function routesDirectory(): string {\n return normalizePath(path.resolve(root, options.routes ?? 'src/routes'));\n }\n\n /** The route files, from the `.brm` files found and the `.ts` files of the directory. */\n function currentRoutes(): RouteFiles {\n const directory = routesDirectory();\n const paths: string[] = [];\n for (const file of files.values()) {\n if (file.startsWith(`${directory}/`)) {\n paths.push(file.slice(directory.length + 1));\n }\n }\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 /**\n * The modules that every page loads early, which the client build wrote,\n * or none before a client build or in development.\n */\n function clientHints(): { all: string[]; bundles: Record<string, string[]> } {\n const file = path.join(clientBuildDirectory(root, options.prerender), HINTS_FILE);\n if (isServe || !existsSync(file)) {\n return { all: [], bundles: {} };\n }\n const read = JSON.parse(readFileSync(file, 'utf8')) as\n | string[]\n | { all: string[]; bundles: Record<string, string[]> };\n return Array.isArray(read) ? { all: read, bundles: {} } : read;\n }\n\n /** The route tree module. A DOM test gets the server version of each component in it. */\n function routeTree(server = false): string {\n const env = envFile();\n const code = routeModule(\n currentRoutes(),\n (file) =>\n `${routesDirectory()}/${file}${server && file.endsWith('.brm') ? SERVER_QUERY : ''}`,\n rpc,\n options.origins,\n isServe,\n middlewareFile(),\n buildId,\n clientHints().all,\n clientHints().bundles,\n );\n // The variables are checked when the server starts, before any route loads.\n const serial = serialImports().join('\\n');\n const parts: string[] = [];\n for (const part of [env ? `import ${JSON.stringify(env)};` : '', serial, code]) {\n if (part) {\n parts.push(part);\n }\n }\n return parts.join('\\n');\n }\n\n /** Writes the paths of the routes as types for `href`, when they changed. */\n function 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 async function inspectComponent(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[]; readers: string[][] }> = {};\n // The code of the browser that reads each slot, such as a handler or an update, which is\n // why its value is in the page state, for the Page state tab.\n function siteLabel(site: Site): string {\n const at = result.locate(site.range.start);\n const where = at.file === undefined ? getLocation(source, at.offset) : undefined;\n return where ? `${site.label} ${where.line}:${where.column}` : site.label;\n }\n // Updates of markup and memos run in the browser as nodes of the graph that can change.\n const liveSites = new Set<Site>();\n for (const node of plan.graph.live) {\n if ('site' in node) {\n liveSites.add(node.site);\n }\n }\n for (const layout of plan.scopes.values()) {\n const slotNames: string[] = [];\n const readers: string[][] = [];\n for (const slot of layout.slots) {\n slotNames.push(slot.name);\n const labels = new Set<string>();\n for (const ref of slot.reads) {\n if (plan.graph.reached.has(ref.site) || liveSites.has(ref.site)) {\n labels.add(siteLabel(ref.site));\n }\n }\n readers.push([...labels]);\n }\n scopes[layout.scope.id] = {\n label: scopeLabel(result.file.source, layout.scope),\n slots: slotNames,\n readers,\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: (typeof plan.graph.nodes)[number][] = [];\n const indexes = new Map<(typeof nodes)[number], number>();\n for (const node of plan.graph.nodes) {\n if (plan.graph.live.has(node)) {\n indexes.set(node, nodes.length);\n nodes.push(node);\n }\n }\n const graphNodes: object[] = [];\n for (const node of nodes) {\n if (node.kind === 'source' || node.kind === 'memo') {\n graphNodes.push({\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 continue;\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 graphNodes.push({\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 const graphEdges: number[][] = [];\n for (const edge of plan.graph.edges) {\n if (indexes.has(edge.from) && indexes.has(edge.to)) {\n graphEdges.push([indexes.get(edge.from)!, indexes.get(edge.to)!]);\n }\n }\n const graph = { nodes: graphNodes, edges: graphEdges };\n // Each anchor of each scope: what it is, its place in the file and the values its updates\n // read, for the Elements tab, which finds them by the `b-b` of an element.\n const anchors: Record<\n number,\n Record<number, { label: string; at?: string; reads: string[] }>\n > = {};\n for (const [target, index] of plan.anchors) {\n const scope = plan.anchorScopes.get(target);\n if (!scope) {\n continue;\n }\n const at = result.locate('range' in target ? target.range.start : target.start);\n const where = at.file === undefined ? getLocation(source, at.offset) : undefined;\n const reads = new Set<string>();\n for (const edge of plan.graph.edges) {\n const node = edge.to;\n if (node.kind === 'source' || node.kind === 'memo') {\n continue;\n }\n const site = node.site;\n const range = !('range' in target) && target.kind === 'insert' ? target : undefined;\n if (\n site === target ||\n site.owner === target ||\n site.block === target ||\n (range && site.range.start >= range.start && site.range.end <= range.end)\n ) {\n if (edge.from.kind === 'source' || edge.from.kind === 'memo') {\n reads.add(edge.from.declaration.name);\n }\n }\n }\n // An insert that is the whole content of its element shares the element's anchor.\n const known = anchors[scope.id]?.[index];\n if (known) {\n known.reads = [...new Set([...known.reads, ...reads])];\n continue;\n }\n (anchors[scope.id] ??= {})[index] = {\n label: anchorLabel(target),\n ...(where ? { at: `${where.line}:${where.column}` } : {}),\n reads: [...reads],\n };\n }\n const text = formatReport(report(source, result, liveProps.get(file)));\n return {\n name: plan.name,\n file: getFileName(file),\n // The absolute path, for the editor, and the URL that the browser loads the code from.\n path: file,\n url: file.startsWith(`${normalizePath(root)}/`)\n ? file.slice(normalizePath(root).length)\n : `/@fs${file}`,\n scopes,\n anchors,\n graph,\n text,\n };\n }\n\n /** The components of the app for the workbench, with what each one needs and its controls. */\n /**\n * The stories of a component: the named exports of the `.stories.ts` file next to it, each a\n * set of props. Values that JSON cannot hold, such as functions, are left out.\n */\n async function workbenchStories(\n server: ViteDevServer,\n file: string,\n ): Promise<{ stories: { name: string; props: unknown }[]; storiesError?: string }> {\n const storiesFile = file.replace(/\\.brm$/, '.stories.ts');\n if (!existsSync(storiesFile)) {\n return { stories: [] };\n }\n try {\n const module = (await server.ssrLoadModule(storiesFile)) as Record<string, unknown>;\n const stories: { name: string; props: unknown }[] = [];\n for (const [name, props] of Object.entries(module)) {\n if (name !== 'default' && props && typeof props === 'object') {\n stories.push({ name, props: JSON.parse(JSON.stringify(props)) as unknown });\n }\n }\n return { stories };\n } catch (error) {\n return { stories: [], storiesError: error instanceof Error ? error.message : String(error) };\n }\n }\n\n /** The group of a component of a package: its name, and the folder under the directory of its files. */\n function packageGroup(owner: BrumatePackage, file: string): string {\n let directory = owner.root;\n for (const item of owner.directories) {\n if (file.startsWith(`${item}/`)) {\n directory = item;\n break;\n }\n }\n const folder = path.posix.dirname(file.slice(directory.length + 1));\n return folder === '.' ? owner.name : `${owner.name}/${folder}`;\n }\n\n async function workbenchComponents(\n server: ViteDevServer,\n ): Promise<{ file: string; selfContained: boolean; [key: string]: unknown }[]> {\n const routes = `${routesDirectory()}/`;\n const list = [...new Set(files.values())];\n const contents = await inBatches(list, (file) => readFile(file, 'utf8'));\n const sources = new Map<string, string>();\n for (const [index, file] of list.entries()) {\n sources.set(file, contents[index]!);\n }\n const classes = classifyComponents(sources, {\n resolve: resolveComponent,\n serverImport: (file, specifier, name) => serverImport(file, specifier, name) !== undefined,\n });\n function relative(file: string): string {\n return normalizePath(path.relative(root, file));\n }\n const shown: string[] = [];\n for (const file of list) {\n if (!file.startsWith(routes) && classes.has(file)) {\n shown.push(file);\n }\n }\n const stories = await inBatches(shown, (file) => workbenchStories(server, file));\n const components: { file: string; selfContained: boolean; [key: string]: unknown }[] = [];\n for (const [index, file] of shown.entries()) {\n const found = classes.get(file)!;\n let controls: unknown[] | undefined = [];\n try {\n controls = propControls(parseComponent(sources.get(file)!, { filename: file }));\n } catch {\n // The compile of the file reports the error. The page says that it has no controls.\n controls = undefined;\n }\n // A component of a package is grouped under the name of the package, and the others by\n // their folder.\n const owner = findPackage(packages, file);\n const needs: (typeof found.needs)[number][] = [];\n for (const need of found.needs) {\n needs.push({ ...need, via: need.via && relative(need.via) });\n }\n components.push({\n file: relative(file),\n group: owner ? packageGroup(owner, file) : path.posix.dirname(relative(file)),\n // The name that the page shows: the import of a component of a package, or its path.\n label: owner ? `${packageGroup(owner, file)}/${path.basename(file)}` : relative(file),\n name: path.basename(file, '.brm'),\n selfContained: found.selfContained,\n needs,\n controls: controls ?? [],\n unreadProps: controls === undefined,\n ...stories[index],\n });\n }\n return components.toSorted((a, b) => a.file.localeCompare(b.file));\n }\n\n // The last list of the workbench. A frame renders on each change of a prop, so it reads this\n // list, and a change of a file clears it.\n let workbenchList: ReturnType<typeof workbenchComponents> | undefined;\n\n /** Makes the list of the workbench and keeps it, unless it fails, so a later read tries again. */\n function listWorkbench(server: ViteDevServer): ReturnType<typeof workbenchComponents> {\n const list = workbenchComponents(server);\n workbenchList = list;\n list.catch(() => {\n if (workbenchList === list) {\n workbenchList = undefined;\n }\n });\n return list;\n }\n\n /**\n * Answers the workbench: its page, the list of components, and the frame that renders one\n * component on the server with props, and resumes it in the browser as a page does.\n */\n async function serveWorkbench(\n server: ViteDevServer,\n request: IncomingMessage,\n response: ServerResponse,\n ): Promise<void> {\n const url = new URL(request.url ?? '/', 'http://localhost');\n if (url.pathname === WORKBENCH || url.pathname === `${WORKBENCH}/`) {\n response.setHeader('content-type', 'text/html; charset=utf-8');\n response.end(workbenchPage(WORKBENCH));\n return;\n }\n if (url.pathname === `${WORKBENCH}/components`) {\n response.setHeader('content-type', 'application/json');\n response.end(JSON.stringify(await listWorkbench(server)));\n return;\n }\n if (url.pathname !== `${WORKBENCH}/frame`) {\n response.statusCode = 404;\n response.end();\n return;\n }\n // Only a component that the workbench lists as self-contained, by its path from the root.\n // Any other renders without the request, the route or the server that it needs, and fails.\n const asked = url.searchParams.get('file') ?? '';\n let listed = false;\n for (const component of await (workbenchList ?? listWorkbench(server))) {\n if (component.file === asked && component.selfContained) {\n listed = true;\n break;\n }\n }\n let file: string | undefined;\n if (listed) {\n for (const candidate of files.values()) {\n if (normalizePath(path.relative(root, candidate)) === asked) {\n file = candidate;\n break;\n }\n }\n }\n if (!file) {\n response.statusCode = 404;\n response.end(`No self-contained component \"${asked}\"`);\n return;\n }\n response.setHeader('content-type', 'text/html; charset=utf-8');\n try {\n const props = JSON.parse(url.searchParams.get('props') || '{}') as Record<string, unknown>;\n const component = (await server.ssrLoadModule(file)).default;\n const { renderToStream } = await server.ssrLoadModule('brumate/server');\n const stream = (renderToStream as typeof RenderToStream)(component, props, {\n start: `<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>${path.basename(file, '.brm')}</title></head><body>`,\n end: '</body></html>',\n // The client of Vite and the loader, as the entry of an app starts it.\n scripts: `<script type=\"module\" src=\"/@vite/client\"></script><script type=\"module\" src=\"/@id/__x00__${START}\"></script>`,\n });\n const reader = stream.getReader();\n for (;;) {\n // oxlint-disable-next-line no-await-in-loop -- The page streams in order.\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n response.write(value);\n }\n response.end();\n } catch (error) {\n // Once the page has started, its status is sent, and a second document would land inside\n // the first. The error goes to the terminal, and the page ends where it stopped.\n if (response.headersSent) {\n server.config.logger.error(\n error instanceof Error ? (error.stack ?? error.message) : String(error),\n );\n response.end();\n return;\n }\n response.statusCode = 500;\n response.end(errorPage(error, server));\n }\n }\n\n async function handleDevRPC(\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 && findPackage(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 { handle } = await server.ssrLoadModule(SERVER);\n // The same path as production, so server functions can read the request.\n const headers: [string, string][] = [];\n for (const [name, value] of Object.entries(request.headers)) {\n if (value !== undefined) {\n headers.push([name, String(value)]);\n }\n }\n const webRequest = new Request(new URL(request.url ?? '/', 'http://localhost'), {\n method: 'POST',\n headers,\n body: new Uint8Array(await readBody(request)),\n });\n const began = performance.now();\n const answer: Response = await handle(webRequest, {\n address: request.socket.remoteAddress,\n });\n // How long the server function took on the server, for the Timeline of the devtools.\n answer.headers.append(\n 'server-timing',\n `brumate;dur=${(performance.now() - began).toFixed(1)};desc=\"server function\"`,\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 function 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 function 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 = getShape((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 let entry: (typeof modules)[number] | undefined;\n for (const module of server.moduleGraph.getModulesByFile(target) ?? []) {\n if (module.id?.endsWith(CLIENT_QUERY)) {\n entry = module;\n break;\n }\n }\n const kept: string[] = [];\n for (const name of after.signals) {\n if (before.signals.includes(name)) {\n kept.push(name);\n }\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: kept,\n }\n : undefined,\n });\n }\n let remounts = false;\n for (const update of updates) {\n if (update.remount) {\n remounts = true;\n break;\n }\n }\n if (remounts) {\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 function packageConfig(config: UserConfig): UserConfig {\n if (packages.length === 0) {\n return {};\n }\n const nameSet = new Set<string>();\n for (const item of packages) {\n nameSet.add(item.name);\n }\n const names = [...nameSet];\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: string[] = [];\n for (const item of packages) {\n if (item.root !== workspace && !item.root.startsWith(`${workspace}/`)) {\n outside.push(item.root);\n }\n }\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 // The devtools show the errors of Vite, so its overlay does not cover them.\n const hmr = config.server?.hmr;\n if (\n env.command === 'serve' &&\n options.devtools !== false &&\n hmr !== false &&\n (typeof hmr !== 'object' || hmr.overlay === undefined)\n ) {\n shared.server = { hmr: { overlay: false } };\n }\n if (!env.isSsrBuild) {\n const preload = config.build?.modulePreload;\n // The files of earlier builds stay, and the build removes the ones that are too old itself.\n const keep = options.skew?.keep ? { build: { emptyOutDir: false } } : {};\n if (preload === false) {\n return { ...shared, ...keep };\n }\n const resolve = typeof preload === 'object' ? preload.resolveDependencies : undefined;\n return {\n ...shared,\n build: {\n ...keep.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: string[] = [];\n for (const dep of list) {\n if (dep !== coreChunk) {\n rest.push(dep);\n }\n }\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 let entries: Record<string, string>;\n if (typeof input === 'string') {\n entries = { [path.basename(input).replace(/\\.[^.]+$/, '')]: input };\n } else if (Array.isArray(input)) {\n entries = {};\n for (const item of input) {\n entries[path.basename(item).replace(/\\.[^.]+$/, '')] = item;\n }\n } else {\n entries = { ...(input as Record<string, string> | undefined) };\n }\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?.(cacheKey);\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 // The core has no code for the features that the counted components do not use, so a\n // component that the count did not reach must not need more of them.\n for (const file of knownFeatures ? loadedComponents : []) {\n if (counted.has(file)) {\n continue;\n }\n const used = getFeatures((await compileFile(file)).result);\n const missing: (keyof Features)[] = [];\n for (const name of Object.keys(used) as (keyof Features)[]) {\n if (used[name] && !knownFeatures![name]) {\n missing.push(name);\n }\n }\n if (missing.length > 0) {\n this.error(\n `${getFileName(file)} uses ${missing.join(', ')}, which the client build left out of the core, since no component that the build found uses them. Import it from a .brm component of the app, or set \\`features: 'all'\\`.`,\n );\n }\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 const modules: Record<string, number> = {};\n for (const [id, module] of Object.entries(item.modules)) {\n modules[id] = module.renderedLength;\n }\n chunks.push({\n fileName: item.fileName,\n code: item.code,\n isEntry: item.isEntry,\n imports: item.imports,\n moduleIds: item.moduleIds,\n modules,\n });\n }\n }\n const list = [...files.values()];\n const contents = await inBatches(list, (file) => readFile(file, 'utf8'));\n const sources = new Map<string, string>();\n for (const [index, file] of list.entries()) {\n sources.set(file, contents[index]!);\n }\n const measured = buildReport({\n chunks,\n sources,\n routes: existsSync(routesDirectory())\n ? { tree: currentRoutes(), resolve: (file) => `${routesDirectory()}/${file}` }\n : undefined,\n budget: options.budget,\n relative: getFileName,\n });\n if (options.report) {\n this.info(`\\n${formatBuildReport(measured, getFileName)}`);\n }\n if (measured.overBudget.length > 0) {\n this.error(measured.overBudget.join('\\n'));\n }\n },\n\n async writeBundle(_output, bundle) {\n if (!isSsrBuild) {\n // The modules that every page loads early, for the `Link` headers of the server build.\n const chunks = new Map<string, Extract<(typeof bundle)[string], { type: 'chunk' }>>();\n for (const item of Object.values(bundle)) {\n if (item.type === 'chunk') {\n chunks.set(item.fileName, item);\n }\n }\n const hints = new Set<string>();\n function add(name: string | undefined): void {\n const chunk = name === undefined ? undefined : chunks.get(name);\n if (chunk && !hints.has(chunk.fileName)) {\n hints.add(chunk.fileName);\n for (const imported of chunk.imports) {\n add(imported);\n }\n }\n }\n add(loaderChunk);\n add(coreChunk);\n // The chunks of the bundle of each root, which its pages load early too.\n const bundleHints: Record<string, string[]> = {};\n for (const chunk of chunks.values()) {\n const facade = chunk.facadeModuleId ?? '';\n if (!facade.startsWith(`\\0${BUNDLE}`)) {\n continue;\n }\n const files = new Set<string>();\n function walk(name: string): void {\n const found = chunks.get(name);\n if (found && !files.has(name) && !hints.has(name)) {\n files.add(name);\n for (const imported of found.imports) {\n walk(imported);\n }\n }\n }\n walk(chunk.fileName);\n const urls: string[] = [];\n for (const name of files) {\n urls.push(`${base}${name}`);\n }\n bundleHints[facade.slice(BUNDLE.length + 1)] = urls;\n }\n await mkdir(path.join(outDir, '.brumate'), { recursive: true });\n const all: string[] = [];\n for (const name of hints) {\n all.push(`${base}${name}`);\n }\n await writeFile(\n path.join(outDir, HINTS_FILE),\n JSON.stringify({ all, bundles: bundleHints }),\n );\n if (buildId !== undefined) {\n const written: string[] = [];\n for (const item of Object.values(bundle)) {\n written.push(item.fileName);\n }\n const removed = pruneBuilds(outDir, buildId, written, options.skew?.keep ?? 0);\n if (removed.length > 0) {\n this.info(`Removed the files of ${removed.length} older builds`);\n }\n }\n return;\n }\n if (!options.prerender || !isSsrBuild) {\n return;\n }\n let chunk: (typeof bundle)[string] | undefined;\n for (const item of Object.values(bundle)) {\n if (item.type === 'chunk' && item.isEntry && item.name === PRERENDER_ENTRY) {\n chunk = item;\n break;\n }\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 if (!isServe) {\n if (isSsrBuild) {\n // The server build names the build of the client, which must come first.\n const client = clientBuildDirectory(root, options.prerender);\n buildId = process.env.BRUMATE_BUILD || readBuildId(client);\n if (buildId === undefined) {\n this.warn(\n `No ${BUILD_FILE} in ${path.relative(root, client)}, so the server does not know its build ID. Build the client first, or set BRUMATE_BUILD, for skew protection`,\n );\n }\n } else {\n buildId =\n process.env.BRUMATE_BUILD || `${Date.now().toString(36)}${hash(String(Math.random()))}`;\n }\n }\n coreModule = isServe\n ? undefined\n : (await this.resolve('brumate/client', path.join(root, 'index.html')))?.id;\n await scan();\n // A rebuild in watch mode counts the features of the components again.\n builtFeatures = undefined;\n knownFeatures = undefined;\n loadedComponents.clear();\n writeRouteTypes();\n },\n\n async resolveId(id, importer, resolveOptions) {\n if (\n id === START ||\n id === MANIFEST ||\n id === SERVER ||\n id === ROUTES ||\n id === TESTING ||\n id.startsWith(BUNDLE)\n ) {\n return `\\0${id}`;\n }\n // In code that the browser loads, only components import the env file, because the\n // compiler checks that their browser code reads no server variable. It cannot check scripts.\n const env = resolveOptions?.ssr ? undefined : envFile();\n const from = importer?.split('?')[0];\n if (\n env &&\n importer &&\n from &&\n from !== env &&\n isScriptFile(from) &&\n !importer.startsWith('\\0') &&\n !importer.includes(SERVER_QUERY) &&\n !importer.includes('/node_modules/')\n ) {\n const resolved = await this.resolve(id, importer, { ...resolveOptions, skipSelf: true });\n if (resolved?.id.split('?')[0] === env) {\n this.error(\n `${relative(from)} imports ${relative(env)}, and the browser loads it. Only components can import the env file in code that the browser loads, because the compiler checks what they read. Read the variable in a component or a server function, and pass the value on.`,\n );\n }\n return resolved ?? undefined;\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) &&\n importer !== `\\0${SERVER}` &&\n importer !== `\\0${ROUTES}`) ||\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/') && !findPackage(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${isServe ? '' : ', loadBundle'} } 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)' : ', loadBundle'}${serialFile() ? `, serial: () => import(${JSON.stringify(serialFile())})` : ''}, rpc: ${JSON.stringify(rpc)}, navigate: ${JSON.stringify(options.navigate ?? true)}${buildId === undefined ? '' : `, build: ${JSON.stringify(buildId)}`} });`,\n // The devtools listen to the core before it starts. Only the dev server has them.\n ...(isServe && options.devtools !== false\n ? [\n // They show the errors of Vite, such as a compile error after an edit, in place of its overlay.\n `import('brumate/devtools').then((m) => m.installDevtools(${JSON.stringify(INSPECT)}, ${JSON.stringify(rpc)}, ${JSON.stringify({ version: BRUMATE_VERSION, vite: viteVersion })}, import.meta.hot));`,\n ]\n : []),\n ].join('\\n');\n }\n if (id === `\\0${MANIFEST}`) {\n return await manifest();\n }\n if (id.startsWith(`\\0${BUNDLE}`)) {\n return await bundleModule(id.slice(BUNDLE.length + 1));\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(!loadOptions?.ssr);\n }\n if (id === `\\0${TESTING}`) {\n const entry = middlewareFile();\n return [\n \"import { answerCalls as answer, createMount, createVisit } from 'brumate/testing';\",\n `import { load } from ${JSON.stringify(MANIFEST)};`,\n ...(entry ? [`import middleware from ${JSON.stringify(entry)};`] : []),\n `export const mount = createMount({ load, rpc: ${JSON.stringify(rpc)} });`,\n // The routes and the server code load on the first visit, so a test of components skips them.\n 'export const visit = createVisit({',\n ' load,',\n ` rpc: ${JSON.stringify(rpc)},`,\n ` routes: async () => (await import(${JSON.stringify(ROUTES)})).handle,`,\n ` calls: async () => (await import(${JSON.stringify(SERVER)})).handle,`,\n '});',\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 ` const server = import(${JSON.stringify(SERVER)});`,\n ` return answer(async () => (await server).functions, { rpc: ${JSON.stringify(rpc)}, ${entry ? 'middleware, ' : ''}fileMiddleware: async () => (await server).fileMiddleware, ...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 await checkEnvReads(file, output, (specifier, importer) =>\n this.resolve(specifier, importer),\n );\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 if (!isServe && !isSsrBuild && isClient) {\n loadedComponents.add(file);\n }\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} (${getFileName(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 const sources: (string | null)[] = [];\n if (map) {\n for (const [index, name] of map.sources.entries()) {\n sources.push(index === 0 ? file : name);\n }\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,\n },\n };\n },\n\n async transform(code, id, transformOptions) {\n // The client build leaves out the code of the features of the core that no component\n // uses. The dev server and the server build keep every feature, and so does a build with\n // `features: 'all'`, such as one that compiles components in the browser.\n if (!isServe && !isSsrBuild && !transformOptions?.ssr && readsFeatures(code)) {\n const features = options.features === 'all' ? allFeatures() : await buildFeatures();\n return { code: writeFeatures(code, features), map: null };\n }\n const [file] = id.split('?');\n // The browser gets the env file without the server variables, and with the values of the\n // public ones, read now.\n if (file && !transformOptions?.ssr && file === envFile()) {\n try {\n return { code: clientEnvModule(code, file, process.env), map: null };\n } catch (error) {\n this.error((error as Error).message);\n }\n }\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 let lang: 'ts' | 'tsx' | 'jsx' = 'jsx';\n if (/\\.[cm]?ts$/.test(file)) {\n lang = 'ts';\n } else if (file.endsWith('.tsx')) {\n lang = 'tsx';\n }\n const result = await transformWithOxc(serverModule(code, file, fileId), file, {\n lang,\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: string[] = [];\n for (const item of packages) {\n if (item.linked) {\n linked.push(...item.directories);\n }\n }\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: string[] = [normalizePath(path.join(root, 'package.json'))];\n for (const item of packages) {\n manifests.push(normalizePath(`${item.root}/package.json`));\n }\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 workbenchList = undefined;\n // The names of the server variables are part of what each component compiles with.\n if (normalizePath(file) === envFile()) {\n compiled.clear();\n }\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 && !findPackage(packages, normalized)) {\n const rest: string[] = [];\n for (const item of appScripts) {\n if (item !== normalized) {\n rest.push(item);\n }\n }\n appScripts = rest;\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 // The source of a file that an error names, for the code of the Errors tab. Only files\n // that Vite would serve, by its `server.fs` options.\n if (request.method === 'GET' && request.url?.startsWith(`${SOURCE}?`)) {\n const asked = new URL(request.url, 'http://localhost').searchParams.get('file') ?? '';\n const file = normalizePath(\n path.isAbsolute(asked) && existsSync(asked)\n ? asked\n : path.join(server.config.root, asked),\n );\n if (!existsSync(file) || !isFileLoadingAllowed(server.config, file)) {\n response.statusCode = 404;\n response.end();\n return;\n }\n response.setHeader('content-type', 'text/plain; charset=utf-8');\n response.end(readFileSync(file, 'utf8'));\n return;\n }\n if (request.method === 'GET' && request.url?.startsWith(`${POSITION}?`)) {\n const params = new URL(request.url, 'http://localhost').searchParams;\n void server.environments.client.moduleGraph\n .getModuleByUrl(params.get('url') ?? '')\n .then((module) => {\n const map = module?.transformResult?.map as\n | { sources: (string | null)[]; mappings: string }\n | null\n | undefined;\n const place =\n map && module?.file\n ? originalPosition(map, Number(params.get('line')), Number(params.get('column')))\n : undefined;\n // A source that starts with `/` is a path from the root of the app, as Vite writes it.\n const file =\n place &&\n normalizePath(\n place.source.startsWith('/') && !existsSync(place.source)\n ? path.join(server.config.root, place.source)\n : path.resolve(path.dirname(module!.file!), place.source),\n );\n response.setHeader('content-type', 'application/json');\n response.end(JSON.stringify(place ? { ...place, file } : null));\n })\n .catch(next);\n return;\n }\n if (request.method === 'GET' && request.url?.startsWith(WORKBENCH)) {\n void serveWorkbench(server, request, response).catch(next);\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 (\n !file.endsWith('.brm') &&\n !dependents.has(normalized) &&\n normalized !== middlewareFile() &&\n normalized !== envFile()\n ) {\n // A module that the server code imports, such as data or Markdown that a page renders,\n // changes the HTML of the page, and the browser has no code that could update it. Vite\n // invalidates the module for the next render, and the page reloads to get it.\n if (environment.moduleGraph.getModulesByFile(normalized)?.size) {\n server.environments.client.hot.send({ type: 'full-reload' });\n }\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\n/** The names that compiled client code exports, such as `h4`, `u5` and `g`. */\nfunction exportNames(codes: string[]): string[] {\n const names = new Set<string>();\n for (const code of codes) {\n for (const match of code.matchAll(\n /^export (?:async )?(?:function\\*? |const |let |var )([\\w$]+)|^export \\{([^}]*)\\}/gm,\n )) {\n if (match[1]) {\n names.add(match[1]);\n }\n for (const item of match[2]?.split(',') ?? []) {\n const name = item\n .trim()\n .split(/\\s+as\\s+/)\n .pop();\n if (name) {\n names.add(name);\n }\n }\n }\n }\n return [...names];\n}\n"],"mappings":";;;;;;;;;;;;;AAUA,MAAM,SAAS;;AAgBf,SAAS,SAAS,MAAgB,OAAe,UAA4B;CAC3E,IAAI,KAAK,SAAS,oBAChB,MAAM,IAAI,MACR,OAAO,MAAM,gBAAgB,SAAS,iEACxC;CAEF,MAAM,OAAiB,CAAC;CACxB,KAAK,MAAM,YAAY,KAAK,YAAY;EACtC,IAAI,SAAS,SAAS,cAAc,CAAC,SAAS,UAAU;GACtD,KAAK,KACH,SAAS,IAAI,SAAS,eAClB,SAAS,IAAI,OACb,OAAQ,SAAS,IAA4B,KAAK,CACxD;GACA;EACF;EACA,MAAM,IAAI,MACR,O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AO,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;CAEU;AACd;;AAWA,SAAS,YAAY,OAA2B;CAC9C,MAAM,wBAAQ,IAAI,IAAY;CAC9B,KAAK,MAAM,QAAQ,OACjB,KAAK,MAAM,SAAS,KAAK,SACvB,oFACF,GAAG;EACD,IAAI,MAAM,IACR,MAAM,IAAI,MAAM,EAAE;EAEpB,KAAK,MAAM,QAAQ,MAAM,EAAE,EAAE,MAAM,GAAG,KAAK,CAAC,GAAG;GAC7C,MAAM,OAAO,KACV,KAAK,CAAC,CACN,MAAM,UAAU,CAAC,CACjB,IAAI;GACP,IAAI,MACF,MAAM,IAAI,IAAI;EAElB;CACF;CAEF,OAAO,CAAC,GAAG,KAAK;AAClB"}
1
+ {"version":3,"file":"vite.js","names":["viteVersion","parseComponent","viteVersion"],"sources":["../src/env-file.ts","../src/features.ts","../src/builds.ts","../src/version.ts","../src/dev-error.ts","../src/workbench-page.ts","../src/workbench.ts","../src/prerender.ts","../src/report.ts","../src/routes.ts","../src/vite.ts"],"sourcesContent":["// The file of environment variables, `src/env.ts`, which calls `defineEnv`\n// from `brumate/env` with the schemas of the server and the public\n// variables. The compiler reads which variables are server values, and the\n// Vite plugin writes the copy of the file that the browser gets: without the\n// server schemas, and with the values of the public variables.\n\nimport { parseSync } from 'oxc-parser';\nimport type { oxc } from './oxc.ts';\n\n/** The name of the function that declares the variables. */\nconst DEFINE = 'defineEnv';\n\nexport interface EnvFile {\n /** The names of the server variables. */\n server: string[];\n /** The names of the public variables. */\n public: string[];\n /** The range of the `server: { … }` property, with its comma, or undefined without one. */\n serverRange?: { start: number; end: number };\n /** The end of the first argument of `defineEnv`, where the options go. */\n schemaEnd: number;\n /** True if the call has options already. */\n hasOptions: boolean;\n}\n\n/** The names of the properties of an object literal. Other keys throw. */\nfunction readKeys(node: oxc.Node, group: string, filename: string): string[] {\n if (node.type !== 'ObjectExpression') {\n throw new Error(\n `The ${group} variables of ${filename} must be an object literal, so the compiler can read their names`,\n );\n }\n const keys: string[] = [];\n for (const property of node.properties) {\n if (property.type === 'Property' && !property.computed) {\n keys.push(\n property.key.type === 'Identifier'\n ? property.key.name\n : String((property.key as { value?: unknown }).value),\n );\n continue;\n }\n throw new Error(\n `The ${group} variables of ${filename} must be plain properties, so the compiler can read their names`,\n );\n }\n return keys;\n}\n\n/** Finds the `defineEnv` call of the file. */\nfunction findCall(program: oxc.Program): oxc.CallExpression | undefined {\n let found: oxc.CallExpression | undefined;\n function visit(node: unknown): void {\n if (found || typeof node !== 'object' || node === null) {\n return;\n }\n const value = node as oxc.Node & { callee?: oxc.Node & { name?: string } };\n if (value.type === 'CallExpression' && value.callee?.name === DEFINE) {\n found = value as oxc.CallExpression;\n return;\n }\n for (const child of Object.values(value)) {\n if (Array.isArray(child)) {\n for (const item of child) {\n visit(item);\n }\n } else if (typeof child === 'object') {\n visit(child);\n }\n }\n }\n visit(program);\n return found;\n}\n\n/**\n * Reads the variables that a file of environment variables declares. The\n * schemas are written in the call, as object literals, so their names can\n * be read without running the file.\n */\nexport function parseEnvFile(source: string, filename: string): EnvFile {\n const { program, errors } = parseSync(filename, source, { lang: 'ts' });\n if (errors[0]) {\n throw new Error(`${errors[0].message} (${filename})`);\n }\n const call = findCall(program);\n const schema = call?.arguments[0];\n if (!call || schema?.type !== 'ObjectExpression') {\n throw new Error(\n `${filename} must call ${DEFINE} with an object literal of server and public variables`,\n );\n }\n const result: EnvFile = {\n server: [],\n public: [],\n schemaEnd: schema.end,\n hasOptions: call.arguments.length > 1,\n };\n for (const [index, property] of schema.properties.entries()) {\n if (property.type !== 'Property' || property.computed || property.key.type !== 'Identifier') {\n throw new Error(`${DEFINE} in ${filename} takes server and public variables only`);\n }\n const group = property.key.name;\n if (group !== 'server' && group !== 'public') {\n throw new Error(`${DEFINE} in ${filename} takes server and public variables, not ${group}`);\n }\n result[group] = readKeys(property.value, group, filename);\n if (group === 'server') {\n // The property with its comma, so the browser's copy stays valid code.\n const next = schema.properties[index + 1];\n const comma = source.indexOf(',', property.end);\n let end = property.end;\n if (next) {\n end = next.start;\n } else if (comma !== -1 && comma < schema.end) {\n end = comma + 1;\n }\n result.serverRange = { start: property.start, end };\n }\n }\n return result;\n}\n\n/**\n * The copy of the file that the browser gets: the server schemas are gone,\n * and the values of the public variables, read when the build or the dev\n * server ran, are the source of the call. The public schemas check them in\n * the browser, as the server's do on the server.\n */\nexport function clientEnvModule(\n source: string,\n filename: string,\n values: Record<string, string | undefined>,\n): string {\n const file = parseEnvFile(source, filename);\n if (file.hasOptions) {\n throw new Error(\n `${DEFINE} in ${filename} takes no options, because the Vite plugin writes the values of the browser`,\n );\n }\n const given: Record<string, string> = {};\n for (const name of file.public) {\n const value = values[name];\n if (value !== undefined) {\n given[name] = value;\n }\n }\n const edits: { start: number; end: number; text: string }[] = [\n { start: file.schemaEnd, end: file.schemaEnd, text: `, { source: ${JSON.stringify(given)} }` },\n ];\n if (file.serverRange) {\n edits.push({ ...file.serverRange, text: '' });\n }\n let result = '';\n let position = 0;\n for (const edit of edits.toSorted((a, b) => a.start - b.start)) {\n result += source.slice(position, edit.start) + edit.text;\n position = edit.end;\n }\n return result + source.slice(position);\n}\n","// The features of the core that a compiled component uses. The Vite plugin turns off, in the\n// client build of an app, the features that none of its components use. See\n// `runtime/features.ts`.\nimport type { CompileResult } from './compile.ts';\n\nexport interface Features {\n /** Children that the browser renders with an export of their own. */\n children: boolean;\n /** `#template` values that the browser calls. */\n templates: boolean;\n /** `<title>` elements in markup. */\n titles: boolean;\n /** `$bind` that a component passes to another. */\n bindings: boolean;\n /** Markup that comes after the page: `#loading`, `#defer` and lists that stream. */\n lateMarkup: boolean;\n /** `$client` callbacks and `#defer` blocks. */\n blocks: boolean;\n /** Handlers of the window or the document. */\n listeners: boolean;\n /** Forms of an `$action`. */\n actions: boolean;\n /** Markup that the browser renders as HTML, not as a clone of a template. */\n clientHTML: boolean;\n}\n\n/** No feature at all, which a build that has no component uses. */\nexport function noFeatures(): Features {\n return {\n children: false,\n templates: false,\n titles: false,\n bindings: false,\n lateMarkup: false,\n blocks: false,\n listeners: false,\n actions: false,\n clientHTML: false,\n };\n}\n\n/** Every feature, for a build that compiles components in the browser. */\nexport function allFeatures(): Features {\n const all = noFeatures();\n for (const name of Object.keys(all) as (keyof Features)[]) {\n all[name] = true;\n }\n return all;\n}\n\n/** The features of the core that a compiled component uses. */\nexport function getFeatures(result: CompileResult): Features {\n const client = [result.client, result.render, ...Object.values(result.parts)].join('\\n');\n // A `#client` body has no markup on the server, so its titles, listeners and forms are only in\n // the code of the browser.\n const all = `${result.server}\\n${client}`;\n return {\n // The server sends a reference to the export that renders them, or the browser makes them.\n children: result.plan.childrenRenders.size > 0 || /\\$\\$b\\.children\\(/.test(client),\n // A template that the browser can call has an export of its own, `t` and a number.\n templates: /\\bexport (?:const|function) t\\d+\\b/.test(client),\n titles: /\\bb-t\\b/.test(all),\n bindings: /\\$\\$b\\.binding\\(/.test(all),\n lateMarkup: /\\$\\$ctx\\.(?:boundary|defer|deferBlock)\\(|\\bgather\\(/.test(result.server),\n blocks: /\\bb-(?:client|defer)\\b/.test(all),\n listeners: /\\bb-listen\\b/.test(all),\n actions: /\\$\\$b\\.action\\(/.test(all),\n // A render function that gives HTML. One with no markup gives an empty string.\n clientHTML: /\\breturn \\$\\$html;/.test(client),\n };\n}\n\n/** The features of several components together. */\nexport function joinFeatures(all: Features[]): Features {\n const joined = noFeatures();\n for (const features of all) {\n joined.children ||= features.children;\n joined.templates ||= features.templates;\n joined.titles ||= features.titles;\n joined.bindings ||= features.bindings;\n joined.lateMarkup ||= features.lateMarkup;\n joined.blocks ||= features.blocks;\n joined.listeners ||= features.listeners;\n joined.actions ||= features.actions;\n joined.clientHTML ||= features.clientHTML;\n }\n return joined;\n}\n\n/** The names of the globals of `runtime/features.ts`, by feature. */\nconst GLOBALS: Record<keyof Features, string> = {\n children: '__BRUMATE_HAS_CHILDREN__',\n templates: '__BRUMATE_HAS_TEMPLATES__',\n titles: '__BRUMATE_HAS_TITLES__',\n bindings: '__BRUMATE_HAS_BINDINGS__',\n lateMarkup: '__BRUMATE_HAS_LATE_MARKUP__',\n blocks: '__BRUMATE_HAS_BLOCKS__',\n listeners: '__BRUMATE_HAS_LISTENERS__',\n actions: '__BRUMATE_HAS_ACTIONS__',\n clientHTML: '__BRUMATE_HAS_CLIENT_HTML__',\n};\n\n/** True for code that reads a feature, such as the core. */\nexport function readsFeatures(code: string): boolean {\n return code.includes('__BRUMATE_HAS_');\n}\n\n/** The code with each feature written in as `true` or `false`. */\nexport function writeFeatures(code: string, features: Features): string {\n let result = code;\n for (const [name, global] of Object.entries(GLOBALS)) {\n // The TypeScript source declares each global, and the declaration stays.\n result = result.replace(\n new RegExp(`(?<!declare const )\\\\b${global}\\\\b`, 'g'),\n String(features[name as keyof Features]),\n );\n }\n return result;\n}\n","// The builds of the client, for skew protection. Each build has an ID, which\n// the client build writes to `.brumate/build.json` and the server build\n// reads. `.brumate/builds.json` lists the last builds with their files, so\n// the files of earlier builds can stay for the pages that are still open,\n// and go when they are old enough.\n\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\n\n/** The file in the client build that names its build. */\nexport const BUILD_FILE = '.brumate/build.json';\n/** The file in the client build that lists the builds whose files are in it. */\nexport const BUILDS_FILE = '.brumate/builds.json';\n\ninterface BuildEntry {\n id: string;\n /** When the build ran, as milliseconds since the epoch. */\n at: number;\n /** The files that the build wrote, relative to the output directory. */\n files: string[];\n}\n\n/** The directory of the client build, from the root and the prerender options. */\nexport function clientBuildDirectory(\n root: string,\n prerender: boolean | { client?: string } | undefined,\n): string {\n const client = typeof prerender === 'object' ? prerender.client : undefined;\n return path.resolve(root, client ?? 'dist/client');\n}\n\n/** The ID of the build in a client build directory, or undefined without one. */\nexport function readBuildId(directory: string): string | undefined {\n const file = path.join(directory, BUILD_FILE);\n if (!existsSync(file)) {\n return undefined;\n }\n try {\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as { build?: unknown };\n return typeof parsed.build === 'string' ? parsed.build : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Writes the ID of a build to its client output, adds the build to the list\n * of builds, and removes the files of builds older than the `keep` builds\n * before this one, unless a kept build wrote the same file. Returns the IDs\n * of the builds whose files went.\n */\nexport function pruneBuilds(\n directory: string,\n id: string,\n files: string[],\n keep: number,\n now: number = Date.now(),\n): string[] {\n const list = path.join(directory, BUILDS_FILE);\n let builds: BuildEntry[] = [];\n if (existsSync(list)) {\n try {\n builds = (JSON.parse(readFileSync(list, 'utf8')) as { builds?: BuildEntry[] }).builds ?? [];\n } catch {\n builds = [];\n }\n }\n const others: BuildEntry[] = [];\n for (const build of builds) {\n if (build.id !== id) {\n others.push(build);\n }\n }\n builds = others;\n builds.push({ id, at: now, files });\n builds.sort((a, b) => a.at - b.at);\n const kept = builds.slice(Math.max(0, builds.length - 1 - keep));\n const dropped = builds.slice(0, builds.length - kept.length);\n const keptFiles = new Set<string>();\n for (const build of kept) {\n for (const file of build.files) {\n keptFiles.add(file);\n }\n }\n for (const build of dropped) {\n for (const file of build.files) {\n if (!keptFiles.has(file)) {\n rmSync(path.join(directory, file), { force: true });\n }\n }\n }\n mkdirSync(path.join(directory, '.brumate'), { recursive: true });\n writeFileSync(path.join(directory, BUILD_FILE), `${JSON.stringify({ build: id })}\\n`);\n writeFileSync(list, `${JSON.stringify({ builds: kept }, null, 2)}\\n`);\n const droppedIds: string[] = [];\n for (const build of dropped) {\n droppedIds.push(build.id);\n }\n return droppedIds;\n}\n","import { readFileSync } from 'node:fs';\n\n/** The version of brumate, which the devtools show. `package.json` is next to `src` and `dist`. */\nexport const BRUMATE_VERSION: string = (\n JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as {\n version: string;\n }\n).version;\n","// An error while the dev server renders a page, shown in Vite's error overlay.\n\nimport { resolve } from 'node:path';\nimport { version as viteVersion } from 'vite';\nimport type { ViteDevServer } from 'vite';\nimport { BRUMATE_VERSION } from './version.ts';\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 const meta = JSON.stringify({ version: BRUMATE_VERSION, vite: viteVersion });\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};\n// The Errors tab of the devtools shows the error with its code. Vite's overlay is the fallback.\ntry {\n const devtools = await import('${base}@id/brumate/devtools');\n devtools.reportError(devtools.installDevtools(undefined, undefined, ${meta}), error, 'server');\n} catch {\n const Overlay = customElements.get('vite-error-overlay');\n if (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}\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","import { LOGO } from './runtime/logo.ts';\n\n// The page of the workbench in the dev server. The sidebar lists the components that depend\n// only on their props, and apart the ones that need more, with why. The canvas renders the\n// picked component in a frame, on the server and resumed in the browser, as a page does, and\n// the panel on the right has the controls of its props. The colors are those of the devtools.\n\n/** The HTML of the workbench page. `base` is the path of the workbench, such as `/__brumate/workbench`. */\nexport function workbenchPage(base: string): string {\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Workbench · brumate</title>\n<link rel=\"icon\" type=\"image/svg+xml\" href=\"data:image/svg+xml,${encodeURIComponent(LOGO.replace('<svg ', '<svg xmlns=\"http://www.w3.org/2000/svg\" '))}\">\n<style>\n :root {\n --bg: #121113; --surface: #19181a; --raised: #222023; --hover: #2a282c; --line: #2f2c31;\n --text: #ece8e4; --dim: #a39a92; --faint: #6f6862; --accent: #ee7a3e; --accent-soft: #ee7a3e22;\n --blue: #7cb7ff; --purple: #c49bff; --green: #7fd99a; --yellow: #ffd166; --red: #ff7a7a;\n --mono: ui-monospace, SFMono-Regular, Menlo, monospace;\n color-scheme: dark;\n }\n * { box-sizing: border-box; }\n [hidden] { display: none !important; }\n html, body { height: 100%; }\n body {\n margin: 0; display: grid; grid-template-columns: 260px minmax(0, 1fr) 300px;\n background: var(--bg); color: var(--text); font: 13px/1.45 system-ui, -apple-system, sans-serif;\n }\n body.no-props { grid-template-columns: 260px minmax(0, 1fr); }\n body.no-props #props { display: none; }\n button, input, select, textarea { font: inherit; color: inherit; }\n button:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible {\n outline: 2px solid var(--accent); outline-offset: 1px;\n }\n .mono { font-family: var(--mono); }\n\n /* Sidebar */\n #sidebar { display: flex; flex-direction: column; min-height: 0; border-right: 1px solid var(--line); background: var(--surface); }\n .brand { display: flex; align-items: center; gap: 10px; padding: 16px 16px 12px; }\n .brand .logo { display: block; width: 22px; height: 22px; }\n .brand strong { font-size: 14px; }\n .brand span { margin-left: auto; color: var(--faint); font-size: 12px; }\n .search { margin: 0 12px 8px; position: relative; }\n .search input {\n width: 100%; padding: 7px 10px 7px 30px; border: 1px solid var(--line); border-radius: 8px;\n background: var(--bg);\n }\n .search svg { position: absolute; left: 10px; top: 50%; transform: translateY(-50%); color: var(--faint); }\n #tree { flex: 1; overflow: auto; padding: 4px 8px 16px; }\n .group { margin-top: 10px; }\n .group-head {\n display: flex; align-items: center; gap: 6px; padding: 4px 8px; color: var(--faint);\n font-size: 11px; font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase;\n }\n .group-head .count { margin-left: auto; font-weight: 500; }\n .item {\n display: flex; align-items: center; gap: 8px; width: 100%; padding: 6px 8px; border: 0; border-radius: 6px;\n background: none; text-align: left; cursor: pointer;\n }\n .item:hover { background: var(--hover); }\n .item[aria-current=\"true\"] { background: var(--accent-soft); box-shadow: inset 2px 0 0 var(--accent); }\n .item[aria-current=\"true\"] .label { color: #ffb48a; font-weight: 600; }\n .item .glyph { flex: none; width: 16px; height: 16px; color: var(--faint); }\n .item[aria-current=\"true\"] .glyph { color: var(--accent); }\n .item .label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n .item .meta { margin-left: auto; color: var(--faint); font-size: 11px; white-space: nowrap; }\n .env .item .label { color: var(--dim); }\n .env .group-head { cursor: pointer; }\n .env .group-head .chev { transition: transform 0.15s; }\n .env.closed .group-head .chev { transform: rotate(-90deg); }\n .env.closed .items { display: none; }\n .kinds { display: flex; gap: 3px; margin-left: auto; }\n .dot { width: 7px; height: 7px; border-radius: 50%; }\n .note { padding: 6px 8px; color: var(--faint); font-size: 12px; }\n\n /* Kinds of needs */\n .k-server { --k: var(--blue); } .k-request { --k: var(--purple); } .k-route { --k: var(--green); }\n .k-action { --k: var(--red); } .k-defer { --k: var(--accent); }\n .k-dynamic { --k: var(--dim); } .k-component { --k: var(--faint); }\n .dot { background: var(--k); }\n .tag {\n display: inline-flex; align-items: center; gap: 6px; padding: 2px 8px; border-radius: 999px;\n background: color-mix(in srgb, var(--k) 16%, transparent); color: var(--k); font-size: 11px; font-weight: 600;\n }\n\n /* Canvas */\n #main { display: grid; grid-template-rows: auto minmax(0, 1fr); min-width: 0; }\n .toolbar {\n display: flex; align-items: center; gap: 10px; min-height: 52px; padding: 8px 16px;\n border-bottom: 1px solid var(--line); background: var(--surface);\n }\n .title { display: flex; align-items: baseline; gap: 10px; min-width: 0; }\n .title h1 { margin: 0; font-size: 15px; font-weight: 650; white-space: nowrap; }\n .title button { padding: 0; border: 0; background: none; color: var(--faint); font: 12px var(--mono); cursor: pointer;\n overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n .title button:hover { color: var(--blue); text-decoration: underline; }\n .tools { display: flex; align-items: center; gap: 6px; margin-left: auto; }\n .segment { display: flex; padding: 2px; border: 1px solid var(--line); border-radius: 8px; background: var(--bg); }\n .segment button, .tool {\n display: grid; place-items: center; height: 26px; min-width: 28px; padding: 0 8px; border: 0; border-radius: 6px;\n background: none; color: var(--dim); cursor: pointer;\n }\n .segment button[aria-pressed=\"true\"] { background: var(--raised); color: var(--text); }\n .tool { border: 1px solid var(--line); background: var(--bg); }\n .tool:hover, .segment button:hover { color: var(--text); }\n .canvas { position: relative; display: grid; place-items: center; overflow: auto; padding: 24px; }\n .canvas.dots { background: radial-gradient(circle, #ffffff14 1px, transparent 1px) 0 0 / 16px 16px, var(--bg); }\n .canvas.light { background: #f4f1ec; }\n .canvas.dark { background: #0b0a0b; }\n .device {\n width: 100%; height: 100%; border: 1px solid var(--line); border-radius: 10px; overflow: hidden;\n background: #fff; box-shadow: 0 12px 40px #0006; transition: width 0.2s, height 0.2s;\n }\n .device iframe { display: block; width: 100%; height: 100%; border: 0; background: #fff; }\n .size { position: absolute; right: 16px; bottom: 10px; color: var(--faint); font: 11px var(--mono); }\n\n /* Cards on the canvas: the start, and a component that needs the environment */\n .card {\n width: min(520px, 100%); padding: 24px 26px; border: 1px solid var(--line); border-radius: 14px; background: var(--surface);\n }\n .card .eyebrow { color: var(--accent); font-size: 12px; font-weight: 600; }\n .card h2 { margin: 6px 0 8px; font-size: 18px; }\n .card p { margin: 0 0 14px; color: var(--dim); }\n .needs { display: grid; gap: 8px; margin: 0 0 16px; padding: 0; list-style: none; }\n .needs li { display: grid; grid-template-columns: auto 1fr; gap: 4px 12px; align-items: baseline;\n padding: 10px 12px; border-radius: 10px; background: var(--raised); }\n .needs .what { font-family: var(--mono); }\n .needs .via { grid-column: 2; color: var(--faint); font-size: 12px; }\n .hint { padding: 10px 12px; border-left: 2px solid var(--accent); border-radius: 0 8px 8px 0; background: var(--accent-soft);\n color: var(--dim); font-size: 12px; }\n .hint code { color: #ffb48a; }\n .stats { display: flex; gap: 18px; margin-top: 4px; }\n .stats div { color: var(--faint); font-size: 12px; }\n .stats strong { display: block; color: var(--text); font-size: 22px; font-weight: 650; }\n\n /* Props */\n #props { display: flex; flex-direction: column; min-height: 0; border-left: 1px solid var(--line); background: var(--surface); }\n .panel-head { display: flex; align-items: center; gap: 8px; min-height: 52px; padding: 8px 16px; border-bottom: 1px solid var(--line); }\n .panel-head h2 { margin: 0; font-size: 13px; }\n .panel-head button { margin-left: auto; }\n #controls { flex: 1; overflow: auto; padding: 8px 0; }\n .prop { padding: 10px 16px; border-bottom: 1px solid #ffffff08; }\n .prop-head { display: flex; align-items: center; gap: 6px; margin-bottom: 6px; }\n .prop-head .name { color: #ffc28f; font-family: var(--mono); }\n .prop-head .req { color: var(--accent); }\n .prop-head .type { margin-left: auto; color: var(--faint); font: 11px var(--mono); }\n .prop-head .reset { padding: 0 4px; border: 0; background: none; color: var(--faint); cursor: pointer; visibility: hidden; }\n .prop.changed .reset { visibility: visible; }\n .prop-head .reset:hover { color: var(--text); }\n .prop input[type=\"text\"], .prop input[type=\"number\"], .prop select, .prop textarea {\n width: 100%; padding: 6px 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--bg);\n }\n .prop textarea { min-height: 76px; resize: vertical; font: 12px/1.5 var(--mono); }\n .prop .invalid { border-color: var(--red); }\n .error { margin-top: 4px; color: var(--red); font-size: 11px; }\n .switch { position: relative; display: inline-flex; align-items: center; gap: 8px; cursor: pointer; color: var(--dim); }\n .switch input { position: absolute; opacity: 0; }\n .switch span { width: 30px; height: 18px; border-radius: 999px; background: var(--raised); border: 1px solid var(--line); position: relative; transition: background 0.15s; }\n .switch span::after { content: ''; position: absolute; top: 2px; left: 2px; width: 12px; height: 12px; border-radius: 50%; background: var(--dim); transition: transform 0.15s; }\n .switch input:checked + span { background: var(--accent); border-color: var(--accent); }\n .switch input:checked + span::after { transform: translateX(12px); background: #fff; }\n .switch input:focus-visible + span { outline: 2px solid var(--accent); outline-offset: 1px; }\n .choices { display: flex; flex-wrap: wrap; gap: 4px; }\n .choices button { padding: 3px 9px; border: 1px solid var(--line); border-radius: 6px; background: var(--bg); color: var(--dim); cursor: pointer; font: 12px var(--mono); }\n .choices button[aria-pressed=\"true\"] { border-color: var(--accent); background: var(--accent-soft); color: #ffb48a; }\n .empty-props { padding: 16px; color: var(--faint); }\n .stories { padding: 12px 16px; border-bottom: 1px solid var(--line); }\n .stories-head { margin-bottom: 8px; color: var(--faint); font-size: 11px; font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase; }\n .stories .choices button { font-family: inherit; }\n .stories-error { color: var(--red); font-size: 12px; }\n .footer { padding: 10px 16px; border-top: 1px solid var(--line); color: var(--faint); font-size: 11px; }\n</style>\n</head>\n<body class=\"no-props\">\n<aside id=\"sidebar\">\n <div class=\"brand\"><span class=\"logo\">${LOGO}</span><strong>Workbench</strong><span id=\"total\"></span></div>\n <label class=\"search\">\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\"><circle cx=\"7\" cy=\"7\" r=\"5\" stroke=\"currentColor\" stroke-width=\"1.5\"/><path d=\"m11 11 3 3\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\"/></svg>\n <input id=\"filter\" type=\"search\" placeholder=\"Find a component\" aria-label=\"Find a component\">\n </label>\n <nav id=\"tree\" aria-label=\"Components\"></nav>\n</aside>\n<main id=\"main\">\n <div class=\"toolbar\">\n <div class=\"title\"><h1 id=\"name\">Workbench</h1><button id=\"file\" type=\"button\" title=\"Open in your editor\" hidden></button></div>\n <div class=\"tools\" id=\"tools\" hidden>\n <div class=\"segment\" role=\"group\" aria-label=\"Width\">\n <button type=\"button\" data-width=\"\" aria-pressed=\"true\" title=\"Fill the canvas\">Fill</button>\n <button type=\"button\" data-width=\"390\" title=\"Phone, 390 px\">390</button>\n <button type=\"button\" data-width=\"768\" title=\"Tablet, 768 px\">768</button>\n <button type=\"button\" data-width=\"1280\" title=\"Desktop, 1280 px\">1280</button>\n </div>\n <div class=\"segment\" role=\"group\" aria-label=\"Background\">\n <button type=\"button\" data-canvas=\"dots\" aria-pressed=\"true\" title=\"Dots\">Dots</button>\n <button type=\"button\" data-canvas=\"light\" title=\"Light\">Light</button>\n <button type=\"button\" data-canvas=\"dark\" title=\"Dark\">Dark</button>\n </div>\n <button class=\"tool\" id=\"reload\" type=\"button\" title=\"Render again\">\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\"><path d=\"M13.5 8a5.5 5.5 0 1 1-1.6-3.9M13.5 2.5v3h-3\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>\n </button>\n <a class=\"tool\" id=\"open\" target=\"_blank\" title=\"Open alone in a new tab\">\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\"><path d=\"M9 3h4v4M13 3 7.5 8.5M12 9.5V13H3V4h3.5\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>\n </a>\n </div>\n </div>\n <div class=\"canvas dots\" id=\"canvas\"></div>\n</main>\n<aside id=\"props\">\n <div class=\"panel-head\"><h2>Props</h2><button class=\"tool\" id=\"resetAll\" type=\"button\" title=\"Reset every prop\">Reset</button></div>\n <div id=\"stories\" class=\"stories\" hidden></div>\n <div id=\"controls\"></div>\n <div class=\"footer\">From the type of <span class=\"mono\">$props&lt;T&gt;()</span>. Function props have no control.</div>\n</aside>\n<script type=\"module\">\nconst base = ${JSON.stringify(base)};\nconst $ = (id) => document.getElementById(id);\nconst make = (tag, props = {}, ...children) => {\n const node = document.createElement(tag);\n for (const [key, value] of Object.entries(props)) {\n if (key === 'class') node.className = value;\n else if (key.startsWith('on')) node.addEventListener(key.slice(2), value);\n else if (value !== undefined && value !== false) node.setAttribute(key, value === true ? '' : value);\n }\n node.append(...children.filter((child) => child !== undefined && child !== null));\n return node;\n};\nconst svg = (markup) => {\n const holder = document.createElement('span');\n holder.innerHTML = markup;\n return holder.firstChild;\n};\nconst COMPONENT = '<svg class=\"glyph\" viewBox=\"0 0 16 16\" fill=\"none\"><rect x=\"2.5\" y=\"2.5\" width=\"11\" height=\"11\" rx=\"3\" stroke=\"currentColor\" stroke-width=\"1.4\"/><path d=\"M5.5 8h5\" stroke=\"currentColor\" stroke-width=\"1.4\" stroke-linecap=\"round\"/></svg>';\nconst LOCKED = '<svg class=\"glyph\" viewBox=\"0 0 16 16\" fill=\"none\"><rect x=\"3\" y=\"7\" width=\"10\" height=\"7\" rx=\"2\" stroke=\"currentColor\" stroke-width=\"1.4\"/><path d=\"M5.5 7V5a2.5 2.5 0 0 1 5 0v2\" stroke=\"currentColor\" stroke-width=\"1.4\"/></svg>';\nconst FOLDER = '<svg width=\"12\" height=\"12\" viewBox=\"0 0 16 16\" fill=\"none\"><path d=\"M2 4.5A1.5 1.5 0 0 1 3.5 3h3l1.5 1.5h4.5A1.5 1.5 0 0 1 14 6v5.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 11.5z\" stroke=\"currentColor\" stroke-width=\"1.4\"/></svg>';\nconst CHEVRON = '<svg class=\"chev\" width=\"10\" height=\"10\" viewBox=\"0 0 16 16\" fill=\"none\"><path d=\"m4 6 4 4 4-4\" stroke=\"currentColor\" stroke-width=\"1.6\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>';\n\n// What each kind of need is, in words, for the tags and the card.\nconst KINDS = {\n server: ['Server', 'calls the server function'],\n request: ['Request', 'reads the request with'],\n route: ['Route', 'reads the route with'],\n action: ['Action', 'has the form action'],\n defer: ['Defer', 'has a block that the server renders later:'],\n dynamic: ['Dynamic tag', 'renders a dynamic tag'],\n component: ['Unknown', 'renders a component that the workbench cannot find:'],\n};\nconst TYPES = { text: 'string', number: 'number', boolean: 'boolean', json: 'JSON' };\n\nconst components = await (await fetch(base + '/components')).json();\nconst ready = components.filter((component) => component.selfContained);\nconst others = components.filter((component) => !component.selfContained);\nlet current;\n// The story of the component that is picked, whose props start the controls.\nlet story;\nlet values = {};\nlet start = {};\nlet timer;\nlet width = '';\nlet envOpen = false;\n\nfunction frameUrl() {\n return base + '/frame?file=' + encodeURIComponent(current.file) + '&props=' + encodeURIComponent(JSON.stringify(values));\n}\n\nfunction render() {\n const url = frameUrl();\n $('open').href = url;\n let frame = $('canvas').querySelector('iframe');\n if (!frame) {\n frame = make('iframe', { title: current.name });\n $('canvas').replaceChildren(make('div', { class: 'device', id: 'device' }, frame), make('div', { class: 'size', id: 'size' }));\n applyWidth();\n }\n frame.src = url;\n}\n\nfunction later() {\n clearTimeout(timer);\n timer = setTimeout(render, 200);\n}\n\nfunction applyWidth() {\n const device = $('device');\n if (!device) return;\n device.style.width = width ? width + 'px' : '100%';\n device.style.maxWidth = '100%';\n $('size').textContent = width ? width + ' px' : '';\n}\n\nfunction set(name, value) {\n if (value === undefined) delete values[name];\n else values[name] = value;\n for (const row of $('controls').querySelectorAll('.prop')) {\n row.classList.toggle('changed', JSON.stringify(values[row.dataset.name]) !== JSON.stringify(start[row.dataset.name]));\n }\n later();\n}\n\nfunction input(spec) {\n const value = values[spec.name];\n if (spec.kind === 'boolean') {\n const box = make('input', { type: 'checkbox', onchange: () => set(spec.name, box.checked) });\n box.checked = Boolean(value);\n return make('label', { class: 'switch' }, box, make('span'), spec.name);\n }\n if (spec.kind === 'choice') {\n const options = spec.optional ? [undefined, ...spec.options] : spec.options;\n if (options.length <= 5) {\n const group = make('div', { class: 'choices', role: 'group', 'aria-label': spec.name });\n for (const option of options) {\n const button = make('button', {\n type: 'button',\n 'aria-pressed': String(option === value),\n onclick: () => {\n for (const other of group.children) other.setAttribute('aria-pressed', String(other === button));\n set(spec.name, option);\n },\n }, option === undefined ? 'none' : String(option));\n group.append(button);\n }\n return group;\n }\n const select = make('select', { 'aria-label': spec.name, onchange: () => set(spec.name, options[select.selectedIndex]) });\n for (const option of options) select.append(make('option', {}, option === undefined ? 'none' : String(option)));\n select.selectedIndex = Math.max(0, options.indexOf(value));\n return select;\n }\n if (spec.kind === 'json') {\n const area = make('textarea', { spellcheck: 'false', 'aria-label': spec.name });\n const error = make('div', { class: 'error', hidden: true });\n area.value = value === undefined ? '' : JSON.stringify(value, null, 2);\n area.addEventListener('input', () => {\n if (area.value.trim() === '') {\n area.classList.remove('invalid');\n error.hidden = true;\n set(spec.name, undefined);\n return;\n }\n try {\n const parsed = JSON.parse(area.value);\n area.classList.remove('invalid');\n error.hidden = true;\n set(spec.name, parsed);\n } catch (problem) {\n area.classList.add('invalid');\n error.hidden = false;\n error.textContent = String(problem.message ?? problem);\n }\n });\n return make('div', {}, area, error);\n }\n const field = make('input', {\n type: spec.kind === 'number' ? 'number' : 'text',\n 'aria-label': spec.name,\n placeholder: spec.optional ? 'undefined' : '',\n oninput: () => set(spec.name, field.value === '' ? undefined : spec.kind === 'number' ? Number(field.value) : field.value),\n });\n field.value = value === undefined ? '' : String(value);\n return field;\n}\n\nfunction typeOf(spec) {\n if (spec.kind === 'choice') return spec.options.map((option) => JSON.stringify(option)).join(' | ');\n return TYPES[spec.kind];\n}\n\nfunction stories() {\n const box = $('stories');\n box.replaceChildren();\n box.hidden = !current.stories?.length && !current.storiesError;\n if (current.storiesError) {\n box.append(make('div', { class: 'stories-error' }, 'The stories do not load: ' + current.storiesError));\n return;\n }\n if (!current.stories?.length) return;\n box.append(make('div', { class: 'stories-head' }, 'Stories'));\n const list = make('div', { class: 'choices' });\n for (const item of [{ name: 'Default', props: {} }, ...current.stories]) {\n list.append(make('button', {\n type: 'button',\n 'aria-pressed': String((story?.name ?? 'Default') === item.name),\n onclick: () => pickStory(item.name === 'Default' ? undefined : item),\n }, item.name));\n }\n box.append(list);\n}\n\n/** Starts the controls from the props of a story, or from the defaults without one. */\nfunction pickStory(next) {\n story = next;\n start = { ...initial(current), ...(next?.props ?? {}) };\n values = structuredClone(start);\n history.replaceState(null, '', '#' + current.file + (next ? '@' + next.name : ''));\n stories();\n controls();\n render();\n}\n\nfunction controls() {\n const box = $('controls');\n box.replaceChildren();\n if (current.unreadProps) {\n box.append(make('div', { class: 'empty-props' }, 'The workbench cannot read the type of the props, such as a type that the file imports. Declare it in the file to get controls.'));\n return;\n }\n if (!current.controls.length) {\n box.append(make('div', { class: 'empty-props' }, 'This component takes no props that the workbench can set.'));\n return;\n }\n for (const spec of current.controls) {\n const reset = make('button', { class: 'reset', type: 'button', title: 'Reset', onclick: () => {\n set(spec.name, start[spec.name]);\n controls();\n } }, '↺');\n box.append(make('div', { class: 'prop', 'data-name': spec.name },\n make('div', { class: 'prop-head' },\n make('span', { class: 'name' }, spec.name),\n spec.optional ? undefined : make('span', { class: 'req', title: 'Required' }, '*'),\n reset,\n make('span', { class: 'type', title: typeOf(spec) }, typeOf(spec).length > 28 ? 'union' : typeOf(spec))),\n input(spec)));\n }\n}\n\nfunction initial(component) {\n const props = {};\n for (const spec of component.controls) {\n if (spec.default !== undefined) props[spec.name] = spec.default;\n // A required prop gets a value, so the component renders at once.\n else if (!spec.optional) {\n props[spec.name] =\n spec.kind === 'text' ? spec.name\n : spec.kind === 'number' ? 0\n : spec.kind === 'boolean' ? false\n : spec.kind === 'choice' ? spec.options[0]\n : (spec.empty ?? null);\n }\n }\n return props;\n}\n\nfunction title(component) {\n $('name').textContent = component ? component.name : 'Workbench';\n $('file').hidden = !component;\n if (component) $('file').textContent = component.label ?? component.file;\n}\n\nfunction select(component) {\n current = component;\n for (const item of $('tree').querySelectorAll('.item')) item.setAttribute('aria-current', String(item.dataset.file === component.file));\n title(component);\n history.replaceState(null, '', '#' + component.file);\n if (!component.selfContained) {\n document.body.classList.add('no-props');\n $('tools').hidden = true;\n explain(component);\n return;\n }\n document.body.classList.remove('no-props');\n $('tools').hidden = false;\n $('canvas').replaceChildren();\n pickStory(undefined);\n}\n\nfunction explain(component) {\n const list = make('ul', { class: 'needs' });\n for (const need of component.needs) {\n const [label, words] = KINDS[need.kind] ?? [need.kind, ''];\n list.append(make('li', {},\n make('span', { class: 'tag k-' + need.kind }, label),\n make('span', {}, words + ' ', make('span', { class: 'what' }, need.name)),\n need.via ? make('span', { class: 'via' }, 'through ' + need.via) : undefined));\n }\n const hint = make('div', { class: 'hint' });\n hint.append('Test it in a page: ', make('code', {}, 'visit()'), ' from ', make('code', {}, 'brumate/testing'),\n ', or an end-to-end test. Its parts that depend only on their props show here.');\n $('canvas').replaceChildren(make('div', { class: 'card' },\n make('div', { class: 'eyebrow' }, 'Needs the environment'),\n make('h2', {}, component.name + ' needs more than its props'),\n make('p', {}, 'The workbench renders a component with nothing around it: no request, no route, no server data and no providers. This one needs:'),\n list, hint));\n}\n\nfunction welcome() {\n const stats = make('div', { class: 'stats' },\n make('div', {}, make('strong', {}, String(ready.length)), 'can show here'),\n make('div', {}, make('strong', {}, String(others.length)), 'need the environment'));\n $('canvas').replaceChildren(make('div', { class: 'card' },\n make('div', { class: 'eyebrow' }, 'Workbench'),\n make('h2', {}, 'Pick a component'),\n make('p', {}, 'Each component renders on the server with the props that you set, and resumes in the browser, as it does in a page.'),\n stats));\n}\n\nfunction item(component) {\n const kinds = [...new Set(component.needs.map((need) => need.kind))];\n return make('button', {\n class: 'item', type: 'button', 'data-file': component.file,\n 'aria-current': String(component === current),\n title: component.file,\n onclick: () => select(component),\n },\n svg(component.selfContained ? COMPONENT : LOCKED),\n make('span', { class: 'label' }, component.name),\n component.selfContained\n ? make('span', { class: 'meta' }, component.stories?.length\n ? component.stories.length + (component.stories.length === 1 ? ' story' : ' stories')\n : component.controls.length ? component.controls.length + (component.controls.length === 1 ? ' prop' : ' props') : '')\n : make('span', { class: 'kinds' }, ...kinds.map((kind) => make('span', { class: 'dot k-' + kind, title: KINDS[kind]?.[0] ?? kind }))));\n}\n\nfunction tree() {\n const query = $('filter').value.trim().toLowerCase();\n const match = (component) => !query || component.name.toLowerCase().includes(query) || component.file.toLowerCase().includes(query);\n const box = $('tree');\n box.replaceChildren();\n const folders = new Map();\n for (const component of ready.filter(match)) {\n const folder = component.group || '.';\n if (!folders.has(folder)) folders.set(folder, []);\n folders.get(folder).push(component);\n }\n for (const [folder, items] of [...folders].sort(([a], [b]) => a.localeCompare(b))) {\n box.append(make('div', { class: 'group' },\n make('div', { class: 'group-head' }, svg(FOLDER), folder, make('span', { class: 'count' }, String(items.length))),\n ...items.map(item)));\n }\n if (!folders.size) box.append(make('div', { class: 'note' }, query ? 'No component matches.' : 'No component depends only on its props.'));\n const shown = others.filter(match);\n if (shown.length) {\n const group = make('div', { class: 'group env' + (envOpen || query ? '' : ' closed') });\n const head = make('div', { class: 'group-head', role: 'button', tabindex: '0', 'aria-expanded': String(envOpen || Boolean(query)) },\n svg(CHEVRON), 'Needs the environment', make('span', { class: 'count' }, String(shown.length)));\n const toggle = () => {\n envOpen = group.classList.toggle('closed') === false;\n head.setAttribute('aria-expanded', String(envOpen));\n };\n head.addEventListener('click', toggle);\n head.addEventListener('keydown', (event) => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); toggle(); } });\n group.append(head, make('div', { class: 'items' }, ...shown.map(item)));\n box.append(group);\n }\n}\n\n$('total').textContent = components.length + ' components';\n$('filter').addEventListener('input', tree);\n$('file').addEventListener('click', () => {\n if (current) fetch('/__open-in-editor?file=' + encodeURIComponent(current.file));\n});\n$('reload').addEventListener('click', render);\n$('resetAll').addEventListener('click', () => {\n values = structuredClone(start);\n controls();\n render();\n});\nfor (const button of document.querySelectorAll('[data-width]')) {\n button.addEventListener('click', () => {\n width = button.dataset.width;\n for (const other of document.querySelectorAll('[data-width]')) other.setAttribute('aria-pressed', String(other === button));\n applyWidth();\n });\n}\nfor (const button of document.querySelectorAll('[data-canvas]')) {\n button.addEventListener('click', () => {\n $('canvas').className = 'canvas ' + button.dataset.canvas;\n for (const other of document.querySelectorAll('[data-canvas]')) other.setAttribute('aria-pressed', String(other === button));\n });\n}\n// The hash names the component, so a link or the back button can pick one.\nfunction fromHash() {\n // The hash is the file, and the name of a story after \\`@\\`.\n const [chosen, storyName] = decodeURIComponent(location.hash.slice(1)).split('@');\n const found = components.find((component) => component.file === chosen);\n if (!found) {\n welcome();\n return;\n }\n const named = found.stories?.find((item) => item.name === storyName);\n if (found === current && named === story) return;\n if (!found.selfContained && !envOpen) {\n envOpen = true;\n tree();\n }\n if (found !== current) select(found);\n if (found.selfContained && named !== story) pickStory(named);\n}\ntree();\nfromHash();\naddEventListener('hashchange', fromHash);\n</script>\n</body>\n</html>`;\n}\n","// Classifies the components of a project by what they depend on, so the workbench lists only\n// the ones that it can show: those that depend on their props, their own state and nothing\n// else. A context counts as neither, since a component without a provider reads its default.\n// A component that calls the server, or reads the request or the route, fits an end-to-end\n// test better. A component needs what the components it renders need.\n\nimport { analyze } from './analyze.ts';\nimport type { Markup, SFCFile } from './ast.ts';\nimport { resolveMacros, walk } from './macros.ts';\nimport type { oxc } from './oxc.ts';\nimport { parse } from './parser.ts';\nimport { forEachNode, importSource, resolveRelative } from './project.ts';\nimport type { Resolve } from './project.ts';\n\nexport type NeedKind =\n /** A server function: one of a `'use server'` file, or one that the component declares. */\n | 'server'\n /** The request, through an import of `brumate/server`, such as `getEvent`. */\n | 'request'\n /** The route, through `$route` or `$navigation`. */\n | 'route'\n /** A form action of `$action`. */\n | 'action'\n /** A `#defer` block, whose body the server renders later. */\n | 'defer'\n /** A dynamic tag without an element to fall back to, which can render any component. */\n | 'dynamic'\n /** A component that the analysis cannot find, such as one of a package that is not a `.brm` file. */\n | 'component';\n\nexport interface Need {\n kind: NeedKind;\n /** What the need is about: the name of a function, an import, a block or a component. */\n name: string;\n /** For a need of a component that this one renders, the file of that component, which can have it from a component that it renders. */\n via?: string;\n}\n\nexport interface Classification {\n /** True when the component depends only on its props and its own state. */\n selfContained: boolean;\n needs: Need[];\n}\n\nexport interface ClassifyOptions {\n /** Resolves the import of a component to its file. */\n resolve?: Resolve;\n /** True for an import of a function of a `'use server'` file. */\n serverImport?: (file: string, specifier: string, name: string) => boolean;\n}\n\n/** True for a string literal, such as `'button'`. */\nfunction isElementName(node: oxc.Node | undefined): boolean {\n return node?.type === 'Literal' && typeof node.value === 'string';\n}\n\n/** The props that destructure with an element name as their default, such as `as = 'button'`. */\nfunction elementDefaults(file: SFCFile): Set<string> {\n const names = new Set<string>();\n for (const statement of file.instanceScript?.program.body ?? []) {\n if (statement.type !== 'VariableDeclaration') {\n continue;\n }\n for (const declarator of statement.declarations) {\n const call = declarator.init;\n if (\n call?.type !== 'CallExpression' ||\n call.callee.type !== 'Identifier' ||\n call.callee.name !== '$props' ||\n declarator.id.type !== 'ObjectPattern'\n ) {\n continue;\n }\n for (const property of declarator.id.properties) {\n if (\n property.type === 'Property' &&\n property.value.type === 'AssignmentPattern' &&\n property.value.left.type === 'Identifier' &&\n isElementName(property.value.right)\n ) {\n names.add(property.value.left.name);\n }\n }\n }\n }\n return names;\n}\n\n/**\n * True for the tag of a dynamic tag that renders an element when the caller gives none: a\n * string, `as ?? 'button'`, or a prop with an element as its default. A part such as a button\n * that takes `as` depends only on its props this way.\n */\nfunction hasElementDefault(tag: oxc.Node, defaults: Set<string>): boolean {\n if (isElementName(tag)) {\n return true;\n }\n if (tag.type === 'Identifier') {\n return defaults.has(tag.name);\n }\n if (tag.type === 'LogicalExpression' && (tag.operator === '??' || tag.operator === '||')) {\n return isElementName(tag.right) || hasElementDefault(tag.right, defaults);\n }\n if (tag.type === 'ConditionalExpression') {\n return (\n hasElementDefault(tag.consequent, defaults) && hasElementDefault(tag.alternate, defaults)\n );\n }\n return tag.type === 'ParenthesizedExpression' && hasElementDefault(tag.expression, defaults);\n}\n\n/** The needs of one file, without those of the components that it renders. */\nfunction ownNeeds(file: SFCFile, options: ClassifyOptions): Need[] {\n const needs: Need[] = [];\n const model = analyze(file);\n for (const declaration of model.declarations) {\n if (declaration.kind === 'server-function') {\n needs.push({ kind: 'server', name: declaration.name });\n } else if (declaration.kind === 'action') {\n needs.push({ kind: 'action', name: declaration.name });\n } else if (declaration.imported) {\n const { source, name } = declaration.imported;\n if (source === 'brumate/server') {\n needs.push({ kind: 'request', name });\n } else if (options.serverImport?.(file.filename, source, name)) {\n needs.push({ kind: 'server', name });\n }\n }\n }\n // The namespace imports, by the start of their name, since the analysis declares one without\n // its module. It resolves each name by its scope, so a read of `api` counts only when it is\n // the import, and a name in a type, a property or a shadowing parameter does not count.\n const namespaces = new Map<number, string>();\n for (const script of [file.moduleScript, file.instanceScript]) {\n for (const statement of script?.program.body ?? []) {\n if (statement.type !== 'ImportDeclaration' || statement.importKind === 'type') {\n continue;\n }\n for (const specifier of statement.specifiers) {\n if (specifier.type === 'ImportNamespaceSpecifier') {\n namespaces.set(specifier.local.start, statement.source.value);\n }\n }\n }\n }\n for (const declaration of model.declarations) {\n const source = namespaces.get(declaration.range.start);\n if (declaration.kind !== 'import' || source === undefined || declaration.reads.length === 0) {\n continue;\n }\n const name = `* as ${declaration.name}`;\n if (source === 'brumate/server') {\n needs.push({ kind: 'request', name });\n } else if (options.serverImport?.(file.filename, source, '*')) {\n needs.push({ kind: 'server', name });\n }\n }\n // `$route` and `$navigation` read the route of the page, which the workbench does not have.\n // A call inside a function, such as a handler, runs later, if at all, so only the others\n // count. The scripts and the expressions of the markup have positions in the file, so one\n // range check finds the functions around a call.\n const functions: oxc.Node[] = [];\n const calls: oxc.CallExpression[] = [];\n walk(\n [file.moduleScript?.program, file.instanceScript?.program, file.children, file.templates],\n (node) => {\n if (\n node.type === 'ArrowFunctionExpression' ||\n node.type === 'FunctionExpression' ||\n node.type === 'FunctionDeclaration'\n ) {\n functions.push(node);\n } else if (\n node.type === 'CallExpression' &&\n node.callee.type === 'Identifier' &&\n (node.callee.name === '$route' || node.callee.name === '$navigation')\n ) {\n calls.push(node);\n }\n },\n );\n for (const call of calls) {\n let inside = false;\n for (const fn of functions) {\n if (fn.start <= call.start && call.end <= fn.end) {\n inside = true;\n break;\n }\n }\n if (!inside) {\n needs.push({ kind: 'route', name: (call.callee as oxc.IdentifierReference).name });\n }\n }\n const defaults = elementDefaults(file);\n function visit(node: Markup): void {\n if (node.kind === 'defer') {\n needs.push({ kind: 'defer', name: '#defer' });\n } else if (node.kind === 'dynamic' && !hasElementDefault(node.tag.ast, defaults)) {\n needs.push({ kind: 'dynamic', name: '<{…}>' });\n }\n }\n forEachNode(file.children, visit);\n for (const template of file.templates) {\n forEachNode(template.body.children, visit);\n }\n return needs;\n}\n\n/** The import specifiers of the components that a file renders. */\nfunction renderedComponents(file: SFCFile): Set<string> {\n const sources = new Set<string>();\n function visit(node: Markup): void {\n if (node.kind === 'component') {\n const source = importSource(file, node.name.split('.')[0]!);\n if (source) {\n sources.add(source);\n }\n }\n }\n forEachNode(file.children, visit);\n for (const template of file.templates) {\n forEachNode(template.body.children, visit);\n }\n return sources;\n}\n\nfunction key(need: Need): string {\n return `${need.kind}:${need.name}`;\n}\n\n/**\n * Classifies every component of a project, by file. A file that does not parse or analyze is\n * not classified, because the workbench could not render it either.\n */\nexport function classifyComponents(\n files: Map<string, string>,\n options: ClassifyOptions = {},\n): Map<string, Classification> {\n const resolve = options.resolve ?? resolveRelative;\n const needs = new Map<string, Map<string, Need>>();\n const children = new Map<string, string[]>();\n for (const [filename, source] of files) {\n let file: SFCFile;\n let own: Need[];\n try {\n file = parse(source, { filename });\n own = ownNeeds(file, options);\n } catch {\n continue;\n }\n const map = new Map<string, Need>();\n for (const need of own) {\n map.set(key(need), need);\n }\n const found: string[] = [];\n for (const specifier of renderedComponents(file)) {\n const target = resolve(specifier, filename);\n if (target !== undefined && files.has(target)) {\n found.push(target);\n } else if (specifier.endsWith('.brm')) {\n map.set(`component:${specifier}`, { kind: 'component', name: specifier });\n }\n }\n needs.set(filename, map);\n children.set(filename, found);\n }\n // A component needs what the components that it renders need. Each round can only add needs,\n // so this ends, also for a component that renders itself.\n for (let changed = true; changed;) {\n changed = false;\n for (const [filename, map] of needs) {\n for (const child of children.get(filename)!) {\n for (const need of needs.get(child)?.values() ?? []) {\n const id = key(need);\n if (!map.has(id)) {\n map.set(id, { ...need, via: child });\n changed = true;\n }\n }\n }\n }\n }\n const result = new Map<string, Classification>();\n for (const [filename, map] of needs) {\n const list = [...map.values()];\n result.set(filename, { selfContained: list.length === 0, needs: list });\n }\n return result;\n}\n\n/** The input of a control, by the type of its prop. */\nexport type ControlInput =\n | { kind: 'text'; default?: string }\n | { kind: 'number'; default?: number }\n | { kind: 'boolean'; default?: boolean }\n | { kind: 'choice'; options: (string | number)[]; default?: string | number }\n | {\n kind: 'json';\n default?: unknown;\n /** The value to start a required prop with: `[]` for an array type, `{}` for an object type. */\n empty?: unknown[] | Record<string, never>;\n };\n\n/** A control of the workbench for one prop of a component. */\nexport type Control = { name: string; optional: boolean } & ControlInput;\n\n/** The interface or type alias of the scripts that has this name. */\nfunction localType(name: string, file: SFCFile): oxc.Node | undefined {\n for (const script of [file.moduleScript, file.instanceScript]) {\n for (let statement of script?.program.body ?? []) {\n if (statement.type === 'ExportNamedDeclaration' && statement.declaration) {\n statement = statement.declaration;\n }\n if (\n (statement.type === 'TSInterfaceDeclaration' ||\n statement.type === 'TSTypeAliasDeclaration') &&\n statement.id.name === name\n ) {\n return statement;\n }\n }\n }\n return undefined;\n}\n\ntype Member = { optional?: boolean };\n\n/**\n * The name of a property or a method of a type, or undefined for a computed one or a signature\n * without a name. A method replaces a prop of the same name that its interface extends.\n */\nfunction memberName(member: oxc.Node): string | undefined {\n if (\n (member.type !== 'TSPropertySignature' && member.type !== 'TSMethodSignature') ||\n member.computed\n ) {\n return undefined;\n }\n return member.key.type === 'Identifier'\n ? member.key.name\n : String((member.key as { value?: unknown }).value);\n}\n\n/**\n * The members of the type of `$props<T>()`: a literal, an interface or alias of the scripts and\n * what it extends, an intersection of those, or `Partial` of one. Undefined for a type that the\n * workbench cannot read, such as one that the file imports.\n */\n/**\n * Merges lists of members by name. A later member takes the place of an earlier one with the\n * same name. With `required`, as for an intersection, the prop is required when any list\n * requires it.\n */\nfunction mergeMembers(lists: oxc.Node[][], required: boolean): oxc.Node[] {\n // A member without a name, such as a method, gets a key that no name can equal.\n const byName = new Map<string | symbol, oxc.Node>();\n for (const list of lists) {\n for (const member of list) {\n const id = memberName(member) ?? Symbol('member');\n const before = byName.get(id);\n byName.set(\n id,\n required && before && !((before as Member).optional && (member as Member).optional)\n ? ({ ...member, optional: false } as oxc.Node)\n : member,\n );\n }\n }\n return [...byName.values()];\n}\n\nfunction propsMembers(\n type: oxc.Node,\n file: SFCFile,\n seen = new Set<string>(),\n // The members of each named type, so a type that many branches reach is read once.\n known = new Map<string, oxc.Node[] | undefined>(),\n): oxc.Node[] | undefined {\n if (type.type === 'TSTypeLiteral') {\n return type.members;\n }\n if (type.type === 'TSIntersectionType') {\n const lists: oxc.Node[][] = [];\n for (const item of type.types) {\n const found = propsMembers(item, file, seen, known);\n if (!found) {\n return undefined;\n }\n lists.push(found);\n }\n return mergeMembers(lists, true);\n }\n if (type.type !== 'TSTypeReference' || type.typeName.type !== 'Identifier') {\n return undefined;\n }\n const name = type.typeName.name;\n const argument = type.typeArguments?.params[0];\n if (name !== 'Partial' && type.typeArguments) {\n // The workbench does not put the arguments of a generic type in its members.\n return undefined;\n }\n if (name === 'Partial' && argument) {\n const members = propsMembers(argument, file, seen, known);\n if (!members) {\n return undefined;\n }\n const optional: oxc.Node[] = [];\n for (const member of members) {\n optional.push({ ...member, optional: true } as oxc.Node);\n }\n return optional;\n }\n if (known.has(name)) {\n return known.get(name);\n }\n const declaration = seen.has(name) ? undefined : localType(name, file);\n if (!declaration || (declaration as { typeParameters?: unknown }).typeParameters) {\n return undefined;\n }\n // The types on the way here, which a type that refers to itself would reach again.\n const path = new Set(seen).add(name);\n let members: oxc.Node[] | undefined;\n if (declaration.type === 'TSTypeAliasDeclaration') {\n members = propsMembers(declaration.typeAnnotation, file, path, known);\n } else if (declaration.type === 'TSInterfaceDeclaration') {\n const lists: oxc.Node[][] = [];\n let readable = true;\n for (const heritage of declaration.extends ?? []) {\n const found =\n heritage.expression.type === 'Identifier'\n ? propsMembers(\n {\n type: 'TSTypeReference',\n typeName: heritage.expression,\n typeArguments: heritage.typeArguments,\n } as oxc.Node,\n file,\n path,\n known,\n )\n : undefined;\n if (!found) {\n readable = false;\n break;\n }\n lists.push(found);\n }\n // A member of the interface replaces one that it extends with the same name.\n members = readable ? mergeMembers([...lists, declaration.body.body], false) : undefined;\n }\n known.set(name, members);\n return members;\n}\n\n/** The value of a literal default, such as `'info'` in `{ tone = 'info' }`. */\nfunction literalValue(node: oxc.Node): unknown {\n if (node.type === 'Literal') {\n return node.value;\n }\n if (node.type === 'TemplateLiteral' && node.expressions.length === 0) {\n return node.quasis[0]?.value.cooked;\n }\n if (\n node.type === 'UnaryExpression' &&\n node.operator === '-' &&\n node.argument.type === 'Literal'\n ) {\n return -Number(node.argument.value);\n }\n return undefined;\n}\n\n/** The control for a type, or undefined for a function, which the workbench cannot make. */\nfunction getControl(\n type: oxc.Node | undefined,\n file: SFCFile,\n seen = new Set<string>(),\n): ControlInput | undefined {\n if (!type) {\n return { kind: 'json' };\n }\n // `Bindable<T>` is a `T` that a parent can bind.\n if (\n type.type === 'TSTypeReference' &&\n type.typeName.type === 'Identifier' &&\n type.typeName.name === 'Bindable' &&\n type.typeArguments?.params[0]\n ) {\n return getControl(type.typeArguments.params[0], file, seen);\n }\n switch (type.type) {\n case 'TSStringKeyword':\n return { kind: 'text' };\n case 'TSNumberKeyword':\n return { kind: 'number' };\n case 'TSBooleanKeyword':\n return { kind: 'boolean' };\n case 'TSFunctionType':\n case 'TSConstructorType':\n return undefined;\n case 'TSParenthesizedType':\n return getControl(type.typeAnnotation, file, seen);\n case 'TSArrayType':\n case 'TSTupleType':\n return { kind: 'json', empty: [] };\n case 'TSTypeLiteral':\n return { kind: 'json', empty: {} };\n case 'TSTypeReference':\n if (type.typeName.type === 'Identifier') {\n if (type.typeName.name === 'Array' || type.typeName.name === 'ReadonlyArray') {\n return { kind: 'json', empty: [] };\n }\n if (type.typeName.name === 'Record') {\n return { kind: 'json', empty: {} };\n }\n // An interface is an object, and an alias has the control of its type.\n const name = type.typeName.name;\n const declaration = seen.has(name) ? undefined : localType(name, file);\n if (declaration?.type === 'TSInterfaceDeclaration') {\n return { kind: 'json', empty: {} };\n }\n if (declaration?.type === 'TSTypeAliasDeclaration') {\n return getControl(declaration.typeAnnotation, file, new Set(seen).add(name));\n }\n }\n return { kind: 'json' };\n case 'TSUnionType': {\n const types: oxc.Node[] = [];\n for (const item of type.types as oxc.Node[]) {\n if (item.type !== 'TSUndefinedKeyword' && item.type !== 'TSNullKeyword') {\n types.push(item);\n }\n }\n const options: (string | number)[] = [];\n for (const item of types) {\n const value = item.type === 'TSLiteralType' ? literalValue(item.literal) : undefined;\n if (typeof value !== 'string' && typeof value !== 'number') {\n return types.length === 1 ? getControl(types[0], file, seen) : { kind: 'json' };\n }\n options.push(value);\n }\n return { kind: 'choice', options };\n }\n default:\n return { kind: 'json' };\n }\n}\n\n/**\n * The controls for the props of a component, from the type of `$props<T>()` and the defaults\n * of its destructuring. A prop whose type is a function, such as a handler, has none. Undefined\n * when the workbench cannot read the type, such as one that the file imports.\n */\nexport function propControls(file: SFCFile): Control[] | undefined {\n // A renamed import, such as `$props as props`, is read as `$props`.\n resolveMacros(file);\n for (const statement of file.instanceScript?.program.body ?? []) {\n if (statement.type !== 'VariableDeclaration') {\n continue;\n }\n for (const declarator of statement.declarations) {\n const call = declarator.init;\n if (\n call?.type !== 'CallExpression' ||\n call.callee.type !== 'Identifier' ||\n call.callee.name !== '$props'\n ) {\n continue;\n }\n const defaults = new Map<string, unknown>();\n if (declarator.id.type === 'ObjectPattern') {\n for (const property of declarator.id.properties) {\n if (\n property.type === 'Property' &&\n property.key.type === 'Identifier' &&\n property.value.type === 'AssignmentPattern'\n ) {\n defaults.set(property.key.name, literalValue(property.value.right));\n }\n }\n }\n const type = (call as { typeArguments?: { params: oxc.Node[] } }).typeArguments?.params[0];\n const members = type ? propsMembers(type, file) : [];\n if (!members) {\n return undefined;\n }\n // A later member with the same name, as of an interface over what it extends, wins, in\n // the place of the first.\n const byName = new Map<string, Control>();\n for (const member of members) {\n const name = memberName(member);\n if (name === undefined || member.type !== 'TSPropertySignature') {\n continue;\n }\n // The children of a part are text in the workbench, whatever their type says.\n const control =\n name === 'children'\n ? { kind: 'text' as const }\n : getControl(member.typeAnnotation?.typeAnnotation, file);\n if (!control) {\n byName.delete(name);\n continue;\n }\n const value = defaults.get(name);\n byName.set(name, {\n name,\n optional: member.optional,\n ...control,\n ...(value === undefined ? {} : { default: value }),\n } as Control);\n }\n return [...byName.values()];\n }\n }\n return [];\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 getPageFile(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(/&amp;/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 let entry: ManifestChunk | undefined;\n for (const chunk of Object.values(manifest)) {\n if (chunk.isEntry) {\n entry = chunk;\n break;\n }\n }\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 // Every page renders from one place, with no client, so rate limits do not count.\n prerender: true,\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, getPageFile(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: getPageFile(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 scripts = new Set<string>();\n for (const page of Object.values(pages)) {\n for (const script of page.scripts) {\n scripts.add(script);\n }\n }\n const result: PrerenderManifest = { pages, scripts: [...scripts] };\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, the code of\n// each component, and what each route loads. A budget fails the build when a\n// 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 /** The size of each module in the chunk, before minifying and gzip. */\n modules?: Record<string, number>;\n}\n\n/** Sizes in bytes, after gzip. */\nexport interface Budget {\n /** The loader, which every page loads. */\n loader?: number;\n /** What a route loads, with the core. */\n route?: number;\n /** The client code of one component. */\n component?: number;\n}\n\nexport interface BuildReport {\n /** The entry and its imports, which every page loads. */\n loader: number;\n /** The runtime, which every page loads when it starts. */\n core: number;\n /**\n * Each component, with the size of its client code, largest first. A chunk that holds several\n * components, such as the bundle of a page, counts for each by the size of its modules.\n */\n components: { file: string; bytes: number }[];\n /** Each route path, with what it loads besides the loader, 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 /** A file as the messages show it. Defaults to the path. */\n relative?: (file: string) => string;\n}\n\n/** Measures the client build. */\nexport function buildReport({\n chunks: list,\n sources,\n routes,\n budget,\n relative = (file) => file,\n}: ReportInput): BuildReport {\n const chunks = new Map<string, (typeof list)[number]>();\n const sizes = new Map<string, number>();\n for (const chunk of list) {\n chunks.set(chunk.fileName, chunk);\n sizes.set(chunk.fileName, gzipSize(chunk.code));\n }\n function 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 let coreChunk: (typeof list)[number] | undefined;\n for (const chunk of list) {\n let isCore = false;\n for (const id of chunk.moduleIds) {\n if (/[\\\\/]runtime[\\\\/]client\\.[jt]s$/.test(id)) {\n isCore = true;\n break;\n }\n }\n if (isCore) {\n coreChunk = chunk;\n break;\n }\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: those that hold its entry and its parts, with what they\n // import. Its size is its share of each chunk that holds its modules.\n const byFile = new Map<string, Set<string>>();\n const shares = new Map<string, number>();\n const everyPage = new Set([...loaderChunks, ...coreChunks]);\n for (const chunk of list) {\n const owned = new Map<string, number>();\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 owned.set(file, (owned.get(file) ?? 0) + (chunk.modules?.[id] ?? 1));\n }\n }\n let total = chunk.moduleIds.length;\n if (chunk.modules) {\n total = 0;\n for (const bytes of Object.values(chunk.modules)) {\n total += bytes;\n }\n }\n for (const [file, bytes] of owned) {\n const share = total > 0 ? ((sizes.get(chunk.fileName) ?? 0) * bytes) / total : 0;\n shares.set(file, (shares.get(file) ?? 0) + share);\n }\n }\n for (const set of byFile.values()) {\n for (const name of everyPage) {\n set.delete(name);\n }\n }\n const components: { file: string; bytes: number }[] = [];\n for (const [file, bytes] of shares) {\n components.push({ file, bytes: Math.round(bytes) });\n }\n components.sort((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 function reachable(files: string[]): Set<string> {\n const seen = new Set<string>();\n function 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 for (const file of files) {\n visit(file);\n }\n return seen;\n }\n const routeSizes: { path: string; bytes: number; components: number }[] = [];\n for (const { path, files } of routes ? routeEntries(routes.tree, routes.resolve) : []) {\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 routeSizes.push({ path, bytes: sum(names), components: reached.size });\n }\n routeSizes.sort((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 for (const component of components) {\n if (budget?.component !== undefined && component.bytes > budget.component) {\n overBudget.push(\n `The component ${relative(component.file)} ships ${formatBytes(component.bytes)}, over the budget of ${formatBytes(budget.component)}.`,\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 ` The loader, on every page: ${formatBytes(report.loader)}`,\n ` The core, when the page starts: ${formatBytes(report.core)}`,\n ];\n if (report.routes.length > 0) {\n lines.push(' What each route loads when it starts, 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 * `middleware` is the path of the entry middleware, which runs for every\n * request, when the app has 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 middleware?: string,\n /** The ID of the build, for skew protection. */\n build?: string,\n /** The modules that every page loads early, from the client build. */\n hints: string[] = [],\n /** The chunks of the bundle of each root component, by ID, from the client build. */\n bundleHints: Record<string, string[]> = {},\n): string {\n // Static imports in a build, because the server registry of server functions imports every\n // file anyway. In development, a route loads when a request needs it, so a file that does not\n // compile breaks only its own pages.\n const imports: string[] = [];\n function load(file: string): string {\n if (dev) {\n return `() => import(${JSON.stringify(resolve(file))})`;\n }\n const name = `m${imports.length}`;\n imports.push(`import * as ${name} from ${JSON.stringify(resolve(file))};`);\n return `() => Promise.resolve(${name})`;\n }\n function 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: string[] = [];\n for (const [name, value] of Object.entries(children)) {\n entries.push(`${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, fileMiddleware } from 'virtual:brumate/server';\",\n ...(middleware ? [`import middleware from ${JSON.stringify(middleware)};`] : []),\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, fileMiddleware${middleware ? ', middleware' : ''}${dev ? ', dev: true' : ''}${build === undefined ? '' : `, build: ${JSON.stringify(build)}`}${hints.length > 0 ? `, hints: ${JSON.stringify(hints)}` : ''}${Object.keys(bundleHints).length > 0 ? `, bundleHints: ${JSON.stringify(bundleHints)}` : ''}, ...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 function 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: string[] = [];\n for (const { path, params } of routePaths(tree)) {\n const names: string[] = [];\n for (const name of params) {\n names.push(`${name}: string`);\n }\n const fields = names.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 lines.push(` ${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 { parseSync } from 'oxc-parser';\nimport type { Site } from './model.ts';\nimport type { oxc } from './oxc.ts';\nimport { existsSync, readFileSync, readdirSync, realpathSync, writeFileSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } 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 isFileLoadingAllowed,\n transformWithOxc,\n version as viteVersion,\n} from 'vite';\nimport type { EnvironmentModuleNode, Plugin, UserConfig, ViteDevServer } from 'vite';\nimport { entryClasses } from './captures.ts';\nimport { refreshedNames } from './refreshes.ts';\nimport { compile } from './compile.ts';\nimport { DEFAULT_MERGE } from './codegen/client.ts';\nimport { defaultExclude, findFiles, findScripts, findServerFiles } from './files.ts';\nimport { clientEnvModule, parseEnvFile } from './env-file.ts';\nimport {\n findPackageServerFile,\n hasServerMiddleware,\n hasUseServer,\n isScriptFile,\n serverExports,\n serverModule,\n serverStubs,\n} from './server-files.ts';\nimport type { CompileOptions, CompileResult } from './compile.ts';\nimport { getLocation } from './error.ts';\nimport { functionId, getComponentName, hash } from './plan.ts';\nimport { analyzeProject, importedComponents, resolveRelative } from './project.ts';\nimport {\n allFeatures,\n getFeatures,\n joinFeatures,\n readsFeatures,\n writeFeatures,\n} from './features.ts';\nimport type { Features } from './features.ts';\nimport { BUILD_FILE, clientBuildDirectory, pruneBuilds, readBuildId } from './builds.ts';\nimport {\n findPackages,\n packageFileName,\n findPackage,\n reachableFiles,\n resolveComponentPackage,\n} from './packages.ts';\nimport type { BrumatePackage } from './packages.ts';\nimport type { NavigateOptions } from './runtime/boot.ts';\nimport { anchorLabel, 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 { originalPosition } from './sourcemap.ts';\nimport { toNodeHeaders } from './runtime/cookies.ts';\nimport { errorPage, errorPayload } from './dev-error.ts';\nimport type { renderToStream as RenderToStream } from './runtime/server.ts';\nimport { workbenchPage } from './workbench-page.ts';\nimport { classifyComponents, propControls } from './workbench.ts';\nimport { parse as parseComponent } from './parser.ts';\nimport { BRUMATE_VERSION } from './version.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 entry middleware, relative to the root. Its default export runs for\n * every request: pages, endpoints, server function calls, form posts and\n * `#defer` bodies. Defaults to `src/middleware.ts` when the file exists.\n * `false` runs none.\n */\n middleware?: string | false;\n /**\n * The serial entry, relative to the root. It exports `plugins` for values\n * of the app, such as a class, and the options of the serializer that it\n * changes. The server and the browser load it. Defaults to `src/serial.ts`\n * when the file exists. `false` uses none.\n */\n serial?: string | false;\n /**\n * The file of environment variables, relative to the root, which calls\n * `defineEnv` from `brumate/env`. The server checks them when it starts,\n * and the browser gets the file without the server variables. Defaults\n * to `src/env.ts` when the file exists. `false` uses none.\n */\n env?: string | false;\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 * The features of the core that the client build keeps. By default it leaves out the code of\n * those that no component of the build uses, such as `#template` values that the browser\n * calls. `'all'` keeps every feature, for an app that compiles components in the browser.\n */\n features?: 'used' | 'all';\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 * Skew protection: a page that was open before a deploy keeps working.\n * Each build has an ID, which the page carries and sends with its calls.\n * A call to a function that is gone, or a page of another build, makes\n * the browser load the page in full. The client build writes its ID to\n * `.brumate/build.json`, and the server build reads it, so build the\n * client first. `BRUMATE_BUILD` in the environment names the ID for both.\n *\n * `keep` is how many earlier builds keep their files in the client\n * output, so a page that is open still finds the code of its handlers\n * after a deploy. The build then does not empty the output directory, and\n * removes the files of older builds itself. Defaults to 0, which empties\n * it as Vite does.\n */\n skew?: { keep?: number };\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. */\n/** How many files a build reads or compiles at once, so a large project does not run out of file handles. */\nconst BATCH = 32;\n\n/** Runs `run` for each item, one batch at a time. */\nasync function inBatches<T, R>(list: T[], run: (item: T) => Promise<R>): Promise<R[]> {\n const results: R[] = [];\n for (let start = 0; start < list.length; start += BATCH) {\n const batch: Promise<R>[] = [];\n for (const item of list.slice(start, start + BATCH)) {\n batch.push(run(item));\n }\n // oxlint-disable-next-line no-await-in-loop -- Each batch waits for the one before, to bound open files.\n results.push(...(await Promise.all(batch)));\n }\n return results;\n}\n\nconst START = 'virtual:brumate/start';\n/** Exports `load(id)`, which imports the client module of a component. */\nconst MANIFEST = 'virtual:brumate/manifest';\n/** `virtual:brumate/bundle/<id>` imports the client modules of a root component and those it renders. */\nconst BUNDLE = 'virtual:brumate/bundle/';\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 ID of the module of Vite's preload helper, which a client build gets from `preloadHelper`. */\nconst PRELOAD_HELPER = '\\0vite/preload-helper.js';\n\n/**\n * Vite's preload helper wraps every `import()` of a client build and preloads the scripts and\n * the stylesheets of the chunk. This one waits for the stylesheets only, so a lazy chunk shows\n * styled, and preloads the imports of the chunk. The scripts of a page come with the `Link`\n * headers of the server (see `hints`).\n */\nfunction preloadHelper(base: string, relative: boolean): string {\n return [\n `export const __vitePreload = (load, deps, from) => {`,\n ` const links = [];`,\n ` for (const dep of deps || []) {`,\n ` const href = ${relative ? 'new URL(dep, from)' : `new URL(${JSON.stringify(base)} + dep, location.href)`}.href;`,\n ` const rel = dep.endsWith('.css') ? 'stylesheet' : 'modulepreload';`,\n ` let found = false;`,\n ` for (const link of document.getElementsByTagName('link')) {`,\n ` found ||= link.rel === rel && link.href === href;`,\n ` }`,\n ` if (!found) {`,\n ` const link = document.createElement('link');`,\n ` link.rel = rel;`,\n ` link.crossOrigin = '';`,\n ` link.href = href;`,\n ` document.head.appendChild(link);`,\n ` // A script loads along with the chunk, so only a stylesheet is waited for.`,\n ` if (rel === 'stylesheet') {`,\n ` links.push(new Promise((resolve, reject) => {`,\n ` link.onload = resolve;`,\n ` link.onerror = reject;`,\n ` }));`,\n ` }`,\n ` }`,\n ` }`,\n ` return Promise.all(links).then(load);`,\n `};`,\n ].join('\\n');\n}\n\n/** The modules that every page loads early, in the client build. See `hints` of `handleRoute`. */\nconst HINTS_FILE = '.brumate/hints.json';\n/** The dev server answers the devtools panel about a component at this path. */\nconst INSPECT = '/__brumate/inspect';\n/** Maps a position of a module that the browser ran to its source, for the Errors tab. */\nconst POSITION = '/__brumate/position';\n/** The dev server sends the source of a file for the Errors tab of the devtools at this path. */\nconst SOURCE = '/__brumate/source';\n/** The workbench of the dev server, which shows the components that depend only on their props. */\nconst WORKBENCH = '/__brumate/workbench';\n\n/** What tells two lists of packages of components apart. */\nfunction packagesKey(list: BrumatePackage[]): string {\n const rows: unknown[][] = [];\n for (const item of list) {\n rows.push([item.prefix, item.root, item.directories]);\n }\n return JSON.stringify(rows);\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 getMarkup(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 getShape(result: CompileResult): Shape {\n const labels: string[] = [];\n const slots: Record<number, string[]> = {};\n const signals: string[] = [];\n for (const layout of result.plan.scopes.values()) {\n const names: string[] = [];\n for (const slot of layout.slots) {\n names.push(slot.name);\n if (slot.kind === 'signal') {\n signals.push(slot.name);\n }\n }\n labels.push(`${layout.scope.id}:${names.join(',')}`);\n slots[layout.scope.id] = names;\n }\n return {\n layout: JSON.stringify([result.table, labels, getMarkup(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,\n signals,\n };\n}\n\n/** What Vitest passes to `configureVitest`, the part that this plugin uses. */\ninterface VitestContext {\n defineCacheKeyGenerator?: (generate: CacheKeyGenerator) => void;\n experimental_defineCacheKeyGenerator?: (generate: CacheKeyGenerator) => void;\n}\n\n/** Makes a part of Vitest's cache key of a module, or returns false to keep it out of the cache. */\ntype CacheKeyGenerator = (context: { id: string }) => string | false;\n\n/**\n * The cache key of a module for Vitest: the hash of this build of brumate. A component is never\n * cached, because its code depends on other files, such as the `.brm.ts` modules that it calls\n * and the props that other components pass it. A key of its own source would go stale.\n */\nfunction cacheKey({ id }: { id: string }): string | false {\n return id.split('?')[0]!.endsWith('.brm') ? false : buildFingerprint();\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 function 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 /** The entry middleware, when the app has one. */\n function middlewareFile(): string | undefined {\n if (options.middleware === false) {\n return undefined;\n }\n const file = normalizePath(path.resolve(root, options.middleware ?? 'src/middleware.ts'));\n if (!existsSync(file)) {\n if (options.middleware !== undefined) {\n throw new Error(`The middleware file ${options.middleware} does not exist`);\n }\n return undefined;\n }\n return file;\n }\n /** The serial entry, when the app has one. */\n function serialFile(): string | undefined {\n if (options.serial === false) {\n return undefined;\n }\n const file = normalizePath(path.resolve(root, options.serial ?? 'src/serial.ts'));\n if (!existsSync(file)) {\n if (options.serial !== undefined) {\n throw new Error(`The serial entry ${options.serial} does not exist`);\n }\n return undefined;\n }\n return file;\n }\n /** The classes that the plugins of the serial entry send, read from its `instanceof` checks. */\n let serialRead: { source: string; classes: string[] } | undefined;\n function serialClasses(): string[] {\n const file = serialFile();\n if (!file) {\n return [];\n }\n const source = readFileSync(file, 'utf8');\n if (serialRead?.source !== source) {\n const { program } = parseSync(file, source, { lang: 'ts' });\n serialRead = { source, classes: entryClasses(program as oxc.Node) };\n }\n return serialRead.classes;\n }\n /** The lines that give the server the serial entry, before anything is written or read. */\n function serialImports(): string[] {\n const file = serialFile();\n return file\n ? [\n `import * as $$serial from ${JSON.stringify(file)};`,\n \"import { useSerialEntry } from 'brumate/server';\",\n 'useSerialEntry($$serial);',\n ]\n : [];\n }\n /** The file of environment variables, when the app has one. */\n function envFile(): string | undefined {\n if (options.env === false) {\n return undefined;\n }\n const file = normalizePath(path.resolve(root, options.env ?? 'src/env.ts'));\n if (!existsSync(file)) {\n if (options.env !== undefined) {\n throw new Error(`The env file ${options.env} does not exist`);\n }\n return undefined;\n }\n return file;\n }\n /** The names of the server variables, read from the env file, by its source. */\n let envKeys: { source: string; server: string[] } | undefined;\n function serverEnvKeys(): string[] | undefined {\n const file = envFile();\n if (!file) {\n return undefined;\n }\n const source = readFileSync(file, 'utf8');\n if (envKeys?.source !== source) {\n envKeys = { source, server: parseEnvFile(source, file).server };\n }\n return envKeys.server;\n }\n const exclude = options.exclude ?? defaultExclude;\n let root = process.cwd();\n let outDir = '';\n /** The ID of the build, for skew protection. Undefined on the dev server. */\n let buildId: string | undefined;\n let base = '/';\n /** Whether a build writes URLs that need the URL of the importing chunk to resolve. */\n let relativeUrls = false;\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 `getShape`. */\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 /** The names of the server functions that the app refreshes, or undefined before the first scan. */\n let refreshed: Set<string> | undefined;\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 function relative(file: string): string {\n return normalizePath(path.relative(root, file));\n }\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 function getFileName(file: string): string {\n let normalized = normalizePath(file);\n let owner = findPackage(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 = findPackage(packages, normalized);\n }\n return owner ? packageFileName(owner, normalized) : relative(file);\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 function 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 = findPackageServerFile(packages, importer, specifier);\n return file ? functionId(serverFileId(file), name, !isServe) : undefined;\n }\n const stem = path.resolve(path.dirname(importer), specifier);\n const candidates = [stem];\n for (const extension of ['.ts', '.tsx', '.js', '.mjs']) {\n candidates.push(stem + extension);\n }\n let found: string | undefined;\n for (const candidate of candidates) {\n if (\n isScriptFile(candidate) &&\n existsSync(candidate) &&\n hasUseServer(readFileSync(candidate, 'utf8'))\n ) {\n found = candidate;\n break;\n }\n }\n return found && functionId(serverFileId(normalizePath(found)), name, !isServe);\n }\n\n function serverFileId(file: string): string {\n return `${path.basename(file).replace(/\\.[^.]+$/, '')}_${hash(getFileName(file))}`;\n }\n function componentId(file: string): string {\n const filename = getFileName(file);\n return `${getComponentName(filename)}_${hash(filename)}`;\n }\n\n async function scan(): Promise<void> {\n const directories: string[] = [];\n for (const item of packages) {\n for (const directory of item.directories) {\n if (existsSync(directory)) {\n directories.push(directory);\n }\n }\n }\n // A package inside the root, such as one of a workspace, is found once, as a package.\n function ownFile(file: string): boolean {\n return !findPackage(packages, file);\n }\n const searches = [findFiles(root, exclude), findServerFiles(root, exclude)];\n for (const directory of directories) {\n searches.push(\n findFiles(directory, packageExclude),\n findServerFiles(directory, packageExclude),\n );\n }\n const [own, ownServer, ...found] = await Promise.all(searches);\n // The scripts of the app, which can import files of packages.\n // The list is assigned once, after the search, so a lookup during the search sees the last one.\n const scripts: string[] = [];\n if (packages.length > 0) {\n for (const file of await findScripts(root, exclude)) {\n if (ownFile(file)) {\n scripts.push(file);\n }\n }\n }\n appScripts = scripts;\n files.clear();\n serverFiles.clear();\n for (const file of own!) {\n if (ownFile(file)) {\n files.set(componentId(file), file);\n }\n }\n for (const file of ownServer!) {\n if (ownFile(file)) {\n serverFiles.set(serverFileId(file), file);\n }\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 try {\n await analyze();\n } finally {\n // A list of the workbench made while the scan ran has the files from before it.\n workbenchList = undefined;\n }\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 function reachable(): Set<string> {\n const roots: string[] = [];\n for (const file of files.values()) {\n if (!findPackage(packages, file)) {\n roots.push(file);\n }\n }\n return reachableFiles(packages, [...roots, ...appScripts], (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 function resolveComponent(specifier: string, importer: string): string | undefined {\n return (\n resolveRelative(specifier, importer) ??\n (specifier.endsWith('.brm')\n ? resolveComponentPackage(packages, specifier, importer)\n : undefined)\n );\n }\n\n // Props are analyzed across the project, so a change to one file can change the output of others.\n async function analyze(): Promise<void> {\n const list = [...files.values()];\n const contents = await inBatches(list, (file) => readFile(file, 'utf8'));\n const sources = new Map<string, string>();\n for (const [index, file] of list.entries()) {\n sources.set(file, contents[index]!);\n }\n liveProps = analyzeProject(sources, resolveComponent);\n // The server functions that the app refreshes, from its components and its scripts.\n const scripts = await findScripts(root, exclude);\n const scriptSources = await inBatches(\n [...new Set([...scripts, ...serverFiles.values()])],\n (file) => readFile(file, 'utf8').catch(() => ''),\n );\n refreshed = refreshedNames([...contents, ...scriptSources]);\n compiled.clear();\n }\n\n /** The features of the core that the components of the build use, once for each build. */\n let builtFeatures: Promise<Features> | undefined;\n /** The files that `builtFeatures` counted, and the features it found. */\n let counted = new Set<string>();\n let knownFeatures: Features | undefined;\n /** The components that the client build loaded. */\n const loadedComponents = new Set<string>();\n function buildFeatures(): Promise<Features> {\n return (builtFeatures ??= (async () => {\n const seen = new Set<string>();\n const all: Features[] = [];\n // The files of the scan, and the components they import from outside it, such as a file\n // of a sibling folder or of a package with no `brumate` field.\n async function visit(file: string): Promise<void> {\n if (seen.has(file)) {\n return;\n }\n seen.add(file);\n const { result } = await compileFile(file);\n all.push(getFeatures(result));\n const imported: string[] = [];\n for (const specifier of importedComponents(result.file)) {\n const target = resolveComponent(specifier, file);\n if (target !== undefined && existsSync(target)) {\n imported.push(target);\n }\n }\n await inBatches(imported, visit);\n }\n await inBatches([...files.values()], visit);\n const features = joinFeatures(all);\n // Client navigation inserts the pages that it loads, and a route with `_loading.brm`\n // streams its body after the page.\n let loading = false;\n for (const file of seen) {\n if (path.basename(file) === '_loading.brm') {\n loading = true;\n break;\n }\n }\n features.lateMarkup ||= options.navigate !== false || loading;\n counted = seen;\n knownFeatures = features;\n return features;\n })());\n }\n\n /** The options of the compile of a file. */\n function compileOptions(file: string): CompileOptions {\n return {\n filename: getFileName(file),\n liveProps: liveProps.get(file),\n refreshed,\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 sendableClasses: serialClasses(),\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 ? resolveComponentPackage(packages, specifier, importer) : undefined;\n return found ? { path: found, source: readFileSync(found, 'utf8') } : local;\n },\n };\n }\n\n // The entry, the parts and the render module of a file come from one compile.\n async function compileFile(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 = { source, result: compile(source, compileOptions(file)) };\n compiled.set(file, cached);\n shapes.set(file, getShape(cached.result));\n }\n return cached;\n }\n\n /** The compiles whose imports were checked for the env file. */\n const envChecked = new WeakSet<CompileResult>();\n /**\n * Compiles a component again with the server variables of the env file,\n * when one of its imports resolves to it, by any specifier, such as an\n * alias. The compile fails when code that runs in the browser reads one.\n */\n async function checkEnvReads(\n file: string,\n { source, result }: { source: string; result: CompileResult },\n resolve: (specifier: string, importer: string) => Promise<{ id: string } | null>,\n ): Promise<void> {\n const env = envFile();\n if (!env || envChecked.has(result)) {\n return;\n }\n const specifiers = new Set<string>();\n for (const declaration of result.plan.graph.model.declarations) {\n if (declaration.imported) {\n specifiers.add(declaration.imported.source);\n }\n }\n const pending: Promise<string | undefined>[] = [];\n for (const specifier of specifiers) {\n pending.push(\n (async () => {\n const found = await resolve(specifier, file);\n return found?.id.split('?')[0] === env ? specifier : undefined;\n })(),\n );\n }\n const imports = new Set<string>();\n for (const specifier of await Promise.all(pending)) {\n if (specifier !== undefined) {\n imports.add(specifier);\n }\n }\n if (imports.size > 0) {\n const server = serverEnvKeys() ?? [];\n compile(source, {\n ...compileOptions(file),\n envImport: (specifier) => (imports.has(specifier) ? server : undefined),\n });\n }\n envChecked.add(result);\n }\n\n /** The components that a component imports, by file. */\n async function componentImports(file: string): Promise<string[]> {\n const { result } = await compileFile(file);\n const found: string[] = [];\n for (const declaration of result.plan.graph.model.declarations) {\n const source = declaration.imported?.source;\n const target = source?.endsWith('.brm') ? resolveComponent(source, file) : undefined;\n if (target !== undefined) {\n found.push(target);\n }\n }\n return found;\n }\n\n /**\n * The bundles of a build: for each component that no other component imports, such as a\n * route or a page, the components with client code that it can render. The page loads the\n * bundles of its roots at once, as one chunk each, so its code comes in one request.\n * Components that only import each other get a bundle too.\n */\n async function bundles(kept: Set<string>): Promise<Map<string, string[]>> {\n const imports = new Map<string, string[]>();\n await inBatches([...files.values()], async (file) => {\n try {\n imports.set(file, await componentImports(file));\n } catch {\n imports.set(file, []);\n }\n });\n const imported = new Set<string>();\n for (const targets of imports.values()) {\n for (const target of targets) {\n imported.add(target);\n }\n }\n const result = new Map<string, string[]>();\n // The components that a bundle holds so far.\n const reached = new Set<string>();\n function addRoot(id: string, file: string): void {\n const seen = new Set<string>();\n function walk(current: string): void {\n if (seen.has(current)) {\n return;\n }\n seen.add(current);\n reached.add(current);\n for (const next of imports.get(current) ?? []) {\n walk(next);\n }\n }\n walk(file);\n const members: string[] = [];\n for (const member of seen) {\n if (kept.has(member)) {\n members.push(member);\n }\n }\n if (members.length > 0) {\n result.set(id, members);\n }\n }\n for (const [id, file] of files) {\n if (!imported.has(file)) {\n addRoot(id, file);\n }\n }\n // Components that import each other, with no other component that imports them, have no\n // root of their own, so the first of them is the root of their bundle.\n for (const [id, file] of files) {\n if (!reached.has(file) && kept.has(file)) {\n addRoot(id, file);\n }\n }\n return result;\n }\n\n /** The ID of each component file. */\n function findComponentId(file: string): string | undefined {\n for (const [id, other] of files) {\n if (other === file) {\n return id;\n }\n }\n return undefined;\n }\n\n /** A bundle module: the client modules of a root component and of those it renders. */\n async function bundleModule(root: string): Promise<string> {\n const list = [...files];\n const needed = await inBatches(\n list,\n async ([, file]) => (await compileFile(file)).result.clientCode,\n );\n const kept = new Set<string>();\n for (const [index, [, file]] of list.entries()) {\n if (needed[index]) {\n kept.add(file);\n }\n }\n const members = (await bundles(kept)).get(root) ?? [];\n // Each module is a plain object of its exports. A namespace object, from `import * as`,\n // would make the bundler write a getter for each export.\n const imports: string[] = [];\n const objects: string[] = [];\n for (const [index, file] of members.entries()) {\n const { result } = await compileFile(file);\n const codes = [result.client];\n for (const [name, code] of Object.entries(result.parts)) {\n if (name !== 'shared') {\n codes.push(code);\n }\n }\n const names = exportNames(codes);\n const aliased: string[] = [];\n const fields: string[] = [];\n for (const name of names) {\n aliased.push(`${name} as $$c${index}_${name}`);\n fields.push(`${name}: $$c${index}_${name}`);\n }\n imports.push(\n `import { ${aliased.join(', ')} } from ${JSON.stringify(`${file}${CLIENT_QUERY}`)};`,\n );\n objects.push(` ${JSON.stringify(findComponentId(file))}: { ${fields.join(', ')} },`);\n }\n return [...imports, 'export const modules = {', ...objects, '};'].join('\\n');\n }\n\n async function manifest(): 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 inBatches(\n list,\n async ([, file]) => isServe || (await compileFile(file)).result.clientCode,\n );\n const kept: [string, string][] = [];\n for (const [index, entry] of list.entries()) {\n if (needed[index]) {\n kept.push(entry);\n }\n }\n if (!isServe) {\n // A build loads code by bundles of roots, so each component's code is in the chunk of\n // the page instead of a chunk of its own.\n const keptFiles = new Set<string>();\n for (const [, file] of kept) {\n keptFiles.add(file);\n }\n const groups = await bundles(keptFiles);\n const owners = new Map<string, string>();\n for (const [root, members] of groups) {\n for (const member of members) {\n const id = findComponentId(member);\n // A root that no earlier bundle holds is its own owner, which the table leaves out.\n if (id !== undefined && !owners.has(id)) {\n owners.set(id, root);\n }\n }\n }\n for (const [id, root] of owners) {\n if (id === root) {\n owners.delete(id);\n }\n }\n const bundleLines: string[] = [];\n for (const root of groups.keys()) {\n bundleLines.push(\n ` ${JSON.stringify(root)}: () => import(${JSON.stringify(`${BUNDLE}${root}`)}),`,\n );\n }\n return [\n 'const bundles = {',\n ...bundleLines,\n '};',\n `const owners = ${JSON.stringify(Object.fromEntries(owners))};`,\n 'const loaded = new Map();',\n 'const pending = new Map();',\n '/** Loads the bundle of a root component of the page. Undefined for a component that is not a root. */',\n 'export function loadBundle(root) {',\n ' let promise = pending.get(root);',\n ' if (!promise && bundles[root]) {',\n ' promise = bundles[root]().then((bundle) => {',\n ' for (const [id, module] of Object.entries(bundle.modules)) {',\n ' loaded.set(id, module);',\n ' }',\n ' });',\n ' pending.set(root, promise);',\n ' promise.catch(() => pending.delete(root));',\n ' }',\n ' return promise;',\n '}',\n '/** The client module of a component, from the bundles of the page, or else from a bundle that holds it. */',\n 'export function load(id) {',\n ' if (loaded.has(id)) {',\n ' return Promise.resolve(loaded.get(id));',\n ' }',\n ' const waiting = [...pending.values()];',\n ' const root = owners[id] ?? (bundles[id] && id);',\n ' const owner = () => (loaded.has(id) || !root ? loaded.get(id) : loadBundle(root).then(() => loaded.get(id)));',\n ' return waiting.length > 0 ? Promise.allSettled(waiting).then(owner) : root ? owner() : undefined;',\n '}',\n ].join('\\n');\n }\n const entries: string[] = [];\n for (const [id, file] of kept) {\n entries.push(\n ` ${JSON.stringify(id)}: () => import(${JSON.stringify(`${file}${CLIENT_QUERY}`)}),`,\n );\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 function serverRegistry(server = false): string {\n const query = server ? SERVER_QUERY : '';\n registered = packages.length > 0 ? reachable() : new Set();\n function keep(file: string): boolean {\n return registered.has(file) || !findPackage(packages, file);\n }\n const components: string[] = [];\n for (const file of files.values()) {\n if (keep(file)) {\n components.push(file);\n }\n }\n // In development, a file that does not compile leaves out its functions, and the pages that\n // import it show its error, so the other pages still work.\n function importAll(prefix: string, list: string[]): string[] {\n if (!isServe) {\n const lines: string[] = [];\n for (const [index, file] of list.entries()) {\n lines.push(`import * as ${prefix}${index} from ${JSON.stringify(file + query)};`);\n }\n return lines;\n }\n if (list.length === 0) {\n return [];\n }\n const loads: string[] = [];\n const names: string[] = [];\n for (const [index, file] of list.entries()) {\n loads.push(`import(${JSON.stringify(file + query)})`);\n names.push(`${prefix}${index}`);\n }\n return [\n `const [${names.join(', ')}] = (await Promise.allSettled([${loads.join(', ')}])).map((result) => (result.status === 'fulfilled' ? result.value : {}));`,\n ];\n }\n const imports = importAll('m', components);\n const spreads: string[] = [];\n for (const index of components.keys()) {\n spreads.push(` ...m${index}.rpc,`);\n }\n // Each exported function of a file of server functions, under the ID that its stub calls.\n const functionFiles: [string, string][] = [];\n for (const entry of serverFiles) {\n if (keep(entry[1])) {\n functionFiles.push(entry);\n }\n }\n const functionPaths: string[] = [];\n for (const [, file] of functionFiles) {\n functionPaths.push(file);\n }\n const fileImports = importAll('f', functionPaths);\n // The middleware of a file runs before each of its functions.\n const guards: string[] = [];\n const fileSpreads: string[] = [];\n for (const [index, [id, file]] of functionFiles.entries()) {\n // The IDs are written here, so a build can hash the names of the functions.\n const source = readFileSync(file, 'utf8');\n const names = serverExports(source, file);\n const guarded = hasServerMiddleware(source, file);\n const lines: string[] = [];\n for (const name of names) {\n const key = JSON.stringify(functionId(id, name, !isServe));\n if (guarded) {\n guards.push(` ${key}: f${index}.middleware,`);\n }\n lines.push(` ${key}: f${index}[${JSON.stringify(name)}],`);\n }\n fileSpreads.push(lines.join('\\n'));\n }\n const env = envFile();\n const entry = middlewareFile();\n return [\n // The variables are checked when the server starts, before anything else loads.\n ...(env ? [`import ${JSON.stringify(env)};`] : []),\n ...serialImports(),\n \"import { handleRequest } from 'brumate/server';\",\n ...(entry ? [`import middleware from ${JSON.stringify(entry)};`] : []),\n ...imports,\n ...fileImports,\n 'export const functions = {',\n ...spreads,\n ...fileSpreads,\n '};',\n 'export const fileMiddleware = {',\n ...guards,\n '};',\n 'export function handle(request, options) {',\n ` return handleRequest(functions, request, ${JSON.stringify(rpc)}, { origins: ${JSON.stringify(options.origins ?? [])}, ${entry ? 'middleware, ' : ''}fileMiddleware${buildId === undefined ? '' : `, build: ${JSON.stringify(buildId)}`}, ...options });`,\n '}',\n ].join('\\n');\n }\n\n function routesDirectory(): string {\n return normalizePath(path.resolve(root, options.routes ?? 'src/routes'));\n }\n\n /** The route files, from the `.brm` files found and the `.ts` files of the directory. */\n function currentRoutes(): RouteFiles {\n const directory = routesDirectory();\n const paths: string[] = [];\n for (const file of files.values()) {\n if (file.startsWith(`${directory}/`)) {\n paths.push(file.slice(directory.length + 1));\n }\n }\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 /**\n * The modules that every page loads early, which the client build wrote,\n * or none before a client build or in development.\n */\n function clientHints(): { all: string[]; bundles: Record<string, string[]> } {\n const file = path.join(clientBuildDirectory(root, options.prerender), HINTS_FILE);\n if (isServe || !existsSync(file)) {\n return { all: [], bundles: {} };\n }\n const read = JSON.parse(readFileSync(file, 'utf8')) as\n | string[]\n | { all: string[]; bundles: Record<string, string[]> };\n return Array.isArray(read) ? { all: read, bundles: {} } : read;\n }\n\n /** The route tree module. A DOM test gets the server version of each component in it. */\n function routeTree(server = false): string {\n const env = envFile();\n const code = routeModule(\n currentRoutes(),\n (file) =>\n `${routesDirectory()}/${file}${server && file.endsWith('.brm') ? SERVER_QUERY : ''}`,\n rpc,\n options.origins,\n isServe,\n middlewareFile(),\n buildId,\n clientHints().all,\n clientHints().bundles,\n );\n // The variables are checked when the server starts, before any route loads.\n const serial = serialImports().join('\\n');\n const parts: string[] = [];\n for (const part of [env ? `import ${JSON.stringify(env)};` : '', serial, code]) {\n if (part) {\n parts.push(part);\n }\n }\n return parts.join('\\n');\n }\n\n /** Writes the paths of the routes as types for `href`, when they changed. */\n function 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 async function inspectComponent(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[]; readers: string[][] }> = {};\n // The code of the browser that reads each slot, such as a handler or an update, which is\n // why its value is in the page state, for the Page state tab.\n function siteLabel(site: Site): string {\n const at = result.locate(site.range.start);\n const where = at.file === undefined ? getLocation(source, at.offset) : undefined;\n return where ? `${site.label} ${where.line}:${where.column}` : site.label;\n }\n // Updates of markup and memos run in the browser as nodes of the graph that can change.\n const liveSites = new Set<Site>();\n for (const node of plan.graph.live) {\n if ('site' in node) {\n liveSites.add(node.site);\n }\n }\n for (const layout of plan.scopes.values()) {\n const slotNames: string[] = [];\n const readers: string[][] = [];\n for (const slot of layout.slots) {\n slotNames.push(slot.name);\n const labels = new Set<string>();\n for (const ref of slot.reads) {\n if (plan.graph.reached.has(ref.site) || liveSites.has(ref.site)) {\n labels.add(siteLabel(ref.site));\n }\n }\n readers.push([...labels]);\n }\n scopes[layout.scope.id] = {\n label: scopeLabel(result.file.source, layout.scope),\n slots: slotNames,\n readers,\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: (typeof plan.graph.nodes)[number][] = [];\n const indexes = new Map<(typeof nodes)[number], number>();\n for (const node of plan.graph.nodes) {\n if (plan.graph.live.has(node)) {\n indexes.set(node, nodes.length);\n nodes.push(node);\n }\n }\n const graphNodes: object[] = [];\n for (const node of nodes) {\n if (node.kind === 'source' || node.kind === 'memo') {\n graphNodes.push({\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 continue;\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 graphNodes.push({\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 const graphEdges: number[][] = [];\n for (const edge of plan.graph.edges) {\n if (indexes.has(edge.from) && indexes.has(edge.to)) {\n graphEdges.push([indexes.get(edge.from)!, indexes.get(edge.to)!]);\n }\n }\n const graph = { nodes: graphNodes, edges: graphEdges };\n // Each anchor of each scope: what it is, its place in the file and the values its updates\n // read, for the Elements tab, which finds them by the `b-b` of an element.\n const anchors: Record<\n number,\n Record<number, { label: string; at?: string; reads: string[] }>\n > = {};\n for (const [target, index] of plan.anchors) {\n const scope = plan.anchorScopes.get(target);\n if (!scope) {\n continue;\n }\n const at = result.locate('range' in target ? target.range.start : target.start);\n const where = at.file === undefined ? getLocation(source, at.offset) : undefined;\n const reads = new Set<string>();\n for (const edge of plan.graph.edges) {\n const node = edge.to;\n if (node.kind === 'source' || node.kind === 'memo') {\n continue;\n }\n const site = node.site;\n const range = !('range' in target) && target.kind === 'insert' ? target : undefined;\n if (\n site === target ||\n site.owner === target ||\n site.block === target ||\n (range && site.range.start >= range.start && site.range.end <= range.end)\n ) {\n if (edge.from.kind === 'source' || edge.from.kind === 'memo') {\n reads.add(edge.from.declaration.name);\n }\n }\n }\n // An insert that is the whole content of its element shares the element's anchor.\n const known = anchors[scope.id]?.[index];\n if (known) {\n known.reads = [...new Set([...known.reads, ...reads])];\n continue;\n }\n (anchors[scope.id] ??= {})[index] = {\n label: anchorLabel(target),\n ...(where ? { at: `${where.line}:${where.column}` } : {}),\n reads: [...reads],\n };\n }\n const text = formatReport(report(source, result, liveProps.get(file)));\n return {\n name: plan.name,\n file: getFileName(file),\n // The absolute path, for the editor, and the URL that the browser loads the code from.\n path: file,\n url: file.startsWith(`${normalizePath(root)}/`)\n ? file.slice(normalizePath(root).length)\n : `/@fs${file}`,\n scopes,\n anchors,\n graph,\n text,\n };\n }\n\n /** The components of the app for the workbench, with what each one needs and its controls. */\n /**\n * The stories of a component: the named exports of the `.stories.ts` file next to it, each a\n * set of props. Values that JSON cannot hold, such as functions, are left out.\n */\n async function workbenchStories(\n server: ViteDevServer,\n file: string,\n ): Promise<{ stories: { name: string; props: unknown }[]; storiesError?: string }> {\n const storiesFile = file.replace(/\\.brm$/, '.stories.ts');\n if (!existsSync(storiesFile)) {\n return { stories: [] };\n }\n try {\n const module = (await server.ssrLoadModule(storiesFile)) as Record<string, unknown>;\n const stories: { name: string; props: unknown }[] = [];\n for (const [name, props] of Object.entries(module)) {\n if (name !== 'default' && props && typeof props === 'object') {\n stories.push({ name, props: JSON.parse(JSON.stringify(props)) as unknown });\n }\n }\n return { stories };\n } catch (error) {\n return { stories: [], storiesError: error instanceof Error ? error.message : String(error) };\n }\n }\n\n /** The group of a component of a package: its name, and the folder under the directory of its files. */\n function packageGroup(owner: BrumatePackage, file: string): string {\n let directory = owner.root;\n for (const item of owner.directories) {\n if (file.startsWith(`${item}/`)) {\n directory = item;\n break;\n }\n }\n const folder = path.posix.dirname(file.slice(directory.length + 1));\n return folder === '.' ? owner.name : `${owner.name}/${folder}`;\n }\n\n async function workbenchComponents(\n server: ViteDevServer,\n ): Promise<{ file: string; selfContained: boolean; [key: string]: unknown }[]> {\n const routes = `${routesDirectory()}/`;\n const list = [...new Set(files.values())];\n const contents = await inBatches(list, (file) => readFile(file, 'utf8'));\n const sources = new Map<string, string>();\n for (const [index, file] of list.entries()) {\n sources.set(file, contents[index]!);\n }\n const classes = classifyComponents(sources, {\n resolve: resolveComponent,\n serverImport: (file, specifier, name) => serverImport(file, specifier, name) !== undefined,\n });\n function relative(file: string): string {\n return normalizePath(path.relative(root, file));\n }\n const shown: string[] = [];\n for (const file of list) {\n if (!file.startsWith(routes) && classes.has(file)) {\n shown.push(file);\n }\n }\n const stories = await inBatches(shown, (file) => workbenchStories(server, file));\n const components: { file: string; selfContained: boolean; [key: string]: unknown }[] = [];\n for (const [index, file] of shown.entries()) {\n const found = classes.get(file)!;\n let controls: unknown[] | undefined = [];\n try {\n controls = propControls(parseComponent(sources.get(file)!, { filename: file }));\n } catch {\n // The compile of the file reports the error. The page says that it has no controls.\n controls = undefined;\n }\n // A component of a package is grouped under the name of the package, and the others by\n // their folder.\n const owner = findPackage(packages, file);\n const needs: (typeof found.needs)[number][] = [];\n for (const need of found.needs) {\n needs.push({ ...need, via: need.via && relative(need.via) });\n }\n components.push({\n file: relative(file),\n group: owner ? packageGroup(owner, file) : path.posix.dirname(relative(file)),\n // The name that the page shows: the import of a component of a package, or its path.\n label: owner ? `${packageGroup(owner, file)}/${path.basename(file)}` : relative(file),\n name: path.basename(file, '.brm'),\n selfContained: found.selfContained,\n needs,\n controls: controls ?? [],\n unreadProps: controls === undefined,\n ...stories[index],\n });\n }\n return components.toSorted((a, b) => a.file.localeCompare(b.file));\n }\n\n // The last list of the workbench. A frame renders on each change of a prop, so it reads this\n // list, and a change of a file clears it.\n let workbenchList: ReturnType<typeof workbenchComponents> | undefined;\n\n /** Makes the list of the workbench and keeps it, unless it fails, so a later read tries again. */\n function listWorkbench(server: ViteDevServer): ReturnType<typeof workbenchComponents> {\n const list = workbenchComponents(server);\n workbenchList = list;\n list.catch(() => {\n if (workbenchList === list) {\n workbenchList = undefined;\n }\n });\n return list;\n }\n\n /**\n * Answers the workbench: its page, the list of components, and the frame that renders one\n * component on the server with props, and resumes it in the browser as a page does.\n */\n async function serveWorkbench(\n server: ViteDevServer,\n request: IncomingMessage,\n response: ServerResponse,\n ): Promise<void> {\n const url = new URL(request.url ?? '/', 'http://localhost');\n if (url.pathname === WORKBENCH || url.pathname === `${WORKBENCH}/`) {\n response.setHeader('content-type', 'text/html; charset=utf-8');\n response.end(workbenchPage(WORKBENCH));\n return;\n }\n if (url.pathname === `${WORKBENCH}/components`) {\n response.setHeader('content-type', 'application/json');\n response.end(JSON.stringify(await listWorkbench(server)));\n return;\n }\n if (url.pathname !== `${WORKBENCH}/frame`) {\n response.statusCode = 404;\n response.end();\n return;\n }\n // Only a component that the workbench lists as self-contained, by its path from the root.\n // Any other renders without the request, the route or the server that it needs, and fails.\n const asked = url.searchParams.get('file') ?? '';\n let listed = false;\n for (const component of await (workbenchList ?? listWorkbench(server))) {\n if (component.file === asked && component.selfContained) {\n listed = true;\n break;\n }\n }\n let file: string | undefined;\n if (listed) {\n for (const candidate of files.values()) {\n if (normalizePath(path.relative(root, candidate)) === asked) {\n file = candidate;\n break;\n }\n }\n }\n if (!file) {\n response.statusCode = 404;\n response.end(`No self-contained component \"${asked}\"`);\n return;\n }\n response.setHeader('content-type', 'text/html; charset=utf-8');\n try {\n const props = JSON.parse(url.searchParams.get('props') || '{}') as Record<string, unknown>;\n const component = (await server.ssrLoadModule(file)).default;\n const { renderToStream } = await server.ssrLoadModule('brumate/server');\n const stream = (renderToStream as typeof RenderToStream)(component, props, {\n start: `<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>${path.basename(file, '.brm')}</title></head><body>`,\n end: '</body></html>',\n // The client of Vite and the loader, as the entry of an app starts it.\n scripts: `<script type=\"module\" src=\"/@vite/client\"></script><script type=\"module\" src=\"/@id/__x00__${START}\"></script>`,\n });\n const reader = stream.getReader();\n for (;;) {\n // oxlint-disable-next-line no-await-in-loop -- The page streams in order.\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n response.write(value);\n }\n response.end();\n } catch (error) {\n // Once the page has started, its status is sent, and a second document would land inside\n // the first. The error goes to the terminal, and the page ends where it stopped.\n if (response.headersSent) {\n server.config.logger.error(\n error instanceof Error ? (error.stack ?? error.message) : String(error),\n );\n response.end();\n return;\n }\n response.statusCode = 500;\n response.end(errorPage(error, server));\n }\n }\n\n async function handleDevRPC(\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 && findPackage(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 { handle } = await server.ssrLoadModule(SERVER);\n // The same path as production, so server functions can read the request.\n const headers: [string, string][] = [];\n for (const [name, value] of Object.entries(request.headers)) {\n if (value !== undefined) {\n headers.push([name, String(value)]);\n }\n }\n const webRequest = new Request(new URL(request.url ?? '/', 'http://localhost'), {\n method: 'POST',\n headers,\n body: new Uint8Array(await readBody(request)),\n });\n const began = performance.now();\n const answer: Response = await handle(webRequest, {\n address: request.socket.remoteAddress,\n });\n // How long the server function took on the server, for the Timeline of the devtools.\n answer.headers.append(\n 'server-timing',\n `brumate;dur=${(performance.now() - began).toFixed(1)};desc=\"server function\"`,\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 function 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 function 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 = getShape((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 let entry: (typeof modules)[number] | undefined;\n for (const module of server.moduleGraph.getModulesByFile(target) ?? []) {\n if (module.id?.endsWith(CLIENT_QUERY)) {\n entry = module;\n break;\n }\n }\n const kept: string[] = [];\n for (const name of after.signals) {\n if (before.signals.includes(name)) {\n kept.push(name);\n }\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: kept,\n }\n : undefined,\n });\n }\n let remounts = false;\n for (const update of updates) {\n if (update.remount) {\n remounts = true;\n break;\n }\n }\n if (remounts) {\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 function packageConfig(config: UserConfig): UserConfig {\n if (packages.length === 0) {\n return {};\n }\n const nameSet = new Set<string>();\n for (const item of packages) {\n nameSet.add(item.name);\n }\n const names = [...nameSet];\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: string[] = [];\n for (const item of packages) {\n if (item.root !== workspace && !item.root.startsWith(`${workspace}/`)) {\n outside.push(item.root);\n }\n }\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 /** The chunks that the loader and the core import, which the server hints at, and the chunks of the bundles. */\n let startChunks = new Set<string>();\n let bundleChunks = new Set<string>();\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 // The devtools show the errors of Vite, so its overlay does not cover them.\n const hmr = config.server?.hmr;\n if (\n env.command === 'serve' &&\n options.devtools !== false &&\n hmr !== false &&\n (typeof hmr !== 'object' || hmr.overlay === undefined)\n ) {\n shared.server = { hmr: { overlay: false } };\n }\n if (!env.isSsrBuild) {\n const preload = config.build?.modulePreload;\n // The files of earlier builds stay, and the build removes the ones that are too old itself.\n const keep = options.skew?.keep ? { build: { emptyOutDir: false } } : {};\n if (preload === false) {\n return { ...shared, ...keep };\n }\n return {\n ...shared,\n build: {\n ...keep.build,\n modulePreload: {\n ...(typeof preload === 'object' ? preload : {}),\n // The replacement of Vite's preload helper (`PRELOAD_HELPER`) waits for stylesheets\n // only. The server sends the hints for the scripts of the page and of the bundles,\n // so the build lists the imports of the other lazy chunks only, which the helper\n // preloads without waiting, so a chunk and its imports load together.\n resolveDependencies(filename, deps) {\n if (bundleChunks.has(filename)) {\n return [];\n }\n const rest: string[] = [];\n for (const dep of deps) {\n if (dep !== filename && !startChunks.has(dep)) {\n rest.push(dep);\n }\n }\n return 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 let entries: Record<string, string>;\n if (typeof input === 'string') {\n entries = { [path.basename(input).replace(/\\.[^.]+$/, '')]: input };\n } else if (Array.isArray(input)) {\n entries = {};\n for (const item of input) {\n entries[path.basename(item).replace(/\\.[^.]+$/, '')] = item;\n }\n } else {\n entries = { ...(input as Record<string, string> | undefined) };\n }\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?.(cacheKey);\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 relativeUrls =\n config.base === './' || config.base === '' || !!config.experimental.renderBuiltUrl;\n isSsrBuild = Boolean(config.build.ssr);\n },\n\n async generateBundle(_output, bundle) {\n if (isSsrBuild) {\n return;\n }\n // The core has no code for the features that the counted components do not use, so a\n // component that the count did not reach must not need more of them.\n for (const file of knownFeatures ? loadedComponents : []) {\n if (counted.has(file)) {\n continue;\n }\n const used = getFeatures((await compileFile(file)).result);\n const missing: (keyof Features)[] = [];\n for (const name of Object.keys(used) as (keyof Features)[]) {\n if (used[name] && !knownFeatures![name]) {\n missing.push(name);\n }\n }\n if (missing.length > 0) {\n this.error(\n `${getFileName(file)} uses ${missing.join(', ')}, which the client build left out of the core, since no component that the build found uses them. Import it from a .brm component of the app, or set \\`features: 'all'\\`.`,\n );\n }\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 startChunks = new Set();\n bundleChunks = new Set();\n function addStart(name: string | undefined): void {\n const found = name === undefined ? undefined : bundle[name];\n if (found?.type === 'chunk' && !startChunks.has(name!)) {\n startChunks.add(name!);\n for (const imported of found.imports) {\n addStart(imported);\n }\n }\n }\n addStart(loaderChunk);\n addStart(coreChunk);\n for (const item of Object.values(bundle)) {\n if (item.type === 'chunk' && item.facadeModuleId?.startsWith(`\\0${BUNDLE}`)) {\n bundleChunks.add(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 const modules: Record<string, number> = {};\n for (const [id, module] of Object.entries(item.modules)) {\n modules[id] = module.renderedLength;\n }\n chunks.push({\n fileName: item.fileName,\n code: item.code,\n isEntry: item.isEntry,\n imports: item.imports,\n moduleIds: item.moduleIds,\n modules,\n });\n }\n }\n const list = [...files.values()];\n const contents = await inBatches(list, (file) => readFile(file, 'utf8'));\n const sources = new Map<string, string>();\n for (const [index, file] of list.entries()) {\n sources.set(file, contents[index]!);\n }\n const measured = buildReport({\n chunks,\n sources,\n routes: existsSync(routesDirectory())\n ? { tree: currentRoutes(), resolve: (file) => `${routesDirectory()}/${file}` }\n : undefined,\n budget: options.budget,\n relative: getFileName,\n });\n if (options.report) {\n this.info(`\\n${formatBuildReport(measured, getFileName)}`);\n }\n if (measured.overBudget.length > 0) {\n this.error(measured.overBudget.join('\\n'));\n }\n },\n\n async writeBundle(_output, bundle) {\n if (!isSsrBuild) {\n // The modules that every page loads early, for the `Link` headers of the server build.\n const chunks = new Map<string, Extract<(typeof bundle)[string], { type: 'chunk' }>>();\n for (const item of Object.values(bundle)) {\n if (item.type === 'chunk') {\n chunks.set(item.fileName, item);\n }\n }\n const hints = new Set<string>();\n function add(name: string | undefined): void {\n const chunk = name === undefined ? undefined : chunks.get(name);\n if (chunk && !hints.has(chunk.fileName)) {\n hints.add(chunk.fileName);\n for (const imported of chunk.imports) {\n add(imported);\n }\n }\n }\n add(loaderChunk);\n add(coreChunk);\n // The chunks of the bundle of each root, which its pages load early too.\n const bundleHints: Record<string, string[]> = {};\n for (const chunk of chunks.values()) {\n const facade = chunk.facadeModuleId ?? '';\n if (!facade.startsWith(`\\0${BUNDLE}`)) {\n continue;\n }\n const files = new Set<string>();\n function walk(name: string): void {\n const found = chunks.get(name);\n if (found && !files.has(name) && !hints.has(name)) {\n files.add(name);\n for (const imported of found.imports) {\n walk(imported);\n }\n }\n }\n walk(chunk.fileName);\n const urls: string[] = [];\n for (const name of files) {\n urls.push(`${base}${name}`);\n }\n bundleHints[facade.slice(BUNDLE.length + 1)] = urls;\n }\n await mkdir(path.join(outDir, '.brumate'), { recursive: true });\n const all: string[] = [];\n for (const name of hints) {\n all.push(`${base}${name}`);\n }\n await writeFile(\n path.join(outDir, HINTS_FILE),\n JSON.stringify({ all, bundles: bundleHints }),\n );\n if (buildId !== undefined) {\n const written: string[] = [];\n for (const item of Object.values(bundle)) {\n written.push(item.fileName);\n }\n const removed = pruneBuilds(outDir, buildId, written, options.skew?.keep ?? 0);\n if (removed.length > 0) {\n this.info(`Removed the files of ${removed.length} older builds`);\n }\n }\n return;\n }\n if (!options.prerender || !isSsrBuild) {\n return;\n }\n let chunk: (typeof bundle)[string] | undefined;\n for (const item of Object.values(bundle)) {\n if (item.type === 'chunk' && item.isEntry && item.name === PRERENDER_ENTRY) {\n chunk = item;\n break;\n }\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 if (!isServe) {\n if (isSsrBuild) {\n // The server build names the build of the client, which must come first.\n const client = clientBuildDirectory(root, options.prerender);\n buildId = process.env.BRUMATE_BUILD || readBuildId(client);\n if (buildId === undefined) {\n this.warn(\n `No ${BUILD_FILE} in ${path.relative(root, client)}, so the server does not know its build ID. Build the client first, or set BRUMATE_BUILD, for skew protection`,\n );\n }\n } else {\n buildId =\n process.env.BRUMATE_BUILD || `${Date.now().toString(36)}${hash(String(Math.random()))}`;\n }\n }\n coreModule = isServe\n ? undefined\n : (await this.resolve('brumate/client', path.join(root, 'index.html')))?.id;\n await scan();\n // A rebuild in watch mode counts the features of the components again.\n builtFeatures = undefined;\n knownFeatures = undefined;\n loadedComponents.clear();\n writeRouteTypes();\n },\n\n async resolveId(id, importer, resolveOptions) {\n if (\n id === START ||\n id === MANIFEST ||\n id === SERVER ||\n id === ROUTES ||\n id === TESTING ||\n id.startsWith(BUNDLE)\n ) {\n return `\\0${id}`;\n }\n // In code that the browser loads, only components import the env file, because the\n // compiler checks that their browser code reads no server variable. It cannot check scripts.\n const env = resolveOptions?.ssr ? undefined : envFile();\n const from = importer?.split('?')[0];\n if (\n env &&\n importer &&\n from &&\n from !== env &&\n isScriptFile(from) &&\n !importer.startsWith('\\0') &&\n !importer.includes(SERVER_QUERY) &&\n !importer.includes('/node_modules/')\n ) {\n const resolved = await this.resolve(id, importer, { ...resolveOptions, skipSelf: true });\n if (resolved?.id.split('?')[0] === env) {\n this.error(\n `${relative(from)} imports ${relative(env)}, and the browser loads it. Only components can import the env file in code that the browser loads, because the compiler checks what they read. Read the variable in a component or a server function, and pass the value on.`,\n );\n }\n return resolved ?? undefined;\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) &&\n importer !== `\\0${SERVER}` &&\n importer !== `\\0${ROUTES}`) ||\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/') && !findPackage(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 if (id === PRELOAD_HELPER && !isServe) {\n return preloadHelper(base, relativeUrls);\n }\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${isServe ? '' : ', loadBundle'} } 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)' : ', loadBundle'}${serialFile() ? `, serial: () => import(${JSON.stringify(serialFile())})` : ''}, rpc: ${JSON.stringify(rpc)}, navigate: ${JSON.stringify(options.navigate ?? true)}${buildId === undefined ? '' : `, build: ${JSON.stringify(buildId)}`} });`,\n // The devtools listen to the core before it starts. Only the dev server has them.\n ...(isServe && options.devtools !== false\n ? [\n // They show the errors of Vite, such as a compile error after an edit, in place of its overlay.\n `import('brumate/devtools').then((m) => m.installDevtools(${JSON.stringify(INSPECT)}, ${JSON.stringify(rpc)}, ${JSON.stringify({ version: BRUMATE_VERSION, vite: viteVersion })}, import.meta.hot));`,\n ]\n : []),\n ].join('\\n');\n }\n if (id === `\\0${MANIFEST}`) {\n return await manifest();\n }\n if (id.startsWith(`\\0${BUNDLE}`)) {\n return await bundleModule(id.slice(BUNDLE.length + 1));\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(!loadOptions?.ssr);\n }\n if (id === `\\0${TESTING}`) {\n const entry = middlewareFile();\n return [\n \"import { answerCalls as answer, createMount, createVisit } from 'brumate/testing';\",\n `import { load } from ${JSON.stringify(MANIFEST)};`,\n ...(entry ? [`import middleware from ${JSON.stringify(entry)};`] : []),\n `export const mount = createMount({ load, rpc: ${JSON.stringify(rpc)} });`,\n // The routes and the server code load on the first visit, so a test of components skips them.\n 'export const visit = createVisit({',\n ' load,',\n ` rpc: ${JSON.stringify(rpc)},`,\n ` routes: async () => (await import(${JSON.stringify(ROUTES)})).handle,`,\n ` calls: async () => (await import(${JSON.stringify(SERVER)})).handle,`,\n '});',\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 ` const server = import(${JSON.stringify(SERVER)});`,\n ` return answer(async () => (await server).functions, { rpc: ${JSON.stringify(rpc)}, ${entry ? 'middleware, ' : ''}fileMiddleware: async () => (await server).fileMiddleware, ...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 await checkEnvReads(file, output, (specifier, importer) =>\n this.resolve(specifier, importer),\n );\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 if (!isServe && !isSsrBuild && isClient) {\n loadedComponents.add(file);\n }\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} (${getFileName(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 const sources: (string | null)[] = [];\n if (map) {\n for (const [index, name] of map.sources.entries()) {\n sources.push(index === 0 ? file : name);\n }\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,\n },\n };\n },\n\n async transform(code, id, transformOptions) {\n // The client build leaves out the code of the features of the core that no component\n // uses. The dev server and the server build keep every feature, and so does a build with\n // `features: 'all'`, such as one that compiles components in the browser.\n if (!isServe && !isSsrBuild && !transformOptions?.ssr && readsFeatures(code)) {\n const features = options.features === 'all' ? allFeatures() : await buildFeatures();\n return { code: writeFeatures(code, features), map: null };\n }\n const [file] = id.split('?');\n // The browser gets the env file without the server variables, and with the values of the\n // public ones, read now.\n if (file && !transformOptions?.ssr && file === envFile()) {\n try {\n return { code: clientEnvModule(code, file, process.env), map: null };\n } catch (error) {\n this.error((error as Error).message);\n }\n }\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 let lang: 'ts' | 'tsx' | 'jsx' = 'jsx';\n if (/\\.[cm]?ts$/.test(file)) {\n lang = 'ts';\n } else if (file.endsWith('.tsx')) {\n lang = 'tsx';\n }\n const result = await transformWithOxc(serverModule(code, file, fileId), file, {\n lang,\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: string[] = [];\n for (const item of packages) {\n if (item.linked) {\n linked.push(...item.directories);\n }\n }\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: string[] = [normalizePath(path.join(root, 'package.json'))];\n for (const item of packages) {\n manifests.push(normalizePath(`${item.root}/package.json`));\n }\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 workbenchList = undefined;\n // The names of the server variables are part of what each component compiles with.\n if (normalizePath(file) === envFile()) {\n compiled.clear();\n }\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 && !findPackage(packages, normalized)) {\n const rest: string[] = [];\n for (const item of appScripts) {\n if (item !== normalized) {\n rest.push(item);\n }\n }\n appScripts = rest;\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 // The source of a file that an error names, for the code of the Errors tab. Only files\n // that Vite would serve, by its `server.fs` options.\n if (request.method === 'GET' && request.url?.startsWith(`${SOURCE}?`)) {\n const asked = new URL(request.url, 'http://localhost').searchParams.get('file') ?? '';\n const file = normalizePath(\n path.isAbsolute(asked) && existsSync(asked)\n ? asked\n : path.join(server.config.root, asked),\n );\n if (!existsSync(file) || !isFileLoadingAllowed(server.config, file)) {\n response.statusCode = 404;\n response.end();\n return;\n }\n response.setHeader('content-type', 'text/plain; charset=utf-8');\n response.end(readFileSync(file, 'utf8'));\n return;\n }\n if (request.method === 'GET' && request.url?.startsWith(`${POSITION}?`)) {\n const params = new URL(request.url, 'http://localhost').searchParams;\n void server.environments.client.moduleGraph\n .getModuleByUrl(params.get('url') ?? '')\n .then((module) => {\n const map = module?.transformResult?.map as\n | { sources: (string | null)[]; mappings: string }\n | null\n | undefined;\n const place =\n map && module?.file\n ? originalPosition(map, Number(params.get('line')), Number(params.get('column')))\n : undefined;\n // A source that starts with `/` is a path from the root of the app, as Vite writes it.\n const file =\n place &&\n normalizePath(\n place.source.startsWith('/') && !existsSync(place.source)\n ? path.join(server.config.root, place.source)\n : path.resolve(path.dirname(module!.file!), place.source),\n );\n response.setHeader('content-type', 'application/json');\n response.end(JSON.stringify(place ? { ...place, file } : null));\n })\n .catch(next);\n return;\n }\n if (request.method === 'GET' && request.url?.startsWith(WORKBENCH)) {\n void serveWorkbench(server, request, response).catch(next);\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 (\n !file.endsWith('.brm') &&\n !dependents.has(normalized) &&\n normalized !== middlewareFile() &&\n normalized !== envFile()\n ) {\n // A module that the server code imports, such as data or Markdown that a page renders,\n // changes the HTML of the page, and the browser has no code that could update it. Vite\n // invalidates the module for the next render, and the page reloads to get it.\n if (environment.moduleGraph.getModulesByFile(normalized)?.size) {\n server.environments.client.hot.send({ type: 'full-reload' });\n }\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\n/** The names that compiled client code exports, such as `h4`, `u5` and `g`. */\nfunction exportNames(codes: string[]): string[] {\n const names = new Set<string>();\n for (const code of codes) {\n for (const match of code.matchAll(\n /^export (?:async )?(?:function\\*? |const |let |var )([\\w$]+)|^export \\{([^}]*)\\}/gm,\n )) {\n if (match[1]) {\n names.add(match[1]);\n }\n for (const item of match[2]?.split(',') ?? []) {\n const name = item\n .trim()\n .split(/\\s+as\\s+/)\n .pop();\n if (name) {\n names.add(name);\n }\n }\n }\n }\n return [...names];\n}\n"],"mappings":";;;;;;;;;;;;;AAUA,MAAM,SAAS;;AAgBf,SAAS,SAAS,MAAgB,OAAe,UAA4B;CAC3E,IAAI,KAAK,SAAS,oBAChB,MAAM,IAAI,MACR,OAAO,MAAM,gBAAgB,SAAS,iEACxC;CAEF,MAAM,OAAiB,CAAC;CACxB,KAAK,MAAM,YAAY,KAAK,YAAY;EACtC,IAAI,SAAS,SAAS,cAAc,CAAC,SAAS,UAAU;GACtD,KAAK,KACH,SAAS,IAAI,SAAS,eAClB,SAAS,IAAI,OACb,OAAQ,SAAS,IAA4B,KAAK,CACxD;GACA;EACF;EACA,MAAM,IAAI,MACR,OAAO,MAAM,gBAAgB,SAAS,gEACxC;CACF;CACA,OAAO;AACT;;AAGA,SAAS,SAAS,SAAsD;CACtE,IAAI;CACJ,SAAS,MAAM,MAAqB;EAClC,IAAI,SAAS,OAAO,SAAS,YAAY,SAAS,MAChD;EAEF,MAAM,QAAQ;EACd,IAAI,MAAM,SAAS,oBAAoB,MAAM,QAAQ,SAAS,QAAQ;GACpE,QAAQ;GACR;EACF;EACA,KAAK,MAAM,SAAS,OAAO,OAAO,KAAK,GACrC,IAAI,MAAM,QAAQ,KAAK,GACrB,KAAK,MAAM,QAAQ,OACjB,MAAM,IAAI;OAEP,IAAI,OAAO,UAAU,UAC1B,MAAM,KAAK;CAGjB;CACA,MAAM,OAAO;CACb,OAAO;AACT;;;;;;AAOA,SA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