@solidjs/vite-plugin 3.0.0-next.35 → 3.0.0-next.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.cjs +88 -25
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/esm/index.mjs +89 -26
- package/dist/esm/index.mjs.map +1 -1
- package/dist/types/src/ssr/index.d.ts +6 -0
- package/package.json +1 -1
package/dist/cjs/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":["../../src/http.ts","../../src/dev-manifest.ts","../../src/environment.ts","../../src/boundary-modules.ts","../../src/diagnostics/index.ts","../../src/server-functions/compile.ts","../../src/server-functions/xxhash32.ts","../../src/server-functions/index.ts","../../src/devtools/index.ts","../../src/ssr/index.ts","../../src/start-env.ts","../../src/index.ts"],"sourcesContent":["// Node <-> web-standard request/response bridging shared by the plugin's dev\n// middlewares (server functions and SSR). The virtual production handlers\n// speak web Request/Response only; this is the node:http glue the dev server\n// needs to talk to them.\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { Readable } from 'node:stream';\n\n/**\n * `urlPath` overrides `req.url` when the middleware needs to dispatch a\n * different URL than the one node saw — the dev middlewares use it to\n * restore the configured Vite `base` that the dev/preview base middleware\n * stripped, so the handler always sees production-shaped URLs.\n *\n * Handles plain HTTP/1 *and* the HTTP/2 compat API: Vite's dev server uses\n * `http2.createSecureServer({ allowHTTP1: true })` whenever `server.https`\n * is set without a proxy, so under https the middlewares receive\n * `Http2ServerRequest`s. The h2/protocol/abort techniques here are\n * reimplemented from srvx's Node adapter (github.com/h3js/srvx,\n * src/adapters/_node) — reference, not copied code.\n */\nexport function webRequestFromNode(\n req: IncomingMessage,\n urlPath?: string,\n res?: ServerResponse,\n): Request {\n // TLS sockets (https and h2) expose `encrypted`; a Request whose url says\n // http: on a TLS connection breaks secure-cookie logic, absolute\n // redirects, and origin checks in application code.\n const protocol = (req.socket as { encrypted?: boolean } | undefined)?.encrypted\n ? 'https'\n : 'http';\n // HTTP/2 has no Host header — the authority travels in the `:authority`\n // pseudo-header instead.\n const host = req.headers.host ?? (req.headers[':authority'] as string | undefined) ?? 'localhost';\n const url = new URL(urlPath ?? req.url ?? '/', `${protocol}://${host}`);\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value === undefined) continue;\n // HTTP/2 pseudo-headers (:method, :path, :authority, :scheme) are not\n // legal field names — Headers#append throws a TypeError on them.\n if (key[0] === ':') continue;\n if (Array.isArray(value)) {\n for (const item of value) headers.append(key, item);\n } else {\n headers.append(key, value);\n }\n }\n // Surface client disconnects as the request's AbortSignal so handlers can\n // cancel work (streamed SSR renders, in-flight fetches). The response's\n // 'close' fires on normal completion too; `writableEnded` distinguishes a\n // finished response from a client that went away.\n let signal: AbortSignal | undefined;\n if (res) {\n const controller = new AbortController();\n res.once('close', () => {\n if (!res.writableEnded) controller.abort();\n });\n signal = controller.signal;\n }\n const method = req.method || 'GET';\n const body =\n method === 'GET' || method === 'HEAD'\n ? undefined\n : (Readable.toWeb(req) as unknown as ReadableStream);\n return new Request(url, {\n method,\n headers,\n body,\n signal,\n // undici requires half-duplex for streamed request bodies.\n ...(body ? { duplex: 'half' } : {}),\n } as RequestInit);\n}\n\nexport async function sendWebResponse(res: ServerResponse, response: Response): Promise<void> {\n res.statusCode = response.status;\n // set-cookie is the one header that must not be comma-joined.\n const cookies: string[] | undefined = (response.headers as any).getSetCookie?.();\n response.headers.forEach((value, key) => {\n if (key !== 'set-cookie') res.setHeader(key, value);\n });\n if (cookies && cookies.length) res.setHeader('set-cookie', cookies);\n // HEAD gets the head only — and the body must be *cancelled*, not pumped:\n // node discards HEAD body writes, so streaming a long (or endless) body\n // into the void just burns the render. (Technique from srvx.)\n if (!response.body || res.req?.method === 'HEAD') {\n response.body?.cancel().catch(() => {});\n res.end();\n return;\n }\n const reader = response.body.getReader();\n res.on('close', () => {\n reader.cancel().catch(() => {});\n });\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n // A response whose client already went away never emits 'drain'\n // (writes are no-ops), so a backpressure wait must also settle on\n // 'close'/'error' or an aborted streaming response parks this promise\n // — and the reader and Response it holds — forever.\n if (res.destroyed) return;\n if (!res.write(value)) {\n const drained = await new Promise<boolean>((resolve) => {\n const settle = (ok: boolean) => {\n res.off('drain', onDrain);\n res.off('close', onGone);\n res.off('error', onGone);\n resolve(ok);\n };\n const onDrain = () => settle(true);\n const onGone = () => settle(false);\n res.once('drain', onDrain);\n res.once('close', onGone);\n res.once('error', onGone);\n });\n // Client gone mid-stream; the 'close' handler cancels the reader.\n if (!drained) return;\n }\n }\n res.end();\n } catch {\n res.destroy();\n }\n}\n\nexport function joinBase(base: string, pathname: string): string {\n // Absolute-URL or relative bases (CDN deploys, './') don't prefix\n // same-origin server paths.\n if (!base.startsWith('/')) return pathname;\n return (base.endsWith('/') ? base.slice(0, -1) : base) + pathname;\n}\n","import path from 'path';\nimport type { DevEnvironment, EnvironmentModuleNode, ViteDevServer } from 'vite';\nimport { joinBase } from './http.js';\n\n/**\n * Dev-mode asset resolution: the `virtual:solid-manifest` module exports a\n * resolver function in dev (instead of the static object a build produces),\n * and the runtime installs it as `context.resolveAssets` verbatim. When\n * server-side `lazy()` resolves a module key, the resolver walks the SSR\n * environment's live module graph collecting transitively imported CSS and\n * answers with inline-style descriptors — SSR'd `<style data-vite-dev-id>`\n * tags that Vite's HMR client adopts on startup, so dev CSS is styled from\n * the first streamed byte without fighting Vite's own style injection.\n *\n * The walk design follows SolidStart's collect-styles (by @katywings): crawl\n * `transformResult.deps` on the SSR environment (the client environment's\n * transform results don't list CSS deps), skipping dynamic imports since\n * dynamically imported modules register their own styles when they render.\n */\n\nexport type DevStyleDescriptor = { id: string; content: string; attrs?: Record<string, string> };\nexport type DevStyleSource = { id: string; url: string };\nexport type DevStyleFilter = (id: string) => boolean;\n\nconst defaultStyleFilter: DevStyleFilter = (id) => !id.includes('node_modules');\n\nexport type ResolvedAssets = {\n js: string[];\n css: (string | DevStyleDescriptor)[];\n};\n\nexport type DevAssetResolver = {\n /**\n * Answers synchronously (a plain object) once the key's assets are known.\n * The sync answer is load-bearing for SSR convergence: the runtime retries\n * a suspended render pass by re-creating the lazy component, which\n * re-requests its assets — if every answer is a fresh pending promise the\n * pass suspends again on a promise that did not exist when the retry\n * began, and never converges (see `createDevAssetResolver`).\n */\n resolve: (key: string) => ResolvedAssets | null | Promise<ResolvedAssets | null>;\n /**\n * Synchronous fast path used by sync consumers (a lazy component's\n * `moduleUrl` getter for islands): the module's dev URL is knowable\n * without the async CSS graph walk.\n */\n resolveSync: (key: string) => ResolvedAssets;\n};\n\n// The resolver is created plugin-side (it closes over the dev server) but is\n// called from the SSR module runner, which only shares `globalThis` with the\n// plugin when it runs in-process (the default). The primary channel is a\n// `Symbol.for`-keyed registry mapping project roots to resolvers; isolated\n// runners (nitro's dev worker, workerd) won't find it and instead fall back\n// to fetching the HTTP bridge endpoint below.\nexport const DEV_MANIFEST_REGISTRY_KEY = '@solidjs/vite-plugin:dev-manifest';\n\nexport function registerDevAssetResolver(root: string, resolver: DevAssetResolver): void {\n const key = Symbol.for(DEV_MANIFEST_REGISTRY_KEY);\n const registry: Record<string, DevAssetResolver> = ((globalThis as any)[key] ??= {});\n registry[root] = resolver;\n}\n\n/**\n * HTTP bridge endpoint for isolated SSR runners. Hosts that evaluate server\n * modules outside the Vite process (nitro's dev worker, workerd via\n * @cloudflare/vite-plugin) can't see the `globalThis` registry, so the dev\n * server itself serves asset resolution: `GET\n * /@solidjs/vite-plugin/dev-manifest?key=<module key>` answers with the\n * resolver's `ResolvedAssets` JSON (`null` when the key can't be resolved).\n * The dev flavor of `virtual:solid-manifest` falls back to fetching it when\n * the registry has no entry for the root — in-process consumers hit the\n * registry and never touch HTTP.\n */\nexport const DEV_MANIFEST_ENDPOINT = '/@solidjs/vite-plugin/dev-manifest';\n\nexport function installDevManifestBridge(server: ViteDevServer): void {\n // configureServer middlewares run ahead of Vite's internals, so `req.url`\n // may or may not still carry the configured `base` — accept both forms.\n const base = (server.config.base || '/').replace(/\\/$/, '');\n const basedEndpoint = base + DEV_MANIFEST_ENDPOINT;\n server.middlewares.use(async (req, res, next) => {\n const url = new URL(req.url || '/', 'http://localhost');\n if (url.pathname !== DEV_MANIFEST_ENDPOINT && url.pathname !== basedEndpoint) return next();\n\n const key = url.searchParams.get('key');\n if (!key) {\n res.statusCode = 400;\n return res.end('Missing asset key');\n }\n\n try {\n const registry: Record<string, DevAssetResolver> | undefined = (globalThis as any)[\n Symbol.for(DEV_MANIFEST_REGISTRY_KEY)\n ];\n const resolver = registry?.[server.config.root];\n if (!resolver) {\n // A silent null strips the module's client assets from the SSR'd\n // hydration asset map and hydration fails much later with a cryptic\n // client-side error — report the miss where it happens.\n console.error(\n `[@solidjs/vite-plugin] The dev manifest registry has no resolver for root \"${server.config.root}\" ` +\n `(requested asset key \"${key}\"). The module's client assets cannot be resolved and hydration ` +\n 'will fail for it. Typical causes: the dev server was not restarted after dependency changes, ' +\n 'or the install is stale.',\n );\n }\n const assets = resolver ? await resolver.resolve(key) : null;\n if (resolver && assets == null) {\n console.error(\n `[@solidjs/vite-plugin] Dev manifest resolver returned no assets for key \"${key}\" (root \"${server.config.root}\"). ` +\n \"The module's hydration preload entry will be missing.\",\n );\n }\n res.setHeader('content-type', 'application/json');\n res.setHeader('cache-control', 'no-store');\n return res.end(JSON.stringify(assets));\n } catch (error) {\n return next(error);\n }\n });\n}\n\n/**\n * The absolute URL isolated runners should fetch the bridge from, baked into\n * the dev flavor of `virtual:solid-manifest` when its code is generated.\n * Generation happens while serving an SSR request, so the server is already\n * listening and `resolvedUrls` carries the real origin (a config-time define\n * could only guess the port). Middleware-mode servers have no origin of\n * their own to advertise — returns null there, and the manifest module keeps\n * the js-only fallback (in-process registry hits are unaffected either way).\n */\nexport function devManifestBridgeUrl(server: ViteDevServer): string | null {\n const local = server.resolvedUrls?.local?.[0];\n let origin: string | null = null;\n if (local) {\n origin = new URL(local).origin;\n } else if (!server.config.server.middlewareMode) {\n const address = server.httpServer?.address();\n if (address && typeof address === 'object') {\n const https = !!server.config.server.https;\n origin = `${https ? 'https' : 'http'}://localhost:${address.port}`;\n }\n }\n if (!origin) return null;\n const base = (server.config.base || '/').replace(/\\/$/, '');\n return origin + base + DEV_MANIFEST_ENDPOINT;\n}\n\n// https://github.com/vitejs/vite/blob/main/packages/vite/src/node/constants.ts\nconst cssFileRegExp = /\\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)$/;\n// Queried css imports (?url, ?inline, ?raw) are not ambient styles — the\n// importer controls them — so they must not be SSR'd as style tags.\nconst nonAmbientQueryRegExp = /[?&](url|inline|raw)\\b/;\n\nconst NULL_BYTE_PLACEHOLDER = '/@id/__x00__';\n\n// Per Vite's convention virtual module ids are prefixed with `\\0`, which\n// cannot appear in an HTML attribute (the parser replaces it). Serialize the\n// same placeholder form Vite's own URLs use. Adoption of virtual-module\n// styles additionally needs `devStylePatch` (below) to run client-side;\n// fs-backed CSS (the overwhelmingly common case) adopts without it.\nfunction wrapId(id: string): string {\n return id.replace(/^\\0/, NULL_BYTE_PLACEHOLDER);\n}\n\n/**\n * Inline dev script reconciling SSR'd style tags with Vite's HMR client.\n * Frameworks that server-render whole documents should inline this in dev,\n * in `<head>` before any module script. It does two things, via a\n * MutationObserver so styles appended by streamed boundaries are handled as\n * they arrive (Vite's client seeds its stylesheet registry from the DOM only\n * once, when its module evaluates):\n *\n * - Rewrites serialized virtual-module ids (`/@id/__x00__…`) back to Vite's\n * null-byte form so seeding matches (a raw `\\0` can't survive HTML).\n * - Dedupes twins: a style tag that streams in after Vite's client has\n * seeded is missed by the scan, so the CSS module injects its own copy\n * client-side. Whenever two style tags share a `data-vite-dev-id`, the\n * SSR'd one (marked `data-asset`) is removed in favor of the Vite-owned\n * one, which is the tag HMR updates.\n *\n * Observation is two-phase to stay cheap: a document-wide subtree observer\n * only for the streaming window (SSR tags can only arrive while the parser\n * is consuming the stream; DOMContentLoaded marks its end), then a\n * childList-only observer on `document.head` for the page lifetime — Vite\n * injects twins into the head during hydration, which continues past\n * DOMContentLoaded, and a non-subtree head observer never fires on app DOM\n * churn, only on head insertions.\n *\n * Descends from SolidStart's PatchVirtualDevStyles (by @katywings); this\n * belongs in Vite itself eventually.\n */\nexport const devStylePatch = `(function(){var P=${JSON.stringify(\n NULL_BYTE_PLACEHOLDER,\n)};var handle=function(el){var v=el.getAttribute(\"data-vite-dev-id\");if(!v)return;if(v.indexOf(P)===0){v=\"\\\\0\"+v.slice(P.length);el.setAttribute(\"data-vite-dev-id\",v)}var all=document.querySelectorAll(\"style[data-vite-dev-id]\");for(var i=0;i<all.length;i++){var o=all[i];if(o!==el&&o.getAttribute(\"data-vite-dev-id\")===v){var ssr=o.hasAttribute(\"data-asset\")?o:el.hasAttribute(\"data-asset\")?el:null;if(ssr)ssr.remove();break}}};var scan=function(n){if(n.nodeType!==1)return;if(n.tagName===\"STYLE\")handle(n);else if(n.querySelectorAll)n.querySelectorAll(\"style[data-vite-dev-id]\").forEach(handle)};var onMuts=function(muts){for(var i=0;i<muts.length;i++)muts[i].addedNodes.forEach(scan)};var headPhase=function(){scan(document.documentElement);new MutationObserver(onMuts).observe(document.head,{childList:true})};scan(document.documentElement);if(document.readyState===\"loading\"){var mo=new MutationObserver(onMuts);mo.observe(document.documentElement,{childList:true,subtree:true});document.addEventListener(\"DOMContentLoaded\",function(){mo.disconnect();headPhase()})}else headPhase()})();`;\n\nasync function getModuleNode(\n env: DevEnvironment,\n file: string,\n importer?: string,\n): Promise<EnvironmentModuleNode | undefined> {\n try {\n // fetchModule resolves through the plugin container with importer\n // context, so dep strings that are placeholder-wrapped virtual URLs\n // (`/@id/__x00__…`) or importer-relative specifiers land on the right\n // module id — a raw moduleGraph/transformRequest lookup would miss them.\n const resolved = await env.fetchModule(file, importer);\n if (!('id' in resolved)) return;\n return env.moduleGraph.getModuleById(resolved.id);\n } catch {\n return;\n }\n}\n\nasync function collectModuleDeps(\n env: DevEnvironment,\n file: string,\n deps: Set<EnvironmentModuleNode>,\n crawled: Set<string>,\n filter: DevStyleFilter,\n onFile?: (file: string) => void,\n importer?: string,\n): Promise<void> {\n crawled.add(file);\n const node = await getModuleNode(env, file, importer);\n if (!node?.id || deps.has(node)) return;\n deps.add(node);\n\n const isCss = cssFileRegExp.test(node.url.split('?')[0]);\n if (!isCss && node.file && !node.id.startsWith('\\0') && !filter(node.file)) return;\n if (node.file) onFile?.(node.file);\n if (isCss) return;\n\n if (!node.transformResult) {\n await env.transformRequest(node.url).catch(() => {});\n }\n const directDeps = node.transformResult?.deps;\n if (!directDeps) return;\n\n // transformResult.deps (unlike importedModules) separates static imports\n // from dynamicDeps — dynamic imports load their own styles when rendered.\n for (const dep of directDeps) {\n if (crawled.has(dep)) continue;\n await collectModuleDeps(env, dep, deps, crawled, filter, onFile, node.id);\n }\n}\n\nfunction injectQuery(url: string, query: string): string {\n return url.includes('?') ? `${url}&${query}` : `${url}?${query}`;\n}\n\n/** Discovers ambient CSS in an entry graph without choosing how it is transported. */\nexport async function collectDevStyleSources(\n env: DevEnvironment,\n files: string[],\n onFile?: (file: string) => void,\n filter: DevStyleFilter = defaultStyleFilter,\n): Promise<DevStyleSource[]> {\n const deps = new Set<EnvironmentModuleNode>();\n const crawled = new Set<string>();\n for (const file of files) {\n await collectModuleDeps(env, file, deps, crawled, filter, onFile);\n }\n\n const css: DevStyleSource[] = [];\n const seen = new Set<string>();\n for (const node of deps) {\n if (!node.id) continue;\n const cleanUrl = node.url.split('?')[0];\n if (!cssFileRegExp.test(cleanUrl) || nonAmbientQueryRegExp.test(node.url)) continue;\n const id = wrapId(node.id);\n if (seen.has(id)) continue;\n seen.add(id);\n css.push({ id, url: node.url });\n }\n return css;\n}\n\n/**\n * Walks the SSR module graph from `files` (root-relative or absolute) and\n * returns inline-style descriptors for every transitively imported CSS\n * module — the same shape the dev asset resolver answers with for lazy\n * modules. Used by SSR start mode's dev middleware to inline the root entry's\n * CSS into `<head>` so server-painted content is styled from the first byte\n * (no FOUC while waiting for Vite's client-side style injection).\n */\nexport async function collectDevStyles(\n server: ViteDevServer,\n files: string[],\n filter: DevStyleFilter = defaultStyleFilter,\n): Promise<DevStyleDescriptor[]> {\n const ssrEnv = server.environments?.ssr;\n const clientEnv = server.environments?.client;\n if (!ssrEnv || !clientEnv) return [];\n\n const sources = await collectDevStyleSources(\n ssrEnv,\n files.map((file) => path.resolve(server.config.root, file)),\n undefined,\n filter,\n );\n\n const css: DevStyleDescriptor[] = [];\n for (const source of sources) {\n // `?direct` yields the compiled stylesheet text (what Vite serves for\n // <link> requests) — through the client environment, whose css\n // pipeline matches what the browser will run for HMR updates.\n const result = await clientEnv\n .transformRequest(injectQuery(source.url, 'direct'))\n .catch(() => null);\n if (result?.code == null) continue;\n css.push({\n id: source.id,\n content: result.code,\n attrs: { 'data-vite-dev-id': source.id },\n });\n }\n return css;\n}\n\nfunction escapeAttr(value: string): string {\n return value.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<');\n}\n\n/**\n * Serializes a dev style descriptor to the exact tag shape the SSR runtime\n * emits for lazy-registered assets (`data-asset` marks the SSR'd copy so\n * `devStylePatch` knows which twin to drop when Vite's client injects its\n * own), so the dedup story is identical for entry styles and lazy styles.\n */\nexport function renderDevStyleTag(desc: DevStyleDescriptor): string {\n let attrs = '';\n for (const name in desc.attrs) {\n attrs += ` ${name}=\"${escapeAttr(String(desc.attrs![name]))}\"`;\n }\n const content = desc.content.replace(/<\\/(style)/gi, '<\\\\/$1');\n return `<style data-asset=\"${escapeAttr(desc.id)}\"${attrs}>${content}</style>`;\n}\n\n/**\n * Browser URL for a lazy module's dev asset key (a project-root-relative\n * path, query included when the module identity carries one). Vite only\n * serves module URLs under the configured `base`, so it is always applied;\n * root-external keys (`../…`, e.g. sibling workspace packages) can't be\n * expressed as root-relative URLs at all — they get Vite's `/@fs/` form on\n * the resolved absolute path instead. Mirrored by the generated fallback in\n * `devManifestCode` (src/index.ts) — keep the two in sync.\n */\nexport function devModuleUrl(root: string, base: string, key: string): string {\n const queryIndex = key.indexOf('?');\n const file = queryIndex === -1 ? key : key.slice(0, queryIndex);\n const query = queryIndex === -1 ? '' : key.slice(queryIndex);\n if (!file.startsWith('..')) return joinBase(base, '/' + key);\n const absolute = path.resolve(root, file).split(path.sep).join('/');\n // Vite's fs URLs collapse the leading slash: /@fs/Users/… (and keep the\n // drive letter on Windows: /@fs/C:/…).\n return joinBase(base, '/@fs/' + absolute.replace(/^\\//, '') + query);\n}\n\nexport function createDevAssetResolver(\n server: ViteDevServer,\n filter: DevStyleFilter = defaultStyleFilter,\n): DevAssetResolver {\n // Server-side lazy() re-requests a module's assets on every retry of a\n // suspended render pass (retries re-create the component). The build\n // manifest answers those repeats synchronously and the pass converges; an\n // always-async resolver instead suspends every retry on a brand-new\n // promise, so a pass whose retry path re-creates the lazy component (a\n // nested route's outlet does) loops forever — each cycle nests one resume\n // closure until the render stack overflows and the escaped rejection kills\n // the dev server. So: dedupe in-flight walks per key and answer\n // synchronously once a key's assets are known. Any watcher event drops the\n // cache — the next request re-walks the updated module graph, keeping dev\n // CSS fresh.\n const resolved = new Map<string, ResolvedAssets>();\n const pending = new Map<string, Promise<ResolvedAssets | null>>();\n const { root, base } = server.config;\n let generation = 0;\n server.watcher.on('all', () => {\n generation++;\n resolved.clear();\n pending.clear();\n });\n\n const resolve = function resolveDevAssets(\n key: string,\n ): ResolvedAssets | Promise<ResolvedAssets | null> {\n const cached = resolved.get(key);\n if (cached) return cached;\n let walk = pending.get(key);\n if (!walk) {\n const startedAt = generation;\n walk = (async (): Promise<ResolvedAssets> => {\n // The module's dev URL doubles as its client entry: modulepreload\n // hint and hydration module-map value.\n const js = [devModuleUrl(root, base, key)];\n const css = await collectDevStyles(server, [key], filter);\n return { js, css };\n })().then(\n (assets) => {\n if (generation === startedAt) {\n resolved.set(key, assets);\n pending.delete(key);\n }\n return assets;\n },\n (error) => {\n if (generation === startedAt) pending.delete(key);\n throw error;\n },\n );\n pending.set(key, walk);\n }\n return walk;\n };\n return {\n resolve,\n resolveSync: (key: string) => resolved.get(key) ?? { js: [devModuleUrl(root, base, key)], css: [] },\n };\n}\n","import type { RunnableDevEnvironment } from 'vite';\n\n/**\n * Cross-instance-safe stand-in for vite's `isRunnableDevEnvironment`.\n *\n * Vite's helper is an `instanceof RunnableDevEnvironment` check against the\n * class of whichever `vite` module the CALLER imported. When this plugin is\n * consumed through a workspace/`link:` install, its own `vite` import can\n * resolve to a different physical copy than the one running the dev server —\n * and then the `instanceof` is false for every environment, silently standing\n * the SSR/dev middlewares down. The `runner` accessor is the type's defining\n * member (`RunnableDevEnvironment` is exactly \"a DevEnvironment with a\n * runner\"), so presence-check it instead of trusting class identity.\n */\nexport function isRunnableEnvironment(\n environment: unknown,\n): environment is RunnableDevEnvironment {\n return !!environment && typeof environment === 'object' && 'runner' in environment;\n}\n\nexport function getEnvironmentConsumer(\n environment: unknown,\n options?: { ssr?: boolean },\n): 'client' | 'server' {\n const consumer = (environment as { config?: { consumer?: string } } | undefined)?.config\n ?.consumer;\n if (consumer === 'client' || consumer === 'server') return consumer;\n return options?.ssr ? 'server' : 'client';\n}\n","import type { Plugin } from 'vite';\nimport { getEnvironmentConsumer } from './environment';\n\nconst VIRTUAL_ID = '\\0@solidjs/vite-plugin:boundary-modules';\n\n/**\n * `server-only` and `client-only` marker modules: importing `server-only`\n * from a module bundled for the client fails the build at resolve time with\n * a descriptive error (and vice versa for `client-only`); in the allowed\n * environment the marker resolves to an empty module.\n *\n * Server-only code pulled into a client bundle otherwise ships silently and\n * crashes at runtime (in hydrating apps, typically as a cryptic hydration\n * failure far from the real cause) — the marker turns that into a build\n * error naming the importer.\n *\n * Always on (`enforce: 'pre'`), so the bare specifiers are claimed by this\n * plugin even when React's `server-only`/`client-only` npm packages are\n * installed — the environment semantics are the same, and claiming them\n * keeps the behavior deterministic and the errors identifiable as ours.\n */\nexport function boundaryModules(): Plugin {\n return {\n name: 'solid:boundary-modules',\n enforce: 'pre',\n resolveId(id, importer, options) {\n // The dep scanner (`vite:dep-scan`) crawls the client entries' RAW\n // import graph — no directive transforms have run, so it walks\n // straight through 'use server' modules into genuinely server-only\n // code. That graph is legal once transforms split it, so the guard\n // must not fire on the scan pass (`options.scan`, set by Rolldown's\n // dependency scanner). Still claim the specifier: resolving to the empty\n // virtual module keeps the scanner from chasing `server-only` /\n // `client-only` as missing bare dependencies, which would abort the\n // scan all the same. Real dev/build module graphs resolve without\n // the flag and stay fully guarded.\n const scan = !!(options as { scan?: boolean } | undefined)?.scan;\n const server = getEnvironmentConsumer(this.environment, options) === 'server';\n if (id === 'server-only') {\n if (!server && !scan)\n this.error(\n `[@solidjs/vite-plugin] Attempt to import 'server-only' in a client module: ${importer}. ` +\n `Code that uses this module must run only on the server — make sure it is only ` +\n `imported by server code (e.g. a server entry, a \"use server\" module, or code ` +\n `reached exclusively from them).`,\n );\n } else if (id === 'client-only') {\n if (server && !scan)\n this.error(\n `[@solidjs/vite-plugin] Attempt to import 'client-only' in a server module: ${importer}. ` +\n `Code that uses this module must run only in the browser — make sure it is only ` +\n `imported by client code (e.g. behind a client-only lazy boundary).`,\n );\n } else {\n return null;\n }\n return VIRTUAL_ID;\n },\n load(id) {\n if (id === VIRTUAL_ID) return 'export {}';\n },\n };\n}\n","/**\n * Agent diagnostics surface (`diagnostics: true`, dev serve only).\n *\n * Three pieces:\n * - an injected client module (virtual, imported by index.html or the\n * start-mode client entry) that installs the in-page bridge from the\n * app's own `@solidjs/diagnostics` and answers requests over Vite's\n * WebSocket custom events;\n * - a collector that forwards requests to the page and correlates\n * responses by id;\n * - an HTTP endpoint (`/__solid/diagnostics`) fronting that round-trip so\n * any out-of-process consumer (agent, MCP tool, curl) can drive capture\n * sessions without holding a WebSocket.\n *\n * `@solidjs/diagnostics` is deliberately a type-only dependency of this\n * plugin: the runtime bridge always comes from the app's own installed\n * copy, so plugin releases and diagnostics releases stay uncoupled. The\n * wire constants are re-declared here with types imported from the\n * package, so drift fails the plugin's own compile.\n */\nimport path from 'path';\nimport type { IncomingMessage, ServerResponse } from 'http';\nimport type { Plugin } from 'vite';\nimport { joinBase } from '../http.js';\n\ntype Protocol = typeof import('@solidjs/diagnostics/protocol');\nconst DIAGNOSTICS_ENDPOINT: Protocol['DIAGNOSTICS_ENDPOINT'] = '/__solid/diagnostics';\nconst REQUEST_EVENT: Protocol['DIAGNOSTICS_REQUEST_EVENT'] = 'solid:diagnostics:request';\nconst RESPONSE_EVENT: Protocol['DIAGNOSTICS_RESPONSE_EVENT'] = 'solid:diagnostics:response';\n\ntype DiagnosticsResponse = import('@solidjs/diagnostics/protocol').DiagnosticsResponse;\n\nexport const DIAGNOSTICS_PACKAGE = '@solidjs/diagnostics';\nexport const DIAGNOSTICS_CLIENT_ID = 'virtual:solid-diagnostics/client';\n\nconst METHODS = ['begin', 'end', 'active', 'whyDidRun', 'costs'] as const satisfies readonly (\n | import('@solidjs/diagnostics/protocol').DiagnosticsMethod\n)[];\n\n/** How long the endpoint waits for a page to answer before failing the call. */\nconst RESPONSE_TIMEOUT_MS = 10_000;\n\nexport function diagnosticsClientModuleCode(): string {\n // Runtime imports resolve to the APP's diagnostics package (see the\n // resolveId assist below) — the page speaks its own package's protocol.\n return [\n `import { installDiagnosticsBridge } from '${DIAGNOSTICS_PACKAGE}/browser';`,\n `import {`,\n ` DIAGNOSTICS_REQUEST_EVENT,`,\n ` DIAGNOSTICS_RESPONSE_EVENT,`,\n `} from '${DIAGNOSTICS_PACKAGE}/protocol';`,\n ``,\n `const bridge = installDiagnosticsBridge();`,\n ``,\n `async function dispatch(request) {`,\n ` switch (request.method) {`,\n ` case 'begin': bridge.begin(request.params); return true;`,\n ` case 'end': return bridge.end();`,\n ` case 'active': return bridge.active();`,\n ` case 'whyDidRun': return bridge.whyDidRun(request.params.name);`,\n ` case 'costs': return bridge.costs();`,\n ` default: throw new Error('Unknown diagnostics method: ' + request.method);`,\n ` }`,\n `}`,\n ``,\n `if (import.meta.hot) {`,\n ` import.meta.hot.on(DIAGNOSTICS_REQUEST_EVENT, async (request) => {`,\n ` let response;`,\n ` try {`,\n ` response = { id: request.id, result: await dispatch(request) };`,\n ` } catch (error) {`,\n ` response = {`,\n ` id: request.id,`,\n ` error: error instanceof Error ? error.message : String(error),`,\n ` };`,\n ` }`,\n ` import.meta.hot.send(DIAGNOSTICS_RESPONSE_EVENT, response);`,\n ` });`,\n `}`,\n ].join('\\n');\n}\n\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n res.statusCode = status;\n res.setHeader('Content-Type', 'application/json');\n res.end(JSON.stringify(body));\n}\n\nfunction readJsonBody(req: IncomingMessage): Promise<unknown> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n req.on('data', (chunk) => chunks.push(chunk));\n req.on('end', () => {\n const text = Buffer.concat(chunks).toString('utf8');\n if (!text) return resolve({});\n try {\n resolve(JSON.parse(text));\n } catch {\n reject(new Error('Request body is not valid JSON'));\n }\n });\n req.on('error', reject);\n });\n}\n\nexport function solidDiagnostics(): Plugin {\n let root = process.cwd();\n let base = '/';\n\n return {\n name: 'solid:diagnostics',\n // Dev-serve only: the channels this fronts exist in dev builds only.\n apply(_config, env) {\n return env.command === 'serve' && !env.isPreview;\n },\n\n configResolved(config) {\n root = config.root;\n base = config.base;\n },\n\n async resolveId(source, importer) {\n if (source === DIAGNOSTICS_CLIENT_ID) {\n return { id: DIAGNOSTICS_CLIENT_ID, moduleSideEffects: true };\n }\n // The virtual module has no directory to resolve bare imports from;\n // resolve the app's diagnostics package from the project root.\n if (importer === DIAGNOSTICS_CLIENT_ID && source.startsWith(DIAGNOSTICS_PACKAGE)) {\n const resolved = await this.resolve(source, path.resolve(root, 'index.html'), {\n skipSelf: true,\n });\n if (!resolved || resolved.id.startsWith('__vite-optional-peer-dep:')) {\n this.error(\n `[@solidjs/vite-plugin] the diagnostics option requires ${DIAGNOSTICS_PACKAGE} ` +\n 'installed in the app (it provides the in-page bridge). Install it as a ' +\n 'development dependency or remove `diagnostics: true`.',\n );\n }\n return resolved;\n }\n return null;\n },\n\n load(id) {\n if (id === DIAGNOSTICS_CLIENT_ID) return diagnosticsClientModuleCode();\n return null;\n },\n\n // Plain (index.html) apps get the client module injected here;\n // start-mode apps import it from the generated client entry instead.\n transformIndexHtml() {\n return [\n {\n tag: 'script',\n attrs: { type: 'module', src: joinBase(base, '/@id/' + DIAGNOSTICS_CLIENT_ID) },\n injectTo: 'head' as const,\n },\n ];\n },\n\n configureServer(server) {\n // Announce the surface in the startup block. This is a discovery\n // channel: agents watching dev-server output learn the endpoint and\n // the skill documents without any project-level pointer (AGENTS.md).\n const originalPrintUrls = server.printUrls.bind(server);\n server.printUrls = () => {\n originalPrintUrls();\n const local = server.resolvedUrls?.local[0];\n const endpoint = local\n ? new URL(DIAGNOSTICS_ENDPOINT, local).href\n : DIAGNOSTICS_ENDPOINT;\n server.config.logger.info(\n ` ➜ Solid diagnostics: ${endpoint} ` +\n `(GET status; POST {\"method\":\"begin\"|\"end\"|\"whyDidRun\"|\"costs\"})\\n` +\n ` ➜ Agent skills: node_modules/${DIAGNOSTICS_PACKAGE}/skills/agent-loops/SKILL.md, ` +\n `node_modules/solid-js/skills/reactivity-diagnostics/SKILL.md`,\n );\n };\n\n interface Pending {\n resolve: (response: DiagnosticsResponse) => void;\n timer: ReturnType<typeof setTimeout>;\n }\n const pending = new Map<number, Pending>();\n let nextId = 1;\n\n server.ws.on(RESPONSE_EVENT, (data: DiagnosticsResponse) => {\n const entry = pending.get(data?.id as number);\n if (!entry) return;\n pending.delete(data.id);\n clearTimeout(entry.timer);\n entry.resolve(data);\n });\n\n server.middlewares.use(DIAGNOSTICS_ENDPOINT, async (req, res) => {\n // The middleware mounts on the exact path; anything deeper is 404.\n if (req.url && req.url !== '/' && req.url !== '') {\n sendJson(res, 404, { error: `Unknown diagnostics path ${req.url}` });\n return;\n }\n if (req.method === 'GET') {\n sendJson(res, 200, {\n ok: true,\n methods: METHODS,\n clients: server.ws.clients.size,\n });\n return;\n }\n if (req.method !== 'POST') {\n sendJson(res, 405, { error: 'Use GET for status or POST { method, params }' });\n return;\n }\n\n let body: { method?: string; params?: unknown };\n try {\n body = (await readJsonBody(req)) as { method?: string; params?: unknown };\n } catch (error) {\n sendJson(res, 400, { error: (error as Error).message });\n return;\n }\n if (!body.method || !(METHODS as readonly string[]).includes(body.method)) {\n sendJson(res, 400, {\n error: `Unknown method ${JSON.stringify(body.method)}; expected one of: ${METHODS.join(', ')}`,\n });\n return;\n }\n if (server.ws.clients.size === 0) {\n sendJson(res, 503, {\n error:\n 'No connected page. Open the app in a browser (dev server) so the ' +\n 'diagnostics bridge can answer.',\n });\n return;\n }\n\n const id = nextId++;\n // Broadcast; with several open tabs the first responder wins. Good\n // enough for the agent loop (one page under test); revisit with\n // client targeting if multi-page capture ever matters.\n const response = await new Promise<DiagnosticsResponse | { timeout: string }>(\n (resolve) => {\n const timer = setTimeout(() => {\n pending.delete(id);\n resolve({\n timeout:\n `No page answered within ${RESPONSE_TIMEOUT_MS}ms. The connected page ` +\n 'may predate `diagnostics: true` — reload it.',\n });\n }, RESPONSE_TIMEOUT_MS);\n pending.set(id, { resolve, timer });\n server.ws.send(REQUEST_EVENT, { id, method: body.method, params: body.params });\n },\n );\n\n if ('timeout' in response) {\n sendJson(res, 504, { error: response.timeout });\n } else if (response.error !== undefined) {\n sendJson(res, 400, { error: response.error });\n } else {\n sendJson(res, 200, { result: response.result });\n }\n });\n },\n };\n}\n","// The `\"use server\"` directive compiler. This wraps the native\n// `transformDirectives` pass from @solidjs/compiler (Rust/Oxc); the\n// original Babel implementation (hoisted from solid-start) lived in this\n// directory through vite-plugin-solid@c052963e and remains the frozen\n// reference for the native pass's fixture suite.\n\nexport interface NamedImportDefinition {\n kind: 'named';\n name: string;\n source: string;\n}\n\nexport interface DefaultImportDefinition {\n kind: 'default';\n source: string;\n}\n\nexport type ImportDefinition = DefaultImportDefinition | NamedImportDefinition;\n\nexport interface CompileOptions {\n mode: 'server' | 'client';\n env: 'production' | 'development';\n /** The directive text (default \"use server\" upstream). */\n directive: string;\n /** Project root; function IDs hash the root-relative path. */\n root: string;\n definitions: {\n register: ImportDefinition;\n create: ImportDefinition;\n };\n}\n\nexport interface CompileResult {\n valid: boolean;\n code: string;\n map: string | null;\n functions: import('@solidjs/compiler').ServerFunctionMeta[];\n}\n\ntype NativeCompiler = typeof import('@solidjs/compiler');\nlet compilerPromise: Promise<NativeCompiler> | undefined;\n\n// Loaded lazily so importing the plugin never pays for the native binding —\n// only setups that enable server functions load it (mirrors the JSX\n// compiler's opt-in loader in index.ts).\nasync function loadCompiler(): Promise<NativeCompiler> {\n try {\n return await (compilerPromise ??= import('@solidjs/compiler'));\n } catch (error) {\n compilerPromise = undefined;\n const reason = error instanceof Error ? `\\n\\nCause: ${error.message}` : '';\n throw new Error(\n '@solidjs/vite-plugin: failed to load @solidjs/compiler (the \"use server\" ' +\n 'transform). Your platform should get a prebuilt native binary or the ' +\n '@solidjs/compiler-wasm32-wasi fallback — check that optional ' +\n 'dependencies were installed.' +\n reason,\n );\n }\n}\n\n/**\n * Runs the directive transform over one module. Function IDs are\n * `hash(relative path)-<counter>`, so the client and server builds of the\n * same checkout agree on every ID (the wire contract) without baking\n * machine-specific absolute paths into the output. A `valid: false` result\n * means the module contained no matching directive and must be left\n * untransformed. Invalid closure captures (a server function referencing a\n * non-top-level binding) throw with the variable name and location.\n */\nexport async function compile(\n id: string,\n code: string,\n options: CompileOptions,\n): Promise<CompileResult> {\n const { transformDirectives } = await loadCompiler();\n const result = transformDirectives(code, {\n filename: id,\n root: options.root,\n mode: options.mode,\n env: options.env,\n directive: options.directive,\n sourceMap: true,\n register: options.definitions.register,\n create: options.definitions.create,\n });\n return {\n valid: result.valid,\n code: result.code,\n map: result.map ?? null,\n functions: result.functions,\n };\n}\n","// @ts-nocheck\n/**\n * Hoisted from solid-start (packages/start/src/directives/xxhash32.ts).\n *\n * Copyright (c) 2019 Jason Dent\n * https://github.com/Jason3S/xxhash\n */\nconst PRIME32_1 = 2654435761;\nconst PRIME32_2 = 2246822519;\nconst PRIME32_3 = 3266489917;\nconst PRIME32_4 = 668265263;\nconst PRIME32_5 = 374761393;\n\nfunction toUtf8(text: string): Uint8Array {\n const bytes: number[] = [];\n for (let i = 0, n = text.length; i < n; ++i) {\n const c = text.charCodeAt(i);\n if (c < 0x80) {\n bytes.push(c);\n } else if (c < 0x800) {\n bytes.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f));\n } else if (c < 0xd800 || c >= 0xe000) {\n bytes.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));\n } else {\n const cp = 0x10000 + (((c & 0x3ff) << 10) | (text.charCodeAt(++i) & 0x3ff));\n bytes.push(\n 0xf0 | ((cp >> 18) & 0x7),\n 0x80 | ((cp >> 12) & 0x3f),\n 0x80 | ((cp >> 6) & 0x3f),\n 0x80 | (cp & 0x3f),\n );\n }\n }\n return new Uint8Array(bytes);\n}\n\n/**\n * @param buffer - byte array or string\n * @param seed - optional seed (32-bit unsigned)\n */\nexport default function xxHash32(buffer: Uint8Array | string, seed = 0): number {\n buffer = typeof buffer === 'string' ? toUtf8(buffer) : buffer;\n const b = buffer;\n\n // Step 1. Initialize internal accumulators\n let acc = (seed + PRIME32_5) & 0xffffffff;\n let offset = 0;\n\n if (b.length >= 16) {\n const accN = [\n (seed + PRIME32_1 + PRIME32_2) & 0xffffffff,\n (seed + PRIME32_2) & 0xffffffff,\n (seed + 0) & 0xffffffff,\n (seed - PRIME32_1) & 0xffffffff,\n ];\n\n // Step 2. Process stripes (16 bytes = 4 lanes of 4 bytes)\n const b = buffer;\n const limit = b.length - 16;\n let lane = 0;\n for (offset = 0; (offset & 0xfffffff0) <= limit; offset += 4) {\n const i = offset;\n const laneN0 = b[i + 0] + (b[i + 1] << 8);\n const laneN1 = b[i + 2] + (b[i + 3] << 8);\n const laneNP = laneN0 * PRIME32_2 + ((laneN1 * PRIME32_2) << 16);\n let acc = (accN[lane] + laneNP) & 0xffffffff;\n acc = (acc << 13) | (acc >>> 19);\n const acc0 = acc & 0xffff;\n const acc1 = acc >>> 16;\n accN[lane] = (acc0 * PRIME32_1 + ((acc1 * PRIME32_1) << 16)) & 0xffffffff;\n lane = (lane + 1) & 0x3;\n }\n\n // Step 3. Accumulator convergence\n acc =\n (((accN[0] << 1) | (accN[0] >>> 31)) +\n ((accN[1] << 7) | (accN[1] >>> 25)) +\n ((accN[2] << 12) | (accN[2] >>> 20)) +\n ((accN[3] << 18) | (accN[3] >>> 14))) &\n 0xffffffff;\n }\n\n // Step 4. Add input length\n acc = (acc + buffer.length) & 0xffffffff;\n\n // Step 5. Consume remaining input (up to 15 bytes)\n const limit = buffer.length - 4;\n for (; offset <= limit; offset += 4) {\n const i = offset;\n const laneN0 = b[i + 0] + (b[i + 1] << 8);\n const laneN1 = b[i + 2] + (b[i + 3] << 8);\n const laneP = laneN0 * PRIME32_3 + ((laneN1 * PRIME32_3) << 16);\n acc = (acc + laneP) & 0xffffffff;\n acc = (acc << 17) | (acc >>> 15);\n acc = ((acc & 0xffff) * PRIME32_4 + (((acc >>> 16) * PRIME32_4) << 16)) & 0xffffffff;\n }\n\n for (; offset < b.length; ++offset) {\n const lane = b[offset];\n acc += lane * PRIME32_5;\n acc = (acc << 11) | (acc >>> 21);\n acc = ((acc & 0xffff) * PRIME32_1 + (((acc >>> 16) * PRIME32_1) << 16)) & 0xffffffff;\n }\n\n // Step 6. Final mix (avalanche)\n acc ^= acc >>> 15;\n acc = (((acc & 0xffff) * PRIME32_2) & 0xffffffff) + (((acc >>> 16) * PRIME32_2) << 16);\n acc ^= acc >>> 13;\n acc = (((acc & 0xffff) * PRIME32_3) & 0xffffffff) + (((acc >>> 16) * PRIME32_3) << 16);\n acc ^= acc >>> 16;\n\n // turn any negatives back into a positive number;\n return acc < 0 ? acc + 4294967296 : acc;\n}\n","// Hoisted from solid-start (packages/start/src/directives/index.ts).\n//\n// Standalone `\"use server\"` support for Vite. The compiler half of server\n// functions lives here; the runtime half (registration on the server, a\n// transport on the client) is @solidjs/web/server-functions by default —\n// the compiled output imports `registerServerReference` /\n// `createServerReference` from that specifier and the package's export\n// conditions resolve the right half per environment. Any runtime satisfying\n// that contract can be swapped in through `options.runtime` (SolidStart's,\n// or your own).\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';\nimport path from 'path';\nimport {\n createFilter,\n type EnvironmentModuleGraph,\n type FilterPattern,\n type Plugin,\n type ViteDevServer,\n} from 'vite';\nimport { getEnvironmentConsumer, isRunnableEnvironment } from '../environment.js';\nimport { joinBase, sendWebResponse, webRequestFromNode } from '../http.js';\nimport { compile, type CompileOptions } from './compile.js';\nimport xxHash32 from './xxhash32.js';\n\n/**\n * Picomatch patterns selecting the modules the directive compiler runs on.\n * Relative patterns (the defaults included) are resolved against the Vite\n * root — not the invocation directory — so running `vite` from outside the\n * project keeps compiling the same files. Absolute patterns are used as-is.\n *\n * @default include \"src/**\\/*.{jsx,tsx,ts,js,mjs,cjs}\", exclude \"node_modules/**\\/*.{jsx,tsx,ts,js,mjs,cjs}\"\n */\nexport interface ServerFunctionsFilter {\n include?: FilterPattern;\n exclude?: FilterPattern;\n}\n\nexport interface ServerFunctionsOptions {\n /**\n * Module specifiers the compiled output imports the runtime from.\n * Each must export `registerServerReference(id, fn)` (server) and\n * `createServerReference(...)` (both sides).\n *\n * @default \"@solidjs/web/server-functions\" for both (the package's export\n * conditions resolve the client or server half per environment)\n */\n runtime?: {\n server: string;\n client: string;\n };\n /**\n * Virtual module id that imports every module containing server functions.\n * Import it for side effects in your server entry so all registrations\n * exist before requests are handled.\n *\n * @default \"virtual:solid-server-function-manifest\"\n */\n manifest?: string;\n filter?: ServerFunctionsFilter;\n /**\n * @default \"use server\"\n */\n directive?: string;\n /**\n * Path the server-function transport posts to. Joined with Vite `base`.\n * Threaded to the built-in dev middleware, the\n * `virtual:solid-server-function-handler` module, and — whenever the\n * resolved path differs from the runtime default (`/_server`) — runtime\n * `configureServerFunctions{Client,Server}` calls appended to compiled\n * modules (so custom runtimes used with a custom endpoint must export\n * those).\n *\n * @default \"/_server\"\n */\n endpoint?: string;\n /**\n * Whether the built-in dev middleware owns the server-function endpoint on\n * the Vite dev server. Only meaningful through the main plugin's\n * `serverFunctions` option (the standalone `serverFunctions()` export\n * never installs the middleware).\n *\n * Set `false` when another plugin's server environment should own\n * dispatch in dev — e.g. @cloudflare/vite-plugin, whose workerd\n * environment carries the bindings (`env`/`ctx`) your server functions\n * need: the middleware executes functions in Vite's node-side SSR\n * environment, so with it installed those requests never reach the\n * worker. With the middleware off, everything else keeps working —\n * compilation, the manifest and handler virtual modules — and endpoint\n * requests fall through to whatever the host serves; the host loads\n * `virtual:solid-server-function-handler` itself and dispatches through\n * its `handleServerFunctionRequest` export, exactly like production.\n * Functions referenced only by client code register on demand through\n * the middleware in dev, so a host owning dispatch should side-effect\n * import the manifest module in its server entry to cover them.\n *\n * When a provider owns the dev server's `ssr` environment (it isn't\n * runnable), the middleware already stands down automatically — no need\n * to set this. See `start.external` for the whole-server switch.\n *\n * @default true (stands down automatically when the `ssr` dev environment isn't runnable)\n */\n devMiddleware?: boolean;\n /**\n * Path to a server-only module (resolved relative to the Vite root, like\n * `start.document`) that the generated\n * `virtual:solid-server-function-handler` module side-effect imports\n * before configuring the runtime. A guaranteed pre-dispatch home for\n * server-side registration — typically `configureServerFunctionsServer`\n * calls whose config the app graph can't reliably install first, e.g. a\n * router's single-flight collector:\n *\n * ```ts\n * // src/server-config.ts\n * import { configureServerFunctionsServer } from '@solidjs/web/server-functions/server';\n * configureServerFunctionsServer({ collectFlightData: createFlightDataCollector(router) });\n * ```\n *\n * Because the module lives in the handler graph, it is evaluated before\n * any dispatch on every surface — the dev middleware and the production\n * handler alike — and is immune to the dev-restart race where\n * registration living in the app graph only loads with the first page\n * render (the handler graph loads before the first mutation). Config\n * calls merge per key, so it composes with the plugin's own\n * `configureServerFunctionsServer` call in the same module.\n *\n * @default undefined\n */\n configure?: string;\n /**\n * Enable server components (experimental): `\"use server\"` functions that\n * return a component. Responses for them are served over the\n * server-function endpoint as streamed HTML that the client runtime\n * applies in place of the boundary (instead of decoding it as data).\n *\n * The plugin's dispatch surfaces — the built-in dev middleware and the\n * `virtual:solid-server-function-handler` module — install the response\n * transform on the server runtime automatically, so this needs no\n * per-request wiring or server code.\n *\n * Document SSR of server components (rendered inline at t=0 and adopted\n * at boot with zero endpoint requests) needs three more pieces: the\n * render must run with the server-component render plugin, the document\n * must carry the bootstrap script, and the client must call\n * `installServerComponents()` before hydrating. With SSR start mode (the\n * main plugin's `start` option with `ssr: true`) and generated entries\n * the plugin emits all three. With authored entries those pieces live in\n * your entry files — import them from `@solidjs/web/frames` (see the\n * README).\n *\n * All of this is pure codegen: when the option is off, no reference to\n * the server-component runtime is emitted anywhere.\n *\n * @default false\n */\n components?: boolean;\n}\n\nconst DEFAULT_INCLUDE = 'src/**/*.{jsx,tsx,ts,js,mjs,cjs}';\nconst DEFAULT_EXCLUDE = 'node_modules/**/*.{jsx,tsx,ts,js,mjs,cjs}';\nconst DEFAULT_MANIFEST = 'virtual:solid-server-function-manifest';\nconst DEFAULT_DIRECTIVE = 'use server';\nconst DEFAULT_RUNTIME = '@solidjs/web/server-functions';\n// Must match the runtime's built-in default — when the resolved endpoint\n// equals it, no configure calls need to be emitted at all.\nconst DEFAULT_ENDPOINT = '/_server';\nconst STORAGE_SOURCE = '@solidjs/web/storage';\n// Server-only handler: importing it wires the endpoint in one line\n// (registrations via the manifest, request-event scoping, endpoint config).\nconst HANDLER_ID = 'virtual:solid-server-function-handler';\n\n// Server functions referenced only from client-side code (e.g. event\n// handlers, which the SSR JSX compile drops) never get imported — or even\n// transformed — by the server build, so their registrations would be missing\n// at runtime. That's why the client transform records modules into the\n// *server* manifest set. The dev server and Vite's builder mode share one\n// process where that just works; the classic two-invocation build\n// (`vite build` then `vite build --ssr`) does not, so the client build\n// persists its findings for the SSR build to merge (mirroring the plugin's\n// dist/client/.vite/manifest.json convention).\nconst PERSISTED_MANIFEST_PATH = '.vite/solid-server-functions.json';\n\nfunction readPersistedManifest(root: string): Set<string> {\n const file = path.resolve(root, 'dist/client', PERSISTED_MANIFEST_PATH);\n if (!existsSync(file)) return new Set();\n try {\n const entries: string[] = JSON.parse(readFileSync(file, 'utf-8'));\n return new Set(\n entries.map((entry) => path.resolve(root, entry)).filter((entry) => existsSync(entry)),\n );\n } catch {\n return new Set();\n }\n}\n\nfunction writePersistedManifest(root: string, outDir: string, entries: Set<string>): void {\n const file = path.resolve(root, outDir, PERSISTED_MANIFEST_PATH);\n mkdirSync(path.dirname(file), { recursive: true });\n const relative = [...entries].map((entry) =>\n path.relative(root, entry).split(path.sep).join('/'),\n );\n writeFileSync(file, JSON.stringify(relative, null, 2));\n}\n\ntype Manifest = Record<CompileOptions['mode'], Set<string>>;\n\nfunction createManifest(): Manifest {\n return {\n server: new Set(),\n client: new Set(),\n };\n}\n\ninterface DeferredPromise<T> {\n reference: Promise<T>;\n resolve: (value: T) => void;\n reject: (value: any) => void;\n}\n\nfunction createDeferredPromise<T>(): DeferredPromise<T> {\n let resolve: DeferredPromise<T>['resolve'];\n let reject: DeferredPromise<T>['reject'];\n\n return {\n reference: new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n }),\n resolve(value) {\n resolve(value);\n },\n reject(value) {\n reject(value);\n },\n };\n}\n\n// The manifest can only be emitted once every module has been transformed\n// (each transform may register new entries), but Vite gives no such signal —\n// so the manifest load resolves a debounced snapshot that transforms keep\n// pushing back while they are still landing.\nclass Debouncer<T> {\n promise: DeferredPromise<T>;\n\n private timeout: ReturnType<typeof setTimeout> | undefined;\n\n constructor(private source: () => T) {\n this.promise = createDeferredPromise();\n this.defer();\n }\n\n defer(): void {\n if (this.timeout) {\n clearTimeout(this.timeout);\n this.timeout = undefined;\n }\n this.timeout = setTimeout(() => {\n this.promise.resolve(this.source());\n }, 1000);\n }\n}\n\nfunction mergeManifestRecord(\n source: Set<string>,\n target: Set<string>,\n): { invalidPreload: boolean; invalidated: string[] } {\n const current = source.size;\n for (const entry of target) {\n source.add(entry);\n }\n return {\n invalidPreload: current !== source.size,\n invalidated: [...source],\n };\n}\n\nfunction invalidateModule(moduleGraph: EnvironmentModuleGraph, path: string) {\n const target = moduleGraph.getModuleById(path);\n if (target) {\n moduleGraph.invalidateModule(target);\n }\n}\n\nfunction invalidateModules(\n server: ViteDevServer | undefined,\n result: ReturnType<typeof mergeManifestRecord>,\n manifest: string,\n): void {\n if (server?.environments && result.invalidPreload) {\n invalidateModule(server.environments.client.moduleGraph, manifest);\n invalidateModule(server.environments.ssr.moduleGraph, manifest);\n }\n}\n\n/**\n * The second parameter is internal wiring for the main plugin's\n * `serverFunctions` option: the built-in dev middleware is only installed\n * through that path, so meta-frameworks composing this factory directly\n * (and dispatching to `handleServerFunctionRequest` themselves) never race\n * it for the endpoint. On the main plugin's path the public\n * `options.devMiddleware` (default true) can opt back out of it.\n */\nexport function serverFunctions(\n options: ServerFunctionsOptions = {},\n internal: { devMiddleware?: boolean; externalDevServer?: boolean; ssrHandler?: string } = {},\n): Plugin[] {\n const filterInclude = options.filter?.include || DEFAULT_INCLUDE;\n const filterExclude = options.filter?.exclude || DEFAULT_EXCLUDE;\n // Recreated in configResolved: relative patterns (the defaults included)\n // must resolve against the Vite root, not process.cwd() — running `vite`\n // from outside the project would otherwise silently skip every module.\n let filter = createFilter(filterInclude, filterExclude);\n const manifestId = options.manifest || DEFAULT_MANIFEST;\n const directive = options.directive || DEFAULT_DIRECTIVE;\n const runtime = options.runtime || { server: DEFAULT_RUNTIME, client: DEFAULT_RUNTIME };\n const endpointOption = options.endpoint || DEFAULT_ENDPOINT;\n const endpoint = endpointOption.startsWith('/') ? endpointOption : '/' + endpointOption;\n const components = !!options.components;\n // The middleware only exists on the main plugin's path to begin with (see the\n // `internal` parameter doc); the public option opts out of it there.\n const installDevMiddleware = !!internal.devMiddleware && options.devMiddleware !== false;\n\n let env: CompileOptions['env'];\n let root = process.cwd();\n let base = '/';\n let isBuild = false;\n let isSsrBuild = false;\n let outDir = 'dist';\n // Endpoint with Vite `base` applied; final after configResolved, which\n // runs before every transform/load/middleware that reads it.\n let resolvedEndpoint = endpoint;\n // Absolute path of the user's `configure` module; resolved (and existence-\n // checked) in configResolved, before any handler load can read it.\n let configureModulePath: string | null = null;\n\n const manifest = createManifest();\n\n const preload: Record<CompileOptions['mode'], Debouncer<string> | undefined> = {\n server: undefined,\n client: undefined,\n };\n let currentServer: ViteDevServer | undefined;\n\n const clientOptions: Pick<CompileOptions, 'directive' | 'definitions'> = {\n directive,\n definitions: {\n register: {\n kind: 'named',\n name: 'registerServerReference',\n source: runtime.client,\n },\n create: {\n kind: 'named',\n name: 'createServerReference',\n source: runtime.client,\n },\n },\n };\n const serverOptions: Pick<CompileOptions, 'directive' | 'definitions'> = {\n directive,\n definitions: {\n register: {\n kind: 'named',\n name: 'registerServerReference',\n source: runtime.server,\n },\n create: {\n kind: 'named',\n name: 'createServerReference',\n source: runtime.server,\n },\n },\n };\n\n // A non-default endpoint (custom option, or Vite `base` prefixing the\n // default) must reach the runtime on both sides — the client transport\n // reads it for every fetch, the server for rendered reference `.url`s.\n // References are only reachable through compiled modules, so appending the\n // configure call to each guarantees it runs before any reference is used.\n // The default endpoint appends nothing, keeping compiled output byte-\n // identical for setups that wire the runtime themselves.\n function endpointConfigureSnippet(mode: CompileOptions['mode']): string {\n if (resolvedEndpoint === DEFAULT_ENDPOINT) return '';\n const name =\n mode === 'server' ? 'configureServerFunctionsServer' : 'configureServerFunctionsClient';\n const source = mode === 'server' ? runtime.server : runtime.client;\n return (\n `\\nimport { ${name} as $$configureServerFunctions } from ${JSON.stringify(source)};` +\n `\\n$$configureServerFunctions({ endpoint: ${JSON.stringify(resolvedEndpoint)} });\\n`\n );\n }\n\n // Dev omits the manifest import: the middleware loads the referenced\n // module on demand instead (importing the debounced manifest would stall\n // the first request and eagerly SSR-load every server-function module).\n // Builds import it so tree-shaking can't drop registrations for functions\n // only client code references.\n function handlerModuleCode(includeManifest: boolean): string {\n // Server components ride the frame-stream wire protocol: the transform\n // serves a function's component result as streamed HTML instead of data.\n // Installing it here (config-level, merged with the other keys) covers\n // both dispatch surfaces — the dev middleware and the prod handler load\n // this module before dispatching — with zero per-request wiring. The\n // import is only emitted when the option is on, so disabled setups keep\n // a server-component-free graph.\n return [\n // The user's `configure` module comes first: a side-effect import in\n // the handler graph, evaluated before any dispatch on both surfaces\n // (dev middleware and prod handler) and bundled into the handler\n // chunk by production builds. Order relative to the configure call\n // below doesn't actually matter — runtime config merges per key —\n // import-first is just the cleaner shape.\n ...(configureModulePath ? [`import ${JSON.stringify(configureModulePath)};`] : []),\n ...(includeManifest ? [`import ${JSON.stringify(manifestId)};`] : []),\n `import { handleServerFunctionRequest as handle, configureServerFunctionsServer } from ${JSON.stringify(runtime.server)};`,\n `import { provideRequestEvent } from ${JSON.stringify(STORAGE_SOURCE)};`,\n ...(components\n ? [\n `import { frameTransformResult, frameTransformFlightResult, frameTransformDirectResult } from '@solidjs/web/frames';`,\n ]\n : []),\n // `transformFlightResult` is the single-flight leg of the same wire\n // protocol: a mutation whose invalidated payload includes markup gets\n // the frame stream as its carrier (regions + envelope in one\n // response). It only runs when a router registered a collectFlightData\n // hook, so installing it unconditionally alongside the result\n // transform costs disabled setups nothing.\n //\n // `transformDirectResult` is ALSO installed here — not just in the\n // generated SSR entry — because flight collection makes direct\n // (in-process) calls during handler dispatch, and the transform is what\n // brands their results with the call address the client matches showing\n // boundaries against. The SSR entry usually loads first and installs\n // the same value (config merges per key), but the handler graph cannot\n // depend on that: in dev, a mutation from an already-open page can be\n // the first request after a server restart.\n `configureServerFunctionsServer({ provideEvent: provideRequestEvent, endpoint: ${JSON.stringify(resolvedEndpoint)}${\n components\n ? ', transformResult: frameTransformResult, transformFlightResult: frameTransformFlightResult, transformDirectResult: frameTransformDirectResult'\n : ''\n } });`,\n `export const endpoint = ${JSON.stringify(resolvedEndpoint)};`,\n // `options.event` is the same wrapper->event extension seam the SSR\n // handler's handleRequest carries (conventionally `nativeEvent`, the\n // platform's raw request object). The runtime's standalone handler\n // creates its own event (`{ request, locals }`) with no init\n // parameter, so the extension threads through its existing\n // `createEvent` option instead — spread before `...options` so an\n // explicit host-provided createEvent still wins.\n `export function handleServerFunctionRequest(request, options) {`,\n ` const { event: eventInit, ...rest } = options || {};`,\n ` return handle(request, {`,\n ` provideEvent: provideRequestEvent,`,\n ` ...(eventInit ? { createEvent: (req) => ({ request: req, locals: {}, ...eventInit }) } : {}),`,\n ` ...rest,`,\n ` });`,\n `}`,\n ].join('\\n');\n }\n\n // Function IDs are `xxHash32(root-relative path)-<count>` (see compile.ts),\n // so the hash segment maps an incoming ID back to its module. Rebuilt\n // whenever a transform has grown the manifest.\n const hashIndex = new Map<string, string>();\n let hashIndexSize = -1;\n function moduleForFunctionId(functionId: string): string | undefined {\n if (manifest.server.size !== hashIndexSize) {\n hashIndex.clear();\n for (const entry of manifest.server) {\n const relative = path.relative(root, entry).split(path.sep).join('/');\n hashIndex.set(xxHash32(relative).toString(16), entry);\n }\n hashIndexSize = manifest.server.size;\n }\n return hashIndex.get(functionId.split('-', 1)[0]!);\n }\n\n function moduleDevUrl(entry: string): string {\n const relative = path.relative(root, entry).split(path.sep).join('/');\n return relative.startsWith('..') ? '/@fs/' + entry : '/' + relative;\n }\n\n const startPlugins: Plugin[] = [\n {\n name: 'solid:server-functions/handler',\n enforce: 'pre',\n resolveId(source, _importer, opts) {\n if (source === HANDLER_ID) {\n if (getEnvironmentConsumer(this.environment, opts) !== 'server') {\n this.error(\n `${HANDLER_ID} is server-only; import it from your server entry (SSR build).`,\n );\n }\n return { id: HANDLER_ID, moduleSideEffects: true };\n }\n return null;\n },\n load(id, opts) {\n if (id === HANDLER_ID && getEnvironmentConsumer(this.environment, opts) === 'server') {\n const externalDev =\n this.environment.mode === 'dev' &&\n (internal.externalDevServer || !isRunnableEnvironment(this.environment));\n return handlerModuleCode(isBuild || externalDev);\n }\n return null;\n },\n },\n ];\n\n if (installDevMiddleware) {\n startPlugins.push({\n name: 'solid:server-functions/dev-middleware',\n apply: 'serve',\n configureServer(server) {\n const ssrEnvironment = server.environments.ssr;\n if (internal.externalDevServer || !isRunnableEnvironment(ssrEnvironment)) {\n return;\n }\n // A call's address is `<endpoint>/<id>` (solidjs/solid#3076) — the\n // mount plus exactly one path segment. Bare-mount requests still\n // reach the runtime handler (it answers 404), so misdirected posts\n // fail through the endpoint rather than falling through to SSR.\n const underMount = (pathname: string, mount: string) =>\n pathname === mount || pathname.startsWith(mount + '/');\n server.middlewares.use((req, res, next) => {\n const url = new URL(req.url || '/', 'http://localhost');\n // Match with and without `base` — middleware-mode hosts may mount\n // vite.middlewares below the base themselves.\n if (!underMount(url.pathname, resolvedEndpoint) && !underMount(url.pathname, endpoint)) {\n return next();\n }\n const basePrefixed = underMount(url.pathname, resolvedEndpoint);\n // When the stripped form matched, restore the base for dispatch:\n // the generated handler compares the request pathname against the\n // base-prefixed endpoint, and production handlers only ever see\n // base-prefixed URLs.\n const dispatchUrl = basePrefixed ? undefined : joinBase(base, req.url || '/');\n (async () => {\n // Make sure the referenced module has been evaluated in the SSR\n // environment so its registration exists — functions only client\n // code references are never loaded by the SSR render itself.\n // The id lives in the path segment after the mount.\n const mount = basePrefixed ? resolvedEndpoint : endpoint;\n const segment = url.pathname.slice(mount.length + 1);\n let functionId: string | null = null;\n if (segment && !segment.includes('/')) {\n try {\n functionId = decodeURIComponent(segment);\n } catch {\n // not an address; the runtime handler answers the 404\n }\n }\n if (!functionId) {\n // TRANSITIONAL (remove before 3.0 stable): the retired header\n // and `?id=` addressing, kept only for the RC window where this\n // plugin meets a @solidjs/web older than the path-addressing\n // change (solidjs/solid#3076).\n const headerId = req.headers['x-server-function-id'];\n functionId =\n (typeof headerId === 'string' ? headerId.split('#')[0] : undefined) ||\n url.searchParams.get('id');\n }\n if (functionId) {\n const entry = moduleForFunctionId(functionId);\n if (entry) await ssrEnvironment.runner.import(moduleDevUrl(entry));\n }\n // Dispatch through a module evaluated in the SSR environment so\n // the handler shares the registry instance with the app modules.\n // With SSR start mode active the main plugin threads its handler id\n // in, and dispatch goes through `handleRequest` instead — one\n // middleware chain and one stub-backed request event front the\n // endpoint exactly as they front page SSR.\n const handler = await ssrEnvironment.runner.import(internal.ssrHandler ?? HANDLER_ID);\n // Both dispatch shapes carry the raw Node request on the event\n // (the `options.event` seam), matching the SSR dev middleware\n // and what a production Node entry passes.\n const dispatchOptions = { event: { nativeEvent: req } };\n const response: Response = internal.ssrHandler\n ? await handler.handleRequest(\n webRequestFromNode(req, dispatchUrl, res),\n dispatchOptions,\n )\n : await handler.handleServerFunctionRequest(\n webRequestFromNode(req, dispatchUrl, res),\n dispatchOptions,\n );\n await sendWebResponse(res, response);\n })().catch((error) => {\n next(error);\n });\n });\n },\n });\n }\n\n return [\n {\n name: 'solid:server-functions/setup',\n enforce: 'pre',\n configResolved(config) {\n env = config.mode !== 'production' ? 'development' : 'production';\n root = config.root;\n base = config.base;\n filter = createFilter(filterInclude, filterExclude, { resolve: root });\n isBuild = config.command === 'build';\n isSsrBuild = !!config.build.ssr;\n outDir = config.build.outDir;\n resolvedEndpoint = joinBase(config.base, endpoint);\n if (options.configure) {\n const absolute = path.isAbsolute(options.configure)\n ? options.configure\n : path.resolve(root, options.configure);\n if (!existsSync(absolute)) {\n throw new Error(\n `[@solidjs/vite-plugin] serverFunctions.configure does not exist: ${options.configure}`,\n );\n }\n configureModulePath = absolute;\n }\n if (isBuild && isSsrBuild) {\n // Classic two-invocation build: pick up the modules the client\n // build discovered so the server manifest registers them even when\n // the SSR module graph never imports them.\n for (const entry of readPersistedManifest(root)) {\n manifest.server.add(entry);\n }\n }\n },\n configureServer(server) {\n currentServer = server;\n },\n writeBundle() {\n // Same client-build detection as the main plugin: builder-mode builds\n // run both environments in one process, so prefer the per-environment\n // consumer over the process-wide --ssr flag.\n const ctx = this as { environment?: { config?: { consumer?: string } } };\n const consumer = ctx.environment?.config?.consumer;\n const isClient = consumer ? consumer === 'client' : !isSsrBuild;\n if (isBuild && isClient) {\n writePersistedManifest(root, outDir, manifest.server);\n }\n },\n },\n {\n name: 'solid:server-functions/manifest',\n enforce: 'pre',\n resolveId(source) {\n if (source === manifestId) {\n return { id: manifestId, moduleSideEffects: true };\n }\n return null;\n },\n async load(id, opts) {\n const mode = getEnvironmentConsumer(this.environment, opts);\n if (id === manifestId) {\n if (isBuild && mode === 'server') {\n // Merge the client build's persisted discoveries at load time,\n // not just configResolved: in builder mode (single process,\n // `vite build` with the environments API) all environment\n // configs resolve before the client build has written the file,\n // but this load runs once the SSR environment builds — after it.\n for (const entry of readPersistedManifest(root)) {\n manifest.server.add(entry);\n }\n }\n const current = new Debouncer(() =>\n [...manifest[mode]].map((entry) => `import ${JSON.stringify(entry)};`).join('\\n'),\n );\n preload[mode] = current;\n const result = await current.promise.reference;\n return result;\n }\n return null;\n },\n },\n {\n name: 'solid:server-functions/compiler',\n enforce: 'pre',\n async transform(code, fileId, opts) {\n const mode = getEnvironmentConsumer(this.environment, opts);\n const [id] = fileId.split('?');\n if (!filter(id)) {\n return null;\n }\n\n // Fast path: the directive has to appear literally, so anything\n // without the substring can skip the native parse entirely.\n if (!code.includes(directive)) {\n return null;\n }\n\n const result = await compile(id!, code, {\n ...(mode === 'server' ? serverOptions : clientOptions),\n mode,\n env,\n root,\n });\n\n if (result.valid) {\n const preloader = preload[mode];\n if (preloader) {\n preloader.defer();\n }\n invalidateModules(\n currentServer,\n mergeManifestRecord(manifest.server, new Set([id!])),\n manifestId,\n );\n\n return {\n // Appended (not prepended) so the source map for the compiled\n // module stays valid; imports hoist and the endpoint is only\n // read at call time, never during module evaluation.\n code: (result.code || '') + endpointConfigureSnippet(mode),\n map: result.map,\n };\n }\n return null;\n },\n },\n ...startPlugins,\n ];\n}\n","export const DEVTOOLS_PACKAGE = '@solidjs/start-devtools';\nexport const DEVTOOLS_MOUNT_ID = 'virtual:solid-devtools/mount';\n\nexport function devtoolsMountModuleCode(): string {\n return [\n `import { mountDevToolbar } from '${DEVTOOLS_PACKAGE}';`,\n `mountDevToolbar();`,\n ].join('\\n');\n}\n","// Start-mode serving for plain Vite apps: `solid({ start: {...} })` (or the\n// zero-config sugar `start: true`) adds a serving layer with conventional\n// entries so no hand-rolled wiring is needed, and the plugin's `ssr`\n// boolean picks the mode — `ssr: true` server-renders the app per request;\n// `ssr: false`/omitted is client mode (the same conventions, but the\n// document shell is served/prerendered empty and the app `render()`s\n// client-side). The flip between them is that one boolean.\n//\n// SSR mode (`start` + `ssr: true`):\n// - Dev: runnable SSR environments are served by a Vite middleware. Provider-\n// owned environments serve through `virtual:solid-ssr-handler` instead.\n// Both paths inject the Vite client, dev style patch, and entry CSS as\n// `<style data-vite-dev-id>` tags before the body can paint.\n// - Prod: the plugin configures a full-app build (client + server bundles\n// via the Vite environments/builder API — a single `vite build` builds\n// both) whose server entry is `virtual:solid-ssr-handler`: an\n// adapter-agnostic named `handleRequest(Request) => Promise<Response>` plus\n// a default Fetchable `{ fetch(request) }` export. Both scope each request\n// with `provideRequestEvent`, stream the render, and resolve hashed client\n// assets through `virtual:solid-manifest`.\n// - Entries are conventional with escape hatches: `src/entry-server.*` /\n// `src/entry-client.*` are used when present (or set explicitly); when\n// absent, default entries are generated from a single root component\n// (`start.app`, defaulting to `src/App.*`) wrapped in a document shell\n// (`start.document`, defaulting to `src/Document.*`, else a built-in one).\n// - When `serverFunctions` is also enabled, the handler composes the\n// endpoint on every surface; the runnable-dev server-function middleware\n// pre-loads the referenced module, then dispatches through this handler.\n// - Every dispatch runs under a stub-backed request event\n// (`createRequestEvent`) with the optional `start.middleware` chain fronting\n// it, and page responses go through the runtime's `createSSRResponse`\n// head lifecycle (commit at shell flush, real pre-flush redirects, the\n// script fallback post-flush).\n// - `vite preview` serves dist/client statically and dispatches everything\n// else through the built handler — the production path, middleware\n// included, with no server file needed.\n//\n// Client mode (`start` without `ssr: true`) rides the same machinery with\n// three deltas: the generated server entry renders the document shell\n// WITHOUT the app (dev serving doubles as history fallback, and a\n// post-build hook prerenders it once into dist/client/index.html), the\n// generated client entry render()s instead of hydrating, and dist/server is\n// dropped from the output unless `serverFunctions` needs it for the\n// endpoint. Client code compiles non-hydratable, exactly like a plain SPA.\nimport { existsSync, rmSync, writeFileSync } from 'fs';\nimport path from 'path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport {\n type DevEnvironment,\n type FilterPattern,\n normalizePath,\n type Plugin,\n type PreviewServer,\n type ViteDevServer,\n} from 'vite';\nimport { getEnvironmentConsumer, isRunnableEnvironment } from '../environment.js';\nimport {\n DEVTOOLS_MOUNT_ID,\n DEVTOOLS_PACKAGE,\n devtoolsMountModuleCode,\n} from '../devtools/index.js';\nimport { DIAGNOSTICS_CLIENT_ID } from '../diagnostics/index.js';\nimport {\n collectDevStyles,\n collectDevStyleSources,\n type DevStyleFilter,\n devStylePatch,\n renderDevStyleTag,\n} from '../dev-manifest.js';\nimport { joinBase, sendWebResponse, webRequestFromNode } from '../http.js';\n\n/**\n * Options for the main plugin's `start` option (`start: true` is\n * sugar for the empty bag). One bag serves both modes — the plugin's `ssr`\n * boolean picks between them, so flipping a project between\n * client-rendered and server-rendered is toggling that boolean, never\n * reshaping this object. Server-only options (`entryServer`, `external`)\n * are documented no-ops in client mode: they stay in the config across a\n * flip instead of erroring.\n */\nexport interface StartOptions {\n /**\n * Root component module for generated entries (the zero-config path).\n * Resolved relative to the Vite root.\n *\n * @default \"src/App.{tsx,jsx,ts,js}\" (also probes lowercase \"src/app.*\")\n */\n app?: string;\n /** Options for development CSS crawling. */\n css?: {\n /**\n * Filter for the modules traversed while collecting the CSS that dev\n * SSR inlines into `<head>`. Patterns are\n * [picomatch](https://github.com/micromatch/picomatch) globs or regexes;\n * relative globs resolve against the Vite root. CSS files themselves\n * and virtual modules always pass — the filter decides which module\n * graphs are crawled, not which stylesheets are kept.\n *\n * `exclude` prunes matching graphs and defaults to `/node_modules/`\n * (providing your own replaces the default). `include` opts matching\n * files back in on top of that baseline — typically a package whose\n * CSS should be server-inlined to avoid a development FOUC, e.g.\n * `{ include: /node_modules\\/some-ui-lib/ }`. A file matching both\n * stays excluded. Development only: production CSS always comes from\n * the built assets.\n */\n filter?: {\n include?: FilterPattern;\n exclude?: FilterPattern;\n };\n };\n /**\n * Server entry module. Must export `render(request?, context?)` returning\n * a `renderToStream` result, an HTML string, or a `Response`.\n * `context.clientEntry` carries the resolved client entry URL.\n *\n * Server mode only — ignored in client mode, where the server entry is\n * always generated (it renders the document shell without the app, for\n * dev serving and the build-time prerender). Conventional\n * `src/entry-server.*` files are likewise ignored there.\n *\n * @default \"src/entry-server.{tsx,jsx,ts,js,mjs}\" when present, else a\n * generated entry rendering `<Document><App /></Document>`\n */\n entryServer?: string;\n /**\n * Client entry module. In SSR mode it hydrates; in client mode it mounts\n * (a generated one calls `render()`), and it stands alone — no pairing\n * rule with a server entry.\n *\n * @default \"src/entry-client.{tsx,jsx,ts,js,mjs}\" when present, else a\n * generated entry\n */\n entryClient?: string;\n /**\n * Document shell component wrapping the app in generated entries. Receives\n * `props.children` and must render the full `<html>` document including\n * `<HydrationScript />` (in client mode, where nothing hydrates, the\n * handler strips its output from the served/prerendered shell — a shared\n * Document costs nothing across the flip; the built-in shell omits it per\n * mode). Only used when the server entry is generated.\n *\n * @default \"src/Document.{tsx,jsx}\" when present, else a built-in shell\n */\n document?: string;\n /**\n * Path to a server-only module (resolved relative to the Vite root) whose\n * default export is one fetch-style middleware function — `(request,\n * next) => Response | Promise<Response>` — or an array of them, composed\n * in order. The chain fronts every request the plugin dispatches — page\n * SSR, the server-function endpoint, dev and production, `vite preview` —\n * and runs inside the request-event scope, so `getRequestEvent()` works\n * exactly as it does in application code (decorate `locals`, write the\n * `response` stub). `next()` advances the chain (pass a `Request` to\n * substitute it downstream); nothing reaches the wire until the outermost\n * middleware returns, so headers on the returned `Response` stay mutable\n * after `next()` — streamed bodies included — and error middleware is a\n * plain `try { return await next(); } catch { ... }`.\n *\n * All methods and accept types dispatch through the chain — API routes\n * and no-JS form POSTs included, in dev exactly as in production. A\n * non-page request (anything but an HTML-accepting GET) that no\n * middleware handled falls back to Vite's own pipeline in dev instead of\n * rendering the page at it.\n *\n * @default undefined\n */\n middleware?: string;\n /**\n * Path to a server-only module (resolved relative to the Vite root) whose\n * default export runs once per request in the generated server entry,\n * after the middleware chain has dispatched to the page render and\n * immediately before `renderToStream`: `(event, App) => Component | void |\n * Promise<Component | void>`. The per-request seam for routers that must\n * prepare an app instance before SSR begins (create a router bound to the\n * request, `await router.load()`, then render): return a component and the\n * generated entry renders it in the app's place inside the Document;\n * return nothing and `<App />` renders unchanged. `event` is the shared\n * request event — the same one the middleware chain decorated (`locals`\n * are visible) — and the hook runs inside the request scope, so\n * `getRequestEvent()` answers in anything it calls.\n *\n * Only meaningful with generated entries: an authored `entry-server`\n * already owns its render function, so configuring both is an error.\n * Server mode only — ignored in client mode (there is no per-request app\n * render to prepare), so the config survives the `ssr` boolean flip.\n *\n * @default undefined\n */\n setup?: string;\n /**\n * Typed, validated environment variables. A schema file — conventionally\n * `env.ts` (or `env.js`) at the project root, probed automatically —\n * default-exports `{ server?, client? }` maps of Standard Schema\n * validators (zod, valibot, arktype, mixable per key), and the plugin\n * exposes the validated values through `virtual:env/server` (all vars,\n * server module graphs only — a client-graph import is a hard error) and\n * `virtual:env/client` (the `VITE_`-prefixed `client` side; the prefix is\n * enforced at config time). Validation runs at config/build time in node\n * only against Vite's `loadEnv` merge of the `.env*` files (with\n * `process.env` winning), which the plugin also folds into `process.env`\n * itself — no `loadEnv` boilerplate in vite.config. Failures fail the\n * build / render the dev error overlay with the per-key report, and a\n * `solid-env.d.ts` is generated next to the schema so both virtual\n * modules are fully typed by inference.\n *\n * Client values are baked as plain JSON (that's what `VITE_` means); no\n * validator ships in a client bundle, and a client-build leak scan\n * errors when a server value shows up in a client chunk. Server values\n * are NOT baked: `virtual:env/server` reads `process.env` at server boot\n * and validates through your schema (imported into the server bundle\n * only), so platform-injected vars work and secrets rotate without a\n * rebuild — no secret exists in any dist artifact. Build-time server\n * failures are a deferred-to-boot warning; dev failures stay hard.\n * Boot validation is synchronous — the generated module carries no\n * top-level await, so server bundles work on non-esnext targets\n * (Nitro's node-server preset needs no `esnext` override) — which is\n * why async validators are rejected for `server` keys at config time\n * (`client` keys may stay async: they are awaited at build time).\n *\n * `true` requires the conventional file (error when missing); a string\n * is an explicit schema path; `false` disables even the probing.\n * Env is a start-mode feature: without `start` there is no env layer.\n *\n * @default undefined (probe env.ts / env.js; off when absent)\n */\n env?: boolean | string;\n /**\n * Enable the development toolbar. By default it is enabled when\n * `@solidjs/start-devtools` is installed. Setting this to `true` requires\n * the package, while `false` disables it.\n *\n * @default undefined\n */\n devtools?: boolean;\n /**\n * Add the default production error boundary to generated entries.\n * Disable this when application middleware owns error handling. Authored\n * entries are unaffected.\n *\n * @default true\n */\n errorBoundary?: boolean;\n /**\n * Let a host integration own the server environment — build wiring and\n * HTTP serving alike. The plugin skips its start-mode server-build config and\n * stands its dev middlewares down (SSR serving and the server-function\n * endpoint); the generated `virtual:solid-ssr-handler` self-serves\n * instead, inlining dev styles through a virtual module and composing the\n * server-function endpoint. Its named `handleRequest(request)` and default\n * Fetchable exports provide the same contract in dev and production.\n * Generated entries and the client manifest are still provided.\n *\n * Often unnecessary: a provider-owned (non-runnable) `ssr` dev environment\n * is detected automatically and the middlewares stand down on their own;\n * the normal `ssr` environment also exposes the handler as an `index`\n * service entry for provider build orchestrators. Set this only when the\n * host does not adopt that environment — for example, when it uses a\n * different name or independently configures the server build. To hand\n * over only the server-function endpoint, use\n * `serverFunctions.devMiddleware: false` instead.\n *\n * Server mode only — ignored in client mode (there is no server side to\n * hand over; the shell prerender and, with `serverFunctions`, the\n * endpoint handler are the whole story).\n *\n * @default false\n */\n external?: boolean;\n}\n\n// Server-only start-mode request handler; also the server bundle's entry so a\n// production server is one import away from `Request -> Response`. Exported\n// for the main plugin to thread into the server-function dev middleware,\n// which dispatches through it when SSR start mode is active (one middleware\n// chain and one request event across both dispatch paths).\nexport const SSR_HANDLER_ID = 'virtual:solid-ssr-handler';\nconst HANDLER_ID = SSR_HANDLER_ID;\n// Dev-only response marker: the generated dev handler answers non-page\n// requests that fell through the whole middleware chain to the terminal\n// page dispatch with a marked 404 instead of rendering HTML at them, and\n// the dev middleware hands those back to Vite's pipeline. Production has no\n// such seam — every unhandled request renders — but production also has no\n// Vite pipeline to fall back to.\nconst DEV_FALLTHROUGH_HEADER = 'x-solid-dev-fallthrough';\n// Private protocol between the two generated modules when `start.setup` is\n// async: the entry hands the handler the renderToStream result under this\n// key, because a promise resolving to the stream BARE would adopt the\n// stream's thenable (which waits for the complete render) and buffer it.\nconst STREAM_BOX = '__solidSetupStream';\nconst DEV_STYLES_ID = 'virtual:solid-ssr-dev-styles';\nconst RESOLVED_DEV_STYLES_ID = '\\0' + DEV_STYLES_ID;\n// Generated default entries / document shell. The `.tsx` suffix routes them\n// through the plugin's normal JSX transform (per-environment SSR/DOM\n// compile), exactly like user-authored entry files.\nconst ENTRY_SERVER_ID = 'virtual:solid-ssr-entry-server.tsx';\nconst ENTRY_CLIENT_ID = 'virtual:solid-ssr-entry-client.tsx';\nconst DOCUMENT_ID = 'virtual:solid-ssr-document.tsx';\nconst ERROR_BOUNDARY_ID = 'virtual:solid-ssr-error-boundary.tsx';\n\nconst MANIFEST_ID = 'virtual:solid-manifest';\nconst SERVER_FUNCTION_HANDLER_ID = 'virtual:solid-server-function-handler';\nconst STORAGE_SOURCE = '@solidjs/web/storage';\n\nconst ENTRY_EXTENSIONS = ['.tsx', '.jsx', '.ts', '.js', '.mjs'];\nconst APP_EXTENSIONS = ['.tsx', '.jsx', '.ts', '.js'];\nconst DOCUMENT_EXTENSIONS = ['.tsx', '.jsx'];\n\nfunction probe(root: string, stem: string, extensions: string[]): string | null {\n for (const ext of extensions) {\n if (existsSync(path.resolve(root, stem + ext))) return stem + ext;\n }\n return null;\n}\n\n/** Normalizes a user-supplied module path to a root-relative one (no leading slash). */\nfunction normalizeUserPath(root: string, spec: string, option: string): string {\n const absolute = path.isAbsolute(spec) ? spec : path.resolve(root, spec);\n if (!existsSync(absolute)) {\n throw new Error(`[@solidjs/vite-plugin] start.${option} does not exist: ${spec}`);\n }\n const relative = path.relative(root, absolute).split(path.sep).join('/');\n if (relative.startsWith('..')) {\n throw new Error(`[@solidjs/vite-plugin] start.${option} must live inside the Vite root: ${spec}`);\n }\n return relative;\n}\n\ninterface ResolvedEntries {\n /** Root-relative path or virtual id. */\n entryServer: string;\n /** Root-relative path or virtual id. */\n entryClient: string;\n /** Whether the entries are generated virtual modules. */\n generated: boolean;\n /** Absolute path of the app root component (generated entries only). */\n app: string | null;\n /** Absolute path of the document shell, or the built-in virtual id. */\n document: string | null;\n}\n\nfunction resolveEntries(root: string, options: StartOptions, clientMode: boolean): ResolvedEntries {\n const explicitClient = options.entryClient\n ? normalizeUserPath(root, options.entryClient, 'entryClient')\n : null;\n\n if (clientMode) {\n // Client mode: the server entry is always generated (it renders the\n // document shell only — no App — for dev serving and the build-time\n // prerender); `start.entryServer` and conventional src/entry-server.*\n // files are documented no-ops here, so a project flipping the `ssr`\n // boolean never has to touch them. No entry pairing rule either: an\n // authored client entry stands alone. The document resolves in every\n // case because it IS the page in this mode.\n const document = options.document\n ? normalizeUserPath(root, options.document, 'document')\n : probe(root, 'src/Document', DOCUMENT_EXTENSIONS);\n const entryClient = explicitClient ?? probe(root, 'src/entry-client', ENTRY_EXTENSIONS);\n if (entryClient) {\n return {\n entryServer: ENTRY_SERVER_ID,\n entryClient,\n generated: false,\n app: null,\n document: document ? path.resolve(root, document) : null,\n };\n }\n const app = options.app\n ? normalizeUserPath(root, options.app, 'app')\n : (probe(root, 'src/App', APP_EXTENSIONS) ?? probe(root, 'src/app', APP_EXTENSIONS));\n if (!app) {\n throw new Error(\n `[@solidjs/vite-plugin] the \\`start\\` option needs an app root: add src/App.tsx ` +\n `(or set start.app), or provide a src/entry-client.* entry.`,\n );\n }\n return {\n entryServer: ENTRY_SERVER_ID,\n entryClient: ENTRY_CLIENT_ID,\n generated: true,\n app: path.resolve(root, app),\n document: document ? path.resolve(root, document) : null,\n };\n }\n\n const explicitServer = options.entryServer\n ? normalizeUserPath(root, options.entryServer, 'entryServer')\n : null;\n const entryServer = explicitServer ?? probe(root, 'src/entry-server', ENTRY_EXTENSIONS);\n const entryClient = explicitClient ?? probe(root, 'src/entry-client', ENTRY_EXTENSIONS);\n\n if (entryServer && entryClient) {\n return { entryServer, entryClient, generated: false, app: null, document: null };\n }\n if (entryServer || entryClient) {\n // One authored entry with a generated counterpart is a hydration\n // mismatch waiting to happen — the generated side wraps the app in the\n // document shell, which the authored side knows nothing about.\n const found = entryServer ? 'entry-server' : 'entry-client';\n const missing = entryServer ? 'entry-client' : 'entry-server';\n throw new Error(\n `[@solidjs/vite-plugin] found ${found} but no ${missing}; entry files come in pairs. ` +\n `Provide both (src/entry-server.* and src/entry-client.*, or the start.entryServer / ` +\n `start.entryClient options) or neither (to generate both from start.app).`,\n );\n }\n\n const app = options.app\n ? normalizeUserPath(root, options.app, 'app')\n : (probe(root, 'src/App', APP_EXTENSIONS) ?? probe(root, 'src/app', APP_EXTENSIONS));\n if (!app) {\n throw new Error(\n `[@solidjs/vite-plugin] the \\`start\\` option needs an app root: add src/App.tsx ` +\n `(or set start.app), or provide src/entry-server.* and src/entry-client.* entries.`,\n );\n }\n const document = options.document\n ? normalizeUserPath(root, options.document, 'document')\n : probe(root, 'src/Document', DOCUMENT_EXTENSIONS);\n\n return {\n entryServer: ENTRY_SERVER_ID,\n entryClient: ENTRY_CLIENT_ID,\n generated: true,\n app: path.resolve(root, app),\n document: document ? path.resolve(root, document) : null,\n };\n}\n\nexport function startServe(\n options: StartOptions,\n internal: {\n serverFunctions?: boolean;\n serverComponents?: boolean;\n ssr?: boolean;\n styleFilter?: DevStyleFilter;\n diagnostics?: boolean;\n } = {},\n): Plugin[] {\n // Client mode (the `start` option without `ssr: true`) rides this exact\n // plugin with three deltas: the generated server entry renders the\n // document shell WITHOUT the app (dev serving doubles as history\n // fallback, and a post-build hook prerenders it once into\n // dist/client/index.html), the generated client entry render()s instead\n // of hydrating, and dist/server is dropped from the output unless\n // `serverFunctions` needs it for the endpoint. Everything else — entry\n // probing, the handler, middleware, dev styles, the manifest — is shared,\n // which is what makes flipping a project between the modes a one-boolean\n // config change.\n const clientMode = !internal.ssr;\n // Server components (`serverFunctions: { components: true }`): generated\n // entries additionally emit the document-SSR wiring — the render plugin +\n // direct-call transform server-side, the bootstrap script in <head>, and\n // the client-side installServerComponents() call. Authored entries carry\n // those pieces themselves (the endpoint response transform is installed by\n // the server-function handler module either way). Everything is gated\n // codegen: with the option off, none of these imports exist anywhere.\n const serverComponents = !!internal.serverComponents;\n const errorBoundary = options.errorBoundary !== false;\n const styleFilter = internal.styleFilter;\n const diagnostics = !!internal.diagnostics;\n let devtoolsEnabled = false;\n let devtoolsResolutions: Partial<\n Record<'client' | 'server', Promise<string | null>>\n > = {};\n let devtoolsIds: Partial<Record<'client' | 'server', string | null>> = {};\n // `external` is server-mode-only (documented no-op in client mode, so a\n // host-integrated config survives the `ssr` boolean flip untouched).\n const externalServer = !clientMode && !!options.external;\n let root = process.cwd();\n let base = '/';\n let isBuild = false;\n let entries: ResolvedEntries | undefined;\n /** Absolute path of the user's middleware module, when configured. */\n let middlewarePath: string | null = null;\n /** Absolute path of the per-request setup module, when configured (server mode). */\n let setupPath: string | null = null;\n\n function requireEntries(): ResolvedEntries {\n // config() always runs before resolveId/load/configureServer.\n if (!entries) throw new Error('[@solidjs/vite-plugin] SSR entries not resolved yet');\n return entries;\n }\n\n async function resolveDevtools(\n resolve: (source: string, importer: string) => Promise<{ id: string } | null>,\n importer: string,\n consumer: 'client' | 'server',\n ): Promise<boolean> {\n if (!devtoolsEnabled) return false;\n // Detect from the app graph first (the documented install location), then\n // from the plugin's own file: in pnpm-isolated apps a copy that is only a\n // dependency of the plugin is not reachable from the app's importers. The\n // resolved id is kept so imports from generated modules can use it.\n devtoolsResolutions[consumer] ??= (async () => {\n // Resolving from the plugin's own file never yields null when the\n // package is absent: it is declared an optional peer dependency, so\n // Vite answers with its `__vite-optional-peer-dep:` stub (an empty\n // module). Treat that stub as \"not installed\".\n const realId = (resolved: { id: string } | null) =>\n resolved && !resolved.id.startsWith('__vite-optional-peer-dep:') ? resolved.id : null;\n return (\n realId(await resolve(DEVTOOLS_PACKAGE, importer)) ??\n realId(await resolve(DEVTOOLS_PACKAGE, fileURLToPath(import.meta.url)))\n );\n })();\n const id = await devtoolsResolutions[consumer];\n devtoolsIds[consumer] = id;\n if (!id && options.devtools === true) {\n throw new Error(\n '[@solidjs/vite-plugin] start.devtools requires @solidjs/start-devtools. ' +\n 'Install it as a development dependency or set start.devtools to false.',\n );\n }\n return id !== null;\n }\n\n /**\n * Cheap walk-up probe mirroring how the optimizer resolves bare\n * `optimizeDeps.include` entries: is @solidjs/start-devtools reachable from\n * this directory? Detection proper (resolveDevtools) runs later with a real\n * importer; this only decides whether the toolbar graph can be pre-bundled\n * at scan time.\n */\n function devtoolsReachableFrom(dir: string): boolean {\n for (let current = dir; ; ) {\n if (existsSync(path.join(current, 'node_modules', DEVTOOLS_PACKAGE, 'package.json'))) {\n return true;\n }\n const parent = path.dirname(current);\n if (parent === current) return false;\n current = parent;\n }\n }\n\n /**\n * The `optimizeDeps.include` spec that pre-bundles the toolbar graph, or\n * null when it cannot be resolved at all. Pre-bundling it is not just a\n * warm-start nicety: the toolbar hangs off virtual modules the scanner\n * never crawls, so without an include the optimizer only discovers it on\n * first request. That re-optimize can pair chunks from different passes\n * whose shared minified exports disagree, taking down the whole client\n * entry graph. The spec must therefore cover every install shape\n * resolveDevtools accepts: bare when the app installs the package, and\n * Vite's nested-include form (`plugin > dep`) when it is only a dependency\n * of this plugin (pnpm-isolated installs).\n */\n function devtoolsIncludeSpec(rootDir: string): string | null {\n if (devtoolsReachableFrom(rootDir)) return DEVTOOLS_PACKAGE;\n if (devtoolsReachableFrom(path.dirname(fileURLToPath(import.meta.url)))) {\n return `@solidjs/vite-plugin > ${DEVTOOLS_PACKAGE}`;\n }\n return null;\n }\n\n /** Import specifier for generated code: absolute for files, id for virtuals. */\n function entryServerSpec(): string {\n const { entryServer } = requireEntries();\n return entryServer === ENTRY_SERVER_ID ? entryServer : path.resolve(root, entryServer);\n }\n\n /** Browser URL of the client entry on the dev server (base applied). */\n function devClientEntryUrl(): string {\n const { entryClient } = requireEntries();\n return entryClient === ENTRY_CLIENT_ID\n ? joinBase(base, '/@id/' + ENTRY_CLIENT_ID)\n : joinBase(base, '/' + entryClient);\n }\n\n function documentSpec(): string {\n const { document } = requireEntries();\n return document ?? DOCUMENT_ID;\n }\n\n function styleRoots(): string[] {\n const { generated, app, document, entryServer, entryClient } = requireEntries();\n if (clientMode) {\n // The app graph's CSS is inlined into the dev shell too (not just the\n // document's): the client injects it again when the modules load and\n // the dev style patch dedupes, so this is pure anti-flash.\n return [\n generated ? app! : path.resolve(root, entryClient),\n ...(document ? [document] : []),\n ];\n }\n return generated ? [app!, ...(document ? [document] : [])] : [path.resolve(root, entryServer)];\n }\n\n async function devStylesModuleCode(\n environment: DevEnvironment,\n watchFile: (file: string) => void,\n ): Promise<string> {\n const styles = await collectDevStyleSources(\n environment,\n styleRoots(),\n watchFile,\n styleFilter,\n );\n if (!styles.length) return `export default '';`;\n\n const imports = styles.map((style, index) => {\n const specifier = style.url.includes('?') ? `${style.url}&inline` : `${style.url}?inline`;\n return `import css${index} from ${JSON.stringify(specifier)};`;\n });\n return [\n ...imports,\n `const ids = ${JSON.stringify(styles.map((style) => style.id))};`,\n `const css = [${styles.map((_, index) => `css${index}`).join(', ')}];`,\n `const escapeAttr = value => value.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<');`,\n `export default css.map((content, index) => {`,\n ` const id = escapeAttr(ids[index]);`,\n ` return '<style data-asset=\"' + id + '\" data-vite-dev-id=\"' + id + '\">' +`,\n ` content.replace(/<\\\\/(style)/gi, '<\\\\\\\\/$1') + '</style>';`,\n `}).join('');`,\n ].join('\\n');\n }\n\n function errorBoundaryImport(): string[] {\n return isBuild && errorBoundary\n ? [`import { DefaultErrorBoundary } from ${JSON.stringify(ERROR_BOUNDARY_ID)};`]\n : [];\n }\n\n function documentTree(root: string, wrapper?: string): string[] {\n const content = wrapper ? `<${wrapper}><${root} /></${wrapper}>` : `<${root} />`;\n return isBuild && errorBoundary\n ? [\n ` <DefaultErrorBoundary>`,\n ` <Document>`,\n ` <DefaultErrorBoundary>`,\n ` ${content}`,\n ` </DefaultErrorBoundary>`,\n ` </Document>`,\n ` </DefaultErrorBoundary>`,\n ]\n : [` <Document>`, ` ${content}`, ` </Document>`];\n }\n\n function generatedEntryServerCode(toolbar: boolean): string {\n if (clientMode) {\n // The client-mode shell: the document without the app. Rendered per\n // request in dev (any HTML GET gets it — history-fallback semantics)\n // and once at build time into dist/client/index.html. The client\n // entry script is injected by the handler, exactly like SSR mode.\n return [\n `import { renderToStream } from '@solidjs/web';`,\n `import manifest from ${JSON.stringify(MANIFEST_ID)};`,\n `import Document from ${JSON.stringify(documentSpec())};`,\n ...errorBoundaryImport(),\n ``,\n `export function render(request, context) {`,\n ` return renderToStream(() => (`,\n ...(isBuild && errorBoundary\n ? [\n ` <DefaultErrorBoundary>`,\n ` <Document />`,\n ` </DefaultErrorBoundary>`,\n ]\n : [` <Document />`]),\n ` ), { manifest });`,\n `}`,\n ].join('\\n');\n }\n const { app } = requireEntries();\n const streamOptions = `{ manifest${serverComponents ? ', plugins: [ServerComponentPlugin]' : ''} }`;\n return [\n `import { renderToStream${setupPath ? ', getRequestEvent' : ''} } from '@solidjs/web';`,\n ...(serverComponents\n ? [\n `import { configureServerFunctionsServer } from '@solidjs/web/server-functions';`,\n `import { frameTransformDirectResult, ServerComponentPlugin } from '@solidjs/web/frames';`,\n ]\n : []),\n `import manifest from ${JSON.stringify(MANIFEST_ID)};`,\n `import Document from ${JSON.stringify(documentSpec())};`,\n `import App from ${JSON.stringify(app)};`,\n ...(toolbar ? [`import { DevToolbar } from ${JSON.stringify(DEVTOOLS_PACKAGE)};`] : []),\n ...errorBoundaryImport(),\n ...(setupPath ? [`import setup from ${JSON.stringify(setupPath)};`] : []),\n ``,\n ...(setupPath\n ? [\n `if (typeof setup !== 'function') {`,\n ` throw new Error('[@solidjs/vite-plugin] start.setup must default-export a function ' +`,\n ` '((event, App) => Component | void | Promise<...>): ' + ${JSON.stringify(options.setup)});`,\n `}`,\n ``,\n ]\n : []),\n ...(serverComponents\n ? [\n // Direct (in-process) server-function calls made during document\n // SSR must resolve to inline-renderable components; the endpoint\n // response transform is installed separately by the\n // server-function handler module (configure calls merge per key).\n `configureServerFunctionsServer({ transformDirectResult: frameTransformDirectResult });`,\n ``,\n ]\n : []),\n ...(setupPath\n ? [\n // The per-request seam: the hook sees the same event the\n // middleware chain decorated and finishes before renderToStream\n // starts. When it is async, the stream must NOT cross the\n // promise boundary bare — a promise resolving to a\n // renderToStream result adopts its thenable (which waits for\n // the *complete* render) and buffers the stream — so it crosses\n // boxed under a private key the generated handler unboxes\n // (both modules are ours).\n `export function render(request, context) {`,\n ` const prepared = setup(getRequestEvent(), App);`,\n ` if (prepared && typeof prepared.then === 'function') {`,\n ` return prepared.then((component) => ({ ${STREAM_BOX}: renderApp(component || App) }));`,\n ` }`,\n ` return renderApp(prepared || App);`,\n `}`,\n ``,\n `function renderApp(Root) {`,\n ` return renderToStream(() => (`,\n ...documentTree('Root', toolbar ? 'DevToolbar' : undefined),\n ` ), ${streamOptions});`,\n `}`,\n ]\n : [\n `export function render(request, context) {`,\n ` return renderToStream(() => (`,\n ...documentTree('App', toolbar ? 'DevToolbar' : undefined),\n ` ), ${streamOptions});`,\n `}`,\n ]),\n ].join('\\n');\n }\n\n function generatedEntryClientCode(toolbar: boolean): string {\n const { app } = requireEntries();\n // Dev-only: the diagnostics bridge fronts dev-mode channels, so builds\n // never see this import (mirrors the plugin's own serve-only `apply`).\n const diagnosticsImport =\n diagnostics && !isBuild ? [`import ${JSON.stringify(DIAGNOSTICS_CLIENT_ID)};`] : [];\n if (clientMode) {\n // render(), not hydrate(): the shell's body is empty, the app mounts\n // fresh. Client code compiles non-hydratable in client mode, so the\n // app cannot claim server DOM anyway. The entry script is injected\n // without `async` (plain module = deferred), so document.body is\n // complete when this runs.\n return [\n ...diagnosticsImport,\n `import { render } from '@solidjs/web';`,\n ...errorBoundaryImport(),\n ...(toolbar ? [`import { DevToolbar } from ${JSON.stringify(DEVTOOLS_PACKAGE)};`] : []),\n `import App from ${JSON.stringify(app)};`,\n ``,\n `render(() => ${\n isBuild && errorBoundary\n ? '<DefaultErrorBoundary><App /></DefaultErrorBoundary>'\n : toolbar\n ? '<DevToolbar><App /></DevToolbar>'\n : '<App />'\n }, document.body);`,\n ].join('\\n');\n }\n return [\n ...diagnosticsImport,\n `import { hydrate } from '@solidjs/web';`,\n ...(toolbar ? [`import { DevToolbar } from ${JSON.stringify(DEVTOOLS_PACKAGE)};`] : []),\n ...(serverComponents\n ? [`import { installServerComponents } from '@solidjs/web/frames';`]\n : []),\n ...errorBoundaryImport(),\n `import Document from ${JSON.stringify(documentSpec())};`,\n `import App from ${JSON.stringify(app)};`,\n ``,\n ...(serverComponents\n ? [\n // Installs the t=0 document-adoption registry and the transport\n // policy (component responses morph their boundary instead of\n // decoding as data). Must run before hydrate().\n `installServerComponents();`,\n ``,\n ]\n : []),\n `hydrate(() => (`,\n ...documentTree('App', toolbar ? 'DevToolbar' : undefined),\n `), document);`,\n ].join('\\n');\n }\n\n // Built-in document shell: minimal, hydration-ready. The client entry\n // script is injected into <head> by the handler (not rendered here) so its\n // URL never has to survive hydration or a manifest lookup client-side.\n // The client-mode variant drops <HydrationScript /> — nothing hydrates,\n // so the shell stays inert HTML. (A user-authored Document carrying\n // HydrationScript is covered too: the handler strips the event-capture\n // script from the client-mode shell.)\n const documentShellCode = [\n ...(clientMode ? [] : [`import { HydrationScript } from '@solidjs/web';`, ``]),\n `export default function Document(props) {`,\n ` return (`,\n ` <html lang=\"en\">`,\n ` <head>`,\n ` <meta charset=\"utf-8\" />`,\n ` <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />`,\n ...(clientMode ? [] : [` <HydrationScript />`]),\n ` </head>`,\n ` <body>{props.children}</body>`,\n ` </html>`,\n ` );`,\n `}`,\n ].join('\\n');\n\n const errorBoundaryCode = [\n `import { Errored } from 'solid-js';`,\n `import { httpStatus, isServer } from '@solidjs/web';`,\n ``,\n `function ErrorFallback(props) {`,\n ` console.error(props.error());`,\n ` httpStatus(500);`,\n ` return (`,\n ` <span style=\"font-size:1.5em;text-align:center;position:fixed;left:0;bottom:55%;width:100%\">`,\n ` {isServer ? '500 | Internal Server Error' : 'Error | Uncaught Client Exception'}`,\n ` </span>`,\n ` );`,\n `}`,\n ``,\n `export function DefaultErrorBoundary(props) {`,\n ` return (`,\n ` <Errored fallback={(error) => <ErrorFallback error={error} />}>`,\n ` {props.children}`,\n ` </Errored>`,\n ` );`,\n `}`,\n ].join('\\n');\n\n // The handler module: dev and prod share the render/response plumbing;\n // they differ in how the client entry URL is known (baked dev URL vs a\n // manifest scan) and what gets injected into <head> (Vite client + style\n // patch in dev). The response-head lifecycle is the runtime's\n // (`createRequestEvent`/`createSSRResponse`/`commitEventResponse` from\n // @solidjs/web): every request runs under a stub-backed event,\n // `httpStatus`/`httpHeader` writes land on the wire at shell flush, a\n // pre-flush redirect becomes a real 3xx and a post-flush one the script\n // fallback, and a Response that skipped the render lifecycle (middleware\n // early return, raw entry.render Response, server functions) has the\n // stub folded on at the handler edge after the middleware chain fully\n // unwinds. When\n // `serverFunctions` is enabled the endpoint is dispatched here on every\n // surface (the runnable-dev middleware routes through this module), so\n // user middleware and the shared request event front it identically.\n function handlerModuleCode(externalDev: boolean): string {\n const { generated, entryClient } = requireEntries();\n const composeServerFunctions = internal.serverFunctions;\n\n const lines = [\n `import { createRequestEvent, createSSRResponse, commitEventResponse${middlewarePath ? ', composeMiddleware' : ''} } from '@solidjs/web';`,\n `import { provideRequestEvent } from ${JSON.stringify(STORAGE_SOURCE)};`,\n `import * as entry from ${JSON.stringify(entryServerSpec())};`,\n ...(middlewarePath\n ? [`import middlewareModule from ${JSON.stringify(middlewarePath)};`]\n : []),\n ...(externalDev ? [`import DEV_STYLES_HEAD from ${JSON.stringify(DEV_STYLES_ID)};`] : []),\n ...(composeServerFunctions\n ? [\n `import { handleServerFunctionRequest, endpoint } from ${JSON.stringify(SERVER_FUNCTION_HANDLER_ID)};`,\n ]\n : []),\n ];\n\n if (isBuild) {\n lines.push(`import manifest from ${JSON.stringify(MANIFEST_ID)};`);\n lines.push(\n ``,\n `function joinAssetPath(base, file) {`,\n ` if (typeof base !== 'string' || !base) base = '/';`,\n ` if (base[base.length - 1] !== '/') base += '/';`,\n ` return base + (file[0] === '/' ? file.slice(1) : file);`,\n `}`,\n ``,\n `let clientEntryUrl;`,\n `function resolveClientEntry() {`,\n ` if (clientEntryUrl !== undefined) return clientEntryUrl;`,\n ` clientEntryUrl = null;`,\n // The plugin's manifest module normalizes lazy facade chunks\n // (isDynamicEntry) so exactly one real entry remains flagged.\n ` for (const key in manifest) {`,\n ` const chunk = manifest[key];`,\n ` if (chunk && chunk.isEntry && chunk.file) {`,\n ` clientEntryUrl = joinAssetPath(manifest._base, chunk.file);`,\n ` break;`,\n ` }`,\n ` }`,\n ` return clientEntryUrl;`,\n `}`,\n );\n } else {\n const devHead =\n `<script>${devStylePatch}</script>` +\n `<script type=\"module\" src=\"${joinBase(base, '/@vite/client')}\"></script>`;\n lines.push(``, `const DEV_HEAD = ${JSON.stringify(devHead)};`);\n }\n\n // Middleware: the user module default-exports one fetch-style function\n // or an array, composed in order. Without one, the chain degenerates to\n // the terminal dispatch.\n lines.push(``);\n if (middlewarePath) {\n lines.push(\n `const middlewares = Array.isArray(middlewareModule) ? middlewareModule : [middlewareModule];`,\n `for (const mw of middlewares) {`,\n ` if (typeof mw !== 'function') {`,\n ` throw new Error('[@solidjs/vite-plugin] start.middleware must default-export a function or an array of functions: ' + ${JSON.stringify(middlewarePath)});`,\n ` }`,\n `}`,\n `const runMiddleware = composeMiddleware(middlewares);`,\n );\n } else {\n lines.push(`const runMiddleware = (request, next) => next(request);`);\n }\n\n // No `_$SC` bootstrap injection: the runtime's serialized\n // server-component references self-bootstrap the registry (each\n // hydration script's first reference carries it as an idempotent\n // expression), so nothing needs to precede the data scripts. The old\n // head-open splice actively broke hydration — a script ahead of the\n // authored <head> elements claims as the first walked child and drifts\n // every positional claim after it.\n lines.push(\n ``,\n `function escapeAttribute(value) {`,\n ` return value.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<');`,\n `}`,\n ``,\n `function createHtmlChunkTransform(clientEntry, extraHead, nonce) {`,\n ` const nonceAttr = nonce ? ' nonce=\"' + escapeAttribute(nonce) + '\"' : '';`,\n ` let first = true;`,\n ` let injected = false;`,\n ` return (chunk) => {`,\n );\n if (!generated) {\n // Authored entries reference the client entry by its dev path (the\n // `<script src=\"/src/entry-client.tsx\">` convention); rewrite it to\n // the resolved URL like the classic server harnesses do.\n lines.push(\n ` if (clientEntry && chunk.includes(${JSON.stringify('/' + entryClient)})) {`,\n ` chunk = chunk.split(${JSON.stringify('/' + entryClient)}).join(clientEntry);`,\n ` }`,\n );\n }\n lines.push(` if (!injected && chunk.includes('</head>')) {`, ` injected = true;`);\n if (clientMode) {\n // Nothing hydrates in client mode, so the event-capture bootstrap\n // `<HydrationScript />` renders (`window._$HY||...`) is dead weight —\n // but a Document shared with SSR mode carries it by design (the flip\n // story). Strip it from the shell here instead of making users fork\n // their Document per mode. (`<!--xs-->` is the script's stream\n // marker; the shell head always arrives in one chunk.)\n lines.push(\n ` chunk = chunk.replace(/<script(?:\\\\s[^>]*)?>window\\\\._\\\\$HY\\\\|\\\\|[\\\\s\\\\S]*?<\\\\/script>(?:<!--xs-->)?/, '');`,\n );\n }\n const headParts: string[] = [];\n // Dev: the style patch + Vite client, then either middleware-provided\n // styles or the external environment's HMR-tracked virtual styles module.\n if (!isBuild) {\n headParts.push(\n `DEV_HEAD`,\n externalDev\n ? `(extraHead === undefined ? DEV_STYLES_HEAD : extraHead)`\n : `(extraHead || '')`,\n );\n }\n if (generated || clientMode) {\n // Client-mode note: the shell never references its client entry\n // itself (even an authored one — the Document knows nothing about\n // entries), so the handler always injects it. Without `async`: module\n // scripts default to deferred execution, which is exactly right for a\n // fresh render-into-body mount (hydration, by contrast, wants to\n // start as early as possible).\n headParts.push(\n `(clientEntry ? '<script type=\"module\"' + nonceAttr + ' src=\"' + clientEntry + '\"${clientMode ? '' : ' async'}></' + 'script>' : '')`,\n );\n }\n if (headParts.length) {\n lines.push(` chunk = chunk.replace('</head>', ${headParts.join(' + ')} + '</head>');`);\n }\n lines.push(\n ` }`,\n ` if (first) { first = false; chunk = '<!DOCTYPE html>' + chunk; }`,\n ` return chunk;`,\n ` };`,\n `}`,\n );\n\n // The handler-edge commit fold — the runtime's `commitEventResponse`\n // (named import above), the second of the response lifecycle's two\n // exits: page results leave through `createSSRResponse`, any other\n // Response (a middleware early return, a raw Response from\n // entry.render, a server-function response) leaves through\n // `commitEventResponse`, which folds the event's response stub onto it\n // (cookies append entry-by-entry, other headers gap-fill, status stays\n // the response's own) and commits the stub. Committed stubs pass\n // through untouched, so the edge applies it unconditionally.\n lines.push(``, `async function dispatchRequest(request, event, options) {`);\n if (composeServerFunctions) {\n lines.push(\n // A call's address is `<endpoint>/<id>` (solidjs/solid#3076); the\n // bare mount still routes so a misaddressed request 404s through the\n // runtime handler instead of rendering a page at it.\n ` const requestPath = new URL(request.url).pathname;`,\n ` if (requestPath === endpoint || requestPath.startsWith(endpoint + '/')) {`,\n // The call shares the middleware chain's event (locals decoration,\n // the response stub); an explicit host-provided createEvent wins.\n // No fold here: the runtime's server-function handler runs the\n // commit seam itself, and anything it left uncommitted is caught by\n // the unconditional edge fold in handleRequest.\n ` return handleServerFunctionRequest(request, {`,\n ` createEvent: () => event,`,\n ` ...options.serverFunctions,`,\n ` });`,\n ` }`,\n );\n }\n if (!isBuild) {\n // Dev terminal gate: the dev middleware dispatches every request the\n // middleware chain might handle (API routes, no-JS form POSTs — all\n // methods and accept types, matching production), passing\n // `pageRequest: false` for the non-page ones. When such a request\n // falls through the whole chain to this terminal dispatch, nothing\n // owns it — answer with the marked 404 so the dev middleware hands\n // it back to Vite's pipeline instead of rendering HTML at it. The\n // gate reflects the wire request: only the dev middleware sets the\n // flag, so external-host dispatch and preview stay render-always.\n lines.push(\n ` if (options.pageRequest === false) {`,\n ` return new Response(null, { status: 404, headers: { ${JSON.stringify(DEV_FALLTHROUGH_HEADER)}: '1' } });`,\n ` }`,\n );\n }\n lines.push(\n isBuild\n ? ` const clientEntry = options.clientEntry || resolveClientEntry();`\n : ` const clientEntry = options.clientEntry || ${JSON.stringify(devClientEntryUrl())};`,\n ` let result = entry.render(request, { clientEntry, ...options.context });`,\n // renderToStream results are thenables whose then() waits for the\n // *complete* render — check for pipe first so streaming survives, and\n // only await plain promises (async render functions).\n ` if (result && typeof result.pipe !== 'function' && typeof result.then === 'function') {`,\n ` result = await result;`,\n ` }`,\n ...(setupPath\n ? [\n // start.setup's async path boxes the stream (see the generated\n // entry): a bare promise resolution would adopt the stream's\n // thenable and buffer the whole render.\n ` if (result && result.${STREAM_BOX}) result = result.${STREAM_BOX};`,\n ]\n : []),\n // Raw Responses fold at the handler edge (handleRequest), after the\n // middleware chain unwinds — not here, where middleware above this\n // frame could still legitimately mutate headers.\n ` if (result instanceof Response) return result;`,\n // The runtime's response-head lifecycle: commit at shell flush,\n // pre-flush Location as a real redirect, post-flush Location as the\n // script fallback; the transform injects the doctype/head pieces.\n ` return createSSRResponse(result, event, {`,\n ` responseInit: options.responseInit,`,\n ` nonce: options.nonce,`,\n ` transformChunk: createHtmlChunkTransform(clientEntry, options.devHead, options.nonce),`,\n ` });`,\n `}`,\n ``,\n `export async function handleRequest(request, options = {}) {`,\n // `options.event` is the public wrapper->event extension seam: extra\n // fields (conventionally `nativeEvent`, the platform's raw request\n // object) spread over the event's defaults at creation, so hosts and\n // custom server entries can extend what getRequestEvent() answers\n // with — no new convention beyond createRequestEvent's own init\n // parameter (spreading undefined is a no-op).\n ` const event = createRequestEvent(request, options.event);`,\n // Middleware runs inside the request scope, after event creation —\n // getRequestEvent() answers in middleware exactly as in app code, and\n // nothing reaches the wire until the outermost middleware returns.\n ` const response = await provideRequestEvent(event, () =>`,\n ` runMiddleware(request, (req) => dispatchRequest(req || request, event, options)),`,\n ` );`,\n // The fold runs strictly AFTER the outermost middleware returned:\n // headers stay mutable through the whole unwind, and a middleware\n // early return (an API handler that never called next()) gets its\n // stub writes — cookies set inside the request scope, status — onto\n // the wire. Unconditional: page responses come back from\n // createSSRResponse committed and pass through untouched.\n ` return commitEventResponse(response, event);`,\n `}`,\n ``,\n `export default {`,\n ` fetch(request) {`,\n // Hosts may pass environment/context arguments after the request.\n // Do not alias fetch directly to handleRequest: its second argument is\n // the Solid handler options bag, not a provider binding object.\n ` return handleRequest(request);`,\n ` },`,\n `};`,\n );\n\n return lines.join('\\n');\n }\n\n return [\n {\n name: 'solid:ssr/setup',\n enforce: 'pre',\n config(userConfig, env) {\n root = path.resolve(userConfig.root || process.cwd());\n devtoolsEnabled =\n env.command === 'serve' && !env.isPreview && options.devtools !== false;\n devtoolsResolutions = {};\n devtoolsIds = {};\n entries = resolveEntries(root, options, clientMode);\n middlewarePath = options.middleware\n ? path.resolve(root, normalizeUserPath(root, options.middleware, 'middleware'))\n : null;\n // Server-mode only, like `entryServer`/`external` (a documented\n // no-op in client mode so configs survive the `ssr` boolean flip).\n setupPath =\n !clientMode && options.setup\n ? path.resolve(root, normalizeUserPath(root, options.setup, 'setup'))\n : null;\n if (setupPath && !entries.generated) {\n // An authored entry-server owns its render function — the seam the\n // hook needs does not exist there.\n throw new Error(\n '[@solidjs/vite-plugin] start.setup only applies to generated entries: your ' +\n 'entry-server owns render() already, so call your setup step there instead ' +\n `(remove start.setup or the authored entry): ${options.setup}`,\n );\n }\n if (env.isPreview) {\n if (clientMode) {\n // Client-mode builds emit a real dist/client/index.html (the\n // prerendered shell), so preview is Vite's stock static +\n // history-fallback story. When server functions are on, the\n // endpoint dispatches through the kept dist/server handler\n // (configurePreviewServer).\n return { appType: 'spa', build: { outDir: 'dist/client' } };\n }\n // `vite preview` serves `build.outDir` statically; point it at the\n // client bundle so hashed assets resolve, while HTML (and\n // everything else unhandled) falls through to the\n // configurePreviewServer dispatch below. No index.html exists, so\n // `custom` keeps preview from attempting an SPA fallback.\n return {\n appType: 'custom',\n ...(externalServer ? {} : { build: { outDir: 'dist/client' } }),\n };\n }\n const build = env.command === 'build';\n const clientInput = entries.generated\n ? ENTRY_CLIENT_ID\n : path.resolve(root, entries.entryClient);\n // Real files only — the dep scanner can't crawl virtual modules.\n // (In client mode the resolved document joins the scan/style roots\n // even with an authored client entry; in SSR mode authored entries\n // own the whole graph.)\n const scanEntries = entries.generated\n ? [entries.app!, ...(entries.document ? [entries.document] : [])]\n : [\n path.resolve(root, entries.entryClient),\n ...(clientMode && entries.document ? [entries.document] : []),\n ];\n return {\n // No index.html: dev must not fall back to SPA-serving one, and\n // the dep scanner needs explicit entries instead.\n appType: 'custom',\n ...(build\n ? externalServer\n ? {\n environments: {\n client: {\n build: {\n manifest: true,\n rollupOptions: { input: clientInput },\n },\n },\n },\n }\n : {\n environments: {\n client: {\n build: {\n manifest: true,\n outDir: 'dist/client',\n rollupOptions: { input: clientInput },\n },\n },\n ssr: {\n consumer: 'server',\n build: {\n outDir: 'dist/server',\n rollupOptions: {\n // `index` is the Vite service convention consumed\n // by provider orchestrators such as Nitro. Keep the\n // standalone artifact's established filename.\n input: { index: HANDLER_ID },\n output: { entryFileNames: 'server.js' },\n },\n },\n },\n },\n // Presence of `builder` makes a plain `vite build` build the\n // whole app (all environments: client then ssr).\n // A classic `vite build --ssr` invocation must stay a\n // single-environment build, so it doesn't get the flag.\n ...(env.isSsrBuild ? {} : { builder: {} }),\n }\n : {\n ...(!clientMode && !externalServer\n ? {\n environments: {\n ssr: {\n consumer: 'server' as const,\n build: {\n outDir: 'dist/server',\n rollupOptions: {\n // Expose the same service entry during serve so\n // provider runtimes can discover and own it.\n input: { index: HANDLER_ID },\n output: { entryFileNames: 'server.js' },\n },\n },\n },\n },\n }\n : {}),\n optimizeDeps: {\n entries: scanEntries,\n // Like the refresh runtime in the main plugin: the toolbar\n // graph is injected behind modules the scanner never crawls,\n // so pre-bundle it and the server-functions runtime up front.\n ...(() => {\n const spec = devtoolsEnabled ? devtoolsIncludeSpec(root) : null;\n return spec ? { include: [spec, '@solidjs/web/server-functions'] } : {};\n })(),\n },\n }),\n };\n },\n configEnvironment(name, config) {\n if (name !== 'ssr') return;\n config.resolve ??= {};\n const noExternal = config.resolve.noExternal;\n if (noExternal !== true) {\n config.resolve.noExternal = [\n ...(Array.isArray(noExternal) ? noExternal : noExternal ? [noExternal] : []),\n DEVTOOLS_PACKAGE,\n ];\n }\n },\n configResolved(config) {\n root = config.root;\n base = config.base;\n isBuild = config.command === 'build';\n },\n resolveId(source, importer, opts) {\n if (source === HANDLER_ID) {\n return { id: HANDLER_ID, moduleSideEffects: true };\n }\n if (source === DEV_STYLES_ID) {\n return { id: RESOLVED_DEV_STYLES_ID, moduleSideEffects: true };\n }\n if (\n source === ENTRY_SERVER_ID ||\n source === ENTRY_CLIENT_ID ||\n source === DOCUMENT_ID ||\n source === ERROR_BOUNDARY_ID\n ) {\n return { id: source, moduleSideEffects: source === ENTRY_CLIENT_ID };\n }\n if (devtoolsEnabled && source === DEVTOOLS_MOUNT_ID) {\n return { id: source, moduleSideEffects: true };\n }\n // Generated modules have no directory for bare-package resolution.\n // Reuse the app-relative id captured during detection.\n const devtoolsId = devtoolsIds[getEnvironmentConsumer(this.environment, opts)];\n if (\n devtoolsId &&\n source === DEVTOOLS_PACKAGE &&\n (importer === ENTRY_SERVER_ID ||\n importer === ENTRY_CLIENT_ID ||\n importer === DEVTOOLS_MOUNT_ID)\n ) {\n return { id: devtoolsId };\n }\n return null;\n },\n async load(id, opts) {\n const consumer = getEnvironmentConsumer(this.environment, opts);\n if (id === HANDLER_ID) {\n if (consumer !== 'server') {\n this.error(`${HANDLER_ID} is server-only; import it from server code (SSR build).`);\n }\n const externalDev =\n !isBuild &&\n this.environment.mode === 'dev' &&\n (externalServer || !isRunnableEnvironment(this.environment));\n return handlerModuleCode(externalDev);\n }\n if (id === RESOLVED_DEV_STYLES_ID) {\n if (consumer !== 'server' || this.environment.mode !== 'dev') {\n this.error(`${DEV_STYLES_ID} is only available to the development server handler.`);\n }\n return devStylesModuleCode(this.environment, (file) => this.addWatchFile(file));\n }\n if (id === ENTRY_SERVER_ID) {\n const toolbar = clientMode\n ? false\n : await resolveDevtools(\n (source, importer) => this.resolve(source, importer, { skipSelf: true }),\n requireEntries().app!,\n 'server',\n );\n return generatedEntryServerCode(toolbar);\n }\n if (id === ENTRY_CLIENT_ID) {\n const toolbar = await resolveDevtools(\n (source, importer) => this.resolve(source, importer, { skipSelf: true }),\n requireEntries().app!,\n 'client',\n );\n return generatedEntryClientCode(toolbar);\n }\n if (id === DOCUMENT_ID) return documentShellCode;\n if (id === ERROR_BOUNDARY_ID) return errorBoundaryCode;\n if (id === DEVTOOLS_MOUNT_ID) {\n let enabled = false;\n if (devtoolsEnabled && consumer === 'client') {\n const { app, entryClient } = requireEntries();\n enabled = await resolveDevtools(\n (source, importer) => this.resolve(source, importer, { skipSelf: true }),\n app ?? path.resolve(root, entryClient),\n 'client',\n );\n }\n if (!enabled) {\n this.error(`${id} is only available to the development client.`);\n }\n return devtoolsMountModuleCode();\n }\n return null;\n },\n async transform(code, id, opts) {\n if (isBuild || (!devtoolsEnabled && !diagnostics)) return null;\n const current = requireEntries();\n if (current.generated || getEnvironmentConsumer(this.environment, opts) !== 'client') {\n return null;\n }\n // Module ids are always forward-slashed; normalize the path.resolve\n // side too so the comparison holds on Windows.\n if (normalizePath(id.split('?')[0]) !== normalizePath(path.resolve(root, current.entryClient))) {\n return null;\n }\n const injected: string[] = [];\n if (diagnostics) injected.push(`import ${JSON.stringify(DIAGNOSTICS_CLIENT_ID)};`);\n if (devtoolsEnabled) {\n const toolbar = await resolveDevtools(\n (source, importer) => this.resolve(source, importer, { skipSelf: true }),\n id,\n 'client',\n );\n if (toolbar) injected.push(`import ${JSON.stringify(DEVTOOLS_MOUNT_ID)};`);\n }\n if (injected.length === 0) return null;\n return {\n code: `${injected.join('\\n')}\\n${code}`,\n map: null,\n };\n },\n configurePreviewServer(server: PreviewServer) {\n // `vite build && vite preview` runs the production artifact as-is:\n // Vite's preview statics serve dist/client (see the config hook) and\n // everything else — pages, the server-function endpoint, middleware\n // included — dispatches through the built handler, exactly like a\n // deployed server. Hosts owning the server build (`start.external`)\n // preview through their own runner instead.\n // Client mode: pages are the static index.html (preview's own\n // history fallback serves them before this post middleware runs);\n // only the server-function endpoint needs the handler, and without\n // server functions there is no dist/server at all.\n if (externalServer || (clientMode && !internal.serverFunctions)) return;\n return () => {\n let handlerPromise: Promise<{\n handleRequest: (\n request: Request,\n options?: { event?: Record<string, unknown> },\n ) => Promise<Response>;\n }> | null = null;\n server.middlewares.use((req, res, next) => {\n (async () => {\n handlerPromise ??= import(\n pathToFileURL(path.resolve(root, 'dist/server/server.js')).href\n );\n const handler = await handlerPromise;\n // Preview's base middleware runs before this post hook and\n // strips the configured `base` from req.url; the built handler\n // compares pathnames against base-prefixed endpoints (the\n // server-function endpoint) and hands the URL to application\n // code, so restore the base — the deployed production handler\n // receives base-prefixed URLs and preview must match it.\n const response = await handler.handleRequest(\n webRequestFromNode(req, joinBase(base, req.url || '/'), res),\n // Same event extension the dev middleware and a production\n // Node entry pass: the raw Node request as `nativeEvent`.\n { event: { nativeEvent: req } },\n );\n // Preview's compression middleware buffers whole responses;\n // opting HTML out keeps SSR streaming observable, matching\n // production behavior.\n if ((response.headers.get('content-type') || '').includes('text/html')) {\n res.setHeader('content-encoding', 'identity');\n }\n await sendWebResponse(res, response);\n })().catch(next);\n });\n };\n },\n configureServer(server: ViteDevServer) {\n // The files whose static import graphs carry the app's entry CSS:\n // the app root (+ document) for generated entries, the authored\n // server entry otherwise. Their transitively imported styles are\n // inlined into <head> per request (Vite injects entry CSS from\n // client JS only, so SSR'd markup would flash unstyled without\n // this); the SSR'd tags carry data-asset + data-vite-dev-id so the\n // dev style patch drops them once Vite's own injection takes over —\n // exactly the lazy-asset dedup story, HMR included.\n // Post middleware: Vite's own middlewares (transforms, static, the\n // server-function endpoint) run first; whatever asks for HTML after\n // that gets the streamed SSR render.\n return () => {\n const ssrEnvironment = server.environments.ssr;\n if (externalServer || !isRunnableEnvironment(ssrEnvironment)) {\n return;\n }\n server.middlewares.use((req, res, next) => {\n const url = new URL(req.url || '/', 'http://localhost');\n if (url.pathname.startsWith('/@')) return next();\n const accept = req.headers.accept || '';\n const pageRequest = req.method === 'GET' && accept.includes('text/html');\n // Production dispatches every request through the handler, so\n // dev must too or API routes and no-JS form POSTs served by\n // `start.middleware` are unreachable under `vite dev`. Without\n // a middleware chain, non-page requests have nothing to reach —\n // they stay on Vite's pipeline (404s) instead of rendering HTML.\n if (!pageRequest && !middlewarePath) return next();\n (async () => {\n // Loaded through the SSR environment so the app, the request\n // event storage, and the handler share one module registry.\n const handler = await ssrEnvironment.runner.import(HANDLER_ID);\n const styles = pageRequest\n ? await collectDevStyles(server, styleRoots(), styleFilter)\n : [];\n const devHead = styles.map(renderDevStyleTag).join('');\n // Post middlewares run after Vite's base middleware stripped\n // the configured `base` from req.url; restore it so the app\n // sees the same URLs in dev as in production (where the\n // deployed handler receives base-prefixed requests).\n const response: Response = await handler.handleRequest(\n webRequestFromNode(req, joinBase(base, req.url || '/'), res),\n {\n devHead,\n pageRequest,\n // The raw Node request on the event, matching what a\n // production Node server entry passes through the\n // `options.event` seam — getRequestEvent().nativeEvent\n // answers the same in dev as deployed.\n event: { nativeEvent: req },\n },\n );\n // A non-page request the chain never handled: the terminal\n // dispatch answered with the marked 404 — hand it back to\n // Vite (its 404, other post middlewares) rather than sending\n // a rendered page at a fetch()/form client.\n if (response.headers.has(DEV_FALLTHROUGH_HEADER)) return next();\n await sendWebResponse(res, response);\n })().catch((error) => {\n // Vite's error middleware renders the overlay-enabled 500 page.\n next(error);\n });\n });\n };\n },\n },\n ...(clientMode\n ? [\n {\n name: 'solid:start/prerender',\n apply: 'build',\n buildApp: {\n // Post order: this hook owns the whole client-mode app build (the\n // client-build-first orchestration pair is SSR-only). It\n // builds client-then-ssr itself — building anything from a\n // hook suppresses Vite's build-all fallback, so the ordering\n // is guaranteed and the manifest is on disk before the shell\n // bundle bakes it in — then runs the built handler once to\n // prerender the shell into dist/client/index.html and drops\n // dist/server unless server functions still need its handler.\n // The shell arrives complete from the handler: the runtime\n // registers every manifest entry's CSS during the render\n // (registerEntryAssets), so the entry graph's stylesheet\n // links are already in its head — injecting them here again\n // double-links every stylesheet.\n order: 'post' as const,\n async handler(builder: any) {\n const client = builder.environments.client;\n const ssrEnvironment = builder.environments.ssr;\n if (client && !client.isBuilt) await builder.build(client);\n if (ssrEnvironment && !ssrEnvironment.isBuilt) {\n await builder.build(ssrEnvironment);\n }\n\n const serverDir = path.resolve(root, 'dist/server');\n const handler = await import(\n pathToFileURL(path.join(serverDir, 'server.js')).href\n );\n const response: Response = await handler.handleRequest(\n new Request(new URL(base || '/', 'http://localhost')),\n );\n writeFileSync(path.resolve(root, 'dist/client/index.html'), await response.text());\n if (!internal.serverFunctions) {\n rmSync(serverDir, { recursive: true, force: true });\n }\n },\n },\n } satisfies Plugin,\n ]\n : []),\n ];\n}\n","// Typed, validated environment variables as a start-mode feature (`start.env`):\n// an `env.ts` at the project root default-exports `{ server, client }` maps\n// of Standard Schema validators (zod, valibot, arktype — mixable per key),\n// and the plugin exposes the validated values through two virtual modules:\n//\n// - `virtual:env/server` — every var; importable only from server module\n// graphs (a client-graph import is a hard error naming the importer).\n// - `virtual:env/client` — the `client` side only, whose keys must carry\n// the public env prefix (`VITE_` unless `envPrefix` says otherwise).\n//\n// Validation runs at config/build time in node only, against Vite's\n// `loadEnv` merge of the `.env*` files with `process.env` winning (CI\n// secrets take precedence) — and the plugin folds the file-loaded vars into\n// `process.env` itself, so templates don't need the classic\n// `process.env = { ...process.env, ...loadEnv(mode, root, '') }` one-liner.\n//\n// Client values are baked into the bundles as validated plain JSON —\n// that's what the public `VITE_` prefix means — so no validator library\n// ever reaches a browser bundle. Server values are NOT baked anywhere:\n// `virtual:env/server` reads `process.env` at module init (server boot)\n// and validates through the user's own schema, which only the server\n// module graph imports. Platform-injected vars that don't exist at build\n// time work, secrets rotate without a rebuild, and no secret value exists\n// in any dist artifact. Build-time server-value failures downgrade to a\n// warning (boot enforces); dev failures stay hard errors — dev IS runtime.\n// Boot validation is synchronous by design: the generated server module\n// contains no top-level await (a TLA chunk forces esnext on downstream\n// bundlers — Nitro's node-server preset rejects it), which is why async\n// validators are rejected for `server` keys (client keys may stay async;\n// they are awaited at build time where the values are baked).\n//\n// A failed validation fails the build; in dev it renders Vite's error\n// overlay with the per-key report (the virtual modules throw it on load)\n// and `.env*`/schema edits revalidate live. A `solid-env.d.ts` is generated\n// next to the schema file so both virtual modules are fully typed by\n// inference from the user's own schema — no manual declarations.\n//\n// Design credit: the shape of this feature — env.ts schema file, the\n// virtual module pair and their names, build-time validation with baked\n// JSON values, the leak scan — follows @vite-env/core by pyyupsk (MIT,\n// https://github.com/pyyupsk/vite-env), the design-correct prior art. The\n// implementation is fresh against this plugin's machinery: Standard Schema\n// is the only contract (no zod dependency or zod-specific paths), the\n// schema file loads through Vite's own `runnerImport`\n// (no jiti), server-graph protection keys off the environment *consumer*\n// rather than environment-name lists, and the types are inferred from the\n// user's schema instead of introspected per-library.\nimport { existsSync, readFileSync, writeFileSync } from 'fs';\nimport path from 'path';\nimport { loadEnv, runnerImport, type Plugin, type ResolvedConfig, type ViteDevServer } from 'vite';\n\nexport const CLIENT_ENV_ID = 'virtual:env/client';\nexport const SERVER_ENV_ID = 'virtual:env/server';\nconst RESOLVED_CLIENT_ENV_ID = '\\0' + CLIENT_ENV_ID;\nconst RESOLVED_SERVER_ENV_ID = '\\0' + SERVER_ENV_ID;\n\n// Conventional schema locations, project-root relative. TypeScript first —\n// the whole point is inferred types — but a plain-JS project works too.\nconst ENV_FILE_CANDIDATES = ['env.ts', 'env.js'];\n// Generated ambient types, written next to the schema file. Deliberately\n// NOT `env.d.ts`: a declaration file sharing the schema file's stem would\n// shadow it in TS resolution (and self-reference its own `typeof import`).\nconst GENERATED_TYPES_FILE = 'solid-env.d.ts';\n\n/**\n * The minimal structural slice of the Standard Schema v1 interface\n * (https://standardschema.dev) this plugin consumes — the spec is designed\n * to be vendored so validating libraries stay decoupled.\n */\ninterface StandardSchemaLike {\n '~standard': {\n version: number;\n vendor?: string;\n validate: (value: unknown) => StandardResultLike | Promise<StandardResultLike>;\n };\n}\ninterface StandardResultLike {\n value?: unknown;\n issues?: ReadonlyArray<{\n message: string;\n path?: ReadonlyArray<PropertyKey | { key: PropertyKey }>;\n }>;\n}\n\ninterface EnvSchema {\n server?: Record<string, StandardSchemaLike>;\n client?: Record<string, StandardSchemaLike>;\n}\n\ninterface LoadedEnv {\n schema: EnvSchema;\n /**\n * Every validated output value (server + client) as seen by the BUILD\n * process — used for fast feedback and the client-chunk leak scan. The\n * server virtual module does not bake these: it re-reads process.env at\n * boot. Keys whose build-time validation failed (deferred to boot) are\n * absent.\n */\n all: Record<string, unknown>;\n /** The client-side subset of {@link all}. */\n client: Record<string, unknown>;\n /** Files the schema module transitively loaded (for dev watching). */\n dependencies: string[];\n}\n\nfunction isStandardSchema(value: unknown): value is StandardSchemaLike {\n return (\n !!value &&\n typeof value === 'object' &&\n typeof (value as StandardSchemaLike)['~standard']?.validate === 'function'\n );\n}\n\n/**\n * Keys the loadEnv fold added to process.env, tracked process-globally.\n * Real environment always wins over files — but values *we* folded must not\n * count as \"real\" on revalidation, or the first fold would pin every .env\n * value forever and live edits would never be seen. Process-global (not\n * plugin-closure) state because Vite restarts the dev server on .env\n * changes, recreating the plugin instances inside the same node process:\n * the new instance must be able to clear the old instance's fold.\n */\nconst FOLDED_KEYS = Symbol.for('@solidjs/vite-plugin:env-folded-keys');\nfunction foldedKeys(): Set<string> {\n const holder = globalThis as { [FOLDED_KEYS]?: Set<string> };\n return (holder[FOLDED_KEYS] ??= new Set());\n}\n\nfunction stringEntries(env: NodeJS.ProcessEnv): Record<string, string> {\n const out: Record<string, string> = {};\n for (const key in env) {\n const value = env[key];\n if (typeof value === 'string') out[key] = value;\n }\n return out;\n}\n\n/** Formats the per-key validation report shared by builds and the dev overlay. */\nfunction formatValidationError(\n issues: Array<{ key: string; message: string }>,\n envFile: string,\n mode: string,\n): string {\n const lines = issues.map(({ key, message }) => ` ✗ ${key}: ${message}`);\n return (\n `[@solidjs/vite-plugin] env validation failed (${issues.length} issue${\n issues.length === 1 ? '' : 's'\n }) — schema: ${envFile}, mode: ${mode}\\n\\n` +\n lines.join('\\n') +\n `\\n\\nSet the variables in your environment or .env files, or adjust the schema.`\n );\n}\n\n/** Loads the schema module through Vite with project resolution. */\nasync function importSchemaModule(\n envFileAbs: string,\n root: string,\n mode: string,\n): Promise<{ exported: unknown; dependencies: string[] }> {\n const { module, dependencies } = await runnerImport<Record<string, unknown>>(envFileAbs, {\n root,\n mode,\n });\n return {\n exported: module?.default,\n dependencies: dependencies\n .map((dep: string) => path.resolve(root, dep))\n .filter((dep: string) => existsSync(dep)),\n };\n}\n\nfunction assertSchemaShape(\n exported: unknown,\n envFile: string,\n envPrefixes: string[],\n): EnvSchema {\n if (!exported || typeof exported !== 'object') {\n throw new Error(\n `[@solidjs/vite-plugin] ${envFile} must default-export an object of the shape ` +\n `{ server?: { VAR: schema }, client?: { VITE_VAR: schema } } where every schema ` +\n `is a Standard Schema validator (zod, valibot, arktype, ...). Got: ${\n exported === null ? 'null' : typeof exported\n }.`,\n );\n }\n const schema = exported as Record<string, unknown>;\n for (const key of Object.keys(schema)) {\n if (key !== 'server' && key !== 'client') {\n throw new Error(\n `[@solidjs/vite-plugin] unknown key \"${key}\" in ${envFile}: the env schema takes ` +\n `only \\`server\\` and \\`client\\` maps of Standard Schema validators.`,\n );\n }\n }\n for (const side of ['server', 'client'] as const) {\n const shape = schema[side];\n if (shape === undefined) continue;\n if (!shape || typeof shape !== 'object') {\n throw new Error(\n `[@solidjs/vite-plugin] \\`${side}\\` in ${envFile} must be an object mapping variable ` +\n `names to Standard Schema validators.`,\n );\n }\n for (const [key, validator] of Object.entries(shape)) {\n if (!isStandardSchema(validator)) {\n throw new Error(\n `[@solidjs/vite-plugin] ${side}.${key} in ${envFile} is not a Standard Schema ` +\n `validator (no callable \\`~standard.validate\\`). Any zod/valibot/arktype ` +\n `schema qualifies; plain values and functions don't.`,\n );\n }\n }\n }\n const typed = schema as EnvSchema;\n for (const key of Object.keys(typed.client ?? {})) {\n if (!envPrefixes.some((prefix) => key.startsWith(prefix))) {\n const wanted = envPrefixes[0] ?? 'VITE_';\n throw new Error(\n `[@solidjs/vite-plugin] client env var \"${key}\" in ${envFile} must carry the public ` +\n `env prefix (\"${envPrefixes.join('\" or \"')}\") — client vars are baked into the ` +\n `browser bundle. Rename it to \"${wanted}${key}\", or move it to \\`server\\` if it ` +\n `is a secret.`,\n );\n }\n if (typed.server && key in typed.server) {\n throw new Error(\n `[@solidjs/vite-plugin] \"${key}\" is defined in both \\`server\\` and \\`client\\` in ` +\n `${envFile}; a variable belongs to exactly one side (\\`client\\` vars are ` +\n `visible to the server too).`,\n );\n }\n }\n // The reverse guard: Vite itself bakes every prefixed variable into\n // `import.meta.env` for the browser, so declaring one under `server`\n // cannot keep it secret — it leaks through Vite's channel with no\n // diagnostics from this plugin's leak scan (which only watches the\n // virtual server module's values).\n for (const key of Object.keys(typed.server ?? {})) {\n const prefix = envPrefixes.find((p) => key.startsWith(p));\n if (prefix) {\n const bare = key.slice(prefix.length);\n throw new Error(\n `[@solidjs/vite-plugin] server env var \"${key}\" in ${envFile} carries the public ` +\n `env prefix \"${prefix}\". Vite exposes every \"${prefix}\"-prefixed variable to ` +\n `the browser through import.meta.env no matter which side declares it, so a ` +\n `\\`server\\` entry cannot keep it secret. ` +\n (bare\n ? `Rename it to \"${bare}\" (in the schema and in your .env/environment), or `\n : `Rename it without the prefix, or `) +\n `move it to \\`client\\` if it is public.`,\n );\n }\n }\n return typed;\n}\n\n/**\n * Generates the ambient `solid-env.d.ts` next to the schema file. The file\n * is self-contained: it infers each variable's type from the user's own\n * schema through the Standard Schema `~standard.types.output` phantom, so\n * any compliant validator library yields full types with no per-library\n * introspection. Only rewritten when the content actually changes.\n */\nfunction generateTypes(schema: EnvSchema, envFileAbs: string): void {\n const dtsPath = path.join(path.dirname(envFileAbs), GENERATED_TYPES_FILE);\n const importSpec = './' + path.basename(envFileAbs).replace(/\\.[mc]?[tj]s$/, '');\n\n const field = (side: 'server' | 'client', key: string) =>\n ` readonly ${JSON.stringify(key)}: __Out<__Schema[${JSON.stringify(side)}][${JSON.stringify(key)}]>;`;\n\n const moduleBlock = (id: string, fields: string[]) =>\n [\n `declare module '${id}' {`,\n ` type __Schema = typeof import(${JSON.stringify(importSpec)})['default'];`,\n ` type __Out<T> = T extends { '~standard': { types?: { output: infer O } | undefined } }`,\n ` ? O`,\n ` : string;`,\n ` const env: {`,\n ...fields,\n ` };`,\n ` export { env };`,\n ` export default env;`,\n `}`,\n ].join('\\n');\n\n const clientFields = Object.keys(schema.client ?? {}).map((key) => field('client', key));\n const serverFields = [\n ...Object.keys(schema.server ?? {}).map((key) => field('server', key)),\n ...clientFields,\n ];\n\n const content =\n `// Generated by @solidjs/vite-plugin (start.env) — do not edit.\\n` +\n `// Regenerated on every dev server and build start from ${path.basename(envFileAbs)}.\\n` +\n `// Keep this file (and the schema) inside your tsconfig \"include\".\\n\\n` +\n moduleBlock(CLIENT_ENV_ID, clientFields) +\n '\\n\\n' +\n moduleBlock(SERVER_ENV_ID, serverFields) +\n '\\n';\n\n try {\n if (existsSync(dtsPath) && readFileSync(dtsPath, 'utf-8') === content) return;\n writeFileSync(dtsPath, content);\n } catch (error) {\n const reason = error instanceof Error ? `: ${error.message}` : '';\n console.warn(\n `[@solidjs/vite-plugin] could not write ${GENERATED_TYPES_FILE} next to the env schema` +\n `${reason} — the virtual env modules stay untyped until it can be written.`,\n );\n }\n}\n\n/**\n * Start-mode typed env (the `start.env` option). Returns no plugin when the\n * feature is off (`env: false`, or nothing to probe); the feature is\n * start-only by construction — the option lives on `start`, so a bare\n * `ssr: true` setup has no env layer (documented).\n */\nexport function startEnv(option: boolean | string | undefined): Plugin[] {\n if (option === false) return [];\n\n let root = process.cwd();\n let config: ResolvedConfig;\n let isBuild = false;\n let isPreview = false;\n let enabled = false;\n /** Absolute path of the schema file once resolved. */\n let envFileAbs: string | null = null;\n /** Root-relative schema path for messages. */\n let envFile = 'env.ts';\n\n let envPromise: Promise<LoadedEnv> | null = null;\n let devErrorLogged = false;\n\n function resolveEnvFile(): void {\n if (typeof option === 'string') {\n const absolute = path.isAbsolute(option) ? option : path.resolve(root, option);\n if (!existsSync(absolute)) {\n throw new Error(`[@solidjs/vite-plugin] start.env does not exist: ${option}`);\n }\n const relative = path.relative(root, absolute).split(path.sep).join('/');\n if (relative.startsWith('..')) {\n throw new Error(\n `[@solidjs/vite-plugin] start.env must live inside the Vite root: ${option}`,\n );\n }\n envFileAbs = absolute;\n envFile = relative;\n enabled = true;\n return;\n }\n for (const candidate of ENV_FILE_CANDIDATES) {\n const absolute = path.resolve(root, candidate);\n if (existsSync(absolute)) {\n envFileAbs = absolute;\n envFile = candidate;\n enabled = true;\n return;\n }\n }\n if (option === true) {\n throw new Error(\n `[@solidjs/vite-plugin] start.env is enabled but no schema file was found: add ` +\n `${ENV_FILE_CANDIDATES.join(' or ')} at the project root (default-exporting ` +\n `{ server, client } maps of Standard Schema validators), or point start.env ` +\n `at a path.`,\n );\n }\n }\n\n function envPrefixes(): string[] {\n const prefix = config?.envPrefix ?? 'VITE_';\n return Array.isArray(prefix) ? prefix : [prefix];\n }\n\n async function loadAndValidate(): Promise<LoadedEnv> {\n const { exported, dependencies } = await (async () => {\n try {\n return await importSchemaModule(envFileAbs!, root, config.mode);\n } catch (error) {\n const reason = error instanceof Error ? `\\n\\nCause: ${error.message}` : '';\n throw new Error(\n `[@solidjs/vite-plugin] could not load the env schema at ${envFile}. It must be a ` +\n `server-side module default-exporting { server?, client? } maps of Standard ` +\n `Schema validators.${reason}`,\n );\n }\n })();\n\n const schema = assertSchemaShape(exported, envFile, envPrefixes());\n // Types depend only on the schema, not the values: generate before\n // validating so a missing variable doesn't also break editor types.\n generateTypes(schema, envFileAbs!);\n\n // Vite's .env story with `loadEnv` merge priority — process.env wins\n // (CI/pipeline secrets over files), then .env.[mode].local down to .env.\n // The fold into process.env is what removes the template's classic\n // `process.env = { ...process.env, ...loadEnv(mode, root, '') }` line:\n // server code reading process.env directly (db clients, SDKs) sees the\n // file-loaded vars too, in dev, build, and the client-mode prerender.\n const envDir =\n (config as { envDir?: string | false }).envDir === false\n ? null\n : config.envDir || root;\n const folded = foldedKeys();\n for (const key of folded) delete process.env[key];\n folded.clear();\n const fileEnv = envDir ? loadEnv(config.mode, envDir, '') : {};\n for (const [key, value] of Object.entries(fileEnv)) {\n if (!(key in process.env)) {\n process.env[key] = value;\n folded.add(key);\n }\n }\n const raw: Record<string, string> = { ...fileEnv, ...stringEntries(process.env) };\n\n const issues: Array<{ key: string; message: string; side: 'server' | 'client' }> = [];\n const all: Record<string, unknown> = {};\n for (const side of ['server', 'client'] as const) {\n for (const [key, validator] of Object.entries(schema[side] ?? {})) {\n let result = validator['~standard'].validate(raw[key]);\n if (result instanceof Promise) {\n // Async validation is fine for `client` keys — their values are\n // baked right here at build time, where awaiting costs nothing.\n // `server` keys validate process.env at boot through generated\n // code that is deliberately synchronous (a top-level await in the\n // server env chunk forces esnext on every downstream bundle\n // target — Nitro's node-server preset rejects it outright), so a\n // Promise-returning server validator could only ever fail at\n // deploy boot. Async-ness is a property of the schema, not the\n // value, so fail fast here with the fix in the message. Boot\n // still backstops (schemas whose sync prefix short-circuits at\n // build time can go async on real values).\n if (side === 'server') {\n throw new Error(\n `[@solidjs/vite-plugin] server env var \"${key}\" in ${envFile} uses an async ` +\n `validator (validate() returned a Promise). Server env is validated ` +\n `synchronously at boot — the generated module contains no top-level ` +\n `await, so server bundles work on non-esnext targets — which async ` +\n `validators cannot do. Make the validator synchronous (drop async ` +\n `refinements/transforms), or run the async check in application code.`,\n );\n }\n result = await result;\n }\n if (result.issues && result.issues.length) {\n for (const issue of result.issues) {\n const at = (issue.path ?? [])\n .map((segment) =>\n typeof segment === 'object' && segment !== null && 'key' in segment\n ? String(segment.key)\n : String(segment),\n )\n .join('.');\n issues.push({ key: at ? `${key}.${at}` : key, message: issue.message, side });\n }\n } else {\n all[key] = result.value;\n }\n }\n }\n if (issues.length) {\n // Client values are baked at build time, so their failures always\n // fail hard. Server values are read from process.env at boot: a\n // build may legitimately run without them (platform-injected vars),\n // so build-time server failures downgrade to a warning and boot\n // validation enforces. Dev failures stay hard — dev IS runtime.\n const clientIssues = issues.filter((issue) => issue.side === 'client');\n if (!isBuild || clientIssues.length) {\n throw new Error(\n formatValidationError(!isBuild ? issues : clientIssues, envFile, config.mode),\n );\n }\n config.logger.warn(\n `\\n[@solidjs/vite-plugin] server env not valid at build time (deferred to boot ` +\n `validation — server env is read from process.env at runtime):\\n` +\n issues.map(({ key, message }) => ` ⚠ ${key}: ${message}`).join('\\n') +\n '\\n',\n );\n }\n\n const client: Record<string, unknown> = {};\n for (const key of Object.keys(schema.client ?? {})) client[key] = all[key];\n\n return { schema, all, client, dependencies };\n }\n\n function ensureEnv(): Promise<LoadedEnv> {\n return (envPromise ??= loadAndValidate());\n }\n\n /**\n * Whether the current hook runs for a server-destined module graph. The\n * environment's `consumer` is authoritative (covers workerd and friends\n * without name lists); classic contexts fall back to the ssr flag.\n */\n function isServerContext(\n ctx: { environment?: { config?: { consumer?: string } } },\n opts?: { ssr?: boolean },\n ): boolean {\n const consumer = ctx.environment?.config?.consumer;\n if (consumer) return consumer === 'server';\n return !!opts?.ssr;\n }\n\n function serverOnlyError(importer?: string): string {\n return (\n `[@solidjs/vite-plugin] ${SERVER_ENV_ID} is server-only and was imported from the ` +\n `client module graph` +\n (importer ? ` (by ${importer})` : '') +\n `. Server env values must never reach the browser bundle: import ` +\n `${CLIENT_ENV_ID} for the public ${envPrefixes().join('/')}-prefixed vars, or move ` +\n `this import into a server-only module (a \"use server\" module, middleware, or the ` +\n `server entry).`\n );\n }\n\n // Baked-JSON module emission (pattern from @vite-env/core, MIT): the\n // validated output values serialize as a frozen object literal, so no\n // validator code exists in the client bundle and tree-shaking sees plain\n // data. `moduleType` marks the virtual source as plain JS for rolldown\n // (Vite 8).\n function envModuleCode(values: Record<string, unknown>) {\n return {\n code:\n `// Generated by @solidjs/vite-plugin (start.env)\\n` +\n `export const env = Object.freeze(${JSON.stringify(values)});\\n` +\n `export default env;`,\n moduleType: 'js' as const,\n };\n }\n\n // The server module is NOT baked: server values are read from\n // process.env at module init (server boot) and validated through the\n // user's own schema, imported straight into the server graph (the\n // validator library is server-only, so shipping it there is fine).\n // Client (public) values stay baked — that's what the VITE_ prefix\n // means. Platform-injected vars that don't exist at build time work,\n // secrets rotate without a rebuild, and no secret value exists in any\n // dist artifact.\n //\n // The generated code is deliberately free of top-level await. Module\n // init is the only point where \"validated and frozen before any\n // importer's body runs\" can be guaranteed — user server modules read\n // `env.KEY` at their own top level — and the only async thing here is\n // Standard Schema's option to return a Promise from validate(). A TLA\n // chunk breaks every downstream bundler with a non-esnext target\n // (Nitro's node-server preset in practice), so validation runs\n // synchronously and a Promise-returning server validator is itself a\n // boot issue (build/config time rejects it earlier when detectable).\n function serverEnvModuleCode(loaded: LoadedEnv) {\n const serverKeys = Object.keys(loaded.schema.server ?? {});\n const baked = `const __env = ${JSON.stringify(loaded.client)};`;\n if (!serverKeys.length) {\n return {\n code:\n `// Generated by @solidjs/vite-plugin (start.env) — server env.\\n` +\n `${baked}\\n` +\n `export const env = Object.freeze(__env);\\n` +\n `export default env;`,\n moduleType: 'js' as const,\n };\n }\n return {\n code: [\n `// Generated by @solidjs/vite-plugin (start.env) — server env.`,\n `// Server values are read from process.env and validated at boot;`,\n `// client (public) values are baked at build time. Boot validation is`,\n `// synchronous on purpose: a top-level await here would force esnext`,\n `// on every downstream bundle target (Nitro's node-server preset and`,\n `// anything else below esnext rejects a TLA chunk outright).`,\n `import __schema from ${JSON.stringify(envFileAbs)};`,\n baked,\n `const __issues = [];`,\n `for (const __key of ${JSON.stringify(serverKeys)}) {`,\n ` const __result = __schema.server[__key]['~standard'].validate(process.env[__key]);`,\n ` if (__result && typeof __result.then === 'function') {`,\n ` __issues.push(' \\\\u2717 ' + __key + ': validator returned a Promise \\\\u2014 async validators are not supported for server keys (boot validation is synchronous so the server bundle carries no top-level await); make this validator synchronous');`,\n ` } else if (__result.issues && __result.issues.length) {`,\n ` for (const __issue of __result.issues) __issues.push(' \\\\u2717 ' + __key + ': ' + __issue.message);`,\n ` } else {`,\n ` __env[__key] = __result.value;`,\n ` }`,\n `}`,\n `if (__issues.length) {`,\n ` throw new Error(`,\n ` '[@solidjs/vite-plugin] server env validation failed at boot (' + __issues.length +`,\n ` ' issue' + (__issues.length === 1 ? '' : 's') + ') \\\\u2014 schema: ' + ${JSON.stringify(envFile)} +`,\n ` '\\\\n\\\\n' + __issues.join('\\\\n') +`,\n ` '\\\\n\\\\nServer env is read from process.env at boot, not baked at build time: set the ' +`,\n ` 'variables in the server process environment.'`,\n ` );`,\n `}`,\n `export const env = Object.freeze(__env);`,\n `export default env;`,\n ].join('\\n'),\n moduleType: 'js' as const,\n };\n }\n\n return [\n {\n name: 'solid:start-env',\n\n config(userConfig, env) {\n root = path.resolve(userConfig.root || process.cwd());\n isPreview = !!env.isPreview;\n resolveEnvFile();\n // Preview serves finished artifacts, so no schema loading or\n // validation happens there — but the built server module reads\n // process.env at boot, and `vite preview` should smoke-test the\n // artifact as hands-off as dev runs it: fold the .env files into\n // process.env (real environment still wins). A production process\n // brings its own environment instead.\n if (isPreview && enabled) {\n const envDirOption = (userConfig as { envDir?: string | false }).envDir;\n const envDir =\n envDirOption === false ? null : path.resolve(root, envDirOption || '.');\n if (envDir) {\n const folded = foldedKeys();\n for (const key of folded) delete process.env[key];\n folded.clear();\n const fileEnv = loadEnv(userConfig.mode || env.mode, envDir, '');\n for (const [key, value] of Object.entries(fileEnv)) {\n if (!(key in process.env)) {\n process.env[key] = value;\n folded.add(key);\n }\n }\n }\n }\n },\n\n configResolved(resolved) {\n config = resolved;\n root = resolved.root;\n isBuild = resolved.command === 'build';\n if (!enabled || isPreview) return;\n // Kick validation off eagerly (the fold must precede any server\n // module execution); buildStart awaits it and owns error routing.\n ensureEnv().catch(() => {});\n },\n\n async buildStart() {\n if (!enabled) return;\n try {\n await ensureEnv();\n } catch (error) {\n // Builds fail with the report; dev logs it once and lets the\n // virtual modules rethrow on load, which renders Vite's error\n // overlay (client imports) or the overlay-enabled 500 (SSR).\n if (isBuild) throw error;\n if (!devErrorLogged) {\n devErrorLogged = true;\n config.logger.error(\n '\\n' + (error instanceof Error ? error.message : String(error)) + '\\n',\n );\n }\n }\n },\n\n resolveId(source, importer, options) {\n if (!enabled) return null;\n if (source === CLIENT_ENV_ID) return RESOLVED_CLIENT_ENV_ID;\n if (source === SERVER_ENV_ID) {\n // The dep scanner probes client entries' import graphs without\n // executing them; deny real client-graph imports only (the load\n // hook double-checks — scanners never load `\\0` ids).\n if (!(options as { scan?: boolean } | undefined)?.scan && !isServerContext(this, options)) {\n this.error(serverOnlyError(importer));\n }\n return RESOLVED_SERVER_ENV_ID;\n }\n return null;\n },\n\n async load(id, opts) {\n if (!enabled) return null;\n if (id !== RESOLVED_CLIENT_ENV_ID && id !== RESOLVED_SERVER_ENV_ID) return null;\n // Throws the validation report when env is invalid — the dev\n // overlay / failed build carries the per-key details.\n const loaded = await ensureEnv();\n if (id === RESOLVED_SERVER_ENV_ID) {\n if (!isServerContext(this, opts)) this.error(serverOnlyError());\n return serverEnvModuleCode(loaded);\n }\n return envModuleCode(loaded.client);\n },\n\n configureServer(server: ViteDevServer) {\n if (!enabled) return;\n const envDir =\n (config as { envDir?: string | false }).envDir === false\n ? null\n : config.envDir || root;\n // Explicit file list (no globs — chokidar 4 dropped them): the four\n // .env variants Vite consults for this mode, the schema module, and\n // whatever it transitively loaded.\n const envFiles = envDir\n ? ['.env', '.env.local', `.env.${config.mode}`, `.env.${config.mode}.local`].map(\n (file) => path.join(envDir, file),\n )\n : [];\n const watched = new Set<string>([...envFiles, envFileAbs!]);\n server.watcher.add([...watched]);\n ensureEnv()\n .then(({ dependencies }) => {\n for (const dep of dependencies) watched.add(dep);\n server.watcher.add(dependencies);\n })\n .catch(() => {});\n\n // Live revalidation (flow from @vite-env/core, MIT): reload sources,\n // rerun the schema, invalidate both virtual modules in every\n // environment, and full-reload — on failure the reload makes the\n // client re-import the virtual module, whose load() now throws the\n // fresh report into the error overlay.\n let debounce: ReturnType<typeof setTimeout> | undefined;\n const onFileEvent = (file: string) => {\n if (!watched.has(file)) return;\n clearTimeout(debounce);\n debounce = setTimeout(async () => {\n envPromise = null;\n devErrorLogged = false;\n let failed = false;\n try {\n const { dependencies } = await ensureEnv();\n for (const dep of dependencies) watched.add(dep);\n server.watcher.add(dependencies);\n } catch (error) {\n failed = true;\n devErrorLogged = true;\n config.logger.error(\n '\\n' + (error instanceof Error ? error.message : String(error)) + '\\n',\n );\n }\n let invalidated = false;\n for (const environment of Object.values(server.environments ?? {})) {\n const graph = (environment as { moduleGraph?: any }).moduleGraph;\n if (!graph) continue;\n for (const id of [RESOLVED_CLIENT_ENV_ID, RESOLVED_SERVER_ENV_ID]) {\n const mod = graph.getModuleById(id);\n if (mod) {\n graph.invalidateModule(mod);\n invalidated = true;\n }\n }\n }\n if (invalidated) {\n const hot = server.hot ?? (server as any).ws;\n hot?.send({ type: 'full-reload' });\n }\n if (!failed) {\n config.logger.info(`[@solidjs/vite-plugin] env revalidated (${envFile})`);\n }\n }, 100);\n };\n server.watcher.on('change', onFileEvent);\n server.watcher.on('add', onFileEvent);\n server.watcher.on('unlink', onFileEvent);\n },\n\n // Leak scan (heuristics from @vite-env/core, MIT): a server var's\n // *value* appearing as a quoted string literal in a client chunk means\n // something inlined it (an env.ts import from shared code, a define,\n // a copy-paste). Values under 8 chars skip (too collision-prone), as\n // do values shared with a client var and pure-vendor chunks.\n async generateBundle(_options, bundle) {\n if (!enabled || !isBuild || isServerContext(this, { ssr: !!config.build.ssr })) return;\n const loaded = await ensureEnv().catch(() => null);\n if (!loaded) return;\n\n const clientValues = new Set(Object.values(loaded.client));\n const secrets = Object.entries(loaded.all).filter(\n (entry): entry is [string, string] =>\n !(entry[0] in loaded.client) &&\n typeof entry[1] === 'string' &&\n entry[1].length >= 8 &&\n !clientValues.has(entry[1]),\n );\n if (!secrets.length) return;\n\n const leaks: string[] = [];\n for (const [fileName, chunk] of Object.entries(bundle)) {\n if (chunk.type !== 'chunk' || !chunk.code) continue;\n const moduleIds = (chunk as { moduleIds?: string[] }).moduleIds ?? [];\n if (moduleIds.length > 0 && moduleIds.every((id) => /[\\\\/]node_modules[\\\\/]/.test(id)))\n continue;\n for (const [key, value] of secrets) {\n const escaped = value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n if (new RegExp(`([\"'\\`])${escaped}\\\\1`).test(chunk.code)) {\n leaks.push(`${key} in ${fileName}`);\n }\n }\n }\n if (leaks.length) {\n this.error(\n `[@solidjs/vite-plugin] server env values leaked into client chunks:\\n` +\n leaks.map((leak) => ` ✗ ${leak}`).join('\\n') +\n `\\n\\nServer env values belong to the server process only (they are not even ` +\n `baked into the server bundle). Check for hand-inlined values and imports of ` +\n `the env schema module from client code, and use ${SERVER_ENV_ID} from ` +\n `server-only modules instead.`,\n );\n }\n },\n },\n ];\n}\n","import * as babel from '@babel/core';\nimport type { TransformOptions as JsxCompilerOptions } from '@solidjs/compiler';\nimport remapping from '@ampproject/remapping';\nimport solid from '@solidjs/babel-plugin';\nimport { existsSync, readFileSync } from 'fs';\nimport { mergeAndConcat } from 'merge-anything';\nimport { createRequire } from 'module';\nimport {\n createDevAssetResolver,\n registerDevAssetResolver,\n installDevManifestBridge,\n devManifestBridgeUrl,\n DEV_MANIFEST_REGISTRY_KEY,\n} from './dev-manifest.js';\nimport { boundaryModules } from './boundary-modules.js';\nimport { solidDiagnostics } from './diagnostics/index.js';\n\nimport { serverFunctions, type ServerFunctionsOptions } from './server-functions/index.js';\nimport { SSR_HANDLER_ID, startServe, type StartOptions } from './ssr/index.js';\nimport { startEnv } from './start-env.js';\n\nexport { devStylePatch } from './dev-manifest.js';\nexport { serverFunctions };\nexport type { ServerFunctionsOptions };\nexport type { ServerFunctionsFilter } from './server-functions/index.js';\nexport type { StartOptions };\nimport path from 'path';\nimport type { FilterPattern, Plugin, ViteDevServer } from 'vite';\nimport { createFilter, defaultClientConditions, defaultServerConditions } from 'vite';\nimport { getEnvironmentConsumer, isRunnableEnvironment } from './environment.js';\nimport { crawlFrameworkPkgs } from 'vitefu';\n\nconst require = createRequire(import.meta.url);\n\n/**\n * The `lazy()` module-URL placeholder contract, shared with the native\n * compiler's `transformLazy` pass: `lazy(() => import(\"spec\"))` calls gain a\n * second string-literal argument of the form\n * `\"__SOLID_LAZY_MODULE__:\" + spec`, which `resolveLazyModuleUrls` swaps for\n * the project-relative resolved module path. The prefix and shape are FROZEN\n * — the emitting side lives in @solidjs/compiler and must match.\n */\nconst LAZY_PLACEHOLDER_PREFIX = '__SOLID_LAZY_MODULE__:';\n\n/**\n * The HMR runtime: the dev-only `solid-js/refresh` core entry. Refresh\n * wrappers are compiled by the native `transformRefresh` pass in every mode\n * and import the runtime through normal module resolution (the legacy\n * solid-refresh package — whose runtime carries a known Solid 2.0 HMR bug,\n * solid-refresh#85 — is no longer used at all).\n */\nconst REFRESH_RUNTIME_SOURCE = 'solid-js/refresh';\n\nconst DEFAULT_STYLE_EXCLUDE = /node_modules/;\n\nconst VIRTUAL_MANIFEST_ID = 'virtual:solid-manifest';\nconst RESOLVED_VIRTUAL_MANIFEST_ID = '\\0' + VIRTUAL_MANIFEST_ID;\n\n// In dev the virtual manifest exports a `{ resolve, resolveSync }` resolver:\n// lazy modules resolve to their dev URL plus transitively imported CSS as\n// inline-style descriptors collected from the live module graph. The resolver\n// itself lives plugin-side (it closes over the dev server) and is reached\n// through a global registry; isolated module runners that don't share\n// globals (nitro's dev worker, workerd) fall back to fetching the dev\n// server's bridge endpoint, whose URL is baked in at generation time\n// (`bridgeUrl` — null outside a live dev server, e.g. the manifest-less SSR\n// build fallback, where js-only resolution remains). Bridge failures log\n// loudly and resolve to null so the runtime's own no-assets warning stays\n// the final catch-all.\n//\n// The generated `moduleUrl` mirrors `devModuleUrl` (src/dev-manifest.ts) —\n// base-prefixed root-relative URLs, `/@fs/` for root-external keys — for the\n// degraded paths that can't reach the plugin-side resolver (no registry and\n// no bridge, or a resolveSync call before the bridge cache warms). Keep the\n// two in sync.\nconst devManifestCode = (root: string, base: string, bridgeUrl: string | null) => `const registry = globalThis[Symbol.for(${JSON.stringify(\n DEV_MANIFEST_REGISTRY_KEY,\n)})];\nconst projectRoot = ${JSON.stringify(root.split(path.sep).join('/'))};\nconst base = ${JSON.stringify(base.startsWith('/') ? base.replace(/\\/$/, '') : '')};\nfunction moduleUrl(key) {\n const queryIndex = key.indexOf(\"?\");\n const file = queryIndex === -1 ? key : key.slice(0, queryIndex);\n const query = queryIndex === -1 ? \"\" : key.slice(queryIndex);\n if (file.slice(0, 2) !== \"..\") return base + \"/\" + key;\n const segments = (projectRoot + \"/\" + file).split(\"/\");\n const resolved = [];\n for (const segment of segments) {\n if (segment === \"..\") resolved.pop();\n else if (segment && segment !== \".\") resolved.push(segment);\n }\n return base + \"/@fs/\" + resolved.join(\"/\") + query;\n}\nconst jsOnly = key => ({ js: [moduleUrl(key)], css: [] });\nconst bridgeUrl = ${JSON.stringify(bridgeUrl)};\nfunction createBridgeResolver() {\n // Convergence cache, mirroring the in-process resolver: server-side lazy()\n // re-requests assets on every retry of a suspended render pass, and only a\n // synchronous answer lets the pass converge (a fresh promise per call\n // suspends every retry anew — nested routes then loop until the render\n // stack overflows). Cached entries can go stale after a CSS edit (no\n // watcher reaches this side of the bridge); the HMR client replaces SSR'd\n // dev styles on load, so staleness self-heals at hydration. Only successful\n // answers are cached: a null (bridge failure) must stay retryable, or one\n // transient miss would strip the module's client assets — silently — for\n // the rest of the dev session. In-flight dedupe still gives retries of the\n // same pass a stable promise, so convergence holds either way.\n const cache = new Map();\n const inFlight = new Map();\n return {\n resolve(key) {\n const cached = cache.get(key);\n if (cached) return cached;\n let request = inFlight.get(key);\n if (!request) {\n request = fetchAssets(key).then(\n (assets) => {\n if (assets) cache.set(key, assets);\n inFlight.delete(key);\n return assets;\n },\n (error) => {\n inFlight.delete(key);\n throw error;\n },\n );\n inFlight.set(key, request);\n }\n return request;\n },\n resolveSync: (key) => cache.get(key) || jsOnly(key),\n };\n}\nasync function fetchAssets(key) {\n const url = new URL(bridgeUrl);\n url.searchParams.set(\"key\", key);\n let response;\n try {\n response = await fetch(url);\n } catch (error) {\n console.error(\n '[@solidjs/vite-plugin] Dev manifest bridge request failed for module key \"' + key +\n '\" (' + url.href + '): ' + ((error && error.message) || error) +\n \". SSR will render without this module's client assets, so its hydration preload entry will be missing.\",\n );\n return null;\n }\n if (!response.ok) {\n // A silent null here strips the module's client assets from the\n // SSR'd hydration asset map and hydration fails much later with a\n // cryptic client-side error — report the miss where it happens.\n console.error(\n '[@solidjs/vite-plugin] Dev manifest bridge request failed with status ' + response.status +\n ' for module key \"' + key + '\" (' + url.href +\n \"). SSR will render without this module's client assets, so its hydration preload entry will be missing.\",\n );\n return null;\n }\n return response.json();\n}\nexport default (registry && registry[${JSON.stringify(root)}]) ||\n (bridgeUrl ? createBridgeResolver() : { resolve: jsOnly, resolveSync: jsOnly });`;\n\n/** Possible options for the extensions property */\nexport interface ExtensionOptions {\n typescript?: boolean;\n}\n\nexport type Compiler = 'babel' | 'native';\nexport type SolidOptions = Omit<JsxCompilerOptions, 'filename' | 'sourceMap'>;\ntype NativeCompiler = typeof import('@solidjs/compiler');\nlet nativeCompilerPromise: Promise<NativeCompiler> | undefined;\n\nasync function loadNativeCompiler() {\n try {\n return await (nativeCompilerPromise ??= import('@solidjs/compiler'));\n } catch (error) {\n nativeCompilerPromise = undefined;\n const reason = error instanceof Error ? `\\n\\nCause: ${error.message}` : '';\n throw new Error(\n '@solidjs/vite-plugin: failed to load @solidjs/compiler, which is required ' +\n 'in every mode (it drives the lazy, refresh, and server-function transforms; ' +\n 'compiler: \"babel\" only switches the JSX transform). Your platform should get ' +\n 'a prebuilt native binary or the @solidjs/compiler-wasm32-wasi fallback ' +\n '— check that optional dependencies were installed.' +\n reason,\n );\n }\n}\n\n/** Configuration options for @solidjs/vite-plugin. */\nexport interface Options {\n /**\n * A [picomatch](https://github.com/micromatch/picomatch) pattern, or array of patterns, which specifies the files\n * the plugin should operate on. Relative patterns are resolved against the\n * Vite root, not the invocation directory.\n */\n include?: FilterPattern;\n /**\n * A [picomatch](https://github.com/micromatch/picomatch) pattern, or array of patterns, which specifies the files\n * to be ignored by the plugin. Relative patterns are resolved against the\n * Vite root, not the invocation directory.\n */\n exclude?: FilterPattern;\n /**\n * This will inject solid-js/dev in place of solid-js in dev mode. Has no\n * effect in prod. If set to `false`, it won't inject it in dev. This is\n * useful for extra logs and debugging.\n *\n * @default true\n */\n dev?: boolean;\n /**\n * Dev-serve only: expose Solid's diagnostic and attribution channels to\n * out-of-process consumers (agents, tests, curl). Injects a client module\n * that installs the in-page bridge from the app's own\n * `@solidjs/diagnostics` (which must be installed as a dev dependency),\n * and serves a `/__solid/diagnostics` endpoint on the dev server that\n * forwards capture control (`begin`/`end`), `whyDidRun`, and cost queries\n * to the page over the Vite WebSocket. No effect on builds or preview.\n *\n * @default false\n */\n diagnostics?: boolean;\n /**\n * Whether the app is server-rendered — one meaning everywhere.\n *\n * Without {@link start}: the legacy transform-only flag, unchanged.\n * `true` enables the SSR transforms (hydratable client code, SSR server\n * code) — you provide the entries and the server yourself.\n *\n * With {@link start}: selects the start mode. `true` is SSR start mode\n * (per-request streaming render + hydration); `false`/omitted is client\n * mode (a static document shell + client-side `render()`). Flipping a\n * start-mode project between SPA and SSR is toggling this one boolean.\n *\n * The flag describes the app's initial document, not the internal\n * pipelines — client mode still compiles the document shell through the\n * SSR transforms to serve/prerender it.\n *\n * Objects are no longer accepted: start-mode options moved to {@link start}\n * (`ssr: { ... }` from 3.0.0-next.23 and earlier becomes\n * `start: { ... }, ssr: true`).\n *\n * @default false\n */\n ssr?: boolean;\n\n /**\n * Start mode — Start as a mode of the plugin: it owns entries, dev\n * serving, and the build — no index.html, no mount file, no server\n * wiring. `start: true` is the zero-config spelling, sugar for the empty\n * options bag `start: {}` (both mean the identical start mode with\n * defaults; `false`/absent is off). Conventions (shared by both modes,\n * so projects flip between them by toggling {@link ssr}): `src/App.*`\n * (or `start.app`) is the root component; `src/Document.*` (or\n * `start.document`) is the optional document shell; authored\n * `src/entry-server.*` / `src/entry-client.*` (or `start.entryServer` /\n * `start.entryClient`) replace the generated entries.\n *\n * With `ssr: true` — SSR start mode:\n *\n * - Dev: a middleware on the Vite dev server streams the rendered app for\n * HTML-accepting GET requests — `vite` just works, no server file.\n * - Build: a plain `vite build` produces both bundles (client to\n * `dist/client`, server to `dist/server` via the environments/builder\n * API). The server bundle's entry is `virtual:solid-ssr-handler`, whose\n * `handleRequest(request)` export maps a web `Request` to a streamed\n * `Response`; its default `{ fetch(request) }` export provides the same\n * handler in the Fetchable shape used by deployment integrations.\n * The normal `ssr` environment exposes it as the `index` service entry\n * so provider Vite plugins can supply the runtime and build orchestration.\n * - With `serverFunctions` also enabled, the prod handler serves the\n * server-function endpoint too (in dev the server-function middleware\n * already runs first).\n *\n * Without `ssr: true` — client mode:\n *\n * - Dev: every HTML-accepting GET streams the rendered document shell\n * (without the app — history-fallback semantics); the generated client\n * entry `render()`s the app into it.\n * - Build: `vite build` emits a static `dist/client` — the shell is\n * prerendered once through the built handler into\n * `dist/client/index.html` with the hashed entry script and CSS links —\n * deployable to any static host. No server bundle remains unless\n * `serverFunctions` is enabled, in which case `dist/server` is kept and\n * its `handleRequest` serves the endpoint (pages stay static).\n * - Client code stays non-hydratable (`generate: 'dom'`), exactly like a\n * plain SPA; server-only options (`entryServer`, `external`) are inert.\n * - `vite preview` serves the static build with history fallback (and\n * dispatches the server-function endpoint through the kept handler).\n *\n * @default undefined\n */\n start?: boolean | StartOptions;\n\n /**\n * JSX compiler backend to use. The default `\"native\"` compiles through\n * `@solidjs/compiler`; `\"babel\"` is the escape hatch running\n * `@solidjs/babel-plugin` instead — if native output ever differs from your\n * expectations, set `compiler: \"babel\"` and file an issue (the behavioral\n * diff between the modes is the bug report). Platforms without a prebuilt\n * native binary (e.g. StackBlitz WebContainers) automatically use the wasm\n * fallback; the compiler package itself is required in every mode.\n *\n * @default \"native\"\n */\n compiler?: Compiler;\n\n /**\n * This will inject HMR runtime in dev mode. Has no effect in prod. If\n * set to `false`, it won't inject the runtime in dev.\n *\n * @default true\n * @deprecated use `refresh` instead\n */\n hot?: boolean;\n /**\n * This registers additional extensions that should be processed by\n * @solidjs/vite-plugin.\n *\n * @default undefined\n */\n extensions?: (string | [string, ExtensionOptions])[];\n /**\n * Pass any additional babel transform options. They will be merged with\n * the transformations required by Solid.\n *\n * Note: with `compiler: \"native\"` the plugin is normally fully Babel-free\n * (native lazy/refresh/JSX passes). Supplying custom babel options\n * reintroduces a Babel support pass ahead of the native JSX transform to\n * host them.\n *\n * @default {}\n */\n babel?:\n | babel.TransformOptions\n | ((source: string, id: string, ssr: boolean) => babel.TransformOptions)\n | ((source: string, id: string, ssr: boolean) => Promise<babel.TransformOptions>);\n /**\n * Pass any additional [@solidjs/babel-plugin](https://github.com/solidjs/solid/tree/main/packages/babel-plugin) options.\n * They will be merged with the plugin's Solid defaults.\n *\n * @default {}\n */\n solid?: SolidOptions;\n\n /**\n * Enable `\"use server\"` server function compilation (experimental). Pass\n * `true` for the defaults (runtime from @solidjs/web/server-functions) or\n * an options object to customize. The directive transform sub-plugins are\n * emitted ahead of the JSX transform in the returned plugin array.\n *\n * Zero-config setup: in dev, a middleware on the Vite server handles the\n * endpoint (default `/_server`, joined with `base`) end to end — no\n * server-function code needed in the server entry. For production SSR\n * builds, import `virtual:solid-server-function-handler` in the server\n * entry and mount its `handleServerFunctionRequest(request)` export on the\n * endpoint; it eagerly imports every module containing server functions so\n * registrations survive tree-shaking.\n *\n * Hosts whose own server environment should own endpoint dispatch in dev\n * (e.g. @cloudflare/vite-plugin, so functions run in workerd with\n * bindings) can keep this option and set\n * `serverFunctions: { devMiddleware: false }` — see\n * {@link ServerFunctionsOptions.devMiddleware}. A server-only module can\n * be pinned into the handler graph for pre-dispatch runtime registration\n * via {@link ServerFunctionsOptions.configure}.\n *\n * Meta-frameworks that need to control plugin ordering themselves (e.g.\n * relative to a file-system router) and dispatch requests through their\n * own server should use the standalone `serverFunctions()` export instead,\n * which never installs the dev middleware.\n *\n * The object form's `components` flag additionally enables server\n * components (experimental) — `\"use server\"` functions returning a\n * component, served over the same endpoint. They come essentially for\n * free: the endpoint transform is installed automatically, and with\n * SSR start mode (the `start` option with `ssr: true`) and generated entries\n * the document wiring is emitted too. See\n * {@link ServerFunctionsOptions.components}.\n *\n * @default undefined\n */\n serverFunctions?: boolean | ServerFunctionsOptions;\n\n /** Options for the solid-refresh HMR transform (dev only). */\n refresh?: RefreshOptions;\n}\n\n/** Options for the solid-refresh HMR transform (dev only). */\nexport interface RefreshOptions {\n /**\n * Disable the refresh transform entirely (equivalent to the deprecated\n * `hot: false`).\n */\n disabled?: boolean;\n /**\n * Emit per-component `signature`/`dependencies` metadata so edits only\n * remount components whose code actually changed.\n *\n * @default true\n */\n granular?: boolean;\n}\n\nfunction getExtension(filename: string): string {\n const index = filename.lastIndexOf('.');\n return index < 0 ? '' : filename.substring(index).replace(/\\?.+$/, '');\n}\nfunction containsSolidField(fields: Record<string, any>) {\n const keys = Object.keys(fields);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n if (key === 'solid') return true;\n if (typeof fields[key] === 'object' && fields[key] != null && containsSolidField(fields[key]))\n return true;\n }\n return false;\n}\n\nfunction getJestDomExport(setupFiles: string[]) {\n return setupFiles?.some((path) => /jest-dom/.test(path))\n ? undefined\n : ['@testing-library/jest-dom/vitest', '@testing-library/jest-dom/extend-expect'].find(\n (path) => {\n try {\n require.resolve(path);\n return true;\n } catch (e) {\n return false;\n }\n },\n );\n}\n\nfunction getSolidOptions(\n options: Partial<Options>,\n isSsr: boolean,\n dev: boolean,\n isTestMode = false,\n): SolidOptions {\n let solidOptions: Pick<SolidOptions, 'generate' | 'hydratable'>;\n\n if (isTestMode) {\n // Vitest compiles with the client posture regardless of the app's `ssr`\n // flag: component tests exercise DOM code and nothing hydrates in a\n // test, so hydratable output would look for markers that aren't there.\n // `generate` still follows the transform's own ssr flag, so explicit\n // node-environment tests (renderToString) keep their server codegen.\n solidOptions = { generate: isSsr ? 'ssr' : 'dom', hydratable: false };\n } else if (options.start && !options.ssr) {\n // Client start mode: client code compiles exactly like a plain SPA\n // (dom, non-hydratable — nothing hydrates); only the document shell\n // render goes through the SSR transforms, also non-hydratable since\n // the shell is inert HTML the client never claims.\n solidOptions = { generate: isSsr ? 'ssr' : 'dom', hydratable: false };\n } else if (options.ssr) {\n if (isSsr) {\n solidOptions = { generate: 'ssr', hydratable: true };\n } else {\n solidOptions = { generate: 'dom', hydratable: true };\n }\n } else {\n solidOptions = { generate: 'dom', hydratable: false };\n }\n\n // Server components (serverFunctions.components) turn on the SSR-side\n // behavior-claims transform: ref/on* positions on intrinsic elements\n // compile to guarded `_bnd` claim holes instead of dropping. SSR-only\n // by construction (the dom generate ignores the flag), and apps without\n // the flag compile byte-for-byte as before.\n const serverComponents =\n typeof options.serverFunctions === 'object' && !!options.serverFunctions.components;\n\n // Solid-specific defaults (moduleName \"@solidjs/web\", the control-flow\n // builtIns, contextToCustomElements, wrapConditionals) are baked into both\n // backends — @solidjs/compiler and @solidjs/babel-plugin — so only the\n // posture this plugin actually decides is passed.\n return {\n ...solidOptions,\n ...(serverComponents && solidOptions.generate === 'ssr' ? { serverComponents: true } : {}),\n dev,\n ...(options.solid || {}),\n };\n}\n\nasync function getBabelUserOptions(\n options: Partial<Options>,\n source: string,\n id: string,\n isSsr: boolean,\n) {\n if (!options.babel) return {};\n if (typeof options.babel !== 'function') return options.babel;\n\n const babelOptions = options.babel(source, id, isSsr);\n return babelOptions instanceof Promise ? await babelOptions : babelOptions;\n}\n\nfunction normalizeSourceMap(\n map: string | babel.TransformOptions['inputSourceMap'] | null | undefined,\n) {\n if (typeof map === 'string') return JSON.parse(map);\n return map || null;\n}\n\ntype ChainableMap = string | babel.TransformOptions['inputSourceMap'] | null | undefined;\n\n/**\n * Merges the sourcemaps of sequential whole-file transforms (given in\n * application order, earliest first) into one map tracing back to the\n * original source.\n */\nfunction combineSourcemaps(maps: ChainableMap[]) {\n const chain = maps.filter((map): map is NonNullable<ChainableMap> => !!map);\n if (chain.length === 0) return null;\n if (chain.length === 1) return normalizeSourceMap(chain[0]);\n // remapping expects most-recent-first.\n return JSON.parse(remapping(chain.reverse() as any, () => null).toString());\n}\n\n/**\n * Chunks emitted for lazy() targets are marked `isEntry` by Rollup even\n * though they are semantically dynamic entries. Reclassify any entry that is\n * dynamically imported by another chunk so the runtime's entry-asset\n * detection (which keys off `isEntry`) can't pick a lazy facade instead of\n * the real client entry. Works on both the Vite manifest.json shape and the\n * raw Rollup output bundle — both key entries by name and expose\n * `dynamicImports` / `isEntry` with the same meaning.\n */\nfunction normalizeEmittedLazyEntries(manifest: Record<string, any>) {\n const dynamicKeys = new Set<string>();\n for (const key in manifest) {\n const imports: string[] | undefined = manifest[key].dynamicImports;\n if (imports) for (const dep of imports) dynamicKeys.add(dep);\n }\n for (const key of dynamicKeys) {\n const entry = manifest[key];\n if (entry && entry.isEntry) {\n entry.isEntry = false;\n entry.isDynamicEntry = true;\n }\n }\n}\n\nexport default function solidPlugin(options: Partial<Options> = {}): Plugin[] {\n if (typeof options.ssr === 'object') {\n throw new Error(\n '[@solidjs/vite-plugin] `ssr` now only accepts a boolean (\"is the app server-rendered\"); ' +\n 'move start-mode options to `start: {}` and set `ssr: true`. Example: ' +\n '`solid({ ssr: { document: … } })` becomes `solid({ start: { document: … }, ssr: true })`.',\n );\n }\n // Recreated in configResolved: relative include/exclude patterns must\n // resolve against the Vite root, not process.cwd() — running `vite` from\n // outside the project would otherwise change what the filter matches.\n let filter = createFilter(options.include, options.exclude);\n const serverComponents =\n typeof options.serverFunctions === 'object' && !!options.serverFunctions.components;\n // `start: true` is sugar for the empty options bag — one start mode,\n // two spellings — so normalize here and let everything downstream see a\n // single shape (`false` behaves exactly like omission).\n const startOptions: StartOptions | null =\n options.start === true ? {} : options.start || null;\n const styleFilterOptions = startOptions?.css?.filter;\n // The CSS crawl walks the module graph from the app's own entries, so a\n // plain createFilter allowlist can't express the option's purpose (opting\n // node_modules graphs in): a bare `include` would reject the app sources\n // the crawl has to traverse to ever reach the included package. Instead\n // `include` rescues files on top of the baseline (everything except\n // `exclude`, which defaults to node_modules), while a file matching both\n // patterns stays excluded — createFilter's own conflict rule.\n const createStyleFilter = (resolve?: string) => {\n const opts = resolve === undefined ? undefined : { resolve };\n const base = createFilter(\n undefined,\n styleFilterOptions?.exclude ?? DEFAULT_STYLE_EXCLUDE,\n opts,\n );\n const include = styleFilterOptions?.include;\n const hasInclude = include != null && (!Array.isArray(include) || include.length > 0);\n const included = hasInclude ? createFilter(include, styleFilterOptions?.exclude, opts) : null;\n return (id: string) => base(id) || (included ? included(id) : false);\n };\n let styleFilter = createStyleFilter();\n const filterDevStyles = (id: string) => styleFilter(id);\n // `start.external` only means something when a server side exists to hand\n // over (SSR start mode); in client mode it is a documented no-op.\n const externalDevServer = !!options.ssr && !!startOptions?.external;\n\n let needHmr = false;\n let replaceDev = false;\n // The live dev server, kept so the dev manifest module can bake the bridge\n // endpoint URL in when its code is generated (see devManifestBridgeUrl).\n let devServer: ViteDevServer | null = null;\n let projectRoot = process.cwd();\n let isTestMode = false;\n let serverTestPosture = false;\n let isBuild = false;\n let isSsrBuild = false;\n let base = '/';\n let clientOutDir: string | null = null;\n let solidPkgsConfig: Awaited<ReturnType<typeof crawlFrameworkPkgs>>;\n\n // The client build's manifest, read back by SSR builds. In builder-mode\n // (single process, e.g. SolidStart's nitro plugin) the client build runs\n // first and generateBundle records its actual outDir — authoritative, since\n // such setups relocate it. Two-invocation builds (`vite build --outDir\n // dist/client` then `vite build --ssr`) run in separate processes, so the\n // SSR process falls back to the `dist/client` convention.\n function clientManifestPath(): string | null {\n for (const dir of [clientOutDir, 'dist/client']) {\n if (!dir) continue;\n const manifestPath = path.resolve(projectRoot, dir, '.vite/manifest.json');\n if (existsSync(manifestPath)) return manifestPath;\n }\n return null;\n }\n\n // Dynamically imported project modules in the client build. Each is\n // emitted as an explicit chunk so it always gets its own manifest entry\n // keyed by source path — even when manualChunks or dual static/dynamic\n // imports would otherwise fold it facade-less into a shared chunk (which\n // would break resolveAssets lookups and hydration module preloading).\n // Driven from moduleParsed so it covers every lazy() target, including\n // import.meta.glob entries that never pass through the moduleUrl transform.\n const emittedLazyChunks = new Set<string>();\n // Keep the emitted references because a lazy module's importer may be\n // removed from the final bundle, leaving no dynamic-import edge to identify\n // its facade chunk during generateBundle.\n const emittedLazyChunkRefs: string[] = [];\n\n // Whether the current hook invocation belongs to a client (browser) build.\n // Builder-mode builds (e.g. SolidStart's nitro plugin) run the client and\n // ssr environments through one Vite process with shared plugins, so the\n // process-wide isSsrBuild flag from configResolved can't tell them apart —\n // the per-environment consumer can. Classic two-invocation builds\n // (`vite build` / `vite build --ssr`) fall back to the flag.\n function isClientBuild(ctx: { environment?: { config?: { consumer?: string } } }): boolean {\n const consumer = ctx.environment?.config?.consumer;\n if (consumer) return consumer === 'client';\n return !isSsrBuild;\n }\n\n /**\n * Replaces lazy() moduleUrl placeholders injected by the babel plugin with\n * project-relative module paths resolved through Vite's resolver.\n */\n async function resolveLazyModuleUrls(ctx: any, code: string, importer: string): Promise<string> {\n const placeholderRe = new RegExp('\"' + LAZY_PLACEHOLDER_PREFIX + '([^\"]+)\"', 'g');\n let match;\n const resolutions: Array<{ placeholder: string; resolved: string }> = [];\n while ((match = placeholderRe.exec(code)) !== null) {\n const specifier = match[1];\n const resolved = await ctx.resolve(specifier, importer);\n if (resolved) {\n // The query is part of the module identity: Rollup keys the facade\n // chunk (and thus the Vite manifest entry) by the queried module id,\n // and in dev the queried URL can serve different plugin output than\n // the bare one — stripping it here would break both lookups.\n const queryIndex = resolved.id.indexOf('?');\n const file = queryIndex === -1 ? resolved.id : resolved.id.slice(0, queryIndex);\n const query = queryIndex === -1 ? '' : resolved.id.slice(queryIndex);\n const relativeId = path.relative(projectRoot, file).split(path.sep).join('/') + query;\n resolutions.push({\n placeholder: match[0],\n resolved: '\"' + relativeId + '\"',\n });\n }\n }\n for (const { placeholder, resolved } of resolutions) {\n code = code.replace(placeholder, resolved);\n }\n return code;\n }\n\n /**\n * SSR transforms append a `$$moduleUrl` export carrying the module's\n * client-manifest key (project-relative source path, module query\n * included — a queried module is its own identity, with its own facade\n * chunk and manifest entry). Server-side `lazy()` reads it off the\n * resolved module when the callsite has no static import specifier to\n * transform — e.g. `lazy` over an `import.meta.glob` entry — so asset\n * resolution and hydration preloading still work. Client builds are\n * untouched.\n */\n function injectSsrModuleId(code: string, id: string, isSsr: boolean): string {\n if (!isSsr || /node_modules/.test(id) || code.includes('$$moduleUrl')) return code;\n const queryIndex = id.indexOf('?');\n const file = queryIndex === -1 ? id : id.slice(0, queryIndex);\n const query = queryIndex === -1 ? '' : id.slice(queryIndex);\n const relativeId = path.relative(projectRoot, file).split(path.sep).join('/') + query;\n return code + `\\nexport const $$moduleUrl = ${JSON.stringify(relativeId)};\\n`;\n }\n\n const mainPlugin: Plugin = {\n name: 'solid',\n enforce: 'pre',\n\n async config(userConfig, { command }) {\n // We inject the dev mode only if the user explicitly wants it or if we are in dev (serve) mode\n replaceDev = options.dev === true || (options.dev !== false && command === 'serve');\n projectRoot = userConfig.root || projectRoot;\n isTestMode = userConfig.mode === 'test';\n // Per-vitest-project posture: the client posture (browser conditions,\n // dom codegen, jsdom default) is right for DOM component tests but\n // wrong for server-runtime unit tests. A project that explicitly opts\n // into a server runtime — `test: { environment: 'node' }` (or\n // 'edge-runtime') — gets the server posture end to end: no browser\n // condition injection, so the framework resolves its real server\n // build (isServer true) with no inline/alias workarounds. DOM\n // environments (the jsdom default, happy-dom, browser mode) keep the\n // client posture. Each vitest project resolves its own config, so the\n // hooks below see the posture of the project they serve.\n serverTestPosture =\n isTestMode &&\n ((userConfig as any).test?.environment === 'node' ||\n (userConfig as any).test?.environment === 'edge-runtime');\n\n solidPkgsConfig = await crawlFrameworkPkgs({\n viteUserConfig: userConfig,\n root: projectRoot || process.cwd(),\n isBuild: command === 'build',\n isFrameworkPkgByJson(pkgJson) {\n return containsSolidField(pkgJson.exports || {});\n },\n });\n\n // fix for bundling dev in production\n const nestedDeps = replaceDev ? ['solid-js', '@solidjs/web'] : [];\n\n const userTest = (userConfig as any).test ?? {};\n const test = {} as any;\n if (userConfig.mode === 'test') {\n // to simplify the processing of the config, we normalize the setupFiles to an array\n const userSetupFiles: string[] =\n typeof userTest.setupFiles === 'string'\n ? [userTest.setupFiles]\n : userTest.setupFiles || [];\n\n // Regardless of the app's `ssr` flag: tests run with the client\n // posture (DOM component tests are the norm), so the default test\n // environment is a DOM. Node-environment tests opt in explicitly.\n // Browser-mode projects get the real browser DOM, so don't default\n // them to jsdom — vitest probes for the environment's package at\n // startup and fails the run if jsdom isn't installed. They fall\n // back to vitest's own node default (no package probe).\n if (!userTest.environment && !userTest.browser?.enabled) {\n test.environment = 'jsdom';\n }\n\n if (serverTestPosture) {\n // The worker pool is shared across the whole vitest workspace and\n // imports externalized deps natively with `--conditions` derived\n // from the ROOT config — which carries the client posture's\n // 'browser'. Inline the framework so every resolution goes through\n // THIS project's (server) conditions instead: one server-build\n // instance end to end (request-event storage included).\n if (!userTest.server?.deps?.inline) {\n test.server = { deps: { inline: [/solid-js/, /@solidjs[+/]web/] } };\n }\n } else if (\n !userTest.server?.deps?.external?.find((item: string | RegExp) =>\n /solid-js/.test(item.toString()),\n )\n ) {\n test.server = { deps: { external: [/solid-js/] } };\n }\n // jest-dom's DOM matchers have no place in a server-posture project;\n // vitest browser mode already has bundled jest-dom assertions\n // https://main.vitest.dev/guide/browser/assertion-api.html#assertion-api\n if (!userTest.browser?.enabled && !serverTestPosture) {\n const jestDomImport = getJestDomExport(userSetupFiles);\n if (jestDomImport) {\n test.setupFiles = [jestDomImport];\n }\n }\n }\n\n return {\n /**\n * We only need esbuild on .ts or .js files.\n * .tsx & .jsx files are handled by us\n */\n // esbuild: { include: /\\.ts$/ },\n // resolve.conditions is handled per-environment in configEnvironment.\n resolve: {\n dedupe: nestedDeps,\n },\n optimizeDeps: {\n include: [\n ...nestedDeps,\n // Dev refresh wrappers import the solid-js/refresh runtime in\n // every mode; pre-bundle it up front so its discovery doesn't\n // trigger a re-optimize + full reload on first use.\n ...(command === 'serve' && options.hot !== false && !options.refresh?.disabled\n ? [REFRESH_RUNTIME_SOURCE]\n : []),\n // The server-components client runtime is imported by the\n // (virtual) client entry, and compiled function references\n // import the server-function client runtime; pre-bundle both up\n // front — in one optimizer pass — so a mid-session discovery\n // can't trigger a re-optimize + full reload, and both entries\n // share one instance of the transport config module (the\n // server-components runtime installs its response policy there).\n ...(command === 'serve' && serverComponents\n ? ['@solidjs/web/frames', '@solidjs/web/server-functions']\n : []),\n ...solidPkgsConfig.optimizeDeps.include,\n ],\n exclude: solidPkgsConfig.optimizeDeps.exclude,\n // Keep Solid TSX from injecting React's automatic runtime during scanning.\n rolldownOptions: { transform: { jsx: { runtime: 'classic' as const } } },\n },\n ...(Object.keys(test).length ? { test } : {}),\n };\n },\n\n configEnvironment(name, config, opts) {\n config.resolve ??= {};\n // Emulate Vite default fallback for `resolve.conditions` if not set\n if (config.resolve.conditions == null) {\n if (config.consumer === 'client' || name === 'client' || opts.isSsrTargetWebworker) {\n config.resolve.conditions = [...defaultClientConditions];\n } else {\n config.resolve.conditions = [...defaultServerConditions];\n }\n }\n config.resolve.conditions = [\n 'solid',\n ...(replaceDev ? ['development'] : []),\n // Tests resolve the browser builds even when the app is\n // server-rendered — the client posture applies to the whole test\n // pipeline, not just the codegen. Projects that explicitly opt into\n // a server runtime (`test.environment: 'node'` / 'edge-runtime')\n // keep the default server conditions instead, so the framework's\n // real server build resolves (isServer true).\n ...(isTestMode && !serverTestPosture && !opts.isSsrTargetWebworker ? ['browser'] : []),\n ...config.resolve.conditions,\n ];\n\n // Set resolve.noExternal and resolve.external for the SSR environment.\n // Only set resolve.external if noExternal is not true (to avoid conflicts with plugins like Cloudflare)\n if (name === 'ssr' && solidPkgsConfig) {\n if (config.resolve.noExternal !== true) {\n config.resolve.noExternal = [\n ...(Array.isArray(config.resolve.noExternal) ? config.resolve.noExternal : []),\n ...solidPkgsConfig.ssr.noExternal,\n ];\n config.resolve.external = [\n ...(Array.isArray(config.resolve.external) ? config.resolve.external : []),\n ...solidPkgsConfig.ssr.external,\n ];\n }\n }\n },\n\n configResolved(config) {\n isBuild = config.command === 'build';\n isSsrBuild = !!config.build.ssr;\n base = config.base;\n projectRoot = config.root;\n filter = createFilter(options.include, options.exclude, { resolve: projectRoot });\n styleFilter = createStyleFilter(projectRoot);\n if (serverComponents && !(options.start && options.ssr)) {\n config.logger.warn(\n '[@solidjs/vite-plugin] serverFunctions.components is set without SSR start mode (the `start` ' +\n 'option with `ssr: true`), so the plugin only installs the endpoint response transform ' +\n '(server functions returning components stream correctly). The document wiring — render ' +\n 'plugin, bootstrap script, and the client-side installServerComponents() call — is ' +\n \"emitted by SSR start mode's generated entries; without it, server components only mount \" +\n 'from post-boot streams and your client code must call installServerComponents() itself.',\n );\n }\n needHmr =\n config.command === 'serve' &&\n config.mode !== 'production' &&\n options.hot !== false &&\n !options.refresh?.disabled;\n },\n\n configureServer(server) {\n devServer = server;\n // Dev asset resolution for SSR: the virtual manifest module (evaluated\n // in the SSR environment) picks this resolver up through the global\n // registry keyed by project root — or, from isolated module runners\n // that don't share globals with this process, through the HTTP bridge\n // endpoint the middleware serves.\n if (options.ssr || options.start) {\n registerDevAssetResolver(\n server.config.root,\n createDevAssetResolver(server, filterDevStyles),\n );\n installDevManifestBridge(server);\n }\n if (!needHmr) return;\n // When a module has a syntax error, Vite sends the error overlay via\n // WebSocket but the failed import triggers invalidation in solid-refresh.\n // This propagates up to @refresh reload boundaries (e.g. document-level\n // App components in SSR), causing a full-reload that overrides the overlay.\n // We suppress update/full-reload messages that immediately follow an error.\n const hot = server.hot ?? (server as any).ws;\n if (!hot) return;\n let lastErrorTime = 0;\n const origSend = hot.send.bind(hot);\n hot.send = function (this: any, ...args: any[]) {\n const payload = args[0];\n if (typeof payload === 'object' && payload) {\n if (payload.type === 'error') {\n lastErrorTime = Date.now();\n } else if (\n lastErrorTime &&\n (payload.type === 'full-reload' || payload.type === 'update')\n ) {\n if (Date.now() - lastErrorTime < 200) return;\n lastErrorTime = 0;\n }\n }\n return origSend(...args);\n } as typeof hot.send;\n },\n\n hotUpdate({ modules }) {\n // solid-refresh only injects HMR boundaries into client modules, so\n // non-client environments have no accept handlers. Without this, Vite\n // would see no boundaries and send full-reload messages that race with\n // client-side HMR updates. Provider-owned (non-runnable) environments\n // fall through instead: their plugin needs the real module list to\n // invalidate its remote runner, and its channel never reaches the\n // browser websocket.\n if (this.environment.name !== 'client' && isRunnableEnvironment(this.environment)) {\n // Returning [] also suppresses the signal environment-runner based\n // servers (e.g. nitro's dev worker) rely on to re-evaluate modules,\n // leaving SSR stale until a manual restart. Send the reload on this\n // environment's own channel — for runner-based environments that is\n // the runner, for the default ssr environment a no-op, and never the\n // browser websocket, so client HMR stays free of full-reload races.\n if (modules.length > 0) {\n this.environment.hot.send({ type: 'full-reload' });\n }\n return [];\n }\n },\n\n resolveId(id) {\n if (id === VIRTUAL_MANIFEST_ID) return RESOLVED_VIRTUAL_MANIFEST_ID;\n },\n\n moduleParsed(info) {\n // SSR-mode client builds only: give every dynamically imported project\n // module its own facade chunk (exports-only preserves `default`\n // re-exports) so it keeps a manifest entry keyed by its source path\n // even when chunk grouping would otherwise absorb it. Plain SPA builds\n // have no manifest lookups to protect.\n if (!isBuild || !options.ssr || !isClientBuild(this)) return;\n for (const depId of info.dynamicallyImportedIds || []) {\n const cleanId = depId.split('?')[0];\n if (/node_modules/.test(cleanId) || cleanId.startsWith('\\0')) continue;\n if (!/\\.[mc]?[tj]sx?$/i.test(cleanId)) continue;\n if (emittedLazyChunks.has(depId)) continue;\n emittedLazyChunks.add(depId);\n emittedLazyChunkRefs.push(\n this.emitFile({ type: 'chunk', id: depId, preserveSignature: 'exports-only' }),\n );\n }\n },\n\n load(id) {\n if (id === RESOLVED_VIRTUAL_MANIFEST_ID) {\n if (!isBuild) {\n return devManifestCode(\n projectRoot,\n base,\n devServer ? devManifestBridgeUrl(devServer) : null,\n );\n }\n const manifestPath = clientManifestPath();\n if (manifestPath) {\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n normalizeEmittedLazyEntries(manifest);\n manifest._base = base;\n return `export default ${JSON.stringify(manifest)};`;\n }\n // SSR build before the client build produced a manifest: bake in the\n // dev-shaped fallback (registry miss degrades to js-only resolution).\n return devManifestCode(projectRoot, base, null);\n }\n },\n\n generateBundle(outputOptions, bundle) {\n if (!isBuild || !isClientBuild(this)) return;\n clientOutDir = outputOptions.dir ?? null;\n // Reclassify emitted lazy facade chunks in the raw bundle (not just the\n // serialized manifest read back later) so downstream plugins inspecting\n // the bundle don't mistake them for application entries. Must precede\n // the client asset map build, which keys off dynamic entries.\n if (options.ssr) {\n for (const ref of emittedLazyChunkRefs) {\n let fileName: string;\n try {\n fileName = this.getFileName(ref);\n } catch {\n // Ignore references retained from a previous watch build.\n continue;\n }\n const chunk = bundle[fileName];\n if (!chunk || chunk.type !== 'chunk') continue;\n chunk.isEntry = false;\n chunk.isDynamicEntry = true;\n }\n normalizeEmittedLazyEntries(bundle);\n }\n },\n\n async transform(source, id, transformOptions) {\n const isSsr = getEnvironmentConsumer(this.environment, transformOptions) === 'server';\n const currentFileExtension = getExtension(id);\n\n const extensionsToWatch = options.extensions || [];\n const allExtensions = extensionsToWatch.map((extension) =>\n // An extension can be a string or a tuple [extension, options]\n typeof extension === 'string' ? extension : extension[0],\n );\n\n if (!filter(id)) {\n return null;\n }\n\n // The queried id is the module's real identity (facade chunk /\n // manifest key / dev URL); keep it for the `$$moduleUrl` injection\n // while the transform pipeline below works on the clean file path.\n const moduleId = id;\n id = id.replace(/\\?.*$/, '');\n\n if (!(/\\.[mc]?[tj]sx$/i.test(id) || allExtensions.includes(currentFileExtension))) {\n return null;\n }\n\n const inNodeModules = /node_modules/.test(id);\n const solidOptions = getSolidOptions(options, !!isSsr, replaceDev, isTestMode);\n\n // We need to know if the current file extension has a typescript options tied to it\n const shouldBeProcessedWithTypescript =\n /\\.[mc]?tsx$/i.test(id) ||\n extensionsToWatch.some((extension) => {\n if (typeof extension === 'string') {\n return extension.includes('tsx');\n }\n\n const [extensionName, extensionOptions] = extension;\n if (extensionName !== currentFileExtension) return false;\n\n return extensionOptions.typescript;\n });\n const plugins: NonNullable<NonNullable<babel.TransformOptions['parserOpts']>['plugins']> = [\n 'jsx',\n 'decorators',\n ];\n\n if (shouldBeProcessedWithTypescript) {\n plugins.push('typescript');\n }\n\n const needRefresh = needHmr && !isSsr && !inNodeModules;\n\n const babelUserOptions = await getBabelUserOptions(options, source, id, !!isSsr);\n\n // The native compiler picks its parser dialect from the file\n // extension; custom extensions registered through `options.extensions`\n // are unknown to it, so borrow a standard one matching the configured\n // TypeScript-ness.\n const nativeFilename = /\\.(?:[mc]?[jt]s|[jt]sx)$/i.test(id)\n ? id\n : id + (shouldBeProcessedWithTypescript ? '.tsx' : '.jsx');\n\n // Shared native prelude for every mode: the lazy() module-URL pass,\n // then (dev/client/non-node_modules) the solid-refresh HMR pass, both\n // operating on pre-JSX source. Only the JSX transform itself differs\n // between compiler backends. Sourcemaps are collected in application\n // order and merged at the end.\n const compiler = await loadNativeCompiler();\n let code = source;\n const maps: ChainableMap[] = [];\n\n const lazyResult = await compiler.transformLazyAsync(code, {\n filename: nativeFilename,\n sourceMap: true,\n });\n code = lazyResult.code;\n maps.push(lazyResult.map);\n\n if (needRefresh) {\n const refreshResult = await compiler.transformRefreshAsync(code, {\n filename: nativeFilename,\n bundler: 'vite',\n fixRender: true,\n // The napi validator rejects explicit undefined; omit to get the\n // pass's default (true).\n ...(typeof options.refresh?.granular === 'boolean'\n ? { granular: options.refresh.granular }\n : {}),\n jsx: false,\n importSource: REFRESH_RUNTIME_SOURCE,\n sourceMap: true,\n });\n code = refreshResult.code;\n maps.push(refreshResult.map);\n }\n\n const babelBaseOptions: babel.TransformOptions = {\n root: projectRoot,\n filename: id,\n sourceFileName: id,\n ast: false,\n sourceMaps: true,\n configFile: false,\n babelrc: false,\n parserOpts: {\n plugins,\n },\n };\n\n if (options.compiler !== 'babel') {\n if (options.babel) {\n // Custom babel options reintroduce a Babel support pass hosting\n // only the user's plugins, ahead of the native JSX transform.\n const supportOptions = mergeAndConcat(\n babelUserOptions,\n babelBaseOptions,\n ) as babel.TransformOptions;\n const supportResult = await babel.transformAsync(code, supportOptions);\n if (!supportResult) {\n return undefined;\n }\n code = supportResult.code || '';\n maps.push(supportResult.map);\n }\n\n const result = await compiler.transformAsync(code, {\n ...solidOptions,\n filename: nativeFilename,\n sourceMap: true,\n });\n maps.push(result.map);\n\n const finalCode = injectSsrModuleId(\n await resolveLazyModuleUrls(this, result.code || '', id),\n moduleId,\n !!isSsr,\n );\n\n return { code: finalCode, map: combineSourcemaps(maps) };\n }\n\n // Babel JSX backend: one babel.transformAsync hosting the user's\n // options plus @solidjs/babel-plugin. Appended to `plugins` (was the\n // sole preset pre-rename): user plugins still run before it, user\n // presets still run after — babel runs plugins before presets and\n // presets in reverse order, so the pass order is unchanged.\n const babelOptions = mergeAndConcat(babelUserOptions, {\n ...babelBaseOptions,\n plugins: [[solid, solidOptions]],\n }) as babel.TransformOptions;\n\n const result = await babel.transformAsync(code, babelOptions);\n if (!result) {\n return undefined;\n }\n maps.push(result.map);\n\n const finalCode = injectSsrModuleId(\n await resolveLazyModuleUrls(this, result.code || '', id),\n moduleId,\n !!isSsr,\n );\n\n return { code: finalCode, map: combineSourcemaps(maps) };\n },\n };\n\n // The directive transform must run before the JSX transform (it operates\n // on raw directives, and client-mode module-level extraction must happen\n // before templates are generated), so its sub-plugins go first. The\n // boundary markers (`server-only` / `client-only`) are always on.\n const plugins: Plugin[] = options.serverFunctions\n ? [\n boundaryModules(),\n ...serverFunctions(options.serverFunctions === true ? {} : options.serverFunctions, {\n devMiddleware: true,\n externalDevServer,\n // With start mode on (either variant), the dev middleware dispatches\n // the endpoint through the SSR handler so user middleware and the\n // stub-backed request event front it exactly like page SSR.\n ...(startOptions ? { ssrHandler: SSR_HANDLER_ID } : {}),\n }),\n mainPlugin,\n ]\n : [boundaryModules(), mainPlugin];\n\n // The `start` option opts into start-mode serving on top of the transforms;\n // the `ssr` boolean picks the mode (a bare `ssr: true` keeps the\n // historical transform-only behavior).\n if (startOptions) {\n plugins.push(\n // Typed env (`start.env`) rides both start modes: config-time\n // validation, the virtual:env/{server,client} modules, generated\n // types, and the client-bundle leak scan.\n ...startEnv(startOptions.env),\n ...startServe(startOptions, {\n serverFunctions: !!options.serverFunctions,\n serverComponents,\n ssr: !!options.ssr,\n styleFilter: filterDevStyles,\n diagnostics: !!options.diagnostics,\n }),\n );\n }\n\n // Agent diagnostics endpoint + injected bridge (dev serve only — the\n // plugin no-ops itself for builds and preview via `apply`).\n if (options.diagnostics) {\n plugins.push(solidDiagnostics());\n }\n\n // Builder-mode (environments API) client-before-server build ordering.\n // Server builds read the client manifest — `virtual:solid-manifest` bakes\n // dist/client/.vite/manifest.json in, and the persisted server-function\n // manifest merges the client build's discoveries — so the client\n // environment must build first. Start mode's own orchestration already\n // orders it that way (environment definition order), but a composed setup\n // whose orchestrator builds server environments first (e.g.\n // @cloudflare/vite-plugin's buildApp, which builds workers before client)\n // would bake a manifest-less fallback into the server bundle. Every user\n // of such a setup had to hand-write this ordering plugin; absorb it.\n //\n // Semantics:\n // - The first hook builds the client environment first, but only where\n // the ordering matters: a client build that emits a manifest and\n // actually has an input. It runs at *normal* order, deliberately not\n // `pre`: pre-order buildApp hooks are where hosts do destructive\n // preparation — nitro v3's `nitro:prepare` rm -rf's the whole output\n // directory from a pre-order hook, so a pre-order client build sorted\n // before it built into a directory that was then wiped (client assets\n // and manifest gone, the manifest-less fallback baked into the server\n // bundle, prod 500s). Normal order still runs before every known\n // server-first orchestrator: a config-level `builder.buildApp`\n // (@cloudflare/vite-plugin's workers-before-client orchestrator) is\n // invoked by Vite only after all pre- and normal-order plugin hooks\n // (just before the first post-order hook), and hook-based orchestrators\n // (nitro's `nitro:main`, cloudflare's own companion hook) declare\n // post order. Orchestrators running after skip the client via `isBuilt`\n // (or at worst rebuild it, which is wasteful but correct — the manifest\n // exists either way when the server environments build).\n // - Building anything from a hook suppresses Vite's own\n // build-all-environments fallback (it only runs when *no* environment\n // is built), so a setup with no real orchestrator — e.g. start mode's\n // plain `builder: {}` — would end up with only the client built. The\n // post-order hook reinstates exactly that fallback: when nothing but\n // our own client build has happened and no other plugin stakes a claim\n // on the app build, build the remaining environments in definition\n // order, precisely what Vite would have done. Another plugin declaring\n // a non-pre `buildApp` hook counts as such a claim even when it hasn't\n // built anything yet (its post-order hook may sort after ours):\n // building on its behalf would break staged orchestration (nitro\n // prerenders and copies public assets before its final server bundle)\n // and can error outright on environments the orchestrator knows to\n // skip (e.g. ones with no rollup input). Pre-order hooks don't count —\n // by convention they prepare (clean output dirs) rather than build.\n if (options.ssr) {\n let clientBuiltFirst = false;\n plugins.push(\n {\n name: 'solid:client-build-first',\n apply: 'build',\n async buildApp(builder) {\n const client = builder.environments.client;\n if (!client || client.isBuilt) return;\n const clientBuild = client.config.build;\n const hasInput =\n !!clientBuild.rollupOptions?.input ||\n existsSync(path.resolve(builder.config.root, 'index.html'));\n if (!clientBuild.manifest || !hasInput) return;\n await builder.build(client);\n clientBuiltFirst = true;\n },\n },\n {\n name: 'solid:client-build-first/complete',\n apply: 'build',\n buildApp: {\n order: 'post',\n async handler(builder) {\n if (!clientBuiltFirst) return;\n // Another plugin declares its own (non-pre) buildApp hook — the\n // app build is spoken for, even if that hook sorts after this\n // one and hasn't run yet.\n const otherOrchestrator = builder.config.plugins.some((p) => {\n if (!p.buildApp || p.name.startsWith('solid:client-build-first')) return false;\n return typeof p.buildApp !== 'object' || p.buildApp.order !== 'pre';\n });\n if (otherOrchestrator) return;\n const environments = Object.values(builder.environments);\n // A config-level orchestrator built something of its own — the\n // app build is spoken for, don't build environments it may have\n // skipped intentionally.\n if (environments.some((env) => env.isBuilt && env.name !== 'client')) return;\n for (const environment of environments) {\n if (!environment.isBuilt) await builder.build(environment);\n }\n },\n },\n },\n );\n }\n\n return plugins;\n}\n\nexport type ViteManifest = Record<\n string,\n {\n file: string;\n css?: string[];\n isEntry?: boolean;\n isDynamicEntry?: boolean;\n imports?: string[];\n }\n> & {\n _base?: string;\n};\n"],"names":["webRequestFromNode","req","urlPath","res","protocol","socket","encrypted","host","headers","url","URL","Headers","key","value","Object","entries","undefined","Array","isArray","item","append","signal","controller","AbortController","once","writableEnded","abort","method","body","Readable","toWeb","Request","duplex","sendWebResponse","response","statusCode","status","cookies","getSetCookie","forEach","setHeader","length","cancel","catch","end","reader","getReader","on","done","read","destroyed","write","drained","Promise","resolve","settle","ok","off","onDrain","onGone","destroy","joinBase","base","pathname","startsWith","endsWith","slice","defaultStyleFilter","id","includes","DEV_MANIFEST_REGISTRY_KEY","registerDevAssetResolver","root","resolver","Symbol","for","registry","globalThis","DEV_MANIFEST_ENDPOINT","installDevManifestBridge","server","config","replace","basedEndpoint","middlewares","use","next","searchParams","get","console","error","assets","JSON","stringify","devManifestBridgeUrl","local","resolvedUrls","origin","middlewareMode","address","httpServer","https","port","cssFileRegExp","nonAmbientQueryRegExp","NULL_BYTE_PLACEHOLDER","wrapId","devStylePatch","getModuleNode","env","file","importer","resolved","fetchModule","moduleGraph","getModuleById","collectModuleDeps","deps","crawled","filter","onFile","add","node","has","isCss","test","split","transformResult","transformRequest","directDeps","dep","injectQuery","query","collectDevStyleSources","files","Set","css","seen","cleanUrl","push","collectDevStyles","ssrEnv","environments","ssr","clientEnv","client","sources","map","path","source","result","code","content","attrs","escapeAttr","renderDevStyleTag","desc","name","String","devModuleUrl","queryIndex","indexOf","absolute","sep","join","createDevAssetResolver","Map","pending","generation","watcher","clear","resolveDevAssets","cached","walk","startedAt","js","then","set","delete","resolveSync","isRunnableEnvironment","environment","getEnvironmentConsumer","options","consumer","VIRTUAL_ID","boundaryModules","enforce","resolveId","scan","load","DIAGNOSTICS_ENDPOINT","REQUEST_EVENT","RESPONSE_EVENT","DIAGNOSTICS_PACKAGE","DIAGNOSTICS_CLIENT_ID","METHODS","RESPONSE_TIMEOUT_MS","diagnosticsClientModuleCode","sendJson","readJsonBody","reject","chunks","chunk","text","Buffer","concat","toString","parse","Error","solidDiagnostics","process","cwd","apply","_config","command","isPreview","configResolved","moduleSideEffects","skipSelf","transformIndexHtml","tag","type","src","injectTo","configureServer","originalPrintUrls","printUrls","bind","endpoint","href","logger","info","nextId","ws","data","entry","clearTimeout","timer","methods","clients","size","message","setTimeout","timeout","send","params","compilerPromise","loadCompiler","reason","compile","transformDirectives","filename","mode","directive","sourceMap","register","definitions","create","valid","functions","PRIME32_1","PRIME32_2","PRIME32_3","PRIME32_4","PRIME32_5","toUtf8","bytes","i","n","c","charCodeAt","cp","Uint8Array","xxHash32","buffer","seed","b","acc","offset","accN","limit","lane","laneN0","laneN1","laneNP","acc0","acc1","laneP","DEFAULT_INCLUDE","DEFAULT_EXCLUDE","DEFAULT_MANIFEST","DEFAULT_DIRECTIVE","DEFAULT_RUNTIME","DEFAULT_ENDPOINT","STORAGE_SOURCE","HANDLER_ID","PERSISTED_MANIFEST_PATH","readPersistedManifest","existsSync","readFileSync","writePersistedManifest","outDir","mkdirSync","dirname","recursive","relative","writeFileSync","createManifest","createDeferredPromise","reference","rej","Debouncer","constructor","promise","defer","mergeManifestRecord","target","current","invalidPreload","invalidated","invalidateModule","invalidateModules","manifest","serverFunctions","internal","filterInclude","include","filterExclude","exclude","createFilter","manifestId","runtime","endpointOption","components","installDevMiddleware","devMiddleware","isBuild","isSsrBuild","resolvedEndpoint","configureModulePath","preload","currentServer","clientOptions","kind","serverOptions","endpointConfigureSnippet","handlerModuleCode","includeManifest","hashIndex","hashIndexSize","moduleForFunctionId","functionId","moduleDevUrl","startPlugins","_importer","opts","externalDev","externalDevServer","ssrEnvironment","underMount","mount","basePrefixed","dispatchUrl","segment","decodeURIComponent","headerId","runner","import","handler","ssrHandler","dispatchOptions","event","nativeEvent","handleRequest","handleServerFunctionRequest","build","configure","isAbsolute","writeBundle","ctx","isClient","transform","fileId","preloader","DEVTOOLS_PACKAGE","DEVTOOLS_MOUNT_ID","devtoolsMountModuleCode","SSR_HANDLER_ID","DEV_FALLTHROUGH_HEADER","STREAM_BOX","DEV_STYLES_ID","RESOLVED_DEV_STYLES_ID","ENTRY_SERVER_ID","ENTRY_CLIENT_ID","DOCUMENT_ID","ERROR_BOUNDARY_ID","MANIFEST_ID","SERVER_FUNCTION_HANDLER_ID","ENTRY_EXTENSIONS","APP_EXTENSIONS","DOCUMENT_EXTENSIONS","probe","stem","extensions","ext","normalizeUserPath","spec","option","resolveEntries","clientMode","explicitClient","entryClient","document","entryServer","generated","app","explicitServer","found","missing","startServe","serverComponents","errorBoundary","styleFilter","diagnostics","devtoolsEnabled","devtoolsResolutions","devtoolsIds","externalServer","external","middlewarePath","setupPath","requireEntries","resolveDevtools","realId","fileURLToPath","devtools","devtoolsReachableFrom","dir","parent","devtoolsIncludeSpec","rootDir","entryServerSpec","devClientEntryUrl","documentSpec","styleRoots","devStylesModuleCode","watchFile","styles","imports","style","index","specifier","_","errorBoundaryImport","documentTree","wrapper","generatedEntryServerCode","toolbar","streamOptions","setup","generatedEntryClientCode","diagnosticsImport","documentShellCode","errorBoundaryCode","composeServerFunctions","lines","devHead","headParts","userConfig","middleware","appType","clientInput","scanEntries","rollupOptions","input","output","entryFileNames","builder","optimizeDeps","configEnvironment","noExternal","devtoolsId","addWatchFile","enabled","normalizePath","injected","configurePreviewServer","handlerPromise","pathToFileURL","accept","pageRequest","buildApp","order","isBuilt","serverDir","rmSync","force","CLIENT_ENV_ID","SERVER_ENV_ID","RESOLVED_CLIENT_ENV_ID","RESOLVED_SERVER_ENV_ID","ENV_FILE_CANDIDATES","GENERATED_TYPES_FILE","isStandardSchema","validate","FOLDED_KEYS","foldedKeys","holder","stringEntries","out","formatValidationError","issues","envFile","importSchemaModule","envFileAbs","module","dependencies","runnerImport","exported","default","assertSchemaShape","envPrefixes","schema","keys","side","shape","validator","typed","some","prefix","wanted","find","p","bare","generateTypes","dtsPath","importSpec","basename","field","moduleBlock","fields","clientFields","serverFields","warn","startEnv","envPromise","devErrorLogged","resolveEnvFile","candidate","envPrefix","loadAndValidate","envDir","folded","fileEnv","loadEnv","raw","all","issue","at","clientIssues","ensureEnv","isServerContext","serverOnlyError","envModuleCode","values","moduleType","serverEnvModuleCode","loaded","serverKeys","baked","envDirOption","buildStart","envFiles","watched","debounce","onFileEvent","failed","graph","mod","hot","generateBundle","_options","bundle","clientValues","secrets","leaks","fileName","moduleIds","every","escaped","RegExp","leak","require","createRequire","LAZY_PLACEHOLDER_PREFIX","REFRESH_RUNTIME_SOURCE","DEFAULT_STYLE_EXCLUDE","VIRTUAL_MANIFEST_ID","RESOLVED_VIRTUAL_MANIFEST_ID","devManifestCode","bridgeUrl","nativeCompilerPromise","loadNativeCompiler","getExtension","lastIndexOf","substring","containsSolidField","getJestDomExport","setupFiles","e","getSolidOptions","isSsr","dev","isTestMode","solidOptions","generate","hydratable","start","solid","getBabelUserOptions","babel","babelOptions","normalizeSourceMap","combineSourcemaps","maps","chain","remapping","reverse","normalizeEmittedLazyEntries","dynamicKeys","dynamicImports","isEntry","isDynamicEntry","solidPlugin","startOptions","styleFilterOptions","createStyleFilter","hasInclude","included","filterDevStyles","needHmr","replaceDev","devServer","projectRoot","serverTestPosture","clientOutDir","solidPkgsConfig","clientManifestPath","manifestPath","emittedLazyChunks","emittedLazyChunkRefs","isClientBuild","resolveLazyModuleUrls","placeholderRe","match","resolutions","exec","relativeId","placeholder","injectSsrModuleId","mainPlugin","crawlFrameworkPkgs","viteUserConfig","isFrameworkPkgByJson","pkgJson","exports","nestedDeps","userTest","userSetupFiles","browser","inline","jestDomImport","dedupe","refresh","disabled","rolldownOptions","jsx","conditions","isSsrTargetWebworker","defaultClientConditions","defaultServerConditions","lastErrorTime","origSend","args","payload","Date","now","hotUpdate","modules","moduleParsed","depId","dynamicallyImportedIds","cleanId","emitFile","preserveSignature","_base","outputOptions","ref","getFileName","transformOptions","currentFileExtension","extensionsToWatch","allExtensions","extension","moduleId","inNodeModules","shouldBeProcessedWithTypescript","extensionName","extensionOptions","typescript","plugins","needRefresh","babelUserOptions","nativeFilename","compiler","lazyResult","transformLazyAsync","refreshResult","transformRefreshAsync","bundler","fixRender","granular","importSource","babelBaseOptions","sourceFileName","ast","sourceMaps","configFile","babelrc","parserOpts","supportOptions","mergeAndConcat","supportResult","transformAsync","finalCode","clientBuiltFirst","clientBuild","hasInput","otherOrchestrator"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;;;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASA,kBAAkBA,CAChCC,GAAoB,EACpBC,OAAgB,EAChBC,GAAoB,EACX;AACT;AACA;AACA;EACA,MAAMC,QAAQ,GAAIH,GAAG,CAACI,MAAM,EAA0CC,SAAS,GAC3E,OAAO,GACP,MAAM;AACV;AACA;AACA,EAAA,MAAMC,IAAI,GAAGN,GAAG,CAACO,OAAO,CAACD,IAAI,IAAKN,GAAG,CAACO,OAAO,CAAC,YAAY,CAAwB,IAAI,WAAW;AACjG,EAAA,MAAMC,GAAG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A,CAAChhB,IAAY,EAAEV,IAAY,EAAE2hB,SAAwB,KAAK,0CAA0C7f,IAAI,CAACC,SAAS,CACxIvB,yBACF,CAAC,CAAA;AACD,oBAAA,EAAsBsB,IAAI,CAACC,SAAS,CAACrB,IAAI,CAACsD,KAAK,CAACsB,IAAI,CAACe,GAAG,CAAC,CAACC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAA;AACpE,aAAA,EAAexE,IAAI,CAACC,SAAS,CAAC/B,IAAI,CAACE,UAAU,CAAC,GAAG,CAAC,GAAGF,IAAI,CAACoB,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,GAAG,EAAE,CAAC,CAAA;AAClF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAA,EAAoBU,IAAI,CAACC,SAAS,CAAC4f,SAAS,CAAC,CAAA;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qCAAA,EAAuC7f,IAAI,CAACC,SAAS,CAACrB,IAAI,CAAC,CAAA;AAC3D,kFAAA,CAAmF;;AAEnF;;AAQA,IAAIkhB,qBAA0D;AAE9D,eAAeC,kBAAkBA,GAAG;EAClC,IAAI;AACF,IAAA,OAAO,OAAOD,qBAAqB,KAAK,OAAO,mBAAmB,CAAC,CAAC;EACtE,CAAC,CAAC,OAAOhgB,KAAK,EAAE;AACdggB,IAAAA,qBAAqB,GAAG1kB,SAAS;AACjC,IAAA,MAAMyO,MAAM,GAAG/J,KAAK,YAAYuH,KAAK,GAAG,CAAA,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AE;UACrB,IAAI,CAACkQ,gBAAgB,EAAE;AACvB;AACA;AACA;UACA,MAAMG,iBAAiB,GAAGrQ,OAAO,CAAC7Y,MAAM,CAACsnB,OAAO,CAACtL,IAAI,CAAEI,CAAC,IAAK;AAC3D,YAAA,IAAI,CAACA,CAAC,CAACzC,QAAQ,IAAIyC,CAAC,CAACxX,IAAI,CAAC7F,UAAU,CAAC,0BAA0B,CAAC,EAAE,OAAO,KAAK;AAC9E,YAAA,OAAO,OAAOqd,CAAC,CAACzC,QAAQ,KAAK,QAAQ,IAAIyC,CAAC,CAACzC,QAAQ,CAACC,KAAK,KAAK,KAAK;AACrE,UAAA,CAAC,CAAC;AACF,UAAA,IAAIsP,iBAAiB,EAAE;UACvB,MAAMrlB,YAAY,GAAGhI,MAAM,CAACuiB,MAAM,CAACvF,OAAO,CAAChV,YAAY,CAAC;AACxD;AACA;AACA;AACA,UAAA,IAAIA,YAAY,CAACmY,IAAI,CAAEpa,GAAG,IAAKA,GAAG,CAACiY,OAAO,IAAIjY,GAAG,CAACgD,IAAI,KAAK,QAAQ,CAAC,EAAE;AACtE,UAAA,KAAK,MAAMwB,WAAW,IAAIvC,YAAY,EAAE;YACtC,IAAI,CAACuC,WAAW,CAACyT,OAAO,EAAE,MAAMhB,OAAO,CAACtG,KAAK,CAACnM,WAAW,CAAC;AAC5D,UAAA;AACF,QAAA;AACF;AACF,KACF,CAAC;AACH,EAAA;AAEA,EAAA,OAAOkhB,OAAO;AAChB;;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../../src/http.ts","../../src/dev-manifest.ts","../../src/environment.ts","../../src/boundary-modules.ts","../../src/diagnostics/index.ts","../../src/server-functions/compile.ts","../../src/server-functions/xxhash32.ts","../../src/server-functions/index.ts","../../src/devtools/index.ts","../../src/ssr/index.ts","../../src/start-env.ts","../../src/index.ts"],"sourcesContent":["// Node <-> web-standard request/response bridging shared by the plugin's dev\n// middlewares (server functions and SSR). The virtual production handlers\n// speak web Request/Response only; this is the node:http glue the dev server\n// needs to talk to them.\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { Readable } from 'node:stream';\n\n/**\n * `urlPath` overrides `req.url` when the middleware needs to dispatch a\n * different URL than the one node saw — the dev middlewares use it to\n * restore the configured Vite `base` that the dev/preview base middleware\n * stripped, so the handler always sees production-shaped URLs.\n *\n * Handles plain HTTP/1 *and* the HTTP/2 compat API: Vite's dev server uses\n * `http2.createSecureServer({ allowHTTP1: true })` whenever `server.https`\n * is set without a proxy, so under https the middlewares receive\n * `Http2ServerRequest`s. The h2/protocol/abort techniques here are\n * reimplemented from srvx's Node adapter (github.com/h3js/srvx,\n * src/adapters/_node) — reference, not copied code.\n */\nexport function webRequestFromNode(\n req: IncomingMessage,\n urlPath?: string,\n res?: ServerResponse,\n): Request {\n // TLS sockets (https and h2) expose `encrypted`; a Request whose url says\n // http: on a TLS connection breaks secure-cookie logic, absolute\n // redirects, and origin checks in application code.\n const protocol = (req.socket as { encrypted?: boolean } | undefined)?.encrypted\n ? 'https'\n : 'http';\n // HTTP/2 has no Host header — the authority travels in the `:authority`\n // pseudo-header instead.\n const host = req.headers.host ?? (req.headers[':authority'] as string | undefined) ?? 'localhost';\n const url = new URL(urlPath ?? req.url ?? '/', `${protocol}://${host}`);\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value === undefined) continue;\n // HTTP/2 pseudo-headers (:method, :path, :authority, :scheme) are not\n // legal field names — Headers#append throws a TypeError on them.\n if (key[0] === ':') continue;\n if (Array.isArray(value)) {\n for (const item of value) headers.append(key, item);\n } else {\n headers.append(key, value);\n }\n }\n // Surface client disconnects as the request's AbortSignal so handlers can\n // cancel work (streamed SSR renders, in-flight fetches). The response's\n // 'close' fires on normal completion too; `writableEnded` distinguishes a\n // finished response from a client that went away.\n let signal: AbortSignal | undefined;\n if (res) {\n const controller = new AbortController();\n res.once('close', () => {\n if (!res.writableEnded) controller.abort();\n });\n signal = controller.signal;\n }\n const method = req.method || 'GET';\n // Only attach a body when the request actually carries one. A web Request\n // built by the browser for a bodyless POST has `body === null`, and the\n // runtime keys off that (a present body that decodes to nothing is a 400\n // since @solidjs/web 2.0.0-rc.5) — so an unconditionally attached (empty)\n // stream misparses bodyless calls. HTTP/1 signals a body via\n // Content-Length/Transfer-Encoding (RFC 9112 §6); the h2 compat API sets\n // `stream.endAfterHeaders` when END_STREAM rode the headers frame.\n const h2Stream = (req as { stream?: { endAfterHeaders?: boolean } }).stream;\n const hasBody =\n method !== 'GET' &&\n method !== 'HEAD' &&\n (h2Stream\n ? !h2Stream.endAfterHeaders\n : req.headers['transfer-encoding'] !== undefined ||\n (req.headers['content-length'] !== undefined && req.headers['content-length'] !== '0'));\n const body = hasBody ? (Readable.toWeb(req) as unknown as ReadableStream) : undefined;\n return new Request(url, {\n method,\n headers,\n body,\n signal,\n // undici requires half-duplex for streamed request bodies.\n ...(body ? { duplex: 'half' } : {}),\n } as RequestInit);\n}\n\nexport async function sendWebResponse(res: ServerResponse, response: Response): Promise<void> {\n res.statusCode = response.status;\n // set-cookie is the one header that must not be comma-joined.\n const cookies: string[] | undefined = (response.headers as any).getSetCookie?.();\n response.headers.forEach((value, key) => {\n if (key !== 'set-cookie') res.setHeader(key, value);\n });\n if (cookies && cookies.length) res.setHeader('set-cookie', cookies);\n // HEAD gets the head only — and the body must be *cancelled*, not pumped:\n // node discards HEAD body writes, so streaming a long (or endless) body\n // into the void just burns the render. (Technique from srvx.)\n if (!response.body || res.req?.method === 'HEAD') {\n response.body?.cancel().catch(() => {});\n res.end();\n return;\n }\n const reader = response.body.getReader();\n res.on('close', () => {\n reader.cancel().catch(() => {});\n });\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n // A response whose client already went away never emits 'drain'\n // (writes are no-ops), so a backpressure wait must also settle on\n // 'close'/'error' or an aborted streaming response parks this promise\n // — and the reader and Response it holds — forever.\n if (res.destroyed) return;\n if (!res.write(value)) {\n const drained = await new Promise<boolean>((resolve) => {\n const settle = (ok: boolean) => {\n res.off('drain', onDrain);\n res.off('close', onGone);\n res.off('error', onGone);\n resolve(ok);\n };\n const onDrain = () => settle(true);\n const onGone = () => settle(false);\n res.once('drain', onDrain);\n res.once('close', onGone);\n res.once('error', onGone);\n });\n // Client gone mid-stream; the 'close' handler cancels the reader.\n if (!drained) return;\n }\n }\n res.end();\n } catch {\n res.destroy();\n }\n}\n\nexport function joinBase(base: string, pathname: string): string {\n // Absolute-URL or relative bases (CDN deploys, './') don't prefix\n // same-origin server paths.\n if (!base.startsWith('/')) return pathname;\n return (base.endsWith('/') ? base.slice(0, -1) : base) + pathname;\n}\n","import path from 'path';\nimport type { DevEnvironment, EnvironmentModuleNode, ViteDevServer } from 'vite';\nimport { joinBase } from './http.js';\n\n/**\n * Dev-mode asset resolution: the `virtual:solid-manifest` module exports a\n * resolver function in dev (instead of the static object a build produces),\n * and the runtime installs it as `context.resolveAssets` verbatim. When\n * server-side `lazy()` resolves a module key, the resolver walks the SSR\n * environment's live module graph collecting transitively imported CSS and\n * answers with inline-style descriptors — SSR'd `<style data-vite-dev-id>`\n * tags that Vite's HMR client adopts on startup, so dev CSS is styled from\n * the first streamed byte without fighting Vite's own style injection.\n *\n * The walk design follows SolidStart's collect-styles (by @katywings): crawl\n * `transformResult.deps` on the SSR environment (the client environment's\n * transform results don't list CSS deps), skipping dynamic imports since\n * dynamically imported modules register their own styles when they render.\n */\n\nexport type DevStyleDescriptor = { id: string; content: string; attrs?: Record<string, string> };\nexport type DevStyleSource = { id: string; url: string };\nexport type DevStyleFilter = (id: string) => boolean;\n\nconst defaultStyleFilter: DevStyleFilter = (id) => !id.includes('node_modules');\n\nexport type ResolvedAssets = {\n js: string[];\n css: (string | DevStyleDescriptor)[];\n};\n\nexport type DevAssetResolver = {\n /**\n * Answers synchronously (a plain object) once the key's assets are known.\n * The sync answer is load-bearing for SSR convergence: the runtime retries\n * a suspended render pass by re-creating the lazy component, which\n * re-requests its assets — if every answer is a fresh pending promise the\n * pass suspends again on a promise that did not exist when the retry\n * began, and never converges (see `createDevAssetResolver`).\n */\n resolve: (key: string) => ResolvedAssets | null | Promise<ResolvedAssets | null>;\n /**\n * Synchronous fast path used by sync consumers (a lazy component's\n * `moduleUrl` getter for islands): the module's dev URL is knowable\n * without the async CSS graph walk.\n */\n resolveSync: (key: string) => ResolvedAssets;\n};\n\n// The resolver is created plugin-side (it closes over the dev server) but is\n// called from the SSR module runner, which only shares `globalThis` with the\n// plugin when it runs in-process (the default). The primary channel is a\n// `Symbol.for`-keyed registry mapping project roots to resolvers; isolated\n// runners (nitro's dev worker, workerd) won't find it and instead fall back\n// to fetching the HTTP bridge endpoint below.\nexport const DEV_MANIFEST_REGISTRY_KEY = '@solidjs/vite-plugin:dev-manifest';\n\nexport function registerDevAssetResolver(root: string, resolver: DevAssetResolver): void {\n const key = Symbol.for(DEV_MANIFEST_REGISTRY_KEY);\n const registry: Record<string, DevAssetResolver> = ((globalThis as any)[key] ??= {});\n registry[root] = resolver;\n}\n\n/**\n * HTTP bridge endpoint for isolated SSR runners. Hosts that evaluate server\n * modules outside the Vite process (nitro's dev worker, workerd via\n * @cloudflare/vite-plugin) can't see the `globalThis` registry, so the dev\n * server itself serves asset resolution: `GET\n * /@solidjs/vite-plugin/dev-manifest?key=<module key>` answers with the\n * resolver's `ResolvedAssets` JSON (`null` when the key can't be resolved).\n * The dev flavor of `virtual:solid-manifest` falls back to fetching it when\n * the registry has no entry for the root — in-process consumers hit the\n * registry and never touch HTTP.\n */\nexport const DEV_MANIFEST_ENDPOINT = '/@solidjs/vite-plugin/dev-manifest';\n\nexport function installDevManifestBridge(server: ViteDevServer): void {\n // configureServer middlewares run ahead of Vite's internals, so `req.url`\n // may or may not still carry the configured `base` — accept both forms.\n const base = (server.config.base || '/').replace(/\\/$/, '');\n const basedEndpoint = base + DEV_MANIFEST_ENDPOINT;\n server.middlewares.use(async (req, res, next) => {\n const url = new URL(req.url || '/', 'http://localhost');\n if (url.pathname !== DEV_MANIFEST_ENDPOINT && url.pathname !== basedEndpoint) return next();\n\n const key = url.searchParams.get('key');\n if (!key) {\n res.statusCode = 400;\n return res.end('Missing asset key');\n }\n\n try {\n const registry: Record<string, DevAssetResolver> | undefined = (globalThis as any)[\n Symbol.for(DEV_MANIFEST_REGISTRY_KEY)\n ];\n const resolver = registry?.[server.config.root];\n if (!resolver) {\n // A silent null strips the module's client assets from the SSR'd\n // hydration asset map and hydration fails much later with a cryptic\n // client-side error — report the miss where it happens.\n console.error(\n `[@solidjs/vite-plugin] The dev manifest registry has no resolver for root \"${server.config.root}\" ` +\n `(requested asset key \"${key}\"). The module's client assets cannot be resolved and hydration ` +\n 'will fail for it. Typical causes: the dev server was not restarted after dependency changes, ' +\n 'or the install is stale.',\n );\n }\n const assets = resolver ? await resolver.resolve(key) : null;\n if (resolver && assets == null) {\n console.error(\n `[@solidjs/vite-plugin] Dev manifest resolver returned no assets for key \"${key}\" (root \"${server.config.root}\"). ` +\n \"The module's hydration preload entry will be missing.\",\n );\n }\n res.setHeader('content-type', 'application/json');\n res.setHeader('cache-control', 'no-store');\n return res.end(JSON.stringify(assets));\n } catch (error) {\n return next(error);\n }\n });\n}\n\n/**\n * The absolute URL isolated runners should fetch the bridge from, baked into\n * the dev flavor of `virtual:solid-manifest` when its code is generated.\n * Generation happens while serving an SSR request, so the server is already\n * listening and `resolvedUrls` carries the real origin (a config-time define\n * could only guess the port). Middleware-mode servers have no origin of\n * their own to advertise — returns null there, and the manifest module keeps\n * the js-only fallback (in-process registry hits are unaffected either way).\n */\nexport function devManifestBridgeUrl(server: ViteDevServer): string | null {\n const local = server.resolvedUrls?.local?.[0];\n let origin: string | null = null;\n if (local) {\n origin = new URL(local).origin;\n } else if (!server.config.server.middlewareMode) {\n const address = server.httpServer?.address();\n if (address && typeof address === 'object') {\n const https = !!server.config.server.https;\n origin = `${https ? 'https' : 'http'}://localhost:${address.port}`;\n }\n }\n if (!origin) return null;\n const base = (server.config.base || '/').replace(/\\/$/, '');\n return origin + base + DEV_MANIFEST_ENDPOINT;\n}\n\n// https://github.com/vitejs/vite/blob/main/packages/vite/src/node/constants.ts\nconst cssFileRegExp = /\\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)$/;\n// Queried css imports (?url, ?inline, ?raw) are not ambient styles — the\n// importer controls them — so they must not be SSR'd as style tags.\nconst nonAmbientQueryRegExp = /[?&](url|inline|raw)\\b/;\n\nconst NULL_BYTE_PLACEHOLDER = '/@id/__x00__';\n\n// Per Vite's convention virtual module ids are prefixed with `\\0`, which\n// cannot appear in an HTML attribute (the parser replaces it). Serialize the\n// same placeholder form Vite's own URLs use. Adoption of virtual-module\n// styles additionally needs `devStylePatch` (below) to run client-side;\n// fs-backed CSS (the overwhelmingly common case) adopts without it.\nfunction wrapId(id: string): string {\n return id.replace(/^\\0/, NULL_BYTE_PLACEHOLDER);\n}\n\n/**\n * Inline dev script reconciling SSR'd style tags with Vite's HMR client.\n * Frameworks that server-render whole documents should inline this in dev,\n * in `<head>` before any module script. It does two things, via a\n * MutationObserver so styles appended by streamed boundaries are handled as\n * they arrive (Vite's client seeds its stylesheet registry from the DOM only\n * once, when its module evaluates):\n *\n * - Rewrites serialized virtual-module ids (`/@id/__x00__…`) back to Vite's\n * null-byte form so seeding matches (a raw `\\0` can't survive HTML).\n * - Dedupes twins: a style tag that streams in after Vite's client has\n * seeded is missed by the scan, so the CSS module injects its own copy\n * client-side. Whenever two style tags share a `data-vite-dev-id`, the\n * SSR'd one (marked `data-asset`) is removed in favor of the Vite-owned\n * one, which is the tag HMR updates.\n *\n * Observation is two-phase to stay cheap: a document-wide subtree observer\n * only for the streaming window (SSR tags can only arrive while the parser\n * is consuming the stream; DOMContentLoaded marks its end), then a\n * childList-only observer on `document.head` for the page lifetime — Vite\n * injects twins into the head during hydration, which continues past\n * DOMContentLoaded, and a non-subtree head observer never fires on app DOM\n * churn, only on head insertions.\n *\n * Descends from SolidStart's PatchVirtualDevStyles (by @katywings); this\n * belongs in Vite itself eventually.\n */\nexport const devStylePatch = `(function(){var P=${JSON.stringify(\n NULL_BYTE_PLACEHOLDER,\n)};var handle=function(el){var v=el.getAttribute(\"data-vite-dev-id\");if(!v)return;if(v.indexOf(P)===0){v=\"\\\\0\"+v.slice(P.length);el.setAttribute(\"data-vite-dev-id\",v)}var all=document.querySelectorAll(\"style[data-vite-dev-id]\");for(var i=0;i<all.length;i++){var o=all[i];if(o!==el&&o.getAttribute(\"data-vite-dev-id\")===v){var ssr=o.hasAttribute(\"data-asset\")?o:el.hasAttribute(\"data-asset\")?el:null;if(ssr)ssr.remove();break}}};var scan=function(n){if(n.nodeType!==1)return;if(n.tagName===\"STYLE\")handle(n);else if(n.querySelectorAll)n.querySelectorAll(\"style[data-vite-dev-id]\").forEach(handle)};var onMuts=function(muts){for(var i=0;i<muts.length;i++)muts[i].addedNodes.forEach(scan)};var headPhase=function(){scan(document.documentElement);new MutationObserver(onMuts).observe(document.head,{childList:true})};scan(document.documentElement);if(document.readyState===\"loading\"){var mo=new MutationObserver(onMuts);mo.observe(document.documentElement,{childList:true,subtree:true});document.addEventListener(\"DOMContentLoaded\",function(){mo.disconnect();headPhase()})}else headPhase()})();`;\n\nasync function getModuleNode(\n env: DevEnvironment,\n file: string,\n importer?: string,\n): Promise<EnvironmentModuleNode | undefined> {\n try {\n // fetchModule resolves through the plugin container with importer\n // context, so dep strings that are placeholder-wrapped virtual URLs\n // (`/@id/__x00__…`) or importer-relative specifiers land on the right\n // module id — a raw moduleGraph/transformRequest lookup would miss them.\n const resolved = await env.fetchModule(file, importer);\n if (!('id' in resolved)) return;\n return env.moduleGraph.getModuleById(resolved.id);\n } catch {\n return;\n }\n}\n\nasync function collectModuleDeps(\n env: DevEnvironment,\n file: string,\n deps: Set<EnvironmentModuleNode>,\n crawled: Set<string>,\n filter: DevStyleFilter,\n onFile?: (file: string) => void,\n importer?: string,\n): Promise<void> {\n crawled.add(file);\n const node = await getModuleNode(env, file, importer);\n if (!node?.id || deps.has(node)) return;\n deps.add(node);\n\n const isCss = cssFileRegExp.test(node.url.split('?')[0]);\n if (!isCss && node.file && !node.id.startsWith('\\0') && !filter(node.file)) return;\n if (node.file) onFile?.(node.file);\n if (isCss) return;\n\n if (!node.transformResult) {\n await env.transformRequest(node.url).catch(() => {});\n }\n const directDeps = node.transformResult?.deps;\n if (!directDeps) return;\n\n // transformResult.deps (unlike importedModules) separates static imports\n // from dynamicDeps — dynamic imports load their own styles when rendered.\n for (const dep of directDeps) {\n if (crawled.has(dep)) continue;\n await collectModuleDeps(env, dep, deps, crawled, filter, onFile, node.id);\n }\n}\n\nfunction injectQuery(url: string, query: string): string {\n return url.includes('?') ? `${url}&${query}` : `${url}?${query}`;\n}\n\n/** Discovers ambient CSS in an entry graph without choosing how it is transported. */\nexport async function collectDevStyleSources(\n env: DevEnvironment,\n files: string[],\n onFile?: (file: string) => void,\n filter: DevStyleFilter = defaultStyleFilter,\n): Promise<DevStyleSource[]> {\n const deps = new Set<EnvironmentModuleNode>();\n const crawled = new Set<string>();\n for (const file of files) {\n await collectModuleDeps(env, file, deps, crawled, filter, onFile);\n }\n\n const css: DevStyleSource[] = [];\n const seen = new Set<string>();\n for (const node of deps) {\n if (!node.id) continue;\n const cleanUrl = node.url.split('?')[0];\n if (!cssFileRegExp.test(cleanUrl) || nonAmbientQueryRegExp.test(node.url)) continue;\n const id = wrapId(node.id);\n if (seen.has(id)) continue;\n seen.add(id);\n css.push({ id, url: node.url });\n }\n return css;\n}\n\n/**\n * Walks the SSR module graph from `files` (root-relative or absolute) and\n * returns inline-style descriptors for every transitively imported CSS\n * module — the same shape the dev asset resolver answers with for lazy\n * modules. Used by SSR start mode's dev middleware to inline the root entry's\n * CSS into `<head>` so server-painted content is styled from the first byte\n * (no FOUC while waiting for Vite's client-side style injection).\n */\nexport async function collectDevStyles(\n server: ViteDevServer,\n files: string[],\n filter: DevStyleFilter = defaultStyleFilter,\n): Promise<DevStyleDescriptor[]> {\n const ssrEnv = server.environments?.ssr;\n const clientEnv = server.environments?.client;\n if (!ssrEnv || !clientEnv) return [];\n\n const sources = await collectDevStyleSources(\n ssrEnv,\n files.map((file) => path.resolve(server.config.root, file)),\n undefined,\n filter,\n );\n\n const css: DevStyleDescriptor[] = [];\n for (const source of sources) {\n // `?direct` yields the compiled stylesheet text (what Vite serves for\n // <link> requests) — through the client environment, whose css\n // pipeline matches what the browser will run for HMR updates.\n const result = await clientEnv\n .transformRequest(injectQuery(source.url, 'direct'))\n .catch(() => null);\n if (result?.code == null) continue;\n css.push({\n id: source.id,\n content: result.code,\n attrs: { 'data-vite-dev-id': source.id },\n });\n }\n return css;\n}\n\nfunction escapeAttr(value: string): string {\n return value.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<');\n}\n\n/**\n * Serializes a dev style descriptor to the exact tag shape the SSR runtime\n * emits for lazy-registered assets (`data-asset` marks the SSR'd copy so\n * `devStylePatch` knows which twin to drop when Vite's client injects its\n * own), so the dedup story is identical for entry styles and lazy styles.\n */\nexport function renderDevStyleTag(desc: DevStyleDescriptor): string {\n let attrs = '';\n for (const name in desc.attrs) {\n attrs += ` ${name}=\"${escapeAttr(String(desc.attrs![name]))}\"`;\n }\n const content = desc.content.replace(/<\\/(style)/gi, '<\\\\/$1');\n return `<style data-asset=\"${escapeAttr(desc.id)}\"${attrs}>${content}</style>`;\n}\n\n/**\n * Browser URL for a lazy module's dev asset key (a project-root-relative\n * path, query included when the module identity carries one). Vite only\n * serves module URLs under the configured `base`, so it is always applied;\n * root-external keys (`../…`, e.g. sibling workspace packages) can't be\n * expressed as root-relative URLs at all — they get Vite's `/@fs/` form on\n * the resolved absolute path instead. Mirrored by the generated fallback in\n * `devManifestCode` (src/index.ts) — keep the two in sync.\n */\nexport function devModuleUrl(root: string, base: string, key: string): string {\n const queryIndex = key.indexOf('?');\n const file = queryIndex === -1 ? key : key.slice(0, queryIndex);\n const query = queryIndex === -1 ? '' : key.slice(queryIndex);\n if (!file.startsWith('..')) return joinBase(base, '/' + key);\n const absolute = path.resolve(root, file).split(path.sep).join('/');\n // Vite's fs URLs collapse the leading slash: /@fs/Users/… (and keep the\n // drive letter on Windows: /@fs/C:/…).\n return joinBase(base, '/@fs/' + absolute.replace(/^\\//, '') + query);\n}\n\nexport function createDevAssetResolver(\n server: ViteDevServer,\n filter: DevStyleFilter = defaultStyleFilter,\n): DevAssetResolver {\n // Server-side lazy() re-requests a module's assets on every retry of a\n // suspended render pass (retries re-create the component). The build\n // manifest answers those repeats synchronously and the pass converges; an\n // always-async resolver instead suspends every retry on a brand-new\n // promise, so a pass whose retry path re-creates the lazy component (a\n // nested route's outlet does) loops forever — each cycle nests one resume\n // closure until the render stack overflows and the escaped rejection kills\n // the dev server. So: dedupe in-flight walks per key and answer\n // synchronously once a key's assets are known. Any watcher event drops the\n // cache — the next request re-walks the updated module graph, keeping dev\n // CSS fresh.\n const resolved = new Map<string, ResolvedAssets>();\n const pending = new Map<string, Promise<ResolvedAssets | null>>();\n const { root, base } = server.config;\n let generation = 0;\n server.watcher.on('all', () => {\n generation++;\n resolved.clear();\n pending.clear();\n });\n\n const resolve = function resolveDevAssets(\n key: string,\n ): ResolvedAssets | Promise<ResolvedAssets | null> {\n const cached = resolved.get(key);\n if (cached) return cached;\n let walk = pending.get(key);\n if (!walk) {\n const startedAt = generation;\n walk = (async (): Promise<ResolvedAssets> => {\n // The module's dev URL doubles as its client entry: modulepreload\n // hint and hydration module-map value.\n const js = [devModuleUrl(root, base, key)];\n const css = await collectDevStyles(server, [key], filter);\n return { js, css };\n })().then(\n (assets) => {\n if (generation === startedAt) {\n resolved.set(key, assets);\n pending.delete(key);\n }\n return assets;\n },\n (error) => {\n if (generation === startedAt) pending.delete(key);\n throw error;\n },\n );\n pending.set(key, walk);\n }\n return walk;\n };\n return {\n resolve,\n resolveSync: (key: string) => resolved.get(key) ?? { js: [devModuleUrl(root, base, key)], css: [] },\n };\n}\n","import type { RunnableDevEnvironment } from 'vite';\n\n/**\n * Cross-instance-safe stand-in for vite's `isRunnableDevEnvironment`.\n *\n * Vite's helper is an `instanceof RunnableDevEnvironment` check against the\n * class of whichever `vite` module the CALLER imported. When this plugin is\n * consumed through a workspace/`link:` install, its own `vite` import can\n * resolve to a different physical copy than the one running the dev server —\n * and then the `instanceof` is false for every environment, silently standing\n * the SSR/dev middlewares down. The `runner` accessor is the type's defining\n * member (`RunnableDevEnvironment` is exactly \"a DevEnvironment with a\n * runner\"), so presence-check it instead of trusting class identity.\n */\nexport function isRunnableEnvironment(\n environment: unknown,\n): environment is RunnableDevEnvironment {\n return !!environment && typeof environment === 'object' && 'runner' in environment;\n}\n\nexport function getEnvironmentConsumer(\n environment: unknown,\n options?: { ssr?: boolean },\n): 'client' | 'server' {\n const consumer = (environment as { config?: { consumer?: string } } | undefined)?.config\n ?.consumer;\n if (consumer === 'client' || consumer === 'server') return consumer;\n return options?.ssr ? 'server' : 'client';\n}\n","import type { Plugin } from 'vite';\nimport { getEnvironmentConsumer } from './environment';\n\nconst VIRTUAL_ID = '\\0@solidjs/vite-plugin:boundary-modules';\n\n/**\n * `server-only` and `client-only` marker modules: importing `server-only`\n * from a module bundled for the client fails the build at resolve time with\n * a descriptive error (and vice versa for `client-only`); in the allowed\n * environment the marker resolves to an empty module.\n *\n * Server-only code pulled into a client bundle otherwise ships silently and\n * crashes at runtime (in hydrating apps, typically as a cryptic hydration\n * failure far from the real cause) — the marker turns that into a build\n * error naming the importer.\n *\n * Always on (`enforce: 'pre'`), so the bare specifiers are claimed by this\n * plugin even when React's `server-only`/`client-only` npm packages are\n * installed — the environment semantics are the same, and claiming them\n * keeps the behavior deterministic and the errors identifiable as ours.\n */\nexport function boundaryModules(): Plugin {\n return {\n name: 'solid:boundary-modules',\n enforce: 'pre',\n resolveId(id, importer, options) {\n // The dep scanner (`vite:dep-scan`) crawls the client entries' RAW\n // import graph — no directive transforms have run, so it walks\n // straight through 'use server' modules into genuinely server-only\n // code. That graph is legal once transforms split it, so the guard\n // must not fire on the scan pass (`options.scan`, set by Rolldown's\n // dependency scanner). Still claim the specifier: resolving to the empty\n // virtual module keeps the scanner from chasing `server-only` /\n // `client-only` as missing bare dependencies, which would abort the\n // scan all the same. Real dev/build module graphs resolve without\n // the flag and stay fully guarded.\n const scan = !!(options as { scan?: boolean } | undefined)?.scan;\n const server = getEnvironmentConsumer(this.environment, options) === 'server';\n if (id === 'server-only') {\n if (!server && !scan)\n this.error(\n `[@solidjs/vite-plugin] Attempt to import 'server-only' in a client module: ${importer}. ` +\n `Code that uses this module must run only on the server — make sure it is only ` +\n `imported by server code (e.g. a server entry, a \"use server\" module, or code ` +\n `reached exclusively from them).`,\n );\n } else if (id === 'client-only') {\n if (server && !scan)\n this.error(\n `[@solidjs/vite-plugin] Attempt to import 'client-only' in a server module: ${importer}. ` +\n `Code that uses this module must run only in the browser — make sure it is only ` +\n `imported by client code (e.g. behind a client-only lazy boundary).`,\n );\n } else {\n return null;\n }\n return VIRTUAL_ID;\n },\n load(id) {\n if (id === VIRTUAL_ID) return 'export {}';\n },\n };\n}\n","/**\n * Agent diagnostics surface (`diagnostics: true`, dev serve only).\n *\n * Three pieces:\n * - an injected client module (virtual, imported by index.html or the\n * start-mode client entry) that installs the in-page bridge from the\n * app's own `@solidjs/diagnostics` and answers requests over Vite's\n * WebSocket custom events;\n * - a collector that forwards requests to the page and correlates\n * responses by id;\n * - an HTTP endpoint (`/__solid/diagnostics`) fronting that round-trip so\n * any out-of-process consumer (agent, MCP tool, curl) can drive capture\n * sessions without holding a WebSocket.\n *\n * `@solidjs/diagnostics` is deliberately a type-only dependency of this\n * plugin: the runtime bridge always comes from the app's own installed\n * copy, so plugin releases and diagnostics releases stay uncoupled. The\n * wire constants are re-declared here with types imported from the\n * package, so drift fails the plugin's own compile.\n */\nimport path from 'path';\nimport type { IncomingMessage, ServerResponse } from 'http';\nimport type { Plugin } from 'vite';\nimport { joinBase } from '../http.js';\n\ntype Protocol = typeof import('@solidjs/diagnostics/protocol');\nconst DIAGNOSTICS_ENDPOINT: Protocol['DIAGNOSTICS_ENDPOINT'] = '/__solid/diagnostics';\nconst REQUEST_EVENT: Protocol['DIAGNOSTICS_REQUEST_EVENT'] = 'solid:diagnostics:request';\nconst RESPONSE_EVENT: Protocol['DIAGNOSTICS_RESPONSE_EVENT'] = 'solid:diagnostics:response';\n\ntype DiagnosticsResponse = import('@solidjs/diagnostics/protocol').DiagnosticsResponse;\n\nexport const DIAGNOSTICS_PACKAGE = '@solidjs/diagnostics';\nexport const DIAGNOSTICS_CLIENT_ID = 'virtual:solid-diagnostics/client';\n\nconst METHODS = ['begin', 'end', 'active', 'whyDidRun', 'costs'] as const satisfies readonly (\n | import('@solidjs/diagnostics/protocol').DiagnosticsMethod\n)[];\n\n/** How long the endpoint waits for a page to answer before failing the call. */\nconst RESPONSE_TIMEOUT_MS = 10_000;\n\nexport function diagnosticsClientModuleCode(): string {\n // Runtime imports resolve to the APP's diagnostics package (see the\n // resolveId assist below) — the page speaks its own package's protocol.\n return [\n `import { installDiagnosticsBridge } from '${DIAGNOSTICS_PACKAGE}/browser';`,\n `import {`,\n ` DIAGNOSTICS_REQUEST_EVENT,`,\n ` DIAGNOSTICS_RESPONSE_EVENT,`,\n `} from '${DIAGNOSTICS_PACKAGE}/protocol';`,\n ``,\n `const bridge = installDiagnosticsBridge();`,\n ``,\n `async function dispatch(request) {`,\n ` switch (request.method) {`,\n ` case 'begin': bridge.begin(request.params); return true;`,\n ` case 'end': return bridge.end();`,\n ` case 'active': return bridge.active();`,\n ` case 'whyDidRun': return bridge.whyDidRun(request.params.name);`,\n ` case 'costs': return bridge.costs();`,\n ` default: throw new Error('Unknown diagnostics method: ' + request.method);`,\n ` }`,\n `}`,\n ``,\n `if (import.meta.hot) {`,\n ` import.meta.hot.on(DIAGNOSTICS_REQUEST_EVENT, async (request) => {`,\n ` let response;`,\n ` try {`,\n ` response = { id: request.id, result: await dispatch(request) };`,\n ` } catch (error) {`,\n ` response = {`,\n ` id: request.id,`,\n ` error: error instanceof Error ? error.message : String(error),`,\n ` };`,\n ` }`,\n ` import.meta.hot.send(DIAGNOSTICS_RESPONSE_EVENT, response);`,\n ` });`,\n `}`,\n ].join('\\n');\n}\n\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n res.statusCode = status;\n res.setHeader('Content-Type', 'application/json');\n res.end(JSON.stringify(body));\n}\n\nfunction readJsonBody(req: IncomingMessage): Promise<unknown> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n req.on('data', (chunk) => chunks.push(chunk));\n req.on('end', () => {\n const text = Buffer.concat(chunks).toString('utf8');\n if (!text) return resolve({});\n try {\n resolve(JSON.parse(text));\n } catch {\n reject(new Error('Request body is not valid JSON'));\n }\n });\n req.on('error', reject);\n });\n}\n\nexport function solidDiagnostics(): Plugin {\n let root = process.cwd();\n let base = '/';\n\n return {\n name: 'solid:diagnostics',\n // Dev-serve only: the channels this fronts exist in dev builds only.\n apply(_config, env) {\n return env.command === 'serve' && !env.isPreview;\n },\n\n configResolved(config) {\n root = config.root;\n base = config.base;\n },\n\n async resolveId(source, importer) {\n if (source === DIAGNOSTICS_CLIENT_ID) {\n return { id: DIAGNOSTICS_CLIENT_ID, moduleSideEffects: true };\n }\n // The virtual module has no directory to resolve bare imports from;\n // resolve the app's diagnostics package from the project root.\n if (importer === DIAGNOSTICS_CLIENT_ID && source.startsWith(DIAGNOSTICS_PACKAGE)) {\n const resolved = await this.resolve(source, path.resolve(root, 'index.html'), {\n skipSelf: true,\n });\n if (!resolved || resolved.id.startsWith('__vite-optional-peer-dep:')) {\n this.error(\n `[@solidjs/vite-plugin] the diagnostics option requires ${DIAGNOSTICS_PACKAGE} ` +\n 'installed in the app (it provides the in-page bridge). Install it as a ' +\n 'development dependency or remove `diagnostics: true`.',\n );\n }\n return resolved;\n }\n return null;\n },\n\n load(id) {\n if (id === DIAGNOSTICS_CLIENT_ID) return diagnosticsClientModuleCode();\n return null;\n },\n\n // Plain (index.html) apps get the client module injected here;\n // start-mode apps import it from the generated client entry instead.\n transformIndexHtml() {\n return [\n {\n tag: 'script',\n attrs: { type: 'module', src: joinBase(base, '/@id/' + DIAGNOSTICS_CLIENT_ID) },\n injectTo: 'head' as const,\n },\n ];\n },\n\n configureServer(server) {\n // Announce the surface in the startup block. This is a discovery\n // channel: agents watching dev-server output learn the endpoint and\n // the skill documents without any project-level pointer (AGENTS.md).\n const originalPrintUrls = server.printUrls.bind(server);\n server.printUrls = () => {\n originalPrintUrls();\n const local = server.resolvedUrls?.local[0];\n const endpoint = local\n ? new URL(DIAGNOSTICS_ENDPOINT, local).href\n : DIAGNOSTICS_ENDPOINT;\n server.config.logger.info(\n ` ➜ Solid diagnostics: ${endpoint} ` +\n `(GET status; POST {\"method\":\"begin\"|\"end\"|\"whyDidRun\"|\"costs\"})\\n` +\n ` ➜ Agent skills: node_modules/${DIAGNOSTICS_PACKAGE}/skills/agent-loops/SKILL.md, ` +\n `node_modules/solid-js/skills/reactivity-diagnostics/SKILL.md`,\n );\n };\n\n interface Pending {\n resolve: (response: DiagnosticsResponse) => void;\n timer: ReturnType<typeof setTimeout>;\n }\n const pending = new Map<number, Pending>();\n let nextId = 1;\n\n server.ws.on(RESPONSE_EVENT, (data: DiagnosticsResponse) => {\n const entry = pending.get(data?.id as number);\n if (!entry) return;\n pending.delete(data.id);\n clearTimeout(entry.timer);\n entry.resolve(data);\n });\n\n server.middlewares.use(DIAGNOSTICS_ENDPOINT, async (req, res) => {\n // The middleware mounts on the exact path; anything deeper is 404.\n if (req.url && req.url !== '/' && req.url !== '') {\n sendJson(res, 404, { error: `Unknown diagnostics path ${req.url}` });\n return;\n }\n if (req.method === 'GET') {\n sendJson(res, 200, {\n ok: true,\n methods: METHODS,\n clients: server.ws.clients.size,\n });\n return;\n }\n if (req.method !== 'POST') {\n sendJson(res, 405, { error: 'Use GET for status or POST { method, params }' });\n return;\n }\n\n let body: { method?: string; params?: unknown };\n try {\n body = (await readJsonBody(req)) as { method?: string; params?: unknown };\n } catch (error) {\n sendJson(res, 400, { error: (error as Error).message });\n return;\n }\n if (!body.method || !(METHODS as readonly string[]).includes(body.method)) {\n sendJson(res, 400, {\n error: `Unknown method ${JSON.stringify(body.method)}; expected one of: ${METHODS.join(', ')}`,\n });\n return;\n }\n if (server.ws.clients.size === 0) {\n sendJson(res, 503, {\n error:\n 'No connected page. Open the app in a browser (dev server) so the ' +\n 'diagnostics bridge can answer.',\n });\n return;\n }\n\n const id = nextId++;\n // Broadcast; with several open tabs the first responder wins. Good\n // enough for the agent loop (one page under test); revisit with\n // client targeting if multi-page capture ever matters.\n const response = await new Promise<DiagnosticsResponse | { timeout: string }>(\n (resolve) => {\n const timer = setTimeout(() => {\n pending.delete(id);\n resolve({\n timeout:\n `No page answered within ${RESPONSE_TIMEOUT_MS}ms. The connected page ` +\n 'may predate `diagnostics: true` — reload it.',\n });\n }, RESPONSE_TIMEOUT_MS);\n pending.set(id, { resolve, timer });\n server.ws.send(REQUEST_EVENT, { id, method: body.method, params: body.params });\n },\n );\n\n if ('timeout' in response) {\n sendJson(res, 504, { error: response.timeout });\n } else if (response.error !== undefined) {\n sendJson(res, 400, { error: response.error });\n } else {\n sendJson(res, 200, { result: response.result });\n }\n });\n },\n };\n}\n","// The `\"use server\"` directive compiler. This wraps the native\n// `transformDirectives` pass from @solidjs/compiler (Rust/Oxc); the\n// original Babel implementation (hoisted from solid-start) lived in this\n// directory through vite-plugin-solid@c052963e and remains the frozen\n// reference for the native pass's fixture suite.\n\nexport interface NamedImportDefinition {\n kind: 'named';\n name: string;\n source: string;\n}\n\nexport interface DefaultImportDefinition {\n kind: 'default';\n source: string;\n}\n\nexport type ImportDefinition = DefaultImportDefinition | NamedImportDefinition;\n\nexport interface CompileOptions {\n mode: 'server' | 'client';\n env: 'production' | 'development';\n /** The directive text (default \"use server\" upstream). */\n directive: string;\n /** Project root; function IDs hash the root-relative path. */\n root: string;\n definitions: {\n register: ImportDefinition;\n create: ImportDefinition;\n };\n}\n\nexport interface CompileResult {\n valid: boolean;\n code: string;\n map: string | null;\n functions: import('@solidjs/compiler').ServerFunctionMeta[];\n}\n\ntype NativeCompiler = typeof import('@solidjs/compiler');\nlet compilerPromise: Promise<NativeCompiler> | undefined;\n\n// Loaded lazily so importing the plugin never pays for the native binding —\n// only setups that enable server functions load it (mirrors the JSX\n// compiler's opt-in loader in index.ts).\nasync function loadCompiler(): Promise<NativeCompiler> {\n try {\n return await (compilerPromise ??= import('@solidjs/compiler'));\n } catch (error) {\n compilerPromise = undefined;\n const reason = error instanceof Error ? `\\n\\nCause: ${error.message}` : '';\n throw new Error(\n '@solidjs/vite-plugin: failed to load @solidjs/compiler (the \"use server\" ' +\n 'transform). Your platform should get a prebuilt native binary or the ' +\n '@solidjs/compiler-wasm32-wasi fallback — check that optional ' +\n 'dependencies were installed.' +\n reason,\n );\n }\n}\n\n/**\n * Runs the directive transform over one module. Function IDs are\n * `hash(relative path)-<counter>`, so the client and server builds of the\n * same checkout agree on every ID (the wire contract) without baking\n * machine-specific absolute paths into the output. A `valid: false` result\n * means the module contained no matching directive and must be left\n * untransformed. Invalid closure captures (a server function referencing a\n * non-top-level binding) throw with the variable name and location.\n */\nexport async function compile(\n id: string,\n code: string,\n options: CompileOptions,\n): Promise<CompileResult> {\n const { transformDirectives } = await loadCompiler();\n const result = transformDirectives(code, {\n filename: id,\n root: options.root,\n mode: options.mode,\n env: options.env,\n directive: options.directive,\n sourceMap: true,\n register: options.definitions.register,\n create: options.definitions.create,\n });\n return {\n valid: result.valid,\n code: result.code,\n map: result.map ?? null,\n functions: result.functions,\n };\n}\n","// @ts-nocheck\n/**\n * Hoisted from solid-start (packages/start/src/directives/xxhash32.ts).\n *\n * Copyright (c) 2019 Jason Dent\n * https://github.com/Jason3S/xxhash\n */\nconst PRIME32_1 = 2654435761;\nconst PRIME32_2 = 2246822519;\nconst PRIME32_3 = 3266489917;\nconst PRIME32_4 = 668265263;\nconst PRIME32_5 = 374761393;\n\nfunction toUtf8(text: string): Uint8Array {\n const bytes: number[] = [];\n for (let i = 0, n = text.length; i < n; ++i) {\n const c = text.charCodeAt(i);\n if (c < 0x80) {\n bytes.push(c);\n } else if (c < 0x800) {\n bytes.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f));\n } else if (c < 0xd800 || c >= 0xe000) {\n bytes.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));\n } else {\n const cp = 0x10000 + (((c & 0x3ff) << 10) | (text.charCodeAt(++i) & 0x3ff));\n bytes.push(\n 0xf0 | ((cp >> 18) & 0x7),\n 0x80 | ((cp >> 12) & 0x3f),\n 0x80 | ((cp >> 6) & 0x3f),\n 0x80 | (cp & 0x3f),\n );\n }\n }\n return new Uint8Array(bytes);\n}\n\n/**\n * @param buffer - byte array or string\n * @param seed - optional seed (32-bit unsigned)\n */\nexport default function xxHash32(buffer: Uint8Array | string, seed = 0): number {\n buffer = typeof buffer === 'string' ? toUtf8(buffer) : buffer;\n const b = buffer;\n\n // Step 1. Initialize internal accumulators\n let acc = (seed + PRIME32_5) & 0xffffffff;\n let offset = 0;\n\n if (b.length >= 16) {\n const accN = [\n (seed + PRIME32_1 + PRIME32_2) & 0xffffffff,\n (seed + PRIME32_2) & 0xffffffff,\n (seed + 0) & 0xffffffff,\n (seed - PRIME32_1) & 0xffffffff,\n ];\n\n // Step 2. Process stripes (16 bytes = 4 lanes of 4 bytes)\n const b = buffer;\n const limit = b.length - 16;\n let lane = 0;\n for (offset = 0; (offset & 0xfffffff0) <= limit; offset += 4) {\n const i = offset;\n const laneN0 = b[i + 0] + (b[i + 1] << 8);\n const laneN1 = b[i + 2] + (b[i + 3] << 8);\n const laneNP = laneN0 * PRIME32_2 + ((laneN1 * PRIME32_2) << 16);\n let acc = (accN[lane] + laneNP) & 0xffffffff;\n acc = (acc << 13) | (acc >>> 19);\n const acc0 = acc & 0xffff;\n const acc1 = acc >>> 16;\n accN[lane] = (acc0 * PRIME32_1 + ((acc1 * PRIME32_1) << 16)) & 0xffffffff;\n lane = (lane + 1) & 0x3;\n }\n\n // Step 3. Accumulator convergence\n acc =\n (((accN[0] << 1) | (accN[0] >>> 31)) +\n ((accN[1] << 7) | (accN[1] >>> 25)) +\n ((accN[2] << 12) | (accN[2] >>> 20)) +\n ((accN[3] << 18) | (accN[3] >>> 14))) &\n 0xffffffff;\n }\n\n // Step 4. Add input length\n acc = (acc + buffer.length) & 0xffffffff;\n\n // Step 5. Consume remaining input (up to 15 bytes)\n const limit = buffer.length - 4;\n for (; offset <= limit; offset += 4) {\n const i = offset;\n const laneN0 = b[i + 0] + (b[i + 1] << 8);\n const laneN1 = b[i + 2] + (b[i + 3] << 8);\n const laneP = laneN0 * PRIME32_3 + ((laneN1 * PRIME32_3) << 16);\n acc = (acc + laneP) & 0xffffffff;\n acc = (acc << 17) | (acc >>> 15);\n acc = ((acc & 0xffff) * PRIME32_4 + (((acc >>> 16) * PRIME32_4) << 16)) & 0xffffffff;\n }\n\n for (; offset < b.length; ++offset) {\n const lane = b[offset];\n acc += lane * PRIME32_5;\n acc = (acc << 11) | (acc >>> 21);\n acc = ((acc & 0xffff) * PRIME32_1 + (((acc >>> 16) * PRIME32_1) << 16)) & 0xffffffff;\n }\n\n // Step 6. Final mix (avalanche)\n acc ^= acc >>> 15;\n acc = (((acc & 0xffff) * PRIME32_2) & 0xffffffff) + (((acc >>> 16) * PRIME32_2) << 16);\n acc ^= acc >>> 13;\n acc = (((acc & 0xffff) * PRIME32_3) & 0xffffffff) + (((acc >>> 16) * PRIME32_3) << 16);\n acc ^= acc >>> 16;\n\n // turn any negatives back into a positive number;\n return acc < 0 ? acc + 4294967296 : acc;\n}\n","// Hoisted from solid-start (packages/start/src/directives/index.ts).\n//\n// Standalone `\"use server\"` support for Vite. The compiler half of server\n// functions lives here; the runtime half (registration on the server, a\n// transport on the client) is @solidjs/web/server-functions by default —\n// the compiled output imports `registerServerReference` /\n// `createServerReference` from that specifier and the package's export\n// conditions resolve the right half per environment. Any runtime satisfying\n// that contract can be swapped in through `options.runtime` (SolidStart's,\n// or your own).\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';\nimport path from 'path';\nimport {\n createFilter,\n type EnvironmentModuleGraph,\n type FilterPattern,\n type Plugin,\n type ViteDevServer,\n} from 'vite';\nimport { getEnvironmentConsumer, isRunnableEnvironment } from '../environment.js';\nimport { joinBase, sendWebResponse, webRequestFromNode } from '../http.js';\nimport { compile, type CompileOptions } from './compile.js';\nimport xxHash32 from './xxhash32.js';\n\n/**\n * Picomatch patterns selecting the modules the directive compiler runs on.\n * Relative patterns (the defaults included) are resolved against the Vite\n * root — not the invocation directory — so running `vite` from outside the\n * project keeps compiling the same files. Absolute patterns are used as-is.\n *\n * @default include \"src/**\\/*.{jsx,tsx,ts,js,mjs,cjs}\", exclude \"node_modules/**\\/*.{jsx,tsx,ts,js,mjs,cjs}\"\n */\nexport interface ServerFunctionsFilter {\n include?: FilterPattern;\n exclude?: FilterPattern;\n}\n\nexport interface ServerFunctionsOptions {\n /**\n * Module specifiers the compiled output imports the runtime from.\n * Each must export `registerServerReference(id, fn)` (server) and\n * `createServerReference(...)` (both sides).\n *\n * @default \"@solidjs/web/server-functions\" for both (the package's export\n * conditions resolve the client or server half per environment)\n */\n runtime?: {\n server: string;\n client: string;\n };\n /**\n * Virtual module id that imports every module containing server functions.\n * Import it for side effects in your server entry so all registrations\n * exist before requests are handled.\n *\n * @default \"virtual:solid-server-function-manifest\"\n */\n manifest?: string;\n filter?: ServerFunctionsFilter;\n /**\n * @default \"use server\"\n */\n directive?: string;\n /**\n * Path the server-function transport posts to. Joined with Vite `base`.\n * Threaded to the built-in dev middleware, the\n * `virtual:solid-server-function-handler` module, and — whenever the\n * resolved path differs from the runtime default (`/_server`) — runtime\n * `configureServerFunctions{Client,Server}` calls appended to compiled\n * modules (so custom runtimes used with a custom endpoint must export\n * those).\n *\n * @default \"/_server\"\n */\n endpoint?: string;\n /**\n * Whether the built-in dev middleware owns the server-function endpoint on\n * the Vite dev server. Only meaningful through the main plugin's\n * `serverFunctions` option (the standalone `serverFunctions()` export\n * never installs the middleware).\n *\n * Set `false` when another plugin's server environment should own\n * dispatch in dev — e.g. @cloudflare/vite-plugin, whose workerd\n * environment carries the bindings (`env`/`ctx`) your server functions\n * need: the middleware executes functions in Vite's node-side SSR\n * environment, so with it installed those requests never reach the\n * worker. With the middleware off, everything else keeps working —\n * compilation, the manifest and handler virtual modules — and endpoint\n * requests fall through to whatever the host serves; the host loads\n * `virtual:solid-server-function-handler` itself and dispatches through\n * its `handleServerFunctionRequest` export, exactly like production.\n * Functions referenced only by client code register on demand through\n * the middleware in dev, so a host owning dispatch should side-effect\n * import the manifest module in its server entry to cover them.\n *\n * When a provider owns the dev server's `ssr` environment (it isn't\n * runnable), the middleware already stands down automatically — no need\n * to set this. See `start.external` for the whole-server switch.\n *\n * @default true (stands down automatically when the `ssr` dev environment isn't runnable)\n */\n devMiddleware?: boolean;\n /**\n * Path to a server-only module (resolved relative to the Vite root, like\n * `start.document`) that the generated\n * `virtual:solid-server-function-handler` module side-effect imports\n * before configuring the runtime. A guaranteed pre-dispatch home for\n * server-side registration — typically `configureServerFunctionsServer`\n * calls whose config the app graph can't reliably install first, e.g. a\n * router's single-flight collector:\n *\n * ```ts\n * // src/server-config.ts\n * import { configureServerFunctionsServer } from '@solidjs/web/server-functions/server';\n * configureServerFunctionsServer({ collectFlightData: createFlightDataCollector(router) });\n * ```\n *\n * Because the module lives in the handler graph, it is evaluated before\n * any dispatch on every surface — the dev middleware and the production\n * handler alike — and is immune to the dev-restart race where\n * registration living in the app graph only loads with the first page\n * render (the handler graph loads before the first mutation). Config\n * calls merge per key, so it composes with the plugin's own\n * `configureServerFunctionsServer` call in the same module.\n *\n * @default undefined\n */\n configure?: string;\n /**\n * Enable server components (experimental): `\"use server\"` functions that\n * return a component. Responses for them are served over the\n * server-function endpoint as streamed HTML that the client runtime\n * applies in place of the boundary (instead of decoding it as data).\n *\n * The plugin's dispatch surfaces — the built-in dev middleware and the\n * `virtual:solid-server-function-handler` module — install the response\n * transform on the server runtime automatically, so this needs no\n * per-request wiring or server code.\n *\n * Document SSR of server components (rendered inline at t=0 and adopted\n * at boot with zero endpoint requests) needs three more pieces: the\n * render must run with the server-component render plugin, the document\n * must carry the bootstrap script, and the client must call\n * `installServerComponents()` before hydrating. With SSR start mode (the\n * main plugin's `start` option with `ssr: true`) and generated entries\n * the plugin emits all three. With authored entries those pieces live in\n * your entry files — import them from `@solidjs/web/frames` (see the\n * README).\n *\n * All of this is pure codegen: when the option is off, no reference to\n * the server-component runtime is emitted anywhere.\n *\n * @default false\n */\n components?: boolean;\n}\n\nconst DEFAULT_INCLUDE = 'src/**/*.{jsx,tsx,ts,js,mjs,cjs}';\nconst DEFAULT_EXCLUDE = 'node_modules/**/*.{jsx,tsx,ts,js,mjs,cjs}';\nconst DEFAULT_MANIFEST = 'virtual:solid-server-function-manifest';\nconst DEFAULT_DIRECTIVE = 'use server';\nconst DEFAULT_RUNTIME = '@solidjs/web/server-functions';\n// Must match the runtime's built-in default — when the resolved endpoint\n// equals it, no configure calls need to be emitted at all.\nconst DEFAULT_ENDPOINT = '/_server';\nconst STORAGE_SOURCE = '@solidjs/web/storage';\n// Server-only handler: importing it wires the endpoint in one line\n// (registrations via the manifest, request-event scoping, endpoint config).\nconst HANDLER_ID = 'virtual:solid-server-function-handler';\n\n// Server functions referenced only from client-side code (e.g. event\n// handlers, which the SSR JSX compile drops) never get imported — or even\n// transformed — by the server build, so their registrations would be missing\n// at runtime. That's why the client transform records modules into the\n// *server* manifest set. The dev server and Vite's builder mode share one\n// process where that just works; the classic two-invocation build\n// (`vite build` then `vite build --ssr`) does not, so the client build\n// persists its findings for the SSR build to merge (mirroring the plugin's\n// dist/client/.vite/manifest.json convention).\nconst PERSISTED_MANIFEST_PATH = '.vite/solid-server-functions.json';\n\nfunction readPersistedManifest(root: string): Set<string> {\n const file = path.resolve(root, 'dist/client', PERSISTED_MANIFEST_PATH);\n if (!existsSync(file)) return new Set();\n try {\n const entries: string[] = JSON.parse(readFileSync(file, 'utf-8'));\n return new Set(\n entries.map((entry) => path.resolve(root, entry)).filter((entry) => existsSync(entry)),\n );\n } catch {\n return new Set();\n }\n}\n\nfunction writePersistedManifest(root: string, outDir: string, entries: Set<string>): void {\n const file = path.resolve(root, outDir, PERSISTED_MANIFEST_PATH);\n mkdirSync(path.dirname(file), { recursive: true });\n const relative = [...entries].map((entry) =>\n path.relative(root, entry).split(path.sep).join('/'),\n );\n writeFileSync(file, JSON.stringify(relative, null, 2));\n}\n\ntype Manifest = Record<CompileOptions['mode'], Set<string>>;\n\nfunction createManifest(): Manifest {\n return {\n server: new Set(),\n client: new Set(),\n };\n}\n\ninterface DeferredPromise<T> {\n reference: Promise<T>;\n resolve: (value: T) => void;\n reject: (value: any) => void;\n}\n\nfunction createDeferredPromise<T>(): DeferredPromise<T> {\n let resolve: DeferredPromise<T>['resolve'];\n let reject: DeferredPromise<T>['reject'];\n\n return {\n reference: new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n }),\n resolve(value) {\n resolve(value);\n },\n reject(value) {\n reject(value);\n },\n };\n}\n\n// The manifest can only be emitted once every module has been transformed\n// (each transform may register new entries), but Vite gives no such signal —\n// so the manifest load resolves a debounced snapshot that transforms keep\n// pushing back while they are still landing.\nclass Debouncer<T> {\n promise: DeferredPromise<T>;\n\n private timeout: ReturnType<typeof setTimeout> | undefined;\n\n constructor(private source: () => T) {\n this.promise = createDeferredPromise();\n this.defer();\n }\n\n defer(): void {\n if (this.timeout) {\n clearTimeout(this.timeout);\n this.timeout = undefined;\n }\n this.timeout = setTimeout(() => {\n this.promise.resolve(this.source());\n }, 1000);\n }\n}\n\nfunction mergeManifestRecord(\n source: Set<string>,\n target: Set<string>,\n): { invalidPreload: boolean; invalidated: string[] } {\n const current = source.size;\n for (const entry of target) {\n source.add(entry);\n }\n return {\n invalidPreload: current !== source.size,\n invalidated: [...source],\n };\n}\n\nfunction invalidateModule(moduleGraph: EnvironmentModuleGraph, path: string) {\n const target = moduleGraph.getModuleById(path);\n if (target) {\n moduleGraph.invalidateModule(target);\n }\n}\n\nfunction invalidateModules(\n server: ViteDevServer | undefined,\n result: ReturnType<typeof mergeManifestRecord>,\n manifest: string,\n): void {\n if (server?.environments && result.invalidPreload) {\n invalidateModule(server.environments.client.moduleGraph, manifest);\n invalidateModule(server.environments.ssr.moduleGraph, manifest);\n }\n}\n\n/**\n * The second parameter is internal wiring for the main plugin's\n * `serverFunctions` option: the built-in dev middleware is only installed\n * through that path, so meta-frameworks composing this factory directly\n * (and dispatching to `handleServerFunctionRequest` themselves) never race\n * it for the endpoint. On the main plugin's path the public\n * `options.devMiddleware` (default true) can opt back out of it.\n */\nexport function serverFunctions(\n options: ServerFunctionsOptions = {},\n internal: { devMiddleware?: boolean; externalDevServer?: boolean; ssrHandler?: string } = {},\n): Plugin[] {\n const filterInclude = options.filter?.include || DEFAULT_INCLUDE;\n const filterExclude = options.filter?.exclude || DEFAULT_EXCLUDE;\n // Recreated in configResolved: relative patterns (the defaults included)\n // must resolve against the Vite root, not process.cwd() — running `vite`\n // from outside the project would otherwise silently skip every module.\n let filter = createFilter(filterInclude, filterExclude);\n const manifestId = options.manifest || DEFAULT_MANIFEST;\n const directive = options.directive || DEFAULT_DIRECTIVE;\n const runtime = options.runtime || { server: DEFAULT_RUNTIME, client: DEFAULT_RUNTIME };\n const endpointOption = options.endpoint || DEFAULT_ENDPOINT;\n const endpoint = endpointOption.startsWith('/') ? endpointOption : '/' + endpointOption;\n const components = !!options.components;\n // The middleware only exists on the main plugin's path to begin with (see the\n // `internal` parameter doc); the public option opts out of it there.\n const installDevMiddleware = !!internal.devMiddleware && options.devMiddleware !== false;\n\n let env: CompileOptions['env'];\n let root = process.cwd();\n let base = '/';\n let isBuild = false;\n let isSsrBuild = false;\n let outDir = 'dist';\n // Endpoint with Vite `base` applied; final after configResolved, which\n // runs before every transform/load/middleware that reads it.\n let resolvedEndpoint = endpoint;\n // Absolute path of the user's `configure` module; resolved (and existence-\n // checked) in configResolved, before any handler load can read it.\n let configureModulePath: string | null = null;\n\n const manifest = createManifest();\n\n const preload: Record<CompileOptions['mode'], Debouncer<string> | undefined> = {\n server: undefined,\n client: undefined,\n };\n let currentServer: ViteDevServer | undefined;\n\n const clientOptions: Pick<CompileOptions, 'directive' | 'definitions'> = {\n directive,\n definitions: {\n register: {\n kind: 'named',\n name: 'registerServerReference',\n source: runtime.client,\n },\n create: {\n kind: 'named',\n name: 'createServerReference',\n source: runtime.client,\n },\n },\n };\n const serverOptions: Pick<CompileOptions, 'directive' | 'definitions'> = {\n directive,\n definitions: {\n register: {\n kind: 'named',\n name: 'registerServerReference',\n source: runtime.server,\n },\n create: {\n kind: 'named',\n name: 'createServerReference',\n source: runtime.server,\n },\n },\n };\n\n // A non-default endpoint (custom option, or Vite `base` prefixing the\n // default) must reach the runtime on both sides — the client transport\n // reads it for every fetch, the server for rendered reference `.url`s.\n // References are only reachable through compiled modules, so appending the\n // configure call to each guarantees it runs before any reference is used.\n // The default endpoint appends nothing, keeping compiled output byte-\n // identical for setups that wire the runtime themselves.\n function endpointConfigureSnippet(mode: CompileOptions['mode']): string {\n if (resolvedEndpoint === DEFAULT_ENDPOINT) return '';\n const name =\n mode === 'server' ? 'configureServerFunctionsServer' : 'configureServerFunctionsClient';\n const source = mode === 'server' ? runtime.server : runtime.client;\n return (\n `\\nimport { ${name} as $$configureServerFunctions } from ${JSON.stringify(source)};` +\n `\\n$$configureServerFunctions({ endpoint: ${JSON.stringify(resolvedEndpoint)} });\\n`\n );\n }\n\n // Dev omits the manifest import: the middleware loads the referenced\n // module on demand instead (importing the debounced manifest would stall\n // the first request and eagerly SSR-load every server-function module).\n // Builds import it so tree-shaking can't drop registrations for functions\n // only client code references.\n function handlerModuleCode(includeManifest: boolean): string {\n // Server components ride the frame-stream wire protocol: the transform\n // serves a function's component result as streamed HTML instead of data.\n // Installing it here (config-level, merged with the other keys) covers\n // both dispatch surfaces — the dev middleware and the prod handler load\n // this module before dispatching — with zero per-request wiring. The\n // import is only emitted when the option is on, so disabled setups keep\n // a server-component-free graph.\n return [\n // The user's `configure` module comes first: a side-effect import in\n // the handler graph, evaluated before any dispatch on both surfaces\n // (dev middleware and prod handler) and bundled into the handler\n // chunk by production builds. Order relative to the configure call\n // below doesn't actually matter — runtime config merges per key —\n // import-first is just the cleaner shape.\n ...(configureModulePath ? [`import ${JSON.stringify(configureModulePath)};`] : []),\n ...(includeManifest ? [`import ${JSON.stringify(manifestId)};`] : []),\n `import { handleServerFunctionRequest as handle, configureServerFunctionsServer } from ${JSON.stringify(runtime.server)};`,\n `import { provideRequestEvent } from ${JSON.stringify(STORAGE_SOURCE)};`,\n ...(components\n ? [\n `import { frameTransformResult, frameTransformFlightResult, frameTransformDirectResult } from '@solidjs/web/frames';`,\n ]\n : []),\n // `transformFlightResult` is the single-flight leg of the same wire\n // protocol: a mutation whose invalidated payload includes markup gets\n // the frame stream as its carrier (regions + envelope in one\n // response). It only runs when a router registered a collectFlightData\n // hook, so installing it unconditionally alongside the result\n // transform costs disabled setups nothing.\n //\n // `transformDirectResult` is ALSO installed here — not just in the\n // generated SSR entry — because flight collection makes direct\n // (in-process) calls during handler dispatch, and the transform is what\n // brands their results with the call address the client matches showing\n // boundaries against. The SSR entry usually loads first and installs\n // the same value (config merges per key), but the handler graph cannot\n // depend on that: in dev, a mutation from an already-open page can be\n // the first request after a server restart.\n `configureServerFunctionsServer({ provideEvent: provideRequestEvent, endpoint: ${JSON.stringify(resolvedEndpoint)}${\n components\n ? ', transformResult: frameTransformResult, transformFlightResult: frameTransformFlightResult, transformDirectResult: frameTransformDirectResult'\n : ''\n } });`,\n `export const endpoint = ${JSON.stringify(resolvedEndpoint)};`,\n // `options.event` is the same wrapper->event extension seam the SSR\n // handler's handleRequest carries (conventionally `nativeEvent`, the\n // platform's raw request object). The runtime's standalone handler\n // creates its own event (`{ request, locals }`) with no init\n // parameter, so the extension threads through its existing\n // `createEvent` option instead — spread before `...options` so an\n // explicit host-provided createEvent still wins.\n `export function handleServerFunctionRequest(request, options) {`,\n ` const { event: eventInit, ...rest } = options || {};`,\n ` return handle(request, {`,\n ` provideEvent: provideRequestEvent,`,\n ` ...(eventInit ? { createEvent: (req) => ({ request: req, locals: {}, ...eventInit }) } : {}),`,\n ` ...rest,`,\n ` });`,\n `}`,\n ].join('\\n');\n }\n\n // Function IDs are `<name>-<xxHash32(root-relative path)>[-<ordinal>]`\n // (identity-keyed, solidjs/solid#3109). The name is a JS identifier and\n // never contains `-`, so the hash is always the second segment and maps\n // an incoming ID back to its module. Rebuilt whenever a transform has\n // grown the manifest.\n const hashIndex = new Map<string, string>();\n let hashIndexSize = -1;\n function moduleForFunctionId(functionId: string): string | undefined {\n if (manifest.server.size !== hashIndexSize) {\n hashIndex.clear();\n for (const entry of manifest.server) {\n const relative = path.relative(root, entry).split(path.sep).join('/');\n hashIndex.set(xxHash32(relative).toString(16), entry);\n }\n hashIndexSize = manifest.server.size;\n }\n return hashIndex.get(functionId.split('-')[1]!);\n }\n\n function moduleDevUrl(entry: string): string {\n const relative = path.relative(root, entry).split(path.sep).join('/');\n return relative.startsWith('..') ? '/@fs/' + entry : '/' + relative;\n }\n\n const startPlugins: Plugin[] = [\n {\n name: 'solid:server-functions/handler',\n enforce: 'pre',\n resolveId(source, _importer, opts) {\n if (source === HANDLER_ID) {\n if (getEnvironmentConsumer(this.environment, opts) !== 'server') {\n this.error(\n `${HANDLER_ID} is server-only; import it from your server entry (SSR build).`,\n );\n }\n return { id: HANDLER_ID, moduleSideEffects: true };\n }\n return null;\n },\n load(id, opts) {\n if (id === HANDLER_ID && getEnvironmentConsumer(this.environment, opts) === 'server') {\n const externalDev =\n this.environment.mode === 'dev' &&\n (internal.externalDevServer || !isRunnableEnvironment(this.environment));\n return handlerModuleCode(isBuild || externalDev);\n }\n return null;\n },\n },\n ];\n\n if (installDevMiddleware) {\n startPlugins.push({\n name: 'solid:server-functions/dev-middleware',\n apply: 'serve',\n configureServer(server) {\n const ssrEnvironment = server.environments.ssr;\n if (internal.externalDevServer || !isRunnableEnvironment(ssrEnvironment)) {\n return;\n }\n // A call's address is `<endpoint>/<id>` — plain HTTP — or\n // `<endpoint>/data/<id>` — the scripted transport's own path\n // (solidjs/solid#3076, #3094). Bare-mount requests still reach the\n // runtime handler (it answers 404), so misdirected posts fail\n // through the endpoint rather than falling through to SSR.\n const underMount = (pathname: string, mount: string) =>\n pathname === mount || pathname.startsWith(mount + '/');\n server.middlewares.use((req, res, next) => {\n const url = new URL(req.url || '/', 'http://localhost');\n // Match with and without `base` — middleware-mode hosts may mount\n // vite.middlewares below the base themselves.\n if (!underMount(url.pathname, resolvedEndpoint) && !underMount(url.pathname, endpoint)) {\n return next();\n }\n const basePrefixed = underMount(url.pathname, resolvedEndpoint);\n // When the stripped form matched, restore the base for dispatch:\n // the generated handler compares the request pathname against the\n // base-prefixed endpoint, and production handlers only ever see\n // base-prefixed URLs.\n const dispatchUrl = basePrefixed ? undefined : joinBase(base, req.url || '/');\n (async () => {\n // Make sure the referenced module has been evaluated in the SSR\n // environment so its registration exists — functions only client\n // code references are never loaded by the SSR render itself.\n // The id lives in the path segment after the mount — behind a\n // literal `data` segment on the scripted transport's address\n // (solidjs/solid#3094). Segment count keeps the two apart: an id\n // occupies exactly one segment, so `data/<id>` is only ever a\n // data address, and a function id spelled `data` still parses at\n // the bare one.\n const mount = basePrefixed ? resolvedEndpoint : endpoint;\n let segment = url.pathname.slice(mount.length + 1);\n if (segment.startsWith('data/')) segment = segment.slice(5);\n let functionId: string | null = null;\n if (segment && !segment.includes('/')) {\n try {\n functionId = decodeURIComponent(segment);\n } catch {\n // not an address; the runtime handler answers the 404\n }\n }\n if (functionId) {\n const entry = moduleForFunctionId(functionId);\n if (entry) await ssrEnvironment.runner.import(moduleDevUrl(entry));\n }\n // Dispatch through a module evaluated in the SSR environment so\n // the handler shares the registry instance with the app modules.\n // With SSR start mode active the main plugin threads its handler id\n // in, and dispatch goes through `handleRequest` instead — one\n // middleware chain and one stub-backed request event front the\n // endpoint exactly as they front page SSR.\n const handler = await ssrEnvironment.runner.import(internal.ssrHandler ?? HANDLER_ID);\n // Both dispatch shapes carry the raw Node request on the event\n // (the `options.event` seam), matching the SSR dev middleware\n // and what a production Node entry passes.\n const dispatchOptions = { event: { nativeEvent: req } };\n const response: Response = internal.ssrHandler\n ? await handler.handleRequest(\n webRequestFromNode(req, dispatchUrl, res),\n dispatchOptions,\n )\n : await handler.handleServerFunctionRequest(\n webRequestFromNode(req, dispatchUrl, res),\n dispatchOptions,\n );\n await sendWebResponse(res, response);\n })().catch((error) => {\n next(error);\n });\n });\n },\n });\n }\n\n return [\n {\n name: 'solid:server-functions/setup',\n enforce: 'pre',\n configResolved(config) {\n env = config.mode !== 'production' ? 'development' : 'production';\n root = config.root;\n base = config.base;\n filter = createFilter(filterInclude, filterExclude, { resolve: root });\n isBuild = config.command === 'build';\n isSsrBuild = !!config.build.ssr;\n outDir = config.build.outDir;\n resolvedEndpoint = joinBase(config.base, endpoint);\n if (options.configure) {\n const absolute = path.isAbsolute(options.configure)\n ? options.configure\n : path.resolve(root, options.configure);\n if (!existsSync(absolute)) {\n throw new Error(\n `[@solidjs/vite-plugin] serverFunctions.configure does not exist: ${options.configure}`,\n );\n }\n configureModulePath = absolute;\n }\n if (isBuild && isSsrBuild) {\n // Classic two-invocation build: pick up the modules the client\n // build discovered so the server manifest registers them even when\n // the SSR module graph never imports them.\n for (const entry of readPersistedManifest(root)) {\n manifest.server.add(entry);\n }\n }\n },\n configureServer(server) {\n currentServer = server;\n },\n writeBundle() {\n // Same client-build detection as the main plugin: builder-mode builds\n // run both environments in one process, so prefer the per-environment\n // consumer over the process-wide --ssr flag.\n const ctx = this as { environment?: { config?: { consumer?: string } } };\n const consumer = ctx.environment?.config?.consumer;\n const isClient = consumer ? consumer === 'client' : !isSsrBuild;\n if (isBuild && isClient) {\n writePersistedManifest(root, outDir, manifest.server);\n }\n },\n },\n {\n name: 'solid:server-functions/manifest',\n enforce: 'pre',\n resolveId(source) {\n if (source === manifestId) {\n return { id: manifestId, moduleSideEffects: true };\n }\n return null;\n },\n async load(id, opts) {\n const mode = getEnvironmentConsumer(this.environment, opts);\n if (id === manifestId) {\n if (isBuild && mode === 'server') {\n // Merge the client build's persisted discoveries at load time,\n // not just configResolved: in builder mode (single process,\n // `vite build` with the environments API) all environment\n // configs resolve before the client build has written the file,\n // but this load runs once the SSR environment builds — after it.\n for (const entry of readPersistedManifest(root)) {\n manifest.server.add(entry);\n }\n }\n const current = new Debouncer(() =>\n [...manifest[mode]].map((entry) => `import ${JSON.stringify(entry)};`).join('\\n'),\n );\n preload[mode] = current;\n const result = await current.promise.reference;\n return result;\n }\n return null;\n },\n },\n {\n name: 'solid:server-functions/compiler',\n enforce: 'pre',\n async transform(code, fileId, opts) {\n const mode = getEnvironmentConsumer(this.environment, opts);\n const [id] = fileId.split('?');\n if (!filter(id)) {\n return null;\n }\n\n // Fast path: the directive has to appear literally, so anything\n // without the substring can skip the native parse entirely.\n if (!code.includes(directive)) {\n return null;\n }\n\n const result = await compile(id!, code, {\n ...(mode === 'server' ? serverOptions : clientOptions),\n mode,\n env,\n root,\n });\n\n if (result.valid) {\n const preloader = preload[mode];\n if (preloader) {\n preloader.defer();\n }\n invalidateModules(\n currentServer,\n mergeManifestRecord(manifest.server, new Set([id!])),\n manifestId,\n );\n\n return {\n // Appended (not prepended) so the source map for the compiled\n // module stays valid; imports hoist and the endpoint is only\n // read at call time, never during module evaluation.\n code: (result.code || '') + endpointConfigureSnippet(mode),\n map: result.map,\n };\n }\n return null;\n },\n },\n ...startPlugins,\n ];\n}\n","export const DEVTOOLS_PACKAGE = '@solidjs/start-devtools';\nexport const DEVTOOLS_MOUNT_ID = 'virtual:solid-devtools/mount';\n\nexport function devtoolsMountModuleCode(): string {\n return [\n `import { mountDevToolbar } from '${DEVTOOLS_PACKAGE}';`,\n `mountDevToolbar();`,\n ].join('\\n');\n}\n","// Start-mode serving for plain Vite apps: `solid({ start: {...} })` (or the\n// zero-config sugar `start: true`) adds a serving layer with conventional\n// entries so no hand-rolled wiring is needed, and the plugin's `ssr`\n// boolean picks the mode — `ssr: true` server-renders the app per request;\n// `ssr: false`/omitted is client mode (the same conventions, but the\n// document shell is served/prerendered empty and the app `render()`s\n// client-side). The flip between them is that one boolean.\n//\n// SSR mode (`start` + `ssr: true`):\n// - Dev: runnable SSR environments are served by a Vite middleware. Provider-\n// owned environments serve through `virtual:solid-ssr-handler` instead.\n// Both paths inject the Vite client, dev style patch, and entry CSS as\n// `<style data-vite-dev-id>` tags before the body can paint.\n// - Prod: the plugin configures a full-app build (client + server bundles\n// via the Vite environments/builder API — a single `vite build` builds\n// both) whose server entry is `virtual:solid-ssr-handler`: an\n// adapter-agnostic named `handleRequest(Request) => Promise<Response>` plus\n// a default Fetchable `{ fetch(request) }` export. Both scope each request\n// with `provideRequestEvent`, stream the render, and resolve hashed client\n// assets through `virtual:solid-manifest`.\n// - Entries are conventional with escape hatches: `src/entry-server.*` /\n// `src/entry-client.*` are used when present (or set explicitly); when\n// absent, default entries are generated from a single root component\n// (`start.app`, defaulting to `src/App.*`) wrapped in a document shell\n// (`start.document`, defaulting to `src/Document.*`, else a built-in one).\n// - When `serverFunctions` is also enabled, the handler composes the\n// endpoint on every surface; the runnable-dev server-function middleware\n// pre-loads the referenced module, then dispatches through this handler.\n// - Every dispatch runs under a stub-backed request event\n// (`createRequestEvent`) with the optional `start.middleware` chain fronting\n// it, and page responses go through the runtime's `createSSRResponse`\n// head lifecycle (commit at shell flush, real pre-flush redirects, the\n// script fallback post-flush).\n// - `vite preview` serves dist/client statically and dispatches everything\n// else through the built handler — the production path, middleware\n// included, with no server file needed.\n//\n// Client mode (`start` without `ssr: true`) rides the same machinery with\n// three deltas: the generated server entry renders the document shell\n// WITHOUT the app (dev serving doubles as history fallback, and a\n// post-build hook prerenders it once into dist/client/index.html), the\n// generated client entry render()s instead of hydrating, and dist/server is\n// dropped from the output unless `serverFunctions` needs it for the\n// endpoint. Client code compiles non-hydratable, exactly like a plain SPA.\nimport { existsSync, rmSync, writeFileSync } from 'fs';\nimport path from 'path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport {\n type DevEnvironment,\n type FilterPattern,\n normalizePath,\n type Plugin,\n type PreviewServer,\n type ViteDevServer,\n} from 'vite';\nimport { getEnvironmentConsumer, isRunnableEnvironment } from '../environment.js';\nimport {\n DEVTOOLS_MOUNT_ID,\n DEVTOOLS_PACKAGE,\n devtoolsMountModuleCode,\n} from '../devtools/index.js';\nimport { DIAGNOSTICS_CLIENT_ID } from '../diagnostics/index.js';\nimport {\n collectDevStyles,\n collectDevStyleSources,\n type DevStyleFilter,\n devStylePatch,\n renderDevStyleTag,\n} from '../dev-manifest.js';\nimport { joinBase, sendWebResponse, webRequestFromNode } from '../http.js';\n\n/**\n * Options for the main plugin's `start` option (`start: true` is\n * sugar for the empty bag). One bag serves both modes — the plugin's `ssr`\n * boolean picks between them, so flipping a project between\n * client-rendered and server-rendered is toggling that boolean, never\n * reshaping this object. Server-only options (`entryServer`, `external`)\n * are documented no-ops in client mode: they stay in the config across a\n * flip instead of erroring.\n */\nexport interface StartOptions {\n /**\n * Root component module for generated entries (the zero-config path).\n * Resolved relative to the Vite root.\n *\n * @default \"src/App.{tsx,jsx,ts,js}\" (also probes lowercase \"src/app.*\")\n */\n app?: string;\n /** Options for development CSS crawling. */\n css?: {\n /**\n * Filter for the modules traversed while collecting the CSS that dev\n * SSR inlines into `<head>`. Patterns are\n * [picomatch](https://github.com/micromatch/picomatch) globs or regexes;\n * relative globs resolve against the Vite root. CSS files themselves\n * and virtual modules always pass — the filter decides which module\n * graphs are crawled, not which stylesheets are kept.\n *\n * `exclude` prunes matching graphs and defaults to `/node_modules/`\n * (providing your own replaces the default). `include` opts matching\n * files back in on top of that baseline — typically a package whose\n * CSS should be server-inlined to avoid a development FOUC, e.g.\n * `{ include: /node_modules\\/some-ui-lib/ }`. A file matching both\n * stays excluded. Development only: production CSS always comes from\n * the built assets.\n */\n filter?: {\n include?: FilterPattern;\n exclude?: FilterPattern;\n };\n };\n /**\n * Server entry module. Must export `render(request?, context?)` returning\n * a `renderToStream` result, an HTML string, or a `Response`.\n * `context.clientEntry` carries the resolved client entry URL.\n *\n * Server mode only — ignored in client mode, where the server entry is\n * always generated (it renders the document shell without the app, for\n * dev serving and the build-time prerender). Conventional\n * `src/entry-server.*` files are likewise ignored there.\n *\n * @default \"src/entry-server.{tsx,jsx,ts,js,mjs}\" when present, else a\n * generated entry rendering `<Document><App /></Document>`\n */\n entryServer?: string;\n /**\n * Client entry module. In SSR mode it hydrates; in client mode it mounts\n * (a generated one calls `render()`), and it stands alone — no pairing\n * rule with a server entry.\n *\n * @default \"src/entry-client.{tsx,jsx,ts,js,mjs}\" when present, else a\n * generated entry\n */\n entryClient?: string;\n /**\n * Document shell component wrapping the app in generated entries. Receives\n * `props.children` and must render the full `<html>` document including\n * `<HydrationScript />` (in client mode, where nothing hydrates, the\n * handler strips its output from the served/prerendered shell — a shared\n * Document costs nothing across the flip; the built-in shell omits it per\n * mode). Only used when the server entry is generated.\n *\n * @default \"src/Document.{tsx,jsx}\" when present, else a built-in shell\n */\n document?: string;\n /**\n * Path to a server-only module (resolved relative to the Vite root) whose\n * default export is one fetch-style middleware function — `(request,\n * next) => Response | Promise<Response>` — or an array of them, composed\n * in order. The chain fronts every request the plugin dispatches — page\n * SSR, the server-function endpoint, dev and production, `vite preview` —\n * and runs inside the request-event scope, so `getRequestEvent()` works\n * exactly as it does in application code (decorate `locals`, write the\n * `response` stub). `next()` advances the chain (pass a `Request` to\n * substitute it downstream); nothing reaches the wire until the outermost\n * middleware returns, so headers on the returned `Response` stay mutable\n * after `next()` — streamed bodies included — and error middleware is a\n * plain `try { return await next(); } catch { ... }`.\n *\n * All methods and accept types dispatch through the chain — API routes\n * and no-JS form POSTs included, in dev exactly as in production. A\n * non-page request (anything but an HTML-accepting GET) that no\n * middleware handled falls back to Vite's own pipeline in dev instead of\n * rendering the page at it.\n *\n * @default undefined\n */\n middleware?: string;\n /**\n * Path to a server-only module (resolved relative to the Vite root) whose\n * default export runs once per request in the generated server entry,\n * after the middleware chain has dispatched to the page render and\n * immediately before `renderToStream`: `(event, App) => Component | void |\n * Promise<Component | void>`. The per-request seam for routers that must\n * prepare an app instance before SSR begins (create a router bound to the\n * request, `await router.load()`, then render): return a component and the\n * generated entry renders it in the app's place inside the Document;\n * return nothing and `<App />` renders unchanged. `event` is the shared\n * request event — the same one the middleware chain decorated (`locals`\n * are visible) — and the hook runs inside the request scope, so\n * `getRequestEvent()` answers in anything it calls.\n *\n * Only meaningful with generated entries: an authored `entry-server`\n * already owns its render function, so configuring both is an error.\n * Server mode only — ignored in client mode (there is no per-request app\n * render to prepare), so the config survives the `ssr` boolean flip.\n *\n * @default undefined\n */\n setup?: string;\n /**\n * Typed, validated environment variables. A schema file — conventionally\n * `env.ts` (or `env.js`) at the project root, probed automatically —\n * default-exports `{ server?, client? }` maps of Standard Schema\n * validators (zod, valibot, arktype, mixable per key), and the plugin\n * exposes the validated values through `virtual:env/server` (all vars,\n * server module graphs only — a client-graph import is a hard error) and\n * `virtual:env/client` (the `VITE_`-prefixed `client` side; the prefix is\n * enforced at config time). Validation runs at config/build time in node\n * only against Vite's `loadEnv` merge of the `.env*` files (with\n * `process.env` winning), which the plugin also folds into `process.env`\n * itself — no `loadEnv` boilerplate in vite.config. Failures fail the\n * build / render the dev error overlay with the per-key report, and a\n * `solid-env.d.ts` is generated next to the schema so both virtual\n * modules are fully typed by inference.\n *\n * Client values are baked as plain JSON (that's what `VITE_` means); no\n * validator ships in a client bundle, and a client-build leak scan\n * errors when a server value shows up in a client chunk. Server values\n * are NOT baked: `virtual:env/server` reads `process.env` at server boot\n * and validates through your schema (imported into the server bundle\n * only), so platform-injected vars work and secrets rotate without a\n * rebuild — no secret exists in any dist artifact. Build-time server\n * failures are a deferred-to-boot warning; dev failures stay hard.\n * Boot validation is synchronous — the generated module carries no\n * top-level await, so server bundles work on non-esnext targets\n * (Nitro's node-server preset needs no `esnext` override) — which is\n * why async validators are rejected for `server` keys at config time\n * (`client` keys may stay async: they are awaited at build time).\n *\n * `true` requires the conventional file (error when missing); a string\n * is an explicit schema path; `false` disables even the probing.\n * Env is a start-mode feature: without `start` there is no env layer.\n *\n * @default undefined (probe env.ts / env.js; off when absent)\n */\n env?: boolean | string;\n /**\n * Enable the development toolbar. By default it is enabled when\n * `@solidjs/start-devtools` is installed. Setting this to `true` requires\n * the package, while `false` disables it.\n *\n * @default undefined\n */\n devtools?: boolean;\n /**\n * Add the default production error boundary to generated entries.\n * Disable this when application middleware owns error handling. Authored\n * entries are unaffected.\n *\n * @default true\n */\n errorBoundary?: boolean;\n /**\n * Let a host integration own the server environment — build wiring and\n * HTTP serving alike. The plugin skips its start-mode server-build config and\n * stands its dev middlewares down (SSR serving and the server-function\n * endpoint); the generated `virtual:solid-ssr-handler` self-serves\n * instead, inlining dev styles through a virtual module and composing the\n * server-function endpoint. Its named `handleRequest(request)` and default\n * Fetchable exports provide the same contract in dev and production.\n * Generated entries and the client manifest are still provided.\n *\n * Often unnecessary: a provider-owned (non-runnable) `ssr` dev environment\n * is detected automatically and the middlewares stand down on their own;\n * the normal `ssr` environment also exposes the handler as an `index`\n * service entry for provider build orchestrators. Set this only when the\n * host does not adopt that environment — for example, when it uses a\n * different name or independently configures the server build. To hand\n * over only the server-function endpoint, use\n * `serverFunctions.devMiddleware: false` instead.\n *\n * Server mode only — ignored in client mode (there is no server side to\n * hand over; the shell prerender and, with `serverFunctions`, the\n * endpoint handler are the whole story).\n *\n * @default false\n */\n external?: boolean;\n}\n\n// Server-only start-mode request handler; also the server bundle's entry so a\n// production server is one import away from `Request -> Response`. Exported\n// for the main plugin to thread into the server-function dev middleware,\n// which dispatches through it when SSR start mode is active (one middleware\n// chain and one request event across both dispatch paths).\nexport const SSR_HANDLER_ID = 'virtual:solid-ssr-handler';\nconst HANDLER_ID = SSR_HANDLER_ID;\n// Dev-only response marker: the generated dev handler answers non-page\n// requests that fell through the whole middleware chain to the terminal\n// page dispatch with a marked 404 instead of rendering HTML at them, and\n// the dev middleware hands those back to Vite's pipeline. Production has no\n// such seam — every unhandled request renders — but production also has no\n// Vite pipeline to fall back to.\nconst DEV_FALLTHROUGH_HEADER = 'x-solid-dev-fallthrough';\n// Private protocol between the two generated modules when `start.setup` is\n// async: the entry hands the handler the renderToStream result under this\n// key, because a promise resolving to the stream BARE would adopt the\n// stream's thenable (which waits for the complete render) and buffer it.\nconst STREAM_BOX = '__solidSetupStream';\nconst DEV_STYLES_ID = 'virtual:solid-ssr-dev-styles';\nconst RESOLVED_DEV_STYLES_ID = '\\0' + DEV_STYLES_ID;\n// Generated default entries / document shell. The `.tsx` suffix routes them\n// through the plugin's normal JSX transform (per-environment SSR/DOM\n// compile), exactly like user-authored entry files.\nconst ENTRY_SERVER_ID = 'virtual:solid-ssr-entry-server.tsx';\nconst ENTRY_CLIENT_ID = 'virtual:solid-ssr-entry-client.tsx';\nconst DOCUMENT_ID = 'virtual:solid-ssr-document.tsx';\nconst ERROR_BOUNDARY_ID = 'virtual:solid-ssr-error-boundary.tsx';\n\nconst MANIFEST_ID = 'virtual:solid-manifest';\nconst SERVER_FUNCTION_HANDLER_ID = 'virtual:solid-server-function-handler';\nconst STORAGE_SOURCE = '@solidjs/web/storage';\n\nconst ENTRY_EXTENSIONS = ['.tsx', '.jsx', '.ts', '.js', '.mjs'];\nconst APP_EXTENSIONS = ['.tsx', '.jsx', '.ts', '.js'];\nconst DOCUMENT_EXTENSIONS = ['.tsx', '.jsx'];\n\nfunction probe(root: string, stem: string, extensions: string[]): string | null {\n for (const ext of extensions) {\n if (existsSync(path.resolve(root, stem + ext))) return stem + ext;\n }\n return null;\n}\n\n/** Normalizes a user-supplied module path to a root-relative one (no leading slash). */\nfunction normalizeUserPath(root: string, spec: string, option: string): string {\n const absolute = path.isAbsolute(spec) ? spec : path.resolve(root, spec);\n if (!existsSync(absolute)) {\n throw new Error(`[@solidjs/vite-plugin] start.${option} does not exist: ${spec}`);\n }\n const relative = path.relative(root, absolute).split(path.sep).join('/');\n if (relative.startsWith('..')) {\n throw new Error(`[@solidjs/vite-plugin] start.${option} must live inside the Vite root: ${spec}`);\n }\n return relative;\n}\n\ninterface ResolvedEntries {\n /** Root-relative path or virtual id. */\n entryServer: string;\n /** Root-relative path or virtual id. */\n entryClient: string;\n /** Whether the entries are generated virtual modules. */\n generated: boolean;\n /** Absolute path of the app root component (generated entries only). */\n app: string | null;\n /** Absolute path of the document shell, or the built-in virtual id. */\n document: string | null;\n}\n\nfunction resolveEntries(root: string, options: StartOptions, clientMode: boolean): ResolvedEntries {\n const explicitClient = options.entryClient\n ? normalizeUserPath(root, options.entryClient, 'entryClient')\n : null;\n\n if (clientMode) {\n // Client mode: the server entry is always generated (it renders the\n // document shell only — no App — for dev serving and the build-time\n // prerender); `start.entryServer` and conventional src/entry-server.*\n // files are documented no-ops here, so a project flipping the `ssr`\n // boolean never has to touch them. No entry pairing rule either: an\n // authored client entry stands alone. The document resolves in every\n // case because it IS the page in this mode.\n const document = options.document\n ? normalizeUserPath(root, options.document, 'document')\n : probe(root, 'src/Document', DOCUMENT_EXTENSIONS);\n const entryClient = explicitClient ?? probe(root, 'src/entry-client', ENTRY_EXTENSIONS);\n if (entryClient) {\n return {\n entryServer: ENTRY_SERVER_ID,\n entryClient,\n generated: false,\n app: null,\n document: document ? path.resolve(root, document) : null,\n };\n }\n const app = options.app\n ? normalizeUserPath(root, options.app, 'app')\n : (probe(root, 'src/App', APP_EXTENSIONS) ?? probe(root, 'src/app', APP_EXTENSIONS));\n if (!app) {\n throw new Error(\n `[@solidjs/vite-plugin] the \\`start\\` option needs an app root: add src/App.tsx ` +\n `(or set start.app), or provide a src/entry-client.* entry.`,\n );\n }\n return {\n entryServer: ENTRY_SERVER_ID,\n entryClient: ENTRY_CLIENT_ID,\n generated: true,\n app: path.resolve(root, app),\n document: document ? path.resolve(root, document) : null,\n };\n }\n\n const explicitServer = options.entryServer\n ? normalizeUserPath(root, options.entryServer, 'entryServer')\n : null;\n const entryServer = explicitServer ?? probe(root, 'src/entry-server', ENTRY_EXTENSIONS);\n const entryClient = explicitClient ?? probe(root, 'src/entry-client', ENTRY_EXTENSIONS);\n\n if (entryServer && entryClient) {\n return { entryServer, entryClient, generated: false, app: null, document: null };\n }\n if (entryServer || entryClient) {\n // One authored entry with a generated counterpart is a hydration\n // mismatch waiting to happen — the generated side wraps the app in the\n // document shell, which the authored side knows nothing about.\n const found = entryServer ? 'entry-server' : 'entry-client';\n const missing = entryServer ? 'entry-client' : 'entry-server';\n throw new Error(\n `[@solidjs/vite-plugin] found ${found} but no ${missing}; entry files come in pairs. ` +\n `Provide both (src/entry-server.* and src/entry-client.*, or the start.entryServer / ` +\n `start.entryClient options) or neither (to generate both from start.app).`,\n );\n }\n\n const app = options.app\n ? normalizeUserPath(root, options.app, 'app')\n : (probe(root, 'src/App', APP_EXTENSIONS) ?? probe(root, 'src/app', APP_EXTENSIONS));\n if (!app) {\n throw new Error(\n `[@solidjs/vite-plugin] the \\`start\\` option needs an app root: add src/App.tsx ` +\n `(or set start.app), or provide src/entry-server.* and src/entry-client.* entries.`,\n );\n }\n const document = options.document\n ? normalizeUserPath(root, options.document, 'document')\n : probe(root, 'src/Document', DOCUMENT_EXTENSIONS);\n\n return {\n entryServer: ENTRY_SERVER_ID,\n entryClient: ENTRY_CLIENT_ID,\n generated: true,\n app: path.resolve(root, app),\n document: document ? path.resolve(root, document) : null,\n };\n}\n\nexport function startServe(\n options: StartOptions,\n internal: {\n serverFunctions?: boolean;\n serverComponents?: boolean;\n ssr?: boolean;\n styleFilter?: DevStyleFilter;\n diagnostics?: boolean;\n /**\n * Reports the resolved document shell path (absolute, or null when the\n * built-in virtual document is used) back to the main plugin, which\n * declines HMR for that module's client compile (solidjs/solid#3151).\n */\n onDocumentResolved?: (documentPath: string | null) => void;\n } = {},\n): Plugin[] {\n // Client mode (the `start` option without `ssr: true`) rides this exact\n // plugin with three deltas: the generated server entry renders the\n // document shell WITHOUT the app (dev serving doubles as history\n // fallback, and a post-build hook prerenders it once into\n // dist/client/index.html), the generated client entry render()s instead\n // of hydrating, and dist/server is dropped from the output unless\n // `serverFunctions` needs it for the endpoint. Everything else — entry\n // probing, the handler, middleware, dev styles, the manifest — is shared,\n // which is what makes flipping a project between the modes a one-boolean\n // config change.\n const clientMode = !internal.ssr;\n // Server components (`serverFunctions: { components: true }`): generated\n // entries additionally emit the document-SSR wiring — the render plugin +\n // direct-call transform server-side, the bootstrap script in <head>, and\n // the client-side installServerComponents() call. Authored entries carry\n // those pieces themselves (the endpoint response transform is installed by\n // the server-function handler module either way). Everything is gated\n // codegen: with the option off, none of these imports exist anywhere.\n const serverComponents = !!internal.serverComponents;\n const errorBoundary = options.errorBoundary !== false;\n const styleFilter = internal.styleFilter;\n const diagnostics = !!internal.diagnostics;\n let devtoolsEnabled = false;\n let devtoolsResolutions: Partial<\n Record<'client' | 'server', Promise<string | null>>\n > = {};\n let devtoolsIds: Partial<Record<'client' | 'server', string | null>> = {};\n // `external` is server-mode-only (documented no-op in client mode, so a\n // host-integrated config survives the `ssr` boolean flip untouched).\n const externalServer = !clientMode && !!options.external;\n let root = process.cwd();\n let base = '/';\n let isBuild = false;\n let entries: ResolvedEntries | undefined;\n /** Absolute path of the user's middleware module, when configured. */\n let middlewarePath: string | null = null;\n /** Absolute path of the per-request setup module, when configured (server mode). */\n let setupPath: string | null = null;\n\n function requireEntries(): ResolvedEntries {\n // config() always runs before resolveId/load/configureServer.\n if (!entries) throw new Error('[@solidjs/vite-plugin] SSR entries not resolved yet');\n return entries;\n }\n\n async function resolveDevtools(\n resolve: (source: string, importer: string) => Promise<{ id: string } | null>,\n importer: string,\n consumer: 'client' | 'server',\n ): Promise<boolean> {\n if (!devtoolsEnabled) return false;\n // Detect from the app graph first (the documented install location), then\n // from the plugin's own file: in pnpm-isolated apps a copy that is only a\n // dependency of the plugin is not reachable from the app's importers. The\n // resolved id is kept so imports from generated modules can use it.\n devtoolsResolutions[consumer] ??= (async () => {\n // Resolving from the plugin's own file never yields null when the\n // package is absent: it is declared an optional peer dependency, so\n // Vite answers with its `__vite-optional-peer-dep:` stub (an empty\n // module). Treat that stub as \"not installed\".\n const realId = (resolved: { id: string } | null) =>\n resolved && !resolved.id.startsWith('__vite-optional-peer-dep:') ? resolved.id : null;\n return (\n realId(await resolve(DEVTOOLS_PACKAGE, importer)) ??\n realId(await resolve(DEVTOOLS_PACKAGE, fileURLToPath(import.meta.url)))\n );\n })();\n const id = await devtoolsResolutions[consumer];\n devtoolsIds[consumer] = id;\n if (!id && options.devtools === true) {\n throw new Error(\n '[@solidjs/vite-plugin] start.devtools requires @solidjs/start-devtools. ' +\n 'Install it as a development dependency or set start.devtools to false.',\n );\n }\n return id !== null;\n }\n\n /**\n * Cheap walk-up probe mirroring how the optimizer resolves bare\n * `optimizeDeps.include` entries: is @solidjs/start-devtools reachable from\n * this directory? Detection proper (resolveDevtools) runs later with a real\n * importer; this only decides whether the toolbar graph can be pre-bundled\n * at scan time.\n */\n function devtoolsReachableFrom(dir: string): boolean {\n for (let current = dir; ; ) {\n if (existsSync(path.join(current, 'node_modules', DEVTOOLS_PACKAGE, 'package.json'))) {\n return true;\n }\n const parent = path.dirname(current);\n if (parent === current) return false;\n current = parent;\n }\n }\n\n /**\n * The `optimizeDeps.include` spec that pre-bundles the toolbar graph, or\n * null when it cannot be resolved at all. Pre-bundling it is not just a\n * warm-start nicety: the toolbar hangs off virtual modules the scanner\n * never crawls, so without an include the optimizer only discovers it on\n * first request. That re-optimize can pair chunks from different passes\n * whose shared minified exports disagree, taking down the whole client\n * entry graph. The spec must therefore cover every install shape\n * resolveDevtools accepts: bare when the app installs the package, and\n * Vite's nested-include form (`plugin > dep`) when it is only a dependency\n * of this plugin (pnpm-isolated installs).\n */\n function devtoolsIncludeSpec(rootDir: string): string | null {\n if (devtoolsReachableFrom(rootDir)) return DEVTOOLS_PACKAGE;\n if (devtoolsReachableFrom(path.dirname(fileURLToPath(import.meta.url)))) {\n return `@solidjs/vite-plugin > ${DEVTOOLS_PACKAGE}`;\n }\n return null;\n }\n\n /** Import specifier for generated code: absolute for files, id for virtuals. */\n function entryServerSpec(): string {\n const { entryServer } = requireEntries();\n return entryServer === ENTRY_SERVER_ID ? entryServer : path.resolve(root, entryServer);\n }\n\n /** Browser URL of the client entry on the dev server (base applied). */\n function devClientEntryUrl(): string {\n const { entryClient } = requireEntries();\n return entryClient === ENTRY_CLIENT_ID\n ? joinBase(base, '/@id/' + ENTRY_CLIENT_ID)\n : joinBase(base, '/' + entryClient);\n }\n\n function documentSpec(): string {\n const { document } = requireEntries();\n return document ?? DOCUMENT_ID;\n }\n\n function styleRoots(): string[] {\n const { generated, app, document, entryServer, entryClient } = requireEntries();\n if (clientMode) {\n // The app graph's CSS is inlined into the dev shell too (not just the\n // document's): the client injects it again when the modules load and\n // the dev style patch dedupes, so this is pure anti-flash.\n return [\n generated ? app! : path.resolve(root, entryClient),\n ...(document ? [document] : []),\n ];\n }\n return generated ? [app!, ...(document ? [document] : [])] : [path.resolve(root, entryServer)];\n }\n\n async function devStylesModuleCode(\n environment: DevEnvironment,\n watchFile: (file: string) => void,\n ): Promise<string> {\n const styles = await collectDevStyleSources(\n environment,\n styleRoots(),\n watchFile,\n styleFilter,\n );\n if (!styles.length) return `export default '';`;\n\n const imports = styles.map((style, index) => {\n const specifier = style.url.includes('?') ? `${style.url}&inline` : `${style.url}?inline`;\n return `import css${index} from ${JSON.stringify(specifier)};`;\n });\n return [\n ...imports,\n `const ids = ${JSON.stringify(styles.map((style) => style.id))};`,\n `const css = [${styles.map((_, index) => `css${index}`).join(', ')}];`,\n `const escapeAttr = value => value.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<');`,\n `export default css.map((content, index) => {`,\n ` const id = escapeAttr(ids[index]);`,\n ` return '<style data-asset=\"' + id + '\" data-vite-dev-id=\"' + id + '\">' +`,\n ` content.replace(/<\\\\/(style)/gi, '<\\\\\\\\/$1') + '</style>';`,\n `}).join('');`,\n ].join('\\n');\n }\n\n function errorBoundaryImport(): string[] {\n return isBuild && errorBoundary\n ? [`import { DefaultErrorBoundary } from ${JSON.stringify(ERROR_BOUNDARY_ID)};`]\n : [];\n }\n\n function documentTree(root: string, wrapper?: string): string[] {\n const content = wrapper ? `<${wrapper}><${root} /></${wrapper}>` : `<${root} />`;\n return isBuild && errorBoundary\n ? [\n ` <DefaultErrorBoundary>`,\n ` <Document>`,\n ` <DefaultErrorBoundary>`,\n ` ${content}`,\n ` </DefaultErrorBoundary>`,\n ` </Document>`,\n ` </DefaultErrorBoundary>`,\n ]\n : [` <Document>`, ` ${content}`, ` </Document>`];\n }\n\n function generatedEntryServerCode(toolbar: boolean): string {\n if (clientMode) {\n // The client-mode shell: the document without the app. Rendered per\n // request in dev (any HTML GET gets it — history-fallback semantics)\n // and once at build time into dist/client/index.html. The client\n // entry script is injected by the handler, exactly like SSR mode.\n return [\n `import { renderToStream } from '@solidjs/web';`,\n `import manifest from ${JSON.stringify(MANIFEST_ID)};`,\n `import Document from ${JSON.stringify(documentSpec())};`,\n ...errorBoundaryImport(),\n ``,\n `export function render(request, context) {`,\n ` return renderToStream(() => (`,\n ...(isBuild && errorBoundary\n ? [\n ` <DefaultErrorBoundary>`,\n ` <Document />`,\n ` </DefaultErrorBoundary>`,\n ]\n : [` <Document />`]),\n ` ), { manifest });`,\n `}`,\n ].join('\\n');\n }\n const { app } = requireEntries();\n const streamOptions = `{ manifest${serverComponents ? ', plugins: [ServerComponentPlugin]' : ''} }`;\n return [\n `import { renderToStream${setupPath ? ', getRequestEvent' : ''} } from '@solidjs/web';`,\n ...(serverComponents\n ? [\n `import { configureServerFunctionsServer } from '@solidjs/web/server-functions';`,\n `import { frameTransformDirectResult, ServerComponentPlugin } from '@solidjs/web/frames';`,\n ]\n : []),\n `import manifest from ${JSON.stringify(MANIFEST_ID)};`,\n `import Document from ${JSON.stringify(documentSpec())};`,\n `import App from ${JSON.stringify(app)};`,\n ...(toolbar ? [`import { DevToolbar } from ${JSON.stringify(DEVTOOLS_PACKAGE)};`] : []),\n ...errorBoundaryImport(),\n ...(setupPath ? [`import setup from ${JSON.stringify(setupPath)};`] : []),\n ``,\n ...(setupPath\n ? [\n `if (typeof setup !== 'function') {`,\n ` throw new Error('[@solidjs/vite-plugin] start.setup must default-export a function ' +`,\n ` '((event, App) => Component | void | Promise<...>): ' + ${JSON.stringify(options.setup)});`,\n `}`,\n ``,\n ]\n : []),\n ...(serverComponents\n ? [\n // Direct (in-process) server-function calls made during document\n // SSR must resolve to inline-renderable components; the endpoint\n // response transform is installed separately by the\n // server-function handler module (configure calls merge per key).\n `configureServerFunctionsServer({ transformDirectResult: frameTransformDirectResult });`,\n ``,\n ]\n : []),\n ...(setupPath\n ? [\n // The per-request seam: the hook sees the same event the\n // middleware chain decorated and finishes before renderToStream\n // starts. When it is async, the stream must NOT cross the\n // promise boundary bare — a promise resolving to a\n // renderToStream result adopts its thenable (which waits for\n // the *complete* render) and buffers the stream — so it crosses\n // boxed under a private key the generated handler unboxes\n // (both modules are ours).\n `export function render(request, context) {`,\n ` const prepared = setup(getRequestEvent(), App);`,\n ` if (prepared && typeof prepared.then === 'function') {`,\n ` return prepared.then((component) => ({ ${STREAM_BOX}: renderApp(component || App) }));`,\n ` }`,\n ` return renderApp(prepared || App);`,\n `}`,\n ``,\n `function renderApp(Root) {`,\n ` return renderToStream(() => (`,\n ...documentTree('Root', toolbar ? 'DevToolbar' : undefined),\n ` ), ${streamOptions});`,\n `}`,\n ]\n : [\n `export function render(request, context) {`,\n ` return renderToStream(() => (`,\n ...documentTree('App', toolbar ? 'DevToolbar' : undefined),\n ` ), ${streamOptions});`,\n `}`,\n ]),\n ].join('\\n');\n }\n\n function generatedEntryClientCode(toolbar: boolean): string {\n const { app } = requireEntries();\n // Dev-only: the diagnostics bridge fronts dev-mode channels, so builds\n // never see this import (mirrors the plugin's own serve-only `apply`).\n const diagnosticsImport =\n diagnostics && !isBuild ? [`import ${JSON.stringify(DIAGNOSTICS_CLIENT_ID)};`] : [];\n if (clientMode) {\n // render(), not hydrate(): the shell's body is empty, the app mounts\n // fresh. Client code compiles non-hydratable in client mode, so the\n // app cannot claim server DOM anyway. The entry script is injected\n // without `async` (plain module = deferred), so document.body is\n // complete when this runs.\n return [\n ...diagnosticsImport,\n `import { render } from '@solidjs/web';`,\n ...errorBoundaryImport(),\n ...(toolbar ? [`import { DevToolbar } from ${JSON.stringify(DEVTOOLS_PACKAGE)};`] : []),\n `import App from ${JSON.stringify(app)};`,\n ``,\n `render(() => ${\n isBuild && errorBoundary\n ? '<DefaultErrorBoundary><App /></DefaultErrorBoundary>'\n : toolbar\n ? '<DevToolbar><App /></DevToolbar>'\n : '<App />'\n }, document.body);`,\n ].join('\\n');\n }\n return [\n ...diagnosticsImport,\n `import { hydrate } from '@solidjs/web';`,\n ...(toolbar ? [`import { DevToolbar } from ${JSON.stringify(DEVTOOLS_PACKAGE)};`] : []),\n ...(serverComponents\n ? [`import { installServerComponents } from '@solidjs/web/frames';`]\n : []),\n ...errorBoundaryImport(),\n `import Document from ${JSON.stringify(documentSpec())};`,\n `import App from ${JSON.stringify(app)};`,\n ``,\n ...(serverComponents\n ? [\n // Installs the t=0 document-adoption registry and the transport\n // policy (component responses morph their boundary instead of\n // decoding as data). Must run before hydrate().\n `installServerComponents();`,\n ``,\n ]\n : []),\n `hydrate(() => (`,\n ...documentTree('App', toolbar ? 'DevToolbar' : undefined),\n `), document);`,\n ].join('\\n');\n }\n\n // Built-in document shell: minimal, hydration-ready. The client entry\n // script is injected into <head> by the handler (not rendered here) so its\n // URL never has to survive hydration or a manifest lookup client-side.\n // The client-mode variant drops <HydrationScript /> — nothing hydrates,\n // so the shell stays inert HTML. (A user-authored Document carrying\n // HydrationScript is covered too: the handler strips the event-capture\n // script from the client-mode shell.)\n const documentShellCode = [\n ...(clientMode ? [] : [`import { HydrationScript } from '@solidjs/web';`, ``]),\n `export default function Document(props) {`,\n ` return (`,\n ` <html lang=\"en\">`,\n ` <head>`,\n ` <meta charset=\"utf-8\" />`,\n ` <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />`,\n ...(clientMode ? [] : [` <HydrationScript />`]),\n ` </head>`,\n ` <body>{props.children}</body>`,\n ` </html>`,\n ` );`,\n `}`,\n ].join('\\n');\n\n const errorBoundaryCode = [\n `import { Errored } from 'solid-js';`,\n `import { httpStatus, isServer } from '@solidjs/web';`,\n ``,\n `function ErrorFallback(props) {`,\n ` console.error(props.error());`,\n ` httpStatus(500);`,\n ` return (`,\n ` <span style=\"font-size:1.5em;text-align:center;position:fixed;left:0;bottom:55%;width:100%\">`,\n ` {isServer ? '500 | Internal Server Error' : 'Error | Uncaught Client Exception'}`,\n ` </span>`,\n ` );`,\n `}`,\n ``,\n `export function DefaultErrorBoundary(props) {`,\n ` return (`,\n ` <Errored fallback={(error) => <ErrorFallback error={error} />}>`,\n ` {props.children}`,\n ` </Errored>`,\n ` );`,\n `}`,\n ].join('\\n');\n\n // The handler module: dev and prod share the render/response plumbing;\n // they differ in how the client entry URL is known (baked dev URL vs a\n // manifest scan) and what gets injected into <head> (Vite client + style\n // patch in dev). The response-head lifecycle is the runtime's\n // (`createRequestEvent`/`createSSRResponse`/`commitEventResponse` from\n // @solidjs/web): every request runs under a stub-backed event,\n // `httpStatus`/`httpHeader` writes land on the wire at shell flush, a\n // pre-flush redirect becomes a real 3xx and a post-flush one the script\n // fallback, and a Response that skipped the render lifecycle (middleware\n // early return, raw entry.render Response, server functions) has the\n // stub folded on at the handler edge after the middleware chain fully\n // unwinds. When\n // `serverFunctions` is enabled the endpoint is dispatched here on every\n // surface (the runnable-dev middleware routes through this module), so\n // user middleware and the shared request event front it identically.\n function handlerModuleCode(externalDev: boolean): string {\n const { generated, entryClient } = requireEntries();\n const composeServerFunctions = internal.serverFunctions;\n\n const lines = [\n `import { createRequestEvent, createSSRResponse, commitEventResponse${middlewarePath ? ', composeMiddleware' : ''} } from '@solidjs/web';`,\n `import { provideRequestEvent } from ${JSON.stringify(STORAGE_SOURCE)};`,\n `import * as entry from ${JSON.stringify(entryServerSpec())};`,\n ...(middlewarePath\n ? [`import middlewareModule from ${JSON.stringify(middlewarePath)};`]\n : []),\n ...(externalDev ? [`import DEV_STYLES_HEAD from ${JSON.stringify(DEV_STYLES_ID)};`] : []),\n ...(composeServerFunctions\n ? [\n `import { handleServerFunctionRequest, endpoint } from ${JSON.stringify(SERVER_FUNCTION_HANDLER_ID)};`,\n ]\n : []),\n ];\n\n if (isBuild) {\n lines.push(`import manifest from ${JSON.stringify(MANIFEST_ID)};`);\n lines.push(\n ``,\n `function joinAssetPath(base, file) {`,\n ` if (typeof base !== 'string' || !base) base = '/';`,\n ` if (base[base.length - 1] !== '/') base += '/';`,\n ` return base + (file[0] === '/' ? file.slice(1) : file);`,\n `}`,\n ``,\n `let clientEntryUrl;`,\n `function resolveClientEntry() {`,\n ` if (clientEntryUrl !== undefined) return clientEntryUrl;`,\n ` clientEntryUrl = null;`,\n // The plugin's manifest module normalizes lazy facade chunks\n // (isDynamicEntry) so exactly one real entry remains flagged.\n ` for (const key in manifest) {`,\n ` const chunk = manifest[key];`,\n ` if (chunk && chunk.isEntry && chunk.file) {`,\n ` clientEntryUrl = joinAssetPath(manifest._base, chunk.file);`,\n ` break;`,\n ` }`,\n ` }`,\n ` return clientEntryUrl;`,\n `}`,\n );\n } else {\n const devHead =\n `<script>${devStylePatch}</script>` +\n `<script type=\"module\" src=\"${joinBase(base, '/@vite/client')}\"></script>`;\n lines.push(``, `const DEV_HEAD = ${JSON.stringify(devHead)};`);\n }\n\n // Middleware: the user module default-exports one fetch-style function\n // or an array, composed in order. Without one, the chain degenerates to\n // the terminal dispatch.\n lines.push(``);\n if (middlewarePath) {\n lines.push(\n `const middlewares = Array.isArray(middlewareModule) ? middlewareModule : [middlewareModule];`,\n `for (const mw of middlewares) {`,\n ` if (typeof mw !== 'function') {`,\n ` throw new Error('[@solidjs/vite-plugin] start.middleware must default-export a function or an array of functions: ' + ${JSON.stringify(middlewarePath)});`,\n ` }`,\n `}`,\n `const runMiddleware = composeMiddleware(middlewares);`,\n );\n } else {\n lines.push(`const runMiddleware = (request, next) => next(request);`);\n }\n\n // No `_$SC` bootstrap injection: the runtime's serialized\n // server-component references self-bootstrap the registry (each\n // hydration script's first reference carries it as an idempotent\n // expression), so nothing needs to precede the data scripts. The old\n // head-open splice actively broke hydration — a script ahead of the\n // authored <head> elements claims as the first walked child and drifts\n // every positional claim after it.\n lines.push(\n ``,\n `function escapeAttribute(value) {`,\n ` return value.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<');`,\n `}`,\n ``,\n `function createHtmlChunkTransform(clientEntry, extraHead, nonce) {`,\n ` const nonceAttr = nonce ? ' nonce=\"' + escapeAttribute(nonce) + '\"' : '';`,\n ` let first = true;`,\n ` let injected = false;`,\n ` return (chunk) => {`,\n );\n if (!generated) {\n // Authored entries reference the client entry by its dev path (the\n // `<script src=\"/src/entry-client.tsx\">` convention); rewrite it to\n // the resolved URL like the classic server harnesses do.\n lines.push(\n ` if (clientEntry && chunk.includes(${JSON.stringify('/' + entryClient)})) {`,\n ` chunk = chunk.split(${JSON.stringify('/' + entryClient)}).join(clientEntry);`,\n ` }`,\n );\n }\n lines.push(` if (!injected && chunk.includes('</head>')) {`, ` injected = true;`);\n if (clientMode) {\n // Nothing hydrates in client mode, so the event-capture bootstrap\n // `<HydrationScript />` renders (`window._$HY||...`) is dead weight —\n // but a Document shared with SSR mode carries it by design (the flip\n // story). Strip it from the shell here instead of making users fork\n // their Document per mode. (`<!--xs-->` is the script's stream\n // marker; the shell head always arrives in one chunk.)\n lines.push(\n ` chunk = chunk.replace(/<script(?:\\\\s[^>]*)?>window\\\\._\\\\$HY\\\\|\\\\|[\\\\s\\\\S]*?<\\\\/script>(?:<!--xs-->)?/, '');`,\n );\n }\n const headParts: string[] = [];\n // Dev: the style patch + Vite client, then either middleware-provided\n // styles or the external environment's HMR-tracked virtual styles module.\n if (!isBuild) {\n headParts.push(\n `DEV_HEAD`,\n externalDev\n ? `(extraHead === undefined ? DEV_STYLES_HEAD : extraHead)`\n : `(extraHead || '')`,\n );\n }\n if (generated || clientMode) {\n // Client-mode note: the shell never references its client entry\n // itself (even an authored one — the Document knows nothing about\n // entries), so the handler always injects it. Without `async`: module\n // scripts default to deferred execution, which is exactly right for a\n // fresh render-into-body mount (hydration, by contrast, wants to\n // start as early as possible).\n headParts.push(\n `(clientEntry ? '<script type=\"module\"' + nonceAttr + ' src=\"' + clientEntry + '\"${clientMode ? '' : ' async'}></' + 'script>' : '')`,\n );\n }\n if (headParts.length) {\n lines.push(` chunk = chunk.replace('</head>', ${headParts.join(' + ')} + '</head>');`);\n }\n lines.push(\n ` }`,\n ` if (first) { first = false; chunk = '<!DOCTYPE html>' + chunk; }`,\n ` return chunk;`,\n ` };`,\n `}`,\n );\n\n // The handler-edge commit fold — the runtime's `commitEventResponse`\n // (named import above), the second of the response lifecycle's two\n // exits: page results leave through `createSSRResponse`, any other\n // Response (a middleware early return, a raw Response from\n // entry.render, a server-function response) leaves through\n // `commitEventResponse`, which folds the event's response stub onto it\n // (cookies append entry-by-entry, other headers gap-fill, status stays\n // the response's own) and commits the stub. Committed stubs pass\n // through untouched, so the edge applies it unconditionally.\n lines.push(``, `async function dispatchRequest(request, event, options) {`);\n if (composeServerFunctions) {\n lines.push(\n // A call's address is `<endpoint>/<id>` or `<endpoint>/data/<id>`\n // (solidjs/solid#3076, #3094); the prefix gate covers both, and the\n // bare mount still routes so a misaddressed request 404s through the\n // runtime handler instead of rendering a page at it.\n ` const requestPath = new URL(request.url).pathname;`,\n ` if (requestPath === endpoint || requestPath.startsWith(endpoint + '/')) {`,\n // The call shares the middleware chain's event (locals decoration,\n // the response stub); an explicit host-provided createEvent wins.\n // No fold here: the runtime's server-function handler runs the\n // commit seam itself, and anything it left uncommitted is caught by\n // the unconditional edge fold in handleRequest.\n ` return handleServerFunctionRequest(request, {`,\n ` createEvent: () => event,`,\n ` ...options.serverFunctions,`,\n ` });`,\n ` }`,\n );\n }\n if (!isBuild) {\n // Dev terminal gate: the dev middleware dispatches every request the\n // middleware chain might handle (API routes, no-JS form POSTs — all\n // methods and accept types, matching production), passing\n // `pageRequest: false` for the non-page ones. When such a request\n // falls through the whole chain to this terminal dispatch, nothing\n // owns it — answer with the marked 404 so the dev middleware hands\n // it back to Vite's pipeline instead of rendering HTML at it. The\n // gate reflects the wire request: only the dev middleware sets the\n // flag, so external-host dispatch and preview stay render-always.\n lines.push(\n ` if (options.pageRequest === false) {`,\n ` return new Response(null, { status: 404, headers: { ${JSON.stringify(DEV_FALLTHROUGH_HEADER)}: '1' } });`,\n ` }`,\n );\n }\n lines.push(\n isBuild\n ? ` const clientEntry = options.clientEntry || resolveClientEntry();`\n : ` const clientEntry = options.clientEntry || ${JSON.stringify(devClientEntryUrl())};`,\n ` let result = entry.render(request, { clientEntry, ...options.context });`,\n // renderToStream results are thenables whose then() waits for the\n // *complete* render — check for pipe first so streaming survives, and\n // only await plain promises (async render functions).\n ` if (result && typeof result.pipe !== 'function' && typeof result.then === 'function') {`,\n ` result = await result;`,\n ` }`,\n ...(setupPath\n ? [\n // start.setup's async path boxes the stream (see the generated\n // entry): a bare promise resolution would adopt the stream's\n // thenable and buffer the whole render.\n ` if (result && result.${STREAM_BOX}) result = result.${STREAM_BOX};`,\n ]\n : []),\n // Raw Responses fold at the handler edge (handleRequest), after the\n // middleware chain unwinds — not here, where middleware above this\n // frame could still legitimately mutate headers.\n ` if (result instanceof Response) return result;`,\n // The runtime's response-head lifecycle: commit at shell flush,\n // pre-flush Location as a real redirect, post-flush Location as the\n // script fallback; the transform injects the doctype/head pieces.\n ` return createSSRResponse(result, event, {`,\n ` responseInit: options.responseInit,`,\n ` nonce: options.nonce,`,\n ` transformChunk: createHtmlChunkTransform(clientEntry, options.devHead, options.nonce),`,\n ` });`,\n `}`,\n ``,\n `export async function handleRequest(request, options = {}) {`,\n // `options.event` is the public wrapper->event extension seam: extra\n // fields (conventionally `nativeEvent`, the platform's raw request\n // object) spread over the event's defaults at creation, so hosts and\n // custom server entries can extend what getRequestEvent() answers\n // with — no new convention beyond createRequestEvent's own init\n // parameter (spreading undefined is a no-op).\n ` const event = createRequestEvent(request, options.event);`,\n // Middleware runs inside the request scope, after event creation —\n // getRequestEvent() answers in middleware exactly as in app code, and\n // nothing reaches the wire until the outermost middleware returns.\n ` const response = await provideRequestEvent(event, () =>`,\n ` runMiddleware(request, (req) => dispatchRequest(req || request, event, options)),`,\n ` );`,\n // The fold runs strictly AFTER the outermost middleware returned:\n // headers stay mutable through the whole unwind, and a middleware\n // early return (an API handler that never called next()) gets its\n // stub writes — cookies set inside the request scope, status — onto\n // the wire. Unconditional: page responses come back from\n // createSSRResponse committed and pass through untouched.\n ` return commitEventResponse(response, event);`,\n `}`,\n ``,\n `export default {`,\n ` fetch(request) {`,\n // Hosts may pass environment/context arguments after the request.\n // Do not alias fetch directly to handleRequest: its second argument is\n // the Solid handler options bag, not a provider binding object.\n ` return handleRequest(request);`,\n ` },`,\n `};`,\n );\n\n return lines.join('\\n');\n }\n\n return [\n {\n name: 'solid:ssr/setup',\n enforce: 'pre',\n config(userConfig, env) {\n root = path.resolve(userConfig.root || process.cwd());\n devtoolsEnabled =\n env.command === 'serve' && !env.isPreview && options.devtools !== false;\n devtoolsResolutions = {};\n devtoolsIds = {};\n entries = resolveEntries(root, options, clientMode);\n internal.onDocumentResolved?.(entries.document);\n middlewarePath = options.middleware\n ? path.resolve(root, normalizeUserPath(root, options.middleware, 'middleware'))\n : null;\n // Server-mode only, like `entryServer`/`external` (a documented\n // no-op in client mode so configs survive the `ssr` boolean flip).\n setupPath =\n !clientMode && options.setup\n ? path.resolve(root, normalizeUserPath(root, options.setup, 'setup'))\n : null;\n if (setupPath && !entries.generated) {\n // An authored entry-server owns its render function — the seam the\n // hook needs does not exist there.\n throw new Error(\n '[@solidjs/vite-plugin] start.setup only applies to generated entries: your ' +\n 'entry-server owns render() already, so call your setup step there instead ' +\n `(remove start.setup or the authored entry): ${options.setup}`,\n );\n }\n if (env.isPreview) {\n if (clientMode) {\n // Client-mode builds emit a real dist/client/index.html (the\n // prerendered shell), so preview is Vite's stock static +\n // history-fallback story. When server functions are on, the\n // endpoint dispatches through the kept dist/server handler\n // (configurePreviewServer).\n return { appType: 'spa', build: { outDir: 'dist/client' } };\n }\n // `vite preview` serves `build.outDir` statically; point it at the\n // client bundle so hashed assets resolve, while HTML (and\n // everything else unhandled) falls through to the\n // configurePreviewServer dispatch below. No index.html exists, so\n // `custom` keeps preview from attempting an SPA fallback.\n return {\n appType: 'custom',\n ...(externalServer ? {} : { build: { outDir: 'dist/client' } }),\n };\n }\n const build = env.command === 'build';\n const clientInput = entries.generated\n ? ENTRY_CLIENT_ID\n : path.resolve(root, entries.entryClient);\n // Real files only — the dep scanner can't crawl virtual modules.\n // (In client mode the resolved document joins the scan/style roots\n // even with an authored client entry; in SSR mode authored entries\n // own the whole graph.)\n const scanEntries = entries.generated\n ? [entries.app!, ...(entries.document ? [entries.document] : [])]\n : [\n path.resolve(root, entries.entryClient),\n ...(clientMode && entries.document ? [entries.document] : []),\n ];\n return {\n // No index.html: dev must not fall back to SPA-serving one, and\n // the dep scanner needs explicit entries instead.\n appType: 'custom',\n ...(build\n ? externalServer\n ? {\n environments: {\n client: {\n build: {\n manifest: true,\n rollupOptions: { input: clientInput },\n },\n },\n },\n }\n : {\n environments: {\n client: {\n build: {\n manifest: true,\n outDir: 'dist/client',\n rollupOptions: { input: clientInput },\n },\n },\n ssr: {\n consumer: 'server',\n build: {\n outDir: 'dist/server',\n rollupOptions: {\n // `index` is the Vite service convention consumed\n // by provider orchestrators such as Nitro. Keep the\n // standalone artifact's established filename.\n input: { index: HANDLER_ID },\n output: { entryFileNames: 'server.js' },\n },\n },\n },\n },\n // Presence of `builder` makes a plain `vite build` build the\n // whole app (all environments: client then ssr).\n // A classic `vite build --ssr` invocation must stay a\n // single-environment build, so it doesn't get the flag.\n ...(env.isSsrBuild ? {} : { builder: {} }),\n }\n : {\n ...(!clientMode && !externalServer\n ? {\n environments: {\n ssr: {\n consumer: 'server' as const,\n build: {\n outDir: 'dist/server',\n rollupOptions: {\n // Expose the same service entry during serve so\n // provider runtimes can discover and own it.\n input: { index: HANDLER_ID },\n output: { entryFileNames: 'server.js' },\n },\n },\n },\n },\n }\n : {}),\n optimizeDeps: {\n entries: scanEntries,\n // Like the refresh runtime in the main plugin: the toolbar\n // graph is injected behind modules the scanner never crawls,\n // so pre-bundle it and the server-functions runtime up front.\n ...(() => {\n const spec = devtoolsEnabled ? devtoolsIncludeSpec(root) : null;\n return spec ? { include: [spec, '@solidjs/web/server-functions'] } : {};\n })(),\n },\n }),\n };\n },\n configEnvironment(name, config) {\n if (name !== 'ssr') return;\n config.resolve ??= {};\n const noExternal = config.resolve.noExternal;\n if (noExternal !== true) {\n config.resolve.noExternal = [\n ...(Array.isArray(noExternal) ? noExternal : noExternal ? [noExternal] : []),\n DEVTOOLS_PACKAGE,\n ];\n }\n },\n configResolved(config) {\n root = config.root;\n base = config.base;\n isBuild = config.command === 'build';\n },\n resolveId(source, importer, opts) {\n if (source === HANDLER_ID) {\n return { id: HANDLER_ID, moduleSideEffects: true };\n }\n if (source === DEV_STYLES_ID) {\n return { id: RESOLVED_DEV_STYLES_ID, moduleSideEffects: true };\n }\n if (\n source === ENTRY_SERVER_ID ||\n source === ENTRY_CLIENT_ID ||\n source === DOCUMENT_ID ||\n source === ERROR_BOUNDARY_ID\n ) {\n return { id: source, moduleSideEffects: source === ENTRY_CLIENT_ID };\n }\n if (devtoolsEnabled && source === DEVTOOLS_MOUNT_ID) {\n return { id: source, moduleSideEffects: true };\n }\n // Generated modules have no directory for bare-package resolution.\n // Reuse the app-relative id captured during detection.\n const devtoolsId = devtoolsIds[getEnvironmentConsumer(this.environment, opts)];\n if (\n devtoolsId &&\n source === DEVTOOLS_PACKAGE &&\n (importer === ENTRY_SERVER_ID ||\n importer === ENTRY_CLIENT_ID ||\n importer === DEVTOOLS_MOUNT_ID)\n ) {\n return { id: devtoolsId };\n }\n return null;\n },\n async load(id, opts) {\n const consumer = getEnvironmentConsumer(this.environment, opts);\n if (id === HANDLER_ID) {\n if (consumer !== 'server') {\n this.error(`${HANDLER_ID} is server-only; import it from server code (SSR build).`);\n }\n const externalDev =\n !isBuild &&\n this.environment.mode === 'dev' &&\n (externalServer || !isRunnableEnvironment(this.environment));\n return handlerModuleCode(externalDev);\n }\n if (id === RESOLVED_DEV_STYLES_ID) {\n if (consumer !== 'server' || this.environment.mode !== 'dev') {\n this.error(`${DEV_STYLES_ID} is only available to the development server handler.`);\n }\n return devStylesModuleCode(this.environment, (file) => this.addWatchFile(file));\n }\n if (id === ENTRY_SERVER_ID) {\n const toolbar = clientMode\n ? false\n : await resolveDevtools(\n (source, importer) => this.resolve(source, importer, { skipSelf: true }),\n requireEntries().app!,\n 'server',\n );\n return generatedEntryServerCode(toolbar);\n }\n if (id === ENTRY_CLIENT_ID) {\n const toolbar = await resolveDevtools(\n (source, importer) => this.resolve(source, importer, { skipSelf: true }),\n requireEntries().app!,\n 'client',\n );\n return generatedEntryClientCode(toolbar);\n }\n if (id === DOCUMENT_ID) return documentShellCode;\n if (id === ERROR_BOUNDARY_ID) return errorBoundaryCode;\n if (id === DEVTOOLS_MOUNT_ID) {\n let enabled = false;\n if (devtoolsEnabled && consumer === 'client') {\n const { app, entryClient } = requireEntries();\n enabled = await resolveDevtools(\n (source, importer) => this.resolve(source, importer, { skipSelf: true }),\n app ?? path.resolve(root, entryClient),\n 'client',\n );\n }\n if (!enabled) {\n this.error(`${id} is only available to the development client.`);\n }\n return devtoolsMountModuleCode();\n }\n return null;\n },\n async transform(code, id, opts) {\n if (isBuild || (!devtoolsEnabled && !diagnostics)) return null;\n const current = requireEntries();\n if (current.generated || getEnvironmentConsumer(this.environment, opts) !== 'client') {\n return null;\n }\n // Module ids are always forward-slashed; normalize the path.resolve\n // side too so the comparison holds on Windows.\n if (normalizePath(id.split('?')[0]) !== normalizePath(path.resolve(root, current.entryClient))) {\n return null;\n }\n const injected: string[] = [];\n if (diagnostics) injected.push(`import ${JSON.stringify(DIAGNOSTICS_CLIENT_ID)};`);\n if (devtoolsEnabled) {\n const toolbar = await resolveDevtools(\n (source, importer) => this.resolve(source, importer, { skipSelf: true }),\n id,\n 'client',\n );\n if (toolbar) injected.push(`import ${JSON.stringify(DEVTOOLS_MOUNT_ID)};`);\n }\n if (injected.length === 0) return null;\n return {\n code: `${injected.join('\\n')}\\n${code}`,\n map: null,\n };\n },\n configurePreviewServer(server: PreviewServer) {\n // `vite build && vite preview` runs the production artifact as-is:\n // Vite's preview statics serve dist/client (see the config hook) and\n // everything else — pages, the server-function endpoint, middleware\n // included — dispatches through the built handler, exactly like a\n // deployed server. Hosts owning the server build (`start.external`)\n // preview through their own runner instead.\n // Client mode: pages are the static index.html (preview's own\n // history fallback serves them before this post middleware runs);\n // only the server-function endpoint needs the handler, and without\n // server functions there is no dist/server at all.\n if (externalServer || (clientMode && !internal.serverFunctions)) return;\n return () => {\n let handlerPromise: Promise<{\n handleRequest: (\n request: Request,\n options?: { event?: Record<string, unknown> },\n ) => Promise<Response>;\n }> | null = null;\n server.middlewares.use((req, res, next) => {\n (async () => {\n handlerPromise ??= import(\n pathToFileURL(path.resolve(root, 'dist/server/server.js')).href\n );\n const handler = await handlerPromise;\n // Preview's base middleware runs before this post hook and\n // strips the configured `base` from req.url; the built handler\n // compares pathnames against base-prefixed endpoints (the\n // server-function endpoint) and hands the URL to application\n // code, so restore the base — the deployed production handler\n // receives base-prefixed URLs and preview must match it.\n const response = await handler.handleRequest(\n webRequestFromNode(req, joinBase(base, req.url || '/'), res),\n // Same event extension the dev middleware and a production\n // Node entry pass: the raw Node request as `nativeEvent`.\n { event: { nativeEvent: req } },\n );\n // Preview's compression middleware buffers whole responses;\n // opting HTML out keeps SSR streaming observable, matching\n // production behavior.\n if ((response.headers.get('content-type') || '').includes('text/html')) {\n res.setHeader('content-encoding', 'identity');\n }\n await sendWebResponse(res, response);\n })().catch(next);\n });\n };\n },\n configureServer(server: ViteDevServer) {\n // The files whose static import graphs carry the app's entry CSS:\n // the app root (+ document) for generated entries, the authored\n // server entry otherwise. Their transitively imported styles are\n // inlined into <head> per request (Vite injects entry CSS from\n // client JS only, so SSR'd markup would flash unstyled without\n // this); the SSR'd tags carry data-asset + data-vite-dev-id so the\n // dev style patch drops them once Vite's own injection takes over —\n // exactly the lazy-asset dedup story, HMR included.\n // Post middleware: Vite's own middlewares (transforms, static, the\n // server-function endpoint) run first; whatever asks for HTML after\n // that gets the streamed SSR render.\n return () => {\n const ssrEnvironment = server.environments.ssr;\n if (externalServer || !isRunnableEnvironment(ssrEnvironment)) {\n return;\n }\n server.middlewares.use((req, res, next) => {\n const url = new URL(req.url || '/', 'http://localhost');\n if (url.pathname.startsWith('/@')) return next();\n const accept = req.headers.accept || '';\n const pageRequest = req.method === 'GET' && accept.includes('text/html');\n // Production dispatches every request through the handler, so\n // dev must too or API routes and no-JS form POSTs served by\n // `start.middleware` are unreachable under `vite dev`. Without\n // a middleware chain, non-page requests have nothing to reach —\n // they stay on Vite's pipeline (404s) instead of rendering HTML.\n if (!pageRequest && !middlewarePath) return next();\n (async () => {\n // Loaded through the SSR environment so the app, the request\n // event storage, and the handler share one module registry.\n const handler = await ssrEnvironment.runner.import(HANDLER_ID);\n const styles = pageRequest\n ? await collectDevStyles(server, styleRoots(), styleFilter)\n : [];\n const devHead = styles.map(renderDevStyleTag).join('');\n // Post middlewares run after Vite's base middleware stripped\n // the configured `base` from req.url; restore it so the app\n // sees the same URLs in dev as in production (where the\n // deployed handler receives base-prefixed requests).\n const response: Response = await handler.handleRequest(\n webRequestFromNode(req, joinBase(base, req.url || '/'), res),\n {\n devHead,\n pageRequest,\n // The raw Node request on the event, matching what a\n // production Node server entry passes through the\n // `options.event` seam — getRequestEvent().nativeEvent\n // answers the same in dev as deployed.\n event: { nativeEvent: req },\n },\n );\n // A non-page request the chain never handled: the terminal\n // dispatch answered with the marked 404 — hand it back to\n // Vite (its 404, other post middlewares) rather than sending\n // a rendered page at a fetch()/form client.\n if (response.headers.has(DEV_FALLTHROUGH_HEADER)) return next();\n await sendWebResponse(res, response);\n })().catch((error) => {\n // Vite's error middleware renders the overlay-enabled 500 page.\n next(error);\n });\n });\n };\n },\n },\n ...(clientMode\n ? [\n {\n name: 'solid:start/prerender',\n apply: 'build',\n buildApp: {\n // Post order: this hook owns the whole client-mode app build (the\n // client-build-first orchestration pair is SSR-only). It\n // builds client-then-ssr itself — building anything from a\n // hook suppresses Vite's build-all fallback, so the ordering\n // is guaranteed and the manifest is on disk before the shell\n // bundle bakes it in — then runs the built handler once to\n // prerender the shell into dist/client/index.html and drops\n // dist/server unless server functions still need its handler.\n // The shell arrives complete from the handler: the runtime\n // registers every manifest entry's CSS during the render\n // (registerEntryAssets), so the entry graph's stylesheet\n // links are already in its head — injecting them here again\n // double-links every stylesheet.\n order: 'post' as const,\n async handler(builder: any) {\n const client = builder.environments.client;\n const ssrEnvironment = builder.environments.ssr;\n if (client && !client.isBuilt) await builder.build(client);\n if (ssrEnvironment && !ssrEnvironment.isBuilt) {\n await builder.build(ssrEnvironment);\n }\n\n const serverDir = path.resolve(root, 'dist/server');\n const handler = await import(\n pathToFileURL(path.join(serverDir, 'server.js')).href\n );\n const response: Response = await handler.handleRequest(\n new Request(new URL(base || '/', 'http://localhost')),\n );\n writeFileSync(path.resolve(root, 'dist/client/index.html'), await response.text());\n if (!internal.serverFunctions) {\n rmSync(serverDir, { recursive: true, force: true });\n }\n },\n },\n } satisfies Plugin,\n ]\n : []),\n ];\n}\n","// Typed, validated environment variables as a start-mode feature (`start.env`):\n// an `env.ts` at the project root default-exports `{ server, client }` maps\n// of Standard Schema validators (zod, valibot, arktype — mixable per key),\n// and the plugin exposes the validated values through two virtual modules:\n//\n// - `virtual:env/server` — every var; importable only from server module\n// graphs (a client-graph import is a hard error naming the importer).\n// - `virtual:env/client` — the `client` side only, whose keys must carry\n// the public env prefix (`VITE_` unless `envPrefix` says otherwise).\n//\n// Validation runs at config/build time in node only, against Vite's\n// `loadEnv` merge of the `.env*` files with `process.env` winning (CI\n// secrets take precedence) — and the plugin folds the file-loaded vars into\n// `process.env` itself, so templates don't need the classic\n// `process.env = { ...process.env, ...loadEnv(mode, root, '') }` one-liner.\n//\n// Client values are baked into the bundles as validated plain JSON —\n// that's what the public `VITE_` prefix means — so no validator library\n// ever reaches a browser bundle. Server values are NOT baked anywhere:\n// `virtual:env/server` reads `process.env` at module init (server boot)\n// and validates through the user's own schema, which only the server\n// module graph imports. Platform-injected vars that don't exist at build\n// time work, secrets rotate without a rebuild, and no secret value exists\n// in any dist artifact. Build-time server-value failures downgrade to a\n// warning (boot enforces); dev failures stay hard errors — dev IS runtime.\n// Boot validation is synchronous by design: the generated server module\n// contains no top-level await (a TLA chunk forces esnext on downstream\n// bundlers — Nitro's node-server preset rejects it), which is why async\n// validators are rejected for `server` keys (client keys may stay async;\n// they are awaited at build time where the values are baked).\n//\n// A failed validation fails the build; in dev it renders Vite's error\n// overlay with the per-key report (the virtual modules throw it on load)\n// and `.env*`/schema edits revalidate live. A `solid-env.d.ts` is generated\n// next to the schema file so both virtual modules are fully typed by\n// inference from the user's own schema — no manual declarations.\n//\n// Design credit: the shape of this feature — env.ts schema file, the\n// virtual module pair and their names, build-time validation with baked\n// JSON values, the leak scan — follows @vite-env/core by pyyupsk (MIT,\n// https://github.com/pyyupsk/vite-env), the design-correct prior art. The\n// implementation is fresh against this plugin's machinery: Standard Schema\n// is the only contract (no zod dependency or zod-specific paths), the\n// schema file loads through Vite's own `runnerImport`\n// (no jiti), server-graph protection keys off the environment *consumer*\n// rather than environment-name lists, and the types are inferred from the\n// user's schema instead of introspected per-library.\nimport { existsSync, readFileSync, writeFileSync } from 'fs';\nimport path from 'path';\nimport { loadEnv, runnerImport, type Plugin, type ResolvedConfig, type ViteDevServer } from 'vite';\n\nexport const CLIENT_ENV_ID = 'virtual:env/client';\nexport const SERVER_ENV_ID = 'virtual:env/server';\nconst RESOLVED_CLIENT_ENV_ID = '\\0' + CLIENT_ENV_ID;\nconst RESOLVED_SERVER_ENV_ID = '\\0' + SERVER_ENV_ID;\n\n// Conventional schema locations, project-root relative. TypeScript first —\n// the whole point is inferred types — but a plain-JS project works too.\nconst ENV_FILE_CANDIDATES = ['env.ts', 'env.js'];\n// Generated ambient types, written next to the schema file. Deliberately\n// NOT `env.d.ts`: a declaration file sharing the schema file's stem would\n// shadow it in TS resolution (and self-reference its own `typeof import`).\nconst GENERATED_TYPES_FILE = 'solid-env.d.ts';\n\n/**\n * The minimal structural slice of the Standard Schema v1 interface\n * (https://standardschema.dev) this plugin consumes — the spec is designed\n * to be vendored so validating libraries stay decoupled.\n */\ninterface StandardSchemaLike {\n '~standard': {\n version: number;\n vendor?: string;\n validate: (value: unknown) => StandardResultLike | Promise<StandardResultLike>;\n };\n}\ninterface StandardResultLike {\n value?: unknown;\n issues?: ReadonlyArray<{\n message: string;\n path?: ReadonlyArray<PropertyKey | { key: PropertyKey }>;\n }>;\n}\n\ninterface EnvSchema {\n server?: Record<string, StandardSchemaLike>;\n client?: Record<string, StandardSchemaLike>;\n}\n\ninterface LoadedEnv {\n schema: EnvSchema;\n /**\n * Every validated output value (server + client) as seen by the BUILD\n * process — used for fast feedback and the client-chunk leak scan. The\n * server virtual module does not bake these: it re-reads process.env at\n * boot. Keys whose build-time validation failed (deferred to boot) are\n * absent.\n */\n all: Record<string, unknown>;\n /** The client-side subset of {@link all}. */\n client: Record<string, unknown>;\n /** Files the schema module transitively loaded (for dev watching). */\n dependencies: string[];\n}\n\nfunction isStandardSchema(value: unknown): value is StandardSchemaLike {\n return (\n !!value &&\n typeof value === 'object' &&\n typeof (value as StandardSchemaLike)['~standard']?.validate === 'function'\n );\n}\n\n/**\n * Keys the loadEnv fold added to process.env, tracked process-globally.\n * Real environment always wins over files — but values *we* folded must not\n * count as \"real\" on revalidation, or the first fold would pin every .env\n * value forever and live edits would never be seen. Process-global (not\n * plugin-closure) state because Vite restarts the dev server on .env\n * changes, recreating the plugin instances inside the same node process:\n * the new instance must be able to clear the old instance's fold.\n */\nconst FOLDED_KEYS = Symbol.for('@solidjs/vite-plugin:env-folded-keys');\nfunction foldedKeys(): Set<string> {\n const holder = globalThis as { [FOLDED_KEYS]?: Set<string> };\n return (holder[FOLDED_KEYS] ??= new Set());\n}\n\nfunction stringEntries(env: NodeJS.ProcessEnv): Record<string, string> {\n const out: Record<string, string> = {};\n for (const key in env) {\n const value = env[key];\n if (typeof value === 'string') out[key] = value;\n }\n return out;\n}\n\n/** Formats the per-key validation report shared by builds and the dev overlay. */\nfunction formatValidationError(\n issues: Array<{ key: string; message: string }>,\n envFile: string,\n mode: string,\n): string {\n const lines = issues.map(({ key, message }) => ` ✗ ${key}: ${message}`);\n return (\n `[@solidjs/vite-plugin] env validation failed (${issues.length} issue${\n issues.length === 1 ? '' : 's'\n }) — schema: ${envFile}, mode: ${mode}\\n\\n` +\n lines.join('\\n') +\n `\\n\\nSet the variables in your environment or .env files, or adjust the schema.`\n );\n}\n\n/** Loads the schema module through Vite with project resolution. */\nasync function importSchemaModule(\n envFileAbs: string,\n root: string,\n mode: string,\n): Promise<{ exported: unknown; dependencies: string[] }> {\n const { module, dependencies } = await runnerImport<Record<string, unknown>>(envFileAbs, {\n root,\n mode,\n });\n return {\n exported: module?.default,\n dependencies: dependencies\n .map((dep: string) => path.resolve(root, dep))\n .filter((dep: string) => existsSync(dep)),\n };\n}\n\nfunction assertSchemaShape(\n exported: unknown,\n envFile: string,\n envPrefixes: string[],\n): EnvSchema {\n if (!exported || typeof exported !== 'object') {\n throw new Error(\n `[@solidjs/vite-plugin] ${envFile} must default-export an object of the shape ` +\n `{ server?: { VAR: schema }, client?: { VITE_VAR: schema } } where every schema ` +\n `is a Standard Schema validator (zod, valibot, arktype, ...). Got: ${\n exported === null ? 'null' : typeof exported\n }.`,\n );\n }\n const schema = exported as Record<string, unknown>;\n for (const key of Object.keys(schema)) {\n if (key !== 'server' && key !== 'client') {\n throw new Error(\n `[@solidjs/vite-plugin] unknown key \"${key}\" in ${envFile}: the env schema takes ` +\n `only \\`server\\` and \\`client\\` maps of Standard Schema validators.`,\n );\n }\n }\n for (const side of ['server', 'client'] as const) {\n const shape = schema[side];\n if (shape === undefined) continue;\n if (!shape || typeof shape !== 'object') {\n throw new Error(\n `[@solidjs/vite-plugin] \\`${side}\\` in ${envFile} must be an object mapping variable ` +\n `names to Standard Schema validators.`,\n );\n }\n for (const [key, validator] of Object.entries(shape)) {\n if (!isStandardSchema(validator)) {\n throw new Error(\n `[@solidjs/vite-plugin] ${side}.${key} in ${envFile} is not a Standard Schema ` +\n `validator (no callable \\`~standard.validate\\`). Any zod/valibot/arktype ` +\n `schema qualifies; plain values and functions don't.`,\n );\n }\n }\n }\n const typed = schema as EnvSchema;\n for (const key of Object.keys(typed.client ?? {})) {\n if (!envPrefixes.some((prefix) => key.startsWith(prefix))) {\n const wanted = envPrefixes[0] ?? 'VITE_';\n throw new Error(\n `[@solidjs/vite-plugin] client env var \"${key}\" in ${envFile} must carry the public ` +\n `env prefix (\"${envPrefixes.join('\" or \"')}\") — client vars are baked into the ` +\n `browser bundle. Rename it to \"${wanted}${key}\", or move it to \\`server\\` if it ` +\n `is a secret.`,\n );\n }\n if (typed.server && key in typed.server) {\n throw new Error(\n `[@solidjs/vite-plugin] \"${key}\" is defined in both \\`server\\` and \\`client\\` in ` +\n `${envFile}; a variable belongs to exactly one side (\\`client\\` vars are ` +\n `visible to the server too).`,\n );\n }\n }\n // The reverse guard: Vite itself bakes every prefixed variable into\n // `import.meta.env` for the browser, so declaring one under `server`\n // cannot keep it secret — it leaks through Vite's channel with no\n // diagnostics from this plugin's leak scan (which only watches the\n // virtual server module's values).\n for (const key of Object.keys(typed.server ?? {})) {\n const prefix = envPrefixes.find((p) => key.startsWith(p));\n if (prefix) {\n const bare = key.slice(prefix.length);\n throw new Error(\n `[@solidjs/vite-plugin] server env var \"${key}\" in ${envFile} carries the public ` +\n `env prefix \"${prefix}\". Vite exposes every \"${prefix}\"-prefixed variable to ` +\n `the browser through import.meta.env no matter which side declares it, so a ` +\n `\\`server\\` entry cannot keep it secret. ` +\n (bare\n ? `Rename it to \"${bare}\" (in the schema and in your .env/environment), or `\n : `Rename it without the prefix, or `) +\n `move it to \\`client\\` if it is public.`,\n );\n }\n }\n return typed;\n}\n\n/**\n * Generates the ambient `solid-env.d.ts` next to the schema file. The file\n * is self-contained: it infers each variable's type from the user's own\n * schema through the Standard Schema `~standard.types.output` phantom, so\n * any compliant validator library yields full types with no per-library\n * introspection. Only rewritten when the content actually changes.\n */\nfunction generateTypes(schema: EnvSchema, envFileAbs: string): void {\n const dtsPath = path.join(path.dirname(envFileAbs), GENERATED_TYPES_FILE);\n const importSpec = './' + path.basename(envFileAbs).replace(/\\.[mc]?[tj]s$/, '');\n\n const field = (side: 'server' | 'client', key: string) =>\n ` readonly ${JSON.stringify(key)}: __Out<__Schema[${JSON.stringify(side)}][${JSON.stringify(key)}]>;`;\n\n const moduleBlock = (id: string, fields: string[]) =>\n [\n `declare module '${id}' {`,\n ` type __Schema = typeof import(${JSON.stringify(importSpec)})['default'];`,\n ` type __Out<T> = T extends { '~standard': { types?: { output: infer O } | undefined } }`,\n ` ? O`,\n ` : string;`,\n ` const env: {`,\n ...fields,\n ` };`,\n ` export { env };`,\n ` export default env;`,\n `}`,\n ].join('\\n');\n\n const clientFields = Object.keys(schema.client ?? {}).map((key) => field('client', key));\n const serverFields = [\n ...Object.keys(schema.server ?? {}).map((key) => field('server', key)),\n ...clientFields,\n ];\n\n const content =\n `// Generated by @solidjs/vite-plugin (start.env) — do not edit.\\n` +\n `// Regenerated on every dev server and build start from ${path.basename(envFileAbs)}.\\n` +\n `// Keep this file (and the schema) inside your tsconfig \"include\".\\n\\n` +\n moduleBlock(CLIENT_ENV_ID, clientFields) +\n '\\n\\n' +\n moduleBlock(SERVER_ENV_ID, serverFields) +\n '\\n';\n\n try {\n if (existsSync(dtsPath) && readFileSync(dtsPath, 'utf-8') === content) return;\n writeFileSync(dtsPath, content);\n } catch (error) {\n const reason = error instanceof Error ? `: ${error.message}` : '';\n console.warn(\n `[@solidjs/vite-plugin] could not write ${GENERATED_TYPES_FILE} next to the env schema` +\n `${reason} — the virtual env modules stay untyped until it can be written.`,\n );\n }\n}\n\n/**\n * Start-mode typed env (the `start.env` option). Returns no plugin when the\n * feature is off (`env: false`, or nothing to probe); the feature is\n * start-only by construction — the option lives on `start`, so a bare\n * `ssr: true` setup has no env layer (documented).\n */\nexport function startEnv(option: boolean | string | undefined): Plugin[] {\n if (option === false) return [];\n\n let root = process.cwd();\n let config: ResolvedConfig;\n let isBuild = false;\n let isPreview = false;\n let enabled = false;\n /** Absolute path of the schema file once resolved. */\n let envFileAbs: string | null = null;\n /** Root-relative schema path for messages. */\n let envFile = 'env.ts';\n\n let envPromise: Promise<LoadedEnv> | null = null;\n let devErrorLogged = false;\n\n function resolveEnvFile(): void {\n if (typeof option === 'string') {\n const absolute = path.isAbsolute(option) ? option : path.resolve(root, option);\n if (!existsSync(absolute)) {\n throw new Error(`[@solidjs/vite-plugin] start.env does not exist: ${option}`);\n }\n const relative = path.relative(root, absolute).split(path.sep).join('/');\n if (relative.startsWith('..')) {\n throw new Error(\n `[@solidjs/vite-plugin] start.env must live inside the Vite root: ${option}`,\n );\n }\n envFileAbs = absolute;\n envFile = relative;\n enabled = true;\n return;\n }\n for (const candidate of ENV_FILE_CANDIDATES) {\n const absolute = path.resolve(root, candidate);\n if (existsSync(absolute)) {\n envFileAbs = absolute;\n envFile = candidate;\n enabled = true;\n return;\n }\n }\n if (option === true) {\n throw new Error(\n `[@solidjs/vite-plugin] start.env is enabled but no schema file was found: add ` +\n `${ENV_FILE_CANDIDATES.join(' or ')} at the project root (default-exporting ` +\n `{ server, client } maps of Standard Schema validators), or point start.env ` +\n `at a path.`,\n );\n }\n }\n\n function envPrefixes(): string[] {\n const prefix = config?.envPrefix ?? 'VITE_';\n return Array.isArray(prefix) ? prefix : [prefix];\n }\n\n async function loadAndValidate(): Promise<LoadedEnv> {\n const { exported, dependencies } = await (async () => {\n try {\n return await importSchemaModule(envFileAbs!, root, config.mode);\n } catch (error) {\n const reason = error instanceof Error ? `\\n\\nCause: ${error.message}` : '';\n throw new Error(\n `[@solidjs/vite-plugin] could not load the env schema at ${envFile}. It must be a ` +\n `server-side module default-exporting { server?, client? } maps of Standard ` +\n `Schema validators.${reason}`,\n );\n }\n })();\n\n const schema = assertSchemaShape(exported, envFile, envPrefixes());\n // Types depend only on the schema, not the values: generate before\n // validating so a missing variable doesn't also break editor types.\n generateTypes(schema, envFileAbs!);\n\n // Vite's .env story with `loadEnv` merge priority — process.env wins\n // (CI/pipeline secrets over files), then .env.[mode].local down to .env.\n // The fold into process.env is what removes the template's classic\n // `process.env = { ...process.env, ...loadEnv(mode, root, '') }` line:\n // server code reading process.env directly (db clients, SDKs) sees the\n // file-loaded vars too, in dev, build, and the client-mode prerender.\n const envDir =\n (config as { envDir?: string | false }).envDir === false\n ? null\n : config.envDir || root;\n const folded = foldedKeys();\n for (const key of folded) delete process.env[key];\n folded.clear();\n const fileEnv = envDir ? loadEnv(config.mode, envDir, '') : {};\n for (const [key, value] of Object.entries(fileEnv)) {\n if (!(key in process.env)) {\n process.env[key] = value;\n folded.add(key);\n }\n }\n const raw: Record<string, string> = { ...fileEnv, ...stringEntries(process.env) };\n\n const issues: Array<{ key: string; message: string; side: 'server' | 'client' }> = [];\n const all: Record<string, unknown> = {};\n for (const side of ['server', 'client'] as const) {\n for (const [key, validator] of Object.entries(schema[side] ?? {})) {\n let result = validator['~standard'].validate(raw[key]);\n if (result instanceof Promise) {\n // Async validation is fine for `client` keys — their values are\n // baked right here at build time, where awaiting costs nothing.\n // `server` keys validate process.env at boot through generated\n // code that is deliberately synchronous (a top-level await in the\n // server env chunk forces esnext on every downstream bundle\n // target — Nitro's node-server preset rejects it outright), so a\n // Promise-returning server validator could only ever fail at\n // deploy boot. Async-ness is a property of the schema, not the\n // value, so fail fast here with the fix in the message. Boot\n // still backstops (schemas whose sync prefix short-circuits at\n // build time can go async on real values).\n if (side === 'server') {\n throw new Error(\n `[@solidjs/vite-plugin] server env var \"${key}\" in ${envFile} uses an async ` +\n `validator (validate() returned a Promise). Server env is validated ` +\n `synchronously at boot — the generated module contains no top-level ` +\n `await, so server bundles work on non-esnext targets — which async ` +\n `validators cannot do. Make the validator synchronous (drop async ` +\n `refinements/transforms), or run the async check in application code.`,\n );\n }\n result = await result;\n }\n if (result.issues && result.issues.length) {\n for (const issue of result.issues) {\n const at = (issue.path ?? [])\n .map((segment) =>\n typeof segment === 'object' && segment !== null && 'key' in segment\n ? String(segment.key)\n : String(segment),\n )\n .join('.');\n issues.push({ key: at ? `${key}.${at}` : key, message: issue.message, side });\n }\n } else {\n all[key] = result.value;\n }\n }\n }\n if (issues.length) {\n // Client values are baked at build time, so their failures always\n // fail hard. Server values are read from process.env at boot: a\n // build may legitimately run without them (platform-injected vars),\n // so build-time server failures downgrade to a warning and boot\n // validation enforces. Dev failures stay hard — dev IS runtime.\n const clientIssues = issues.filter((issue) => issue.side === 'client');\n if (!isBuild || clientIssues.length) {\n throw new Error(\n formatValidationError(!isBuild ? issues : clientIssues, envFile, config.mode),\n );\n }\n config.logger.warn(\n `\\n[@solidjs/vite-plugin] server env not valid at build time (deferred to boot ` +\n `validation — server env is read from process.env at runtime):\\n` +\n issues.map(({ key, message }) => ` ⚠ ${key}: ${message}`).join('\\n') +\n '\\n',\n );\n }\n\n const client: Record<string, unknown> = {};\n for (const key of Object.keys(schema.client ?? {})) client[key] = all[key];\n\n return { schema, all, client, dependencies };\n }\n\n function ensureEnv(): Promise<LoadedEnv> {\n return (envPromise ??= loadAndValidate());\n }\n\n /**\n * Whether the current hook runs for a server-destined module graph. The\n * environment's `consumer` is authoritative (covers workerd and friends\n * without name lists); classic contexts fall back to the ssr flag.\n */\n function isServerContext(\n ctx: { environment?: { config?: { consumer?: string } } },\n opts?: { ssr?: boolean },\n ): boolean {\n const consumer = ctx.environment?.config?.consumer;\n if (consumer) return consumer === 'server';\n return !!opts?.ssr;\n }\n\n function serverOnlyError(importer?: string): string {\n return (\n `[@solidjs/vite-plugin] ${SERVER_ENV_ID} is server-only and was imported from the ` +\n `client module graph` +\n (importer ? ` (by ${importer})` : '') +\n `. Server env values must never reach the browser bundle: import ` +\n `${CLIENT_ENV_ID} for the public ${envPrefixes().join('/')}-prefixed vars, or move ` +\n `this import into a server-only module (a \"use server\" module, middleware, or the ` +\n `server entry).`\n );\n }\n\n // Baked-JSON module emission (pattern from @vite-env/core, MIT): the\n // validated output values serialize as a frozen object literal, so no\n // validator code exists in the client bundle and tree-shaking sees plain\n // data. `moduleType` marks the virtual source as plain JS for rolldown\n // (Vite 8).\n function envModuleCode(values: Record<string, unknown>) {\n return {\n code:\n `// Generated by @solidjs/vite-plugin (start.env)\\n` +\n `export const env = Object.freeze(${JSON.stringify(values)});\\n` +\n `export default env;`,\n moduleType: 'js' as const,\n };\n }\n\n // The server module is NOT baked: server values are read from\n // process.env at module init (server boot) and validated through the\n // user's own schema, imported straight into the server graph (the\n // validator library is server-only, so shipping it there is fine).\n // Client (public) values stay baked — that's what the VITE_ prefix\n // means. Platform-injected vars that don't exist at build time work,\n // secrets rotate without a rebuild, and no secret value exists in any\n // dist artifact.\n //\n // The generated code is deliberately free of top-level await. Module\n // init is the only point where \"validated and frozen before any\n // importer's body runs\" can be guaranteed — user server modules read\n // `env.KEY` at their own top level — and the only async thing here is\n // Standard Schema's option to return a Promise from validate(). A TLA\n // chunk breaks every downstream bundler with a non-esnext target\n // (Nitro's node-server preset in practice), so validation runs\n // synchronously and a Promise-returning server validator is itself a\n // boot issue (build/config time rejects it earlier when detectable).\n function serverEnvModuleCode(loaded: LoadedEnv) {\n const serverKeys = Object.keys(loaded.schema.server ?? {});\n const baked = `const __env = ${JSON.stringify(loaded.client)};`;\n if (!serverKeys.length) {\n return {\n code:\n `// Generated by @solidjs/vite-plugin (start.env) — server env.\\n` +\n `${baked}\\n` +\n `export const env = Object.freeze(__env);\\n` +\n `export default env;`,\n moduleType: 'js' as const,\n };\n }\n return {\n code: [\n `// Generated by @solidjs/vite-plugin (start.env) — server env.`,\n `// Server values are read from process.env and validated at boot;`,\n `// client (public) values are baked at build time. Boot validation is`,\n `// synchronous on purpose: a top-level await here would force esnext`,\n `// on every downstream bundle target (Nitro's node-server preset and`,\n `// anything else below esnext rejects a TLA chunk outright).`,\n `import __schema from ${JSON.stringify(envFileAbs)};`,\n baked,\n `const __issues = [];`,\n `for (const __key of ${JSON.stringify(serverKeys)}) {`,\n ` const __result = __schema.server[__key]['~standard'].validate(process.env[__key]);`,\n ` if (__result && typeof __result.then === 'function') {`,\n ` __issues.push(' \\\\u2717 ' + __key + ': validator returned a Promise \\\\u2014 async validators are not supported for server keys (boot validation is synchronous so the server bundle carries no top-level await); make this validator synchronous');`,\n ` } else if (__result.issues && __result.issues.length) {`,\n ` for (const __issue of __result.issues) __issues.push(' \\\\u2717 ' + __key + ': ' + __issue.message);`,\n ` } else {`,\n ` __env[__key] = __result.value;`,\n ` }`,\n `}`,\n `if (__issues.length) {`,\n ` throw new Error(`,\n ` '[@solidjs/vite-plugin] server env validation failed at boot (' + __issues.length +`,\n ` ' issue' + (__issues.length === 1 ? '' : 's') + ') \\\\u2014 schema: ' + ${JSON.stringify(envFile)} +`,\n ` '\\\\n\\\\n' + __issues.join('\\\\n') +`,\n ` '\\\\n\\\\nServer env is read from process.env at boot, not baked at build time: set the ' +`,\n ` 'variables in the server process environment.'`,\n ` );`,\n `}`,\n `export const env = Object.freeze(__env);`,\n `export default env;`,\n ].join('\\n'),\n moduleType: 'js' as const,\n };\n }\n\n return [\n {\n name: 'solid:start-env',\n\n config(userConfig, env) {\n root = path.resolve(userConfig.root || process.cwd());\n isPreview = !!env.isPreview;\n resolveEnvFile();\n // Preview serves finished artifacts, so no schema loading or\n // validation happens there — but the built server module reads\n // process.env at boot, and `vite preview` should smoke-test the\n // artifact as hands-off as dev runs it: fold the .env files into\n // process.env (real environment still wins). A production process\n // brings its own environment instead.\n if (isPreview && enabled) {\n const envDirOption = (userConfig as { envDir?: string | false }).envDir;\n const envDir =\n envDirOption === false ? null : path.resolve(root, envDirOption || '.');\n if (envDir) {\n const folded = foldedKeys();\n for (const key of folded) delete process.env[key];\n folded.clear();\n const fileEnv = loadEnv(userConfig.mode || env.mode, envDir, '');\n for (const [key, value] of Object.entries(fileEnv)) {\n if (!(key in process.env)) {\n process.env[key] = value;\n folded.add(key);\n }\n }\n }\n }\n },\n\n configResolved(resolved) {\n config = resolved;\n root = resolved.root;\n isBuild = resolved.command === 'build';\n if (!enabled || isPreview) return;\n // Kick validation off eagerly (the fold must precede any server\n // module execution); buildStart awaits it and owns error routing.\n ensureEnv().catch(() => {});\n },\n\n async buildStart() {\n if (!enabled) return;\n try {\n await ensureEnv();\n } catch (error) {\n // Builds fail with the report; dev logs it once and lets the\n // virtual modules rethrow on load, which renders Vite's error\n // overlay (client imports) or the overlay-enabled 500 (SSR).\n if (isBuild) throw error;\n if (!devErrorLogged) {\n devErrorLogged = true;\n config.logger.error(\n '\\n' + (error instanceof Error ? error.message : String(error)) + '\\n',\n );\n }\n }\n },\n\n resolveId(source, importer, options) {\n if (!enabled) return null;\n if (source === CLIENT_ENV_ID) return RESOLVED_CLIENT_ENV_ID;\n if (source === SERVER_ENV_ID) {\n // The dep scanner probes client entries' import graphs without\n // executing them; deny real client-graph imports only (the load\n // hook double-checks — scanners never load `\\0` ids).\n if (!(options as { scan?: boolean } | undefined)?.scan && !isServerContext(this, options)) {\n this.error(serverOnlyError(importer));\n }\n return RESOLVED_SERVER_ENV_ID;\n }\n return null;\n },\n\n async load(id, opts) {\n if (!enabled) return null;\n if (id !== RESOLVED_CLIENT_ENV_ID && id !== RESOLVED_SERVER_ENV_ID) return null;\n // Throws the validation report when env is invalid — the dev\n // overlay / failed build carries the per-key details.\n const loaded = await ensureEnv();\n if (id === RESOLVED_SERVER_ENV_ID) {\n if (!isServerContext(this, opts)) this.error(serverOnlyError());\n return serverEnvModuleCode(loaded);\n }\n return envModuleCode(loaded.client);\n },\n\n configureServer(server: ViteDevServer) {\n if (!enabled) return;\n const envDir =\n (config as { envDir?: string | false }).envDir === false\n ? null\n : config.envDir || root;\n // Explicit file list (no globs — chokidar 4 dropped them): the four\n // .env variants Vite consults for this mode, the schema module, and\n // whatever it transitively loaded.\n const envFiles = envDir\n ? ['.env', '.env.local', `.env.${config.mode}`, `.env.${config.mode}.local`].map(\n (file) => path.join(envDir, file),\n )\n : [];\n const watched = new Set<string>([...envFiles, envFileAbs!]);\n server.watcher.add([...watched]);\n ensureEnv()\n .then(({ dependencies }) => {\n for (const dep of dependencies) watched.add(dep);\n server.watcher.add(dependencies);\n })\n .catch(() => {});\n\n // Live revalidation (flow from @vite-env/core, MIT): reload sources,\n // rerun the schema, invalidate both virtual modules in every\n // environment, and full-reload — on failure the reload makes the\n // client re-import the virtual module, whose load() now throws the\n // fresh report into the error overlay.\n let debounce: ReturnType<typeof setTimeout> | undefined;\n const onFileEvent = (file: string) => {\n if (!watched.has(file)) return;\n clearTimeout(debounce);\n debounce = setTimeout(async () => {\n envPromise = null;\n devErrorLogged = false;\n let failed = false;\n try {\n const { dependencies } = await ensureEnv();\n for (const dep of dependencies) watched.add(dep);\n server.watcher.add(dependencies);\n } catch (error) {\n failed = true;\n devErrorLogged = true;\n config.logger.error(\n '\\n' + (error instanceof Error ? error.message : String(error)) + '\\n',\n );\n }\n let invalidated = false;\n for (const environment of Object.values(server.environments ?? {})) {\n const graph = (environment as { moduleGraph?: any }).moduleGraph;\n if (!graph) continue;\n for (const id of [RESOLVED_CLIENT_ENV_ID, RESOLVED_SERVER_ENV_ID]) {\n const mod = graph.getModuleById(id);\n if (mod) {\n graph.invalidateModule(mod);\n invalidated = true;\n }\n }\n }\n if (invalidated) {\n const hot = server.hot ?? (server as any).ws;\n hot?.send({ type: 'full-reload' });\n }\n if (!failed) {\n config.logger.info(`[@solidjs/vite-plugin] env revalidated (${envFile})`);\n }\n }, 100);\n };\n server.watcher.on('change', onFileEvent);\n server.watcher.on('add', onFileEvent);\n server.watcher.on('unlink', onFileEvent);\n },\n\n // Leak scan (heuristics from @vite-env/core, MIT): a server var's\n // *value* appearing as a quoted string literal in a client chunk means\n // something inlined it (an env.ts import from shared code, a define,\n // a copy-paste). Values under 8 chars skip (too collision-prone), as\n // do values shared with a client var and pure-vendor chunks.\n async generateBundle(_options, bundle) {\n if (!enabled || !isBuild || isServerContext(this, { ssr: !!config.build.ssr })) return;\n const loaded = await ensureEnv().catch(() => null);\n if (!loaded) return;\n\n const clientValues = new Set(Object.values(loaded.client));\n const secrets = Object.entries(loaded.all).filter(\n (entry): entry is [string, string] =>\n !(entry[0] in loaded.client) &&\n typeof entry[1] === 'string' &&\n entry[1].length >= 8 &&\n !clientValues.has(entry[1]),\n );\n if (!secrets.length) return;\n\n const leaks: string[] = [];\n for (const [fileName, chunk] of Object.entries(bundle)) {\n if (chunk.type !== 'chunk' || !chunk.code) continue;\n const moduleIds = (chunk as { moduleIds?: string[] }).moduleIds ?? [];\n if (moduleIds.length > 0 && moduleIds.every((id) => /[\\\\/]node_modules[\\\\/]/.test(id)))\n continue;\n for (const [key, value] of secrets) {\n const escaped = value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n if (new RegExp(`([\"'\\`])${escaped}\\\\1`).test(chunk.code)) {\n leaks.push(`${key} in ${fileName}`);\n }\n }\n }\n if (leaks.length) {\n this.error(\n `[@solidjs/vite-plugin] server env values leaked into client chunks:\\n` +\n leaks.map((leak) => ` ✗ ${leak}`).join('\\n') +\n `\\n\\nServer env values belong to the server process only (they are not even ` +\n `baked into the server bundle). Check for hand-inlined values and imports of ` +\n `the env schema module from client code, and use ${SERVER_ENV_ID} from ` +\n `server-only modules instead.`,\n );\n }\n },\n },\n ];\n}\n","import * as babel from '@babel/core';\nimport type { TransformOptions as JsxCompilerOptions } from '@solidjs/compiler';\nimport remapping from '@ampproject/remapping';\nimport solid from '@solidjs/babel-plugin';\nimport { existsSync, readFileSync } from 'fs';\nimport { mergeAndConcat } from 'merge-anything';\nimport { createRequire } from 'module';\nimport {\n createDevAssetResolver,\n registerDevAssetResolver,\n installDevManifestBridge,\n devManifestBridgeUrl,\n DEV_MANIFEST_REGISTRY_KEY,\n} from './dev-manifest.js';\nimport { boundaryModules } from './boundary-modules.js';\nimport { solidDiagnostics } from './diagnostics/index.js';\n\nimport { serverFunctions, type ServerFunctionsOptions } from './server-functions/index.js';\nimport { SSR_HANDLER_ID, startServe, type StartOptions } from './ssr/index.js';\nimport { startEnv } from './start-env.js';\n\nexport { devStylePatch } from './dev-manifest.js';\nexport { serverFunctions };\nexport type { ServerFunctionsOptions };\nexport type { ServerFunctionsFilter } from './server-functions/index.js';\nexport type { StartOptions };\nimport path from 'path';\nimport type { FilterPattern, Plugin, ViteDevServer } from 'vite';\nimport {\n createFilter,\n defaultClientConditions,\n defaultExternalConditions,\n defaultServerConditions,\n} from 'vite';\nimport { getEnvironmentConsumer, isRunnableEnvironment } from './environment.js';\nimport { crawlFrameworkPkgs } from 'vitefu';\n\nconst require = createRequire(import.meta.url);\n\n/**\n * The `lazy()` module-URL placeholder contract, shared with the native\n * compiler's `transformLazy` pass: `lazy(() => import(\"spec\"))` calls gain a\n * second string-literal argument of the form\n * `\"__SOLID_LAZY_MODULE__:\" + spec`, which `resolveLazyModuleUrls` swaps for\n * the project-relative resolved module path. The prefix and shape are FROZEN\n * — the emitting side lives in @solidjs/compiler and must match.\n */\nconst LAZY_PLACEHOLDER_PREFIX = '__SOLID_LAZY_MODULE__:';\n\n/**\n * The HMR runtime: the dev-only `solid-js/refresh` core entry. Refresh\n * wrappers are compiled by the native `transformRefresh` pass in every mode\n * and import the runtime through normal module resolution (the legacy\n * solid-refresh package — whose runtime carries a known Solid 2.0 HMR bug,\n * solid-refresh#85 — is no longer used at all).\n */\nconst REFRESH_RUNTIME_SOURCE = 'solid-js/refresh';\n\n// Appended to the document shell's client compile instead of a refresh\n// boundary (see documentModuleId in solidPlugin): self-accept, then\n// invalidate — Vite's spelling for \"this module cannot hot-update, reload\".\nconst DOCUMENT_HMR_DECLINE =\n '\\nif (import.meta.hot) {\\n import.meta.hot.accept(() => import.meta.hot.invalidate());\\n}\\n';\n\nconst DEFAULT_STYLE_EXCLUDE = /node_modules/;\n\nconst VIRTUAL_MANIFEST_ID = 'virtual:solid-manifest';\nconst RESOLVED_VIRTUAL_MANIFEST_ID = '\\0' + VIRTUAL_MANIFEST_ID;\n\n// In dev the virtual manifest exports a `{ resolve, resolveSync }` resolver:\n// lazy modules resolve to their dev URL plus transitively imported CSS as\n// inline-style descriptors collected from the live module graph. The resolver\n// itself lives plugin-side (it closes over the dev server) and is reached\n// through a global registry; isolated module runners that don't share\n// globals (nitro's dev worker, workerd) fall back to fetching the dev\n// server's bridge endpoint, whose URL is baked in at generation time\n// (`bridgeUrl` — null outside a live dev server, e.g. the manifest-less SSR\n// build fallback, where js-only resolution remains). Bridge failures log\n// loudly and resolve to null so the runtime's own no-assets warning stays\n// the final catch-all.\n//\n// The generated `moduleUrl` mirrors `devModuleUrl` (src/dev-manifest.ts) —\n// base-prefixed root-relative URLs, `/@fs/` for root-external keys — for the\n// degraded paths that can't reach the plugin-side resolver (no registry and\n// no bridge, or a resolveSync call before the bridge cache warms). Keep the\n// two in sync.\nconst devManifestCode = (root: string, base: string, bridgeUrl: string | null) => `const registry = globalThis[Symbol.for(${JSON.stringify(\n DEV_MANIFEST_REGISTRY_KEY,\n)})];\nconst projectRoot = ${JSON.stringify(root.split(path.sep).join('/'))};\nconst base = ${JSON.stringify(base.startsWith('/') ? base.replace(/\\/$/, '') : '')};\nfunction moduleUrl(key) {\n const queryIndex = key.indexOf(\"?\");\n const file = queryIndex === -1 ? key : key.slice(0, queryIndex);\n const query = queryIndex === -1 ? \"\" : key.slice(queryIndex);\n if (file.slice(0, 2) !== \"..\") return base + \"/\" + key;\n const segments = (projectRoot + \"/\" + file).split(\"/\");\n const resolved = [];\n for (const segment of segments) {\n if (segment === \"..\") resolved.pop();\n else if (segment && segment !== \".\") resolved.push(segment);\n }\n return base + \"/@fs/\" + resolved.join(\"/\") + query;\n}\nconst jsOnly = key => ({ js: [moduleUrl(key)], css: [] });\nconst bridgeUrl = ${JSON.stringify(bridgeUrl)};\nfunction createBridgeResolver() {\n // Convergence cache, mirroring the in-process resolver: server-side lazy()\n // re-requests assets on every retry of a suspended render pass, and only a\n // synchronous answer lets the pass converge (a fresh promise per call\n // suspends every retry anew — nested routes then loop until the render\n // stack overflows). Cached entries can go stale after a CSS edit (no\n // watcher reaches this side of the bridge); the HMR client replaces SSR'd\n // dev styles on load, so staleness self-heals at hydration. Only successful\n // answers are cached: a null (bridge failure) must stay retryable, or one\n // transient miss would strip the module's client assets — silently — for\n // the rest of the dev session. In-flight dedupe still gives retries of the\n // same pass a stable promise, so convergence holds either way.\n const cache = new Map();\n const inFlight = new Map();\n return {\n resolve(key) {\n const cached = cache.get(key);\n if (cached) return cached;\n let request = inFlight.get(key);\n if (!request) {\n request = fetchAssets(key).then(\n (assets) => {\n if (assets) cache.set(key, assets);\n inFlight.delete(key);\n return assets;\n },\n (error) => {\n inFlight.delete(key);\n throw error;\n },\n );\n inFlight.set(key, request);\n }\n return request;\n },\n resolveSync: (key) => cache.get(key) || jsOnly(key),\n };\n}\nasync function fetchAssets(key) {\n const url = new URL(bridgeUrl);\n url.searchParams.set(\"key\", key);\n let response;\n try {\n response = await fetch(url);\n } catch (error) {\n console.error(\n '[@solidjs/vite-plugin] Dev manifest bridge request failed for module key \"' + key +\n '\" (' + url.href + '): ' + ((error && error.message) || error) +\n \". SSR will render without this module's client assets, so its hydration preload entry will be missing.\",\n );\n return null;\n }\n if (!response.ok) {\n // A silent null here strips the module's client assets from the\n // SSR'd hydration asset map and hydration fails much later with a\n // cryptic client-side error — report the miss where it happens.\n console.error(\n '[@solidjs/vite-plugin] Dev manifest bridge request failed with status ' + response.status +\n ' for module key \"' + key + '\" (' + url.href +\n \"). SSR will render without this module's client assets, so its hydration preload entry will be missing.\",\n );\n return null;\n }\n return response.json();\n}\nexport default (registry && registry[${JSON.stringify(root)}]) ||\n (bridgeUrl ? createBridgeResolver() : { resolve: jsOnly, resolveSync: jsOnly });`;\n\n/** Possible options for the extensions property */\nexport interface ExtensionOptions {\n typescript?: boolean;\n}\n\nexport type Compiler = 'babel' | 'native';\nexport type SolidOptions = Omit<JsxCompilerOptions, 'filename' | 'sourceMap'>;\ntype NativeCompiler = typeof import('@solidjs/compiler');\nlet nativeCompilerPromise: Promise<NativeCompiler> | undefined;\n\nasync function loadNativeCompiler() {\n try {\n return await (nativeCompilerPromise ??= import('@solidjs/compiler'));\n } catch (error) {\n nativeCompilerPromise = undefined;\n const reason = error instanceof Error ? `\\n\\nCause: ${error.message}` : '';\n throw new Error(\n '@solidjs/vite-plugin: failed to load @solidjs/compiler, which is required ' +\n 'in every mode (it drives the lazy, refresh, and server-function transforms; ' +\n 'compiler: \"babel\" only switches the JSX transform). Your platform should get ' +\n 'a prebuilt native binary or the @solidjs/compiler-wasm32-wasi fallback ' +\n '— check that optional dependencies were installed.' +\n reason,\n );\n }\n}\n\n/** Configuration options for @solidjs/vite-plugin. */\nexport interface Options {\n /**\n * A [picomatch](https://github.com/micromatch/picomatch) pattern, or array of patterns, which specifies the files\n * the plugin should operate on. Relative patterns are resolved against the\n * Vite root, not the invocation directory.\n */\n include?: FilterPattern;\n /**\n * A [picomatch](https://github.com/micromatch/picomatch) pattern, or array of patterns, which specifies the files\n * to be ignored by the plugin. Relative patterns are resolved against the\n * Vite root, not the invocation directory.\n */\n exclude?: FilterPattern;\n /**\n * This will inject solid-js/dev in place of solid-js in dev mode. Has no\n * effect in prod. If set to `false`, it won't inject it in dev. This is\n * useful for extra logs and debugging.\n *\n * @default true\n */\n dev?: boolean;\n /**\n * Dev-serve only: expose Solid's diagnostic and attribution channels to\n * out-of-process consumers (agents, tests, curl). Injects a client module\n * that installs the in-page bridge from the app's own\n * `@solidjs/diagnostics` (which must be installed as a dev dependency),\n * and serves a `/__solid/diagnostics` endpoint on the dev server that\n * forwards capture control (`begin`/`end`), `whyDidRun`, and cost queries\n * to the page over the Vite WebSocket. No effect on builds or preview.\n *\n * @default false\n */\n diagnostics?: boolean;\n /**\n * Whether the app is server-rendered — one meaning everywhere.\n *\n * Without {@link start}: the legacy transform-only flag, unchanged.\n * `true` enables the SSR transforms (hydratable client code, SSR server\n * code) — you provide the entries and the server yourself.\n *\n * With {@link start}: selects the start mode. `true` is SSR start mode\n * (per-request streaming render + hydration); `false`/omitted is client\n * mode (a static document shell + client-side `render()`). Flipping a\n * start-mode project between SPA and SSR is toggling this one boolean.\n *\n * The flag describes the app's initial document, not the internal\n * pipelines — client mode still compiles the document shell through the\n * SSR transforms to serve/prerender it.\n *\n * Objects are no longer accepted: start-mode options moved to {@link start}\n * (`ssr: { ... }` from 3.0.0-next.23 and earlier becomes\n * `start: { ... }, ssr: true`).\n *\n * @default false\n */\n ssr?: boolean;\n\n /**\n * Start mode — Start as a mode of the plugin: it owns entries, dev\n * serving, and the build — no index.html, no mount file, no server\n * wiring. `start: true` is the zero-config spelling, sugar for the empty\n * options bag `start: {}` (both mean the identical start mode with\n * defaults; `false`/absent is off). Conventions (shared by both modes,\n * so projects flip between them by toggling {@link ssr}): `src/App.*`\n * (or `start.app`) is the root component; `src/Document.*` (or\n * `start.document`) is the optional document shell; authored\n * `src/entry-server.*` / `src/entry-client.*` (or `start.entryServer` /\n * `start.entryClient`) replace the generated entries.\n *\n * With `ssr: true` — SSR start mode:\n *\n * - Dev: a middleware on the Vite dev server streams the rendered app for\n * HTML-accepting GET requests — `vite` just works, no server file.\n * - Build: a plain `vite build` produces both bundles (client to\n * `dist/client`, server to `dist/server` via the environments/builder\n * API). The server bundle's entry is `virtual:solid-ssr-handler`, whose\n * `handleRequest(request)` export maps a web `Request` to a streamed\n * `Response`; its default `{ fetch(request) }` export provides the same\n * handler in the Fetchable shape used by deployment integrations.\n * The normal `ssr` environment exposes it as the `index` service entry\n * so provider Vite plugins can supply the runtime and build orchestration.\n * - With `serverFunctions` also enabled, the prod handler serves the\n * server-function endpoint too (in dev the server-function middleware\n * already runs first).\n *\n * Without `ssr: true` — client mode:\n *\n * - Dev: every HTML-accepting GET streams the rendered document shell\n * (without the app — history-fallback semantics); the generated client\n * entry `render()`s the app into it.\n * - Build: `vite build` emits a static `dist/client` — the shell is\n * prerendered once through the built handler into\n * `dist/client/index.html` with the hashed entry script and CSS links —\n * deployable to any static host. No server bundle remains unless\n * `serverFunctions` is enabled, in which case `dist/server` is kept and\n * its `handleRequest` serves the endpoint (pages stay static).\n * - Client code stays non-hydratable (`generate: 'dom'`), exactly like a\n * plain SPA; server-only options (`entryServer`, `external`) are inert.\n * - `vite preview` serves the static build with history fallback (and\n * dispatches the server-function endpoint through the kept handler).\n *\n * @default undefined\n */\n start?: boolean | StartOptions;\n\n /**\n * JSX compiler backend to use. The default `\"native\"` compiles through\n * `@solidjs/compiler`; `\"babel\"` is the escape hatch running\n * `@solidjs/babel-plugin` instead — if native output ever differs from your\n * expectations, set `compiler: \"babel\"` and file an issue (the behavioral\n * diff between the modes is the bug report). Platforms without a prebuilt\n * native binary (e.g. StackBlitz WebContainers) automatically use the wasm\n * fallback; the compiler package itself is required in every mode.\n *\n * @default \"native\"\n */\n compiler?: Compiler;\n\n /**\n * This will inject HMR runtime in dev mode. Has no effect in prod. If\n * set to `false`, it won't inject the runtime in dev.\n *\n * @default true\n * @deprecated use `refresh` instead\n */\n hot?: boolean;\n /**\n * This registers additional extensions that should be processed by\n * @solidjs/vite-plugin.\n *\n * @default undefined\n */\n extensions?: (string | [string, ExtensionOptions])[];\n /**\n * Pass any additional babel transform options. They will be merged with\n * the transformations required by Solid.\n *\n * Note: with `compiler: \"native\"` the plugin is normally fully Babel-free\n * (native lazy/refresh/JSX passes). Supplying custom babel options\n * reintroduces a Babel support pass ahead of the native JSX transform to\n * host them.\n *\n * @default {}\n */\n babel?:\n | babel.TransformOptions\n | ((source: string, id: string, ssr: boolean) => babel.TransformOptions)\n | ((source: string, id: string, ssr: boolean) => Promise<babel.TransformOptions>);\n /**\n * Pass any additional [@solidjs/babel-plugin](https://github.com/solidjs/solid/tree/main/packages/babel-plugin) options.\n * They will be merged with the plugin's Solid defaults.\n *\n * @default {}\n */\n solid?: SolidOptions;\n\n /**\n * Enable `\"use server\"` server function compilation (experimental). Pass\n * `true` for the defaults (runtime from @solidjs/web/server-functions) or\n * an options object to customize. The directive transform sub-plugins are\n * emitted ahead of the JSX transform in the returned plugin array.\n *\n * Zero-config setup: in dev, a middleware on the Vite server handles the\n * endpoint (default `/_server`, joined with `base`) end to end — no\n * server-function code needed in the server entry. For production SSR\n * builds, import `virtual:solid-server-function-handler` in the server\n * entry and mount its `handleServerFunctionRequest(request)` export on the\n * endpoint; it eagerly imports every module containing server functions so\n * registrations survive tree-shaking.\n *\n * Hosts whose own server environment should own endpoint dispatch in dev\n * (e.g. @cloudflare/vite-plugin, so functions run in workerd with\n * bindings) can keep this option and set\n * `serverFunctions: { devMiddleware: false }` — see\n * {@link ServerFunctionsOptions.devMiddleware}. A server-only module can\n * be pinned into the handler graph for pre-dispatch runtime registration\n * via {@link ServerFunctionsOptions.configure}.\n *\n * Meta-frameworks that need to control plugin ordering themselves (e.g.\n * relative to a file-system router) and dispatch requests through their\n * own server should use the standalone `serverFunctions()` export instead,\n * which never installs the dev middleware.\n *\n * The object form's `components` flag additionally enables server\n * components (experimental) — `\"use server\"` functions returning a\n * component, served over the same endpoint. They come essentially for\n * free: the endpoint transform is installed automatically, and with\n * SSR start mode (the `start` option with `ssr: true`) and generated entries\n * the document wiring is emitted too. See\n * {@link ServerFunctionsOptions.components}.\n *\n * @default undefined\n */\n serverFunctions?: boolean | ServerFunctionsOptions;\n\n /** Options for the solid-refresh HMR transform (dev only). */\n refresh?: RefreshOptions;\n}\n\n/** Options for the solid-refresh HMR transform (dev only). */\nexport interface RefreshOptions {\n /**\n * Disable the refresh transform entirely (equivalent to the deprecated\n * `hot: false`).\n */\n disabled?: boolean;\n /**\n * Emit per-component `signature`/`dependencies` metadata so edits only\n * remount components whose code actually changed.\n *\n * @default true\n */\n granular?: boolean;\n}\n\nfunction getExtension(filename: string): string {\n const index = filename.lastIndexOf('.');\n return index < 0 ? '' : filename.substring(index).replace(/\\?.+$/, '');\n}\nfunction containsSolidField(fields: Record<string, any>) {\n const keys = Object.keys(fields);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n if (key === 'solid') return true;\n if (typeof fields[key] === 'object' && fields[key] != null && containsSolidField(fields[key]))\n return true;\n }\n return false;\n}\n\nfunction getJestDomExport(setupFiles: string[]) {\n return setupFiles?.some((path) => /jest-dom/.test(path))\n ? undefined\n : ['@testing-library/jest-dom/vitest', '@testing-library/jest-dom/extend-expect'].find(\n (path) => {\n try {\n require.resolve(path);\n return true;\n } catch (e) {\n return false;\n }\n },\n );\n}\n\nfunction getSolidOptions(\n options: Partial<Options>,\n isSsr: boolean,\n dev: boolean,\n isTestMode = false,\n): SolidOptions {\n let solidOptions: Pick<SolidOptions, 'generate' | 'hydratable'>;\n\n if (isTestMode) {\n // Vitest compiles with the client posture regardless of the app's `ssr`\n // flag: component tests exercise DOM code and nothing hydrates in a\n // test, so hydratable output would look for markers that aren't there.\n // `generate` still follows the transform's own ssr flag, so explicit\n // node-environment tests (renderToString) keep their server codegen.\n solidOptions = { generate: isSsr ? 'ssr' : 'dom', hydratable: false };\n } else if (options.start && !options.ssr) {\n // Client start mode: client code compiles exactly like a plain SPA\n // (dom, non-hydratable — nothing hydrates); only the document shell\n // render goes through the SSR transforms, also non-hydratable since\n // the shell is inert HTML the client never claims.\n solidOptions = { generate: isSsr ? 'ssr' : 'dom', hydratable: false };\n } else if (options.ssr) {\n if (isSsr) {\n solidOptions = { generate: 'ssr', hydratable: true };\n } else {\n solidOptions = { generate: 'dom', hydratable: true };\n }\n } else {\n solidOptions = { generate: 'dom', hydratable: false };\n }\n\n // Server components (serverFunctions.components) turn on the SSR-side\n // behavior-claims transform: ref/on* positions on intrinsic elements\n // compile to guarded `_bnd` claim holes instead of dropping. SSR-only\n // by construction (the dom generate ignores the flag), and apps without\n // the flag compile byte-for-byte as before.\n const serverComponents =\n typeof options.serverFunctions === 'object' && !!options.serverFunctions.components;\n\n // Solid-specific defaults (moduleName \"@solidjs/web\", the control-flow\n // builtIns, contextToCustomElements, wrapConditionals) are baked into both\n // backends — @solidjs/compiler and @solidjs/babel-plugin — so only the\n // posture this plugin actually decides is passed.\n return {\n ...solidOptions,\n ...(serverComponents && solidOptions.generate === 'ssr' ? { serverComponents: true } : {}),\n dev,\n ...(options.solid || {}),\n };\n}\n\nasync function getBabelUserOptions(\n options: Partial<Options>,\n source: string,\n id: string,\n isSsr: boolean,\n) {\n if (!options.babel) return {};\n if (typeof options.babel !== 'function') return options.babel;\n\n const babelOptions = options.babel(source, id, isSsr);\n return babelOptions instanceof Promise ? await babelOptions : babelOptions;\n}\n\nfunction normalizeSourceMap(\n map: string | babel.TransformOptions['inputSourceMap'] | null | undefined,\n) {\n if (typeof map === 'string') return JSON.parse(map);\n return map || null;\n}\n\ntype ChainableMap = string | babel.TransformOptions['inputSourceMap'] | null | undefined;\n\n/**\n * Merges the sourcemaps of sequential whole-file transforms (given in\n * application order, earliest first) into one map tracing back to the\n * original source.\n */\nfunction combineSourcemaps(maps: ChainableMap[]) {\n const chain = maps.filter((map): map is NonNullable<ChainableMap> => !!map);\n if (chain.length === 0) return null;\n if (chain.length === 1) return normalizeSourceMap(chain[0]);\n // remapping expects most-recent-first.\n return JSON.parse(remapping(chain.reverse() as any, () => null).toString());\n}\n\n/**\n * Chunks emitted for lazy() targets are marked `isEntry` by Rollup even\n * though they are semantically dynamic entries. Reclassify any entry that is\n * dynamically imported by another chunk so the runtime's entry-asset\n * detection (which keys off `isEntry`) can't pick a lazy facade instead of\n * the real client entry. Works on both the Vite manifest.json shape and the\n * raw Rollup output bundle — both key entries by name and expose\n * `dynamicImports` / `isEntry` with the same meaning.\n */\nfunction normalizeEmittedLazyEntries(manifest: Record<string, any>) {\n const dynamicKeys = new Set<string>();\n for (const key in manifest) {\n const imports: string[] | undefined = manifest[key].dynamicImports;\n if (imports) for (const dep of imports) dynamicKeys.add(dep);\n }\n for (const key of dynamicKeys) {\n const entry = manifest[key];\n if (entry && entry.isEntry) {\n entry.isEntry = false;\n entry.isDynamicEntry = true;\n }\n }\n}\n\nexport default function solidPlugin(options: Partial<Options> = {}): Plugin[] {\n if (typeof options.ssr === 'object') {\n throw new Error(\n '[@solidjs/vite-plugin] `ssr` now only accepts a boolean (\"is the app server-rendered\"); ' +\n 'move start-mode options to `start: {}` and set `ssr: true`. Example: ' +\n '`solid({ ssr: { document: … } })` becomes `solid({ start: { document: … }, ssr: true })`.',\n );\n }\n // Recreated in configResolved: relative include/exclude patterns must\n // resolve against the Vite root, not process.cwd() — running `vite` from\n // outside the project would otherwise change what the filter matches.\n let filter = createFilter(options.include, options.exclude);\n const serverComponents =\n typeof options.serverFunctions === 'object' && !!options.serverFunctions.components;\n // `start: true` is sugar for the empty options bag — one start mode,\n // two spellings — so normalize here and let everything downstream see a\n // single shape (`false` behaves exactly like omission).\n const startOptions: StartOptions | null =\n options.start === true ? {} : options.start || null;\n const styleFilterOptions = startOptions?.css?.filter;\n // The CSS crawl walks the module graph from the app's own entries, so a\n // plain createFilter allowlist can't express the option's purpose (opting\n // node_modules graphs in): a bare `include` would reject the app sources\n // the crawl has to traverse to ever reach the included package. Instead\n // `include` rescues files on top of the baseline (everything except\n // `exclude`, which defaults to node_modules), while a file matching both\n // patterns stays excluded — createFilter's own conflict rule.\n const createStyleFilter = (resolve?: string) => {\n const opts = resolve === undefined ? undefined : { resolve };\n const base = createFilter(\n undefined,\n styleFilterOptions?.exclude ?? DEFAULT_STYLE_EXCLUDE,\n opts,\n );\n const include = styleFilterOptions?.include;\n const hasInclude = include != null && (!Array.isArray(include) || include.length > 0);\n const included = hasInclude ? createFilter(include, styleFilterOptions?.exclude, opts) : null;\n return (id: string) => base(id) || (included ? included(id) : false);\n };\n let styleFilter = createStyleFilter();\n const filterDevStyles = (id: string) => styleFilter(id);\n // `start.external` only means something when a server side exists to hand\n // over (SSR start mode); in client mode it is a documented no-op.\n const externalDevServer = !!options.ssr && !!startOptions?.external;\n\n let needHmr = false;\n let replaceDev = false;\n // Resolved absolute path of the start-mode document shell (normalized to\n // forward slashes, matching Vite ids), reported back by the start plugin's\n // config hook. The document is the one module whose client compile must\n // decline HMR instead of taking a refresh boundary: it hydrates the whole\n // `document`, and no component swap can re-claim `document.documentElement`\n // — an accepted update would be absorbed with nothing visibly changing\n // (solidjs/solid#3151). Declining makes a save invalidate the module, so\n // Vite falls back to a full page reload: the honest cost.\n let documentModuleId: string | null = null;\n // The live dev server, kept so the dev manifest module can bake the bridge\n // endpoint URL in when its code is generated (see devManifestBridgeUrl).\n let devServer: ViteDevServer | null = null;\n let projectRoot = process.cwd();\n let isTestMode = false;\n let serverTestPosture = false;\n let isBuild = false;\n let isSsrBuild = false;\n let base = '/';\n let clientOutDir: string | null = null;\n let solidPkgsConfig: Awaited<ReturnType<typeof crawlFrameworkPkgs>>;\n\n // The client build's manifest, read back by SSR builds. In builder-mode\n // (single process, e.g. SolidStart's nitro plugin) the client build runs\n // first and generateBundle records its actual outDir — authoritative, since\n // such setups relocate it. Two-invocation builds (`vite build --outDir\n // dist/client` then `vite build --ssr`) run in separate processes, so the\n // SSR process falls back to the `dist/client` convention.\n function clientManifestPath(): string | null {\n for (const dir of [clientOutDir, 'dist/client']) {\n if (!dir) continue;\n const manifestPath = path.resolve(projectRoot, dir, '.vite/manifest.json');\n if (existsSync(manifestPath)) return manifestPath;\n }\n return null;\n }\n\n // Dynamically imported project modules in the client build. Each is\n // emitted as an explicit chunk so it always gets its own manifest entry\n // keyed by source path — even when manualChunks or dual static/dynamic\n // imports would otherwise fold it facade-less into a shared chunk (which\n // would break resolveAssets lookups and hydration module preloading).\n // Driven from moduleParsed so it covers every lazy() target, including\n // import.meta.glob entries that never pass through the moduleUrl transform.\n const emittedLazyChunks = new Set<string>();\n // Keep the emitted references because a lazy module's importer may be\n // removed from the final bundle, leaving no dynamic-import edge to identify\n // its facade chunk during generateBundle.\n const emittedLazyChunkRefs: string[] = [];\n\n // Whether the current hook invocation belongs to a client (browser) build.\n // Builder-mode builds (e.g. SolidStart's nitro plugin) run the client and\n // ssr environments through one Vite process with shared plugins, so the\n // process-wide isSsrBuild flag from configResolved can't tell them apart —\n // the per-environment consumer can. Classic two-invocation builds\n // (`vite build` / `vite build --ssr`) fall back to the flag.\n function isClientBuild(ctx: { environment?: { config?: { consumer?: string } } }): boolean {\n const consumer = ctx.environment?.config?.consumer;\n if (consumer) return consumer === 'client';\n return !isSsrBuild;\n }\n\n /**\n * Replaces lazy() moduleUrl placeholders injected by the babel plugin with\n * project-relative module paths resolved through Vite's resolver.\n */\n async function resolveLazyModuleUrls(ctx: any, code: string, importer: string): Promise<string> {\n const placeholderRe = new RegExp('\"' + LAZY_PLACEHOLDER_PREFIX + '([^\"]+)\"', 'g');\n let match;\n const resolutions: Array<{ placeholder: string; resolved: string }> = [];\n while ((match = placeholderRe.exec(code)) !== null) {\n const specifier = match[1];\n const resolved = await ctx.resolve(specifier, importer);\n if (resolved) {\n // The query is part of the module identity: Rollup keys the facade\n // chunk (and thus the Vite manifest entry) by the queried module id,\n // and in dev the queried URL can serve different plugin output than\n // the bare one — stripping it here would break both lookups.\n const queryIndex = resolved.id.indexOf('?');\n const file = queryIndex === -1 ? resolved.id : resolved.id.slice(0, queryIndex);\n const query = queryIndex === -1 ? '' : resolved.id.slice(queryIndex);\n const relativeId = path.relative(projectRoot, file).split(path.sep).join('/') + query;\n resolutions.push({\n placeholder: match[0],\n resolved: '\"' + relativeId + '\"',\n });\n }\n }\n for (const { placeholder, resolved } of resolutions) {\n code = code.replace(placeholder, resolved);\n }\n return code;\n }\n\n /**\n * SSR transforms append a `$$moduleUrl` export carrying the module's\n * client-manifest key (project-relative source path, module query\n * included — a queried module is its own identity, with its own facade\n * chunk and manifest entry). Server-side `lazy()` reads it off the\n * resolved module when the callsite has no static import specifier to\n * transform — e.g. `lazy` over an `import.meta.glob` entry — so asset\n * resolution and hydration preloading still work. Client builds are\n * untouched.\n */\n function injectSsrModuleId(code: string, id: string, isSsr: boolean): string {\n if (!isSsr || /node_modules/.test(id) || code.includes('$$moduleUrl')) return code;\n const queryIndex = id.indexOf('?');\n const file = queryIndex === -1 ? id : id.slice(0, queryIndex);\n const query = queryIndex === -1 ? '' : id.slice(queryIndex);\n const relativeId = path.relative(projectRoot, file).split(path.sep).join('/') + query;\n return code + `\\nexport const $$moduleUrl = ${JSON.stringify(relativeId)};\\n`;\n }\n\n const mainPlugin: Plugin = {\n name: 'solid',\n enforce: 'pre',\n\n async config(userConfig, { command }) {\n // We inject the dev mode only if the user explicitly wants it or if we are in dev (serve) mode\n replaceDev = options.dev === true || (options.dev !== false && command === 'serve');\n projectRoot = userConfig.root || projectRoot;\n isTestMode = userConfig.mode === 'test';\n // Per-vitest-project posture: the client posture (browser conditions,\n // dom codegen, jsdom default) is right for DOM component tests but\n // wrong for server-runtime unit tests. A project that explicitly opts\n // into a server runtime — `test: { environment: 'node' }` (or\n // 'edge-runtime') — gets the server posture end to end: no browser\n // condition injection, so the framework resolves its real server\n // build (isServer true) with no inline/alias workarounds. DOM\n // environments (the jsdom default, happy-dom, browser mode) keep the\n // client posture. Each vitest project resolves its own config, so the\n // hooks below see the posture of the project they serve.\n serverTestPosture =\n isTestMode &&\n ((userConfig as any).test?.environment === 'node' ||\n (userConfig as any).test?.environment === 'edge-runtime');\n\n solidPkgsConfig = await crawlFrameworkPkgs({\n viteUserConfig: userConfig,\n root: projectRoot || process.cwd(),\n isBuild: command === 'build',\n isFrameworkPkgByJson(pkgJson) {\n return containsSolidField(pkgJson.exports || {});\n },\n });\n\n // fix for bundling dev in production\n const nestedDeps = replaceDev ? ['solid-js', '@solidjs/web'] : [];\n\n const userTest = (userConfig as any).test ?? {};\n const test = {} as any;\n if (userConfig.mode === 'test') {\n // to simplify the processing of the config, we normalize the setupFiles to an array\n const userSetupFiles: string[] =\n typeof userTest.setupFiles === 'string'\n ? [userTest.setupFiles]\n : userTest.setupFiles || [];\n\n // Regardless of the app's `ssr` flag: tests run with the client\n // posture (DOM component tests are the norm), so the default test\n // environment is a DOM. Node-environment tests opt in explicitly.\n // Browser-mode projects get the real browser DOM, so don't default\n // them to jsdom — vitest probes for the environment's package at\n // startup and fails the run if jsdom isn't installed. They fall\n // back to vitest's own node default (no package probe).\n if (!userTest.environment && !userTest.browser?.enabled) {\n test.environment = 'jsdom';\n }\n\n if (serverTestPosture) {\n // The worker pool is shared across the whole vitest workspace and\n // imports externalized deps natively with `--conditions` derived\n // from the ROOT config — which carries the client posture's\n // 'browser'. Inline the framework so every resolution goes through\n // THIS project's (server) conditions instead: one server-build\n // instance end to end (request-event storage included).\n if (!userTest.server?.deps?.inline) {\n test.server = { deps: { inline: [/solid-js/, /@solidjs[+/]web/] } };\n }\n } else if (\n !userTest.server?.deps?.external?.find((item: string | RegExp) =>\n /solid-js/.test(item.toString()),\n )\n ) {\n test.server = { deps: { external: [/solid-js/] } };\n }\n // jest-dom's DOM matchers have no place in a server-posture project;\n // vitest browser mode already has bundled jest-dom assertions\n // https://main.vitest.dev/guide/browser/assertion-api.html#assertion-api\n if (!userTest.browser?.enabled && !serverTestPosture) {\n const jestDomImport = getJestDomExport(userSetupFiles);\n if (jestDomImport) {\n test.setupFiles = [jestDomImport];\n }\n }\n }\n\n return {\n /**\n * We only need esbuild on .ts or .js files.\n * .tsx & .jsx files are handled by us\n */\n // esbuild: { include: /\\.ts$/ },\n // resolve.conditions is handled per-environment in configEnvironment.\n resolve: {\n dedupe: nestedDeps,\n },\n optimizeDeps: {\n include: [\n ...nestedDeps,\n // Dev refresh wrappers import the solid-js/refresh runtime in\n // every mode; pre-bundle it up front so its discovery doesn't\n // trigger a re-optimize + full reload on first use.\n ...(command === 'serve' && options.hot !== false && !options.refresh?.disabled\n ? [REFRESH_RUNTIME_SOURCE]\n : []),\n // The server-components client runtime is imported by the\n // (virtual) client entry, and compiled function references\n // import the server-function client runtime; pre-bundle both up\n // front — in one optimizer pass — so a mid-session discovery\n // can't trigger a re-optimize + full reload, and both entries\n // share one instance of the transport config module (the\n // server-components runtime installs its response policy there).\n ...(command === 'serve' && serverComponents\n ? ['@solidjs/web/frames', '@solidjs/web/server-functions']\n : []),\n ...solidPkgsConfig.optimizeDeps.include,\n ],\n exclude: solidPkgsConfig.optimizeDeps.exclude,\n // Keep Solid TSX from injecting React's automatic runtime during scanning.\n rolldownOptions: { transform: { jsx: { runtime: 'classic' as const } } },\n },\n ...(Object.keys(test).length ? { test } : {}),\n };\n },\n\n configEnvironment(name, config, opts) {\n config.resolve ??= {};\n // Emulate Vite default fallback for `resolve.conditions` if not set\n if (config.resolve.conditions == null) {\n if (config.consumer === 'client' || name === 'client' || opts.isSsrTargetWebworker) {\n config.resolve.conditions = [...defaultClientConditions];\n } else {\n config.resolve.conditions = [...defaultServerConditions];\n }\n }\n config.resolve.conditions = [\n 'solid',\n ...(replaceDev ? ['development'] : []),\n // Tests resolve the browser builds even when the app is\n // server-rendered — the client posture applies to the whole test\n // pipeline, not just the codegen. Projects that explicitly opt into\n // a server runtime (`test.environment: 'node'` / 'edge-runtime')\n // keep the default server conditions instead, so the framework's\n // real server build resolves (isServer true).\n ...(isTestMode && !serverTestPosture && !opts.isSsrTargetWebworker ? ['browser'] : []),\n ...config.resolve.conditions,\n ];\n\n // `resolve.conditions` above only governs modules Vite inlines.\n // Externalized server deps are resolved by `fetchModule` with\n // `resolve.externalConditions` (default `['node', 'module-sync']`) and\n // handed to the module runner as concrete file paths — without\n // `development` there, packages that select their dev build through\n // the `development` export condition (@solidjs/web's server-functions\n // runtime among them) run their PRODUCTION copy under `vite dev`:\n // server errors reach the client sanitized to \"Internal Server Error\"\n // instead of carrying the real message, dev-only diagnostics vanish.\n // So the dev flag has to reach both lists.\n if (replaceDev && config.consumer !== 'client' && name !== 'client') {\n config.resolve.externalConditions = [\n 'development',\n ...(config.resolve.externalConditions ?? defaultExternalConditions),\n ];\n }\n\n // Set resolve.noExternal and resolve.external for the SSR environment.\n // Only set resolve.external if noExternal is not true (to avoid conflicts with plugins like Cloudflare)\n if (name === 'ssr' && solidPkgsConfig) {\n if (config.resolve.noExternal !== true) {\n config.resolve.noExternal = [\n ...(Array.isArray(config.resolve.noExternal) ? config.resolve.noExternal : []),\n ...solidPkgsConfig.ssr.noExternal,\n ];\n config.resolve.external = [\n ...(Array.isArray(config.resolve.external) ? config.resolve.external : []),\n ...solidPkgsConfig.ssr.external,\n ];\n }\n }\n },\n\n configResolved(config) {\n isBuild = config.command === 'build';\n isSsrBuild = !!config.build.ssr;\n base = config.base;\n projectRoot = config.root;\n filter = createFilter(options.include, options.exclude, { resolve: projectRoot });\n styleFilter = createStyleFilter(projectRoot);\n if (serverComponents && !(options.start && options.ssr)) {\n config.logger.warn(\n '[@solidjs/vite-plugin] serverFunctions.components is set without SSR start mode (the `start` ' +\n 'option with `ssr: true`), so the plugin only installs the endpoint response transform ' +\n '(server functions returning components stream correctly). The document wiring — render ' +\n 'plugin, bootstrap script, and the client-side installServerComponents() call — is ' +\n \"emitted by SSR start mode's generated entries; without it, server components only mount \" +\n 'from post-boot streams and your client code must call installServerComponents() itself.',\n );\n }\n needHmr =\n config.command === 'serve' &&\n config.mode !== 'production' &&\n options.hot !== false &&\n !options.refresh?.disabled;\n },\n\n configureServer(server) {\n devServer = server;\n // Dev asset resolution for SSR: the virtual manifest module (evaluated\n // in the SSR environment) picks this resolver up through the global\n // registry keyed by project root — or, from isolated module runners\n // that don't share globals with this process, through the HTTP bridge\n // endpoint the middleware serves.\n if (options.ssr || options.start) {\n registerDevAssetResolver(\n server.config.root,\n createDevAssetResolver(server, filterDevStyles),\n );\n installDevManifestBridge(server);\n }\n if (!needHmr) return;\n // When a module has a syntax error, Vite sends the error overlay via\n // WebSocket but the failed import triggers invalidation in solid-refresh.\n // This propagates up to @refresh reload boundaries (e.g. document-level\n // App components in SSR), causing a full-reload that overrides the overlay.\n // We suppress update/full-reload messages that immediately follow an error.\n const hot = server.hot ?? (server as any).ws;\n if (!hot) return;\n let lastErrorTime = 0;\n const origSend = hot.send.bind(hot);\n hot.send = function (this: any, ...args: any[]) {\n const payload = args[0];\n if (typeof payload === 'object' && payload) {\n if (payload.type === 'error') {\n lastErrorTime = Date.now();\n } else if (\n lastErrorTime &&\n (payload.type === 'full-reload' || payload.type === 'update')\n ) {\n if (Date.now() - lastErrorTime < 200) return;\n lastErrorTime = 0;\n }\n }\n return origSend(...args);\n } as typeof hot.send;\n },\n\n hotUpdate({ modules, file }) {\n // solid-refresh only injects HMR boundaries into client modules, so\n // non-client environments have no accept handlers. Without this, Vite\n // would see no boundaries and send full-reload messages that race with\n // client-side HMR updates. Provider-owned (non-runnable) environments\n // fall through instead: their plugin needs the real module list to\n // invalidate its remote runner, and its channel never reaches the\n // browser websocket.\n if (this.environment.name !== 'client' && isRunnableEnvironment(this.environment)) {\n // Returning [] also suppresses the signal environment-runner based\n // servers (e.g. nitro's dev worker) rely on to re-evaluate modules,\n // leaving SSR stale until a manual restart. Send the reload on this\n // environment's own channel — for runner-based environments that is\n // the runner, for the default ssr environment a no-op, and never the\n // browser websocket, so client HMR stays free of full-reload races.\n if (modules.length > 0) {\n this.environment.hot.send({ type: 'full-reload' });\n // Server-only modules are the exception to the suppression: a file\n // with no modules in the client graph has no browser HMR path at\n // all — nothing client-side accepts it, so staying silent leaves\n // the browser rendering stale server output until a manual refresh\n // (e.g. the document shell, which only the server ever imports;\n // solidjs/solid#3151). Reload the page: the honest cost, and there\n // is no client update to race with by construction.\n const clientEnv = devServer?.environments.client;\n if (clientEnv && !clientEnv.moduleGraph.getModulesByFile(file)?.size) {\n clientEnv.hot.send({ type: 'full-reload' });\n }\n }\n return [];\n }\n },\n\n resolveId(id) {\n if (id === VIRTUAL_MANIFEST_ID) return RESOLVED_VIRTUAL_MANIFEST_ID;\n },\n\n moduleParsed(info) {\n // SSR-mode client builds only: give every dynamically imported project\n // module its own facade chunk (exports-only preserves `default`\n // re-exports) so it keeps a manifest entry keyed by its source path\n // even when chunk grouping would otherwise absorb it. Plain SPA builds\n // have no manifest lookups to protect.\n if (!isBuild || !options.ssr || !isClientBuild(this)) return;\n for (const depId of info.dynamicallyImportedIds || []) {\n const cleanId = depId.split('?')[0];\n if (/node_modules/.test(cleanId) || cleanId.startsWith('\\0')) continue;\n if (!/\\.[mc]?[tj]sx?$/i.test(cleanId)) continue;\n if (emittedLazyChunks.has(depId)) continue;\n emittedLazyChunks.add(depId);\n emittedLazyChunkRefs.push(\n this.emitFile({ type: 'chunk', id: depId, preserveSignature: 'exports-only' }),\n );\n }\n },\n\n load(id) {\n if (id === RESOLVED_VIRTUAL_MANIFEST_ID) {\n if (!isBuild) {\n return devManifestCode(\n projectRoot,\n base,\n devServer ? devManifestBridgeUrl(devServer) : null,\n );\n }\n const manifestPath = clientManifestPath();\n if (manifestPath) {\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n normalizeEmittedLazyEntries(manifest);\n manifest._base = base;\n return `export default ${JSON.stringify(manifest)};`;\n }\n // SSR build before the client build produced a manifest: bake in the\n // dev-shaped fallback (registry miss degrades to js-only resolution).\n return devManifestCode(projectRoot, base, null);\n }\n },\n\n generateBundle(outputOptions, bundle) {\n if (!isBuild || !isClientBuild(this)) return;\n clientOutDir = outputOptions.dir ?? null;\n // Reclassify emitted lazy facade chunks in the raw bundle (not just the\n // serialized manifest read back later) so downstream plugins inspecting\n // the bundle don't mistake them for application entries. Must precede\n // the client asset map build, which keys off dynamic entries.\n if (options.ssr) {\n for (const ref of emittedLazyChunkRefs) {\n let fileName: string;\n try {\n fileName = this.getFileName(ref);\n } catch {\n // Ignore references retained from a previous watch build.\n continue;\n }\n const chunk = bundle[fileName];\n if (!chunk || chunk.type !== 'chunk') continue;\n chunk.isEntry = false;\n chunk.isDynamicEntry = true;\n }\n normalizeEmittedLazyEntries(bundle);\n }\n },\n\n async transform(source, id, transformOptions) {\n const isSsr = getEnvironmentConsumer(this.environment, transformOptions) === 'server';\n const currentFileExtension = getExtension(id);\n\n const extensionsToWatch = options.extensions || [];\n const allExtensions = extensionsToWatch.map((extension) =>\n // An extension can be a string or a tuple [extension, options]\n typeof extension === 'string' ? extension : extension[0],\n );\n\n if (!filter(id)) {\n return null;\n }\n\n // The queried id is the module's real identity (facade chunk /\n // manifest key / dev URL); keep it for the `$$moduleUrl` injection\n // while the transform pipeline below works on the clean file path.\n const moduleId = id;\n id = id.replace(/\\?.*$/, '');\n\n if (!(/\\.[mc]?[tj]sx$/i.test(id) || allExtensions.includes(currentFileExtension))) {\n return null;\n }\n\n const inNodeModules = /node_modules/.test(id);\n const solidOptions = getSolidOptions(options, !!isSsr, replaceDev, isTestMode);\n\n // We need to know if the current file extension has a typescript options tied to it\n const shouldBeProcessedWithTypescript =\n /\\.[mc]?tsx$/i.test(id) ||\n extensionsToWatch.some((extension) => {\n if (typeof extension === 'string') {\n return extension.includes('tsx');\n }\n\n const [extensionName, extensionOptions] = extension;\n if (extensionName !== currentFileExtension) return false;\n\n return extensionOptions.typescript;\n });\n const plugins: NonNullable<NonNullable<babel.TransformOptions['parserOpts']>['plugins']> = [\n 'jsx',\n 'decorators',\n ];\n\n if (shouldBeProcessedWithTypescript) {\n plugins.push('typescript');\n }\n\n // See the documentModuleId declaration: the document shell declines HMR\n // (no refresh boundary, explicit self-invalidation) so edits full-reload.\n const isDocumentShell = documentModuleId !== null && id === documentModuleId;\n const needRefresh = needHmr && !isSsr && !inNodeModules && !isDocumentShell;\n const declineHmr = isDocumentShell && needHmr && !isSsr;\n\n const babelUserOptions = await getBabelUserOptions(options, source, id, !!isSsr);\n\n // The native compiler picks its parser dialect from the file\n // extension; custom extensions registered through `options.extensions`\n // are unknown to it, so borrow a standard one matching the configured\n // TypeScript-ness.\n const nativeFilename = /\\.(?:[mc]?[jt]s|[jt]sx)$/i.test(id)\n ? id\n : id + (shouldBeProcessedWithTypescript ? '.tsx' : '.jsx');\n\n // Shared native prelude for every mode: the lazy() module-URL pass,\n // then (dev/client/non-node_modules) the solid-refresh HMR pass, both\n // operating on pre-JSX source. Only the JSX transform itself differs\n // between compiler backends. Sourcemaps are collected in application\n // order and merged at the end.\n const compiler = await loadNativeCompiler();\n let code = source;\n const maps: ChainableMap[] = [];\n\n const lazyResult = await compiler.transformLazyAsync(code, {\n filename: nativeFilename,\n sourceMap: true,\n });\n code = lazyResult.code;\n maps.push(lazyResult.map);\n\n if (needRefresh) {\n const refreshResult = await compiler.transformRefreshAsync(code, {\n filename: nativeFilename,\n bundler: 'vite',\n fixRender: true,\n // The napi validator rejects explicit undefined; omit to get the\n // pass's default (true).\n ...(typeof options.refresh?.granular === 'boolean'\n ? { granular: options.refresh.granular }\n : {}),\n jsx: false,\n importSource: REFRESH_RUNTIME_SOURCE,\n sourceMap: true,\n });\n code = refreshResult.code;\n maps.push(refreshResult.map);\n }\n\n const babelBaseOptions: babel.TransformOptions = {\n root: projectRoot,\n filename: id,\n sourceFileName: id,\n ast: false,\n sourceMaps: true,\n configFile: false,\n babelrc: false,\n parserOpts: {\n plugins,\n },\n };\n\n if (options.compiler !== 'babel') {\n if (options.babel) {\n // Custom babel options reintroduce a Babel support pass hosting\n // only the user's plugins, ahead of the native JSX transform.\n const supportOptions = mergeAndConcat(\n babelUserOptions,\n babelBaseOptions,\n ) as babel.TransformOptions;\n const supportResult = await babel.transformAsync(code, supportOptions);\n if (!supportResult) {\n return undefined;\n }\n code = supportResult.code || '';\n maps.push(supportResult.map);\n }\n\n const result = await compiler.transformAsync(code, {\n ...solidOptions,\n filename: nativeFilename,\n sourceMap: true,\n });\n maps.push(result.map);\n\n const finalCode = injectSsrModuleId(\n await resolveLazyModuleUrls(this, result.code || '', id),\n moduleId,\n !!isSsr,\n );\n\n return {\n code: declineHmr ? finalCode + DOCUMENT_HMR_DECLINE : finalCode,\n map: combineSourcemaps(maps),\n };\n }\n\n // Babel JSX backend: one babel.transformAsync hosting the user's\n // options plus @solidjs/babel-plugin. Appended to `plugins` (was the\n // sole preset pre-rename): user plugins still run before it, user\n // presets still run after — babel runs plugins before presets and\n // presets in reverse order, so the pass order is unchanged.\n const babelOptions = mergeAndConcat(babelUserOptions, {\n ...babelBaseOptions,\n plugins: [[solid, solidOptions]],\n }) as babel.TransformOptions;\n\n const result = await babel.transformAsync(code, babelOptions);\n if (!result) {\n return undefined;\n }\n maps.push(result.map);\n\n const finalCode = injectSsrModuleId(\n await resolveLazyModuleUrls(this, result.code || '', id),\n moduleId,\n !!isSsr,\n );\n\n return {\n code: declineHmr ? finalCode + DOCUMENT_HMR_DECLINE : finalCode,\n map: combineSourcemaps(maps),\n };\n },\n };\n\n // The directive transform must run before the JSX transform (it operates\n // on raw directives, and client-mode module-level extraction must happen\n // before templates are generated), so its sub-plugins go first. The\n // boundary markers (`server-only` / `client-only`) are always on.\n const plugins: Plugin[] = options.serverFunctions\n ? [\n boundaryModules(),\n ...serverFunctions(options.serverFunctions === true ? {} : options.serverFunctions, {\n devMiddleware: true,\n externalDevServer,\n // With start mode on (either variant), the dev middleware dispatches\n // the endpoint through the SSR handler so user middleware and the\n // stub-backed request event front it exactly like page SSR.\n ...(startOptions ? { ssrHandler: SSR_HANDLER_ID } : {}),\n }),\n mainPlugin,\n ]\n : [boundaryModules(), mainPlugin];\n\n // The `start` option opts into start-mode serving on top of the transforms;\n // the `ssr` boolean picks the mode (a bare `ssr: true` keeps the\n // historical transform-only behavior).\n if (startOptions) {\n plugins.push(\n // Typed env (`start.env`) rides both start modes: config-time\n // validation, the virtual:env/{server,client} modules, generated\n // types, and the client-bundle leak scan.\n ...startEnv(startOptions.env),\n ...startServe(startOptions, {\n serverFunctions: !!options.serverFunctions,\n serverComponents,\n ssr: !!options.ssr,\n styleFilter: filterDevStyles,\n diagnostics: !!options.diagnostics,\n onDocumentResolved(documentPath) {\n // Normalize to forward slashes to match Vite's transform ids.\n documentModuleId = documentPath ? documentPath.split(path.sep).join('/') : null;\n },\n }),\n );\n }\n\n // Agent diagnostics endpoint + injected bridge (dev serve only — the\n // plugin no-ops itself for builds and preview via `apply`).\n if (options.diagnostics) {\n plugins.push(solidDiagnostics());\n }\n\n // Builder-mode (environments API) client-before-server build ordering.\n // Server builds read the client manifest — `virtual:solid-manifest` bakes\n // dist/client/.vite/manifest.json in, and the persisted server-function\n // manifest merges the client build's discoveries — so the client\n // environment must build first. Start mode's own orchestration already\n // orders it that way (environment definition order), but a composed setup\n // whose orchestrator builds server environments first (e.g.\n // @cloudflare/vite-plugin's buildApp, which builds workers before client)\n // would bake a manifest-less fallback into the server bundle. Every user\n // of such a setup had to hand-write this ordering plugin; absorb it.\n //\n // Semantics:\n // - The first hook builds the client environment first, but only where\n // the ordering matters: a client build that emits a manifest and\n // actually has an input. It runs at *normal* order, deliberately not\n // `pre`: pre-order buildApp hooks are where hosts do destructive\n // preparation — nitro v3's `nitro:prepare` rm -rf's the whole output\n // directory from a pre-order hook, so a pre-order client build sorted\n // before it built into a directory that was then wiped (client assets\n // and manifest gone, the manifest-less fallback baked into the server\n // bundle, prod 500s). Normal order still runs before every known\n // server-first orchestrator: a config-level `builder.buildApp`\n // (@cloudflare/vite-plugin's workers-before-client orchestrator) is\n // invoked by Vite only after all pre- and normal-order plugin hooks\n // (just before the first post-order hook), and hook-based orchestrators\n // (nitro's `nitro:main`, cloudflare's own companion hook) declare\n // post order. Orchestrators running after skip the client via `isBuilt`\n // (or at worst rebuild it, which is wasteful but correct — the manifest\n // exists either way when the server environments build).\n // - Building anything from a hook suppresses Vite's own\n // build-all-environments fallback (it only runs when *no* environment\n // is built), so a setup with no real orchestrator — e.g. start mode's\n // plain `builder: {}` — would end up with only the client built. The\n // post-order hook reinstates exactly that fallback: when nothing but\n // our own client build has happened and no other plugin stakes a claim\n // on the app build, build the remaining environments in definition\n // order, precisely what Vite would have done. Another plugin declaring\n // a non-pre `buildApp` hook counts as such a claim even when it hasn't\n // built anything yet (its post-order hook may sort after ours):\n // building on its behalf would break staged orchestration (nitro\n // prerenders and copies public assets before its final server bundle)\n // and can error outright on environments the orchestrator knows to\n // skip (e.g. ones with no rollup input). Pre-order hooks don't count —\n // by convention they prepare (clean output dirs) rather than build.\n if (options.ssr) {\n let clientBuiltFirst = false;\n plugins.push(\n {\n name: 'solid:client-build-first',\n apply: 'build',\n async buildApp(builder) {\n const client = builder.environments.client;\n if (!client || client.isBuilt) return;\n const clientBuild = client.config.build;\n const hasInput =\n !!clientBuild.rollupOptions?.input ||\n existsSync(path.resolve(builder.config.root, 'index.html'));\n if (!clientBuild.manifest || !hasInput) return;\n await builder.build(client);\n clientBuiltFirst = true;\n },\n },\n {\n name: 'solid:client-build-first/complete',\n apply: 'build',\n buildApp: {\n order: 'post',\n async handler(builder) {\n if (!clientBuiltFirst) return;\n // Another plugin declares its own (non-pre) buildApp hook — the\n // app build is spoken for, even if that hook sorts after this\n // one and hasn't run yet.\n const otherOrchestrator = builder.config.plugins.some((p) => {\n if (!p.buildApp || p.name.startsWith('solid:client-build-first')) return false;\n return typeof p.buildApp !== 'object' || p.buildApp.order !== 'pre';\n });\n if (otherOrchestrator) return;\n const environments = Object.values(builder.environments);\n // A config-level orchestrator built something of its own — the\n // app build is spoken for, don't build environments it may have\n // skipped intentionally.\n if (environments.some((env) => env.isBuilt && env.name !== 'client')) return;\n for (const environment of environments) {\n if (!environment.isBuilt) await builder.build(environment);\n }\n },\n },\n },\n );\n }\n\n return plugins;\n}\n\nexport type ViteManifest = Record<\n string,\n {\n file: string;\n css?: string[];\n isEntry?: boolean;\n isDynamicEntry?: boolean;\n imports?: string[];\n }\n> & {\n _base?: string;\n};\n"],"names":["webRequestFromNode","req","urlPath","res","protocol","socket","encrypted","host","headers","url","URL","Headers","key","value","Object","entries","undefined","Array","isArray","item","append","signal","controller","AbortController","once","writableEnded","abort","method","h2Stream","stream","hasBody","endAfterHeaders","body","Readable","toWeb","Request","duplex","sendWebResponse","response","statusCode","status","cookies","getSetCookie","forEach","setHeader","length","cancel","catch","end","reader","getReader","on","done","read","destroyed","write","drained","Promise","resolve","settle","ok","off","onDrain","onGone","destroy","joinBase","base","pathname","startsWith","endsWith","slice","defaultStyleFilter","id","includes","DEV_MANIFEST_REGISTRY_KEY","registerDevAssetResolver","root","resolver","Symbol","for","registry","globalThis","DEV_MANIFEST_ENDPOINT","installDevManifestBridge","server","config","replace","basedEndpoint","middlewares","use","next","searchParams","get","console","error","assets","JSON","stringify","devManifestBridgeUrl","local","resolvedUrls","origin","middlewareMode","address","httpServer","https","port","cssFileRegExp","nonAmbientQueryRegExp","NULL_BYTE_PLACEHOLDER","wrapId","devStylePatch","getModuleNode","env","file","importer","resolved","fetchModule","moduleGraph","getModuleById","collectModuleDeps","deps","crawled","filter","onFile","add","node","has","isCss","test","split","transformResult","transformRequest","directDeps","dep","injectQuery","query","collectDevStyleSources","files","Set","css","seen","cleanUrl","push","collectDevStyles","ssrEnv","environments","ssr","clientEnv","client","sources","map","path","source","result","code","content","attrs","escapeAttr","renderDevStyleTag","desc","name","String","devModuleUrl","queryIndex","indexOf","absolute","sep","join","createDevAssetResolver","Map","pending","generation","watcher","clear","resolveDevAssets","cached","walk","startedAt","js","then","set","delete","resolveSync","isRunnableEnvironment","environment","getEnvironmentConsumer","options","consumer","VIRTUAL_ID","boundaryModules","enforce","resolveId","scan","load","DIAGNOSTICS_ENDPOINT","REQUEST_EVENT","RESPONSE_EVENT","DIAGNOSTICS_PACKAGE","DIAGNOSTICS_CLIENT_ID","METHODS","RESPONSE_TIMEOUT_MS","diagnosticsClientModuleCode","sendJson","readJsonBody","reject","chunks","chunk","text","Buffer","concat","toString","parse","Error","solidDiagnostics","process","cwd","apply","_config","command","isPreview","configResolved","moduleSideEffects","skipSelf","transformIndexHtml","tag","type","src","injectTo","configureServer","originalPrintUrls","printUrls","bind","endpoint","href","logger","info","nextId","ws","data","entry","clearTimeout","timer","methods","clients","size","message","setTimeout","timeout","send","params","compilerPromise","loadCompiler","reason","compile","transformDirectives","filename","mode","directive","sourceMap","register","definitions","create","valid","functions","PRIME32_1","PRIME32_2","PRIME32_3","PRIME32_4","PRIME32_5","toUtf8","bytes","i","n","c","charCodeAt","cp","Uint8Array","xxHash32","buffer","seed","b","acc","offset","accN","limit","lane","laneN0","laneN1","laneNP","acc0","acc1","laneP","DEFAULT_INCLUDE","DEFAULT_EXCLUDE","DEFAULT_MANIFEST","DEFAULT_DIRECTIVE","DEFAULT_RUNTIME","DEFAULT_ENDPOINT","STORAGE_SOURCE","HANDLER_ID","PERSISTED_MANIFEST_PATH","readPersistedManifest","existsSync","readFileSync","writePersistedManifest","outDir","mkdirSync","dirname","recursive","relative","writeFileSync","createManifest","createDeferredPromise","reference","rej","Debouncer","constructor","promise","defer","mergeManifestRecord","target","current","invalidPreload","invalidated","invalidateModule","invalidateModules","manifest","serverFunctions","internal","filterInclude","include","filterExclude","exclude","createFilter","manifestId","runtime","endpointOption","components","installDevMiddleware","devMiddleware","isBuild","isSsrBuild","resolvedEndpoint","configureModulePath","preload","currentServer","clientOptions","kind","serverOptions","endpointConfigureSnippet","handlerModuleCode","includeManifest","hashIndex","hashIndexSize","moduleForFunctionId","functionId","moduleDevUrl","startPlugins","_importer","opts","externalDev","externalDevServer","ssrEnvironment","underMount","mount","basePrefixed","dispatchUrl","segment","decodeURIComponent","runner","import","handler","ssrHandler","dispatchOptions","event","nativeEvent","handleRequest","handleServerFunctionRequest","build","configure","isAbsolute","writeBundle","ctx","isClient","transform","fileId","preloader","DEVTOOLS_PACKAGE","DEVTOOLS_MOUNT_ID","devtoolsMountModuleCode","SSR_HANDLER_ID","DEV_FALLTHROUGH_HEADER","STREAM_BOX","DEV_STYLES_ID","RESOLVED_DEV_STYLES_ID","ENTRY_SERVER_ID","ENTRY_CLIENT_ID","DOCUMENT_ID","ERROR_BOUNDARY_ID","MANIFEST_ID","SERVER_FUNCTION_HANDLER_ID","ENTRY_EXTENSIONS","APP_EXTENSIONS","DOCUMENT_EXTENSIONS","probe","stem","extensions","ext","normalizeUserPath","spec","option","resolveEntries","clientMode","explicitClient","entryClient","document","entryServer","generated","app","explicitServer","found","missing","startServe","serverComponents","errorBoundary","styleFilter","diagnostics","devtoolsEnabled","devtoolsResolutions","devtoolsIds","externalServer","external","middlewarePath","setupPath","requireEntries","resolveDevtools","realId","fileURLToPath","devtools","devtoolsReachableFrom","dir","parent","devtoolsIncludeSpec","rootDir","entryServerSpec","devClientEntryUrl","documentSpec","styleRoots","devStylesModuleCode","watchFile","styles","imports","style","index","specifier","_","errorBoundaryImport","documentTree","wrapper","generatedEntryServerCode","toolbar","streamOptions","setup","generatedEntryClientCode","diagnosticsImport","documentShellCode","errorBoundaryCode","composeServerFunctions","lines","devHead","headParts","userConfig","onDocumentResolved","middleware","appType","clientInput","scanEntries","rollupOptions","input","output","entryFileNames","builder","optimizeDeps","configEnvironment","noExternal","devtoolsId","addWatchFile","enabled","normalizePath","injected","configurePreviewServer","handlerPromise","pathToFileURL","accept","pageRequest","buildApp","order","isBuilt","serverDir","rmSync","force","CLIENT_ENV_ID","SERVER_ENV_ID","RESOLVED_CLIENT_ENV_ID","RESOLVED_SERVER_ENV_ID","ENV_FILE_CANDIDATES","GENERATED_TYPES_FILE","isStandardSchema","validate","FOLDED_KEYS","foldedKeys","holder","stringEntries","out","formatValidationError","issues","envFile","importSchemaModule","envFileAbs","module","dependencies","runnerImport","exported","default","assertSchemaShape","envPrefixes","schema","keys","side","shape","validator","typed","some","prefix","wanted","find","p","bare","generateTypes","dtsPath","importSpec","basename","field","moduleBlock","fields","clientFields","serverFields","warn","startEnv","envPromise","devErrorLogged","resolveEnvFile","candidate","envPrefix","loadAndValidate","envDir","folded","fileEnv","loadEnv","raw","all","issue","at","clientIssues","ensureEnv","isServerContext","serverOnlyError","envModuleCode","values","moduleType","serverEnvModuleCode","loaded","serverKeys","baked","envDirOption","buildStart","envFiles","watched","debounce","onFileEvent","failed","graph","mod","hot","generateBundle","_options","bundle","clientValues","secrets","leaks","fileName","moduleIds","every","escaped","RegExp","leak","require","createRequire","LAZY_PLACEHOLDER_PREFIX","REFRESH_RUNTIME_SOURCE","DOCUMENT_HMR_DECLINE","DEFAULT_STYLE_EXCLUDE","VIRTUAL_MANIFEST_ID","RESOLVED_VIRTUAL_MANIFEST_ID","devManifestCode","bridgeUrl","nativeCompilerPromise","loadNativeCompiler","getExtension","lastIndexOf","substring","containsSolidField","getJestDomExport","setupFiles","e","getSolidOptions","isSsr","dev","isTestMode","solidOptions","generate","hydratable","start","solid","getBabelUserOptions","babel","babelOptions","normalizeSourceMap","combineSourcemaps","maps","chain","remapping","reverse","normalizeEmittedLazyEntries","dynamicKeys","dynamicImports","isEntry","isDynamicEntry","solidPlugin","startOptions","styleFilterOptions","createStyleFilter","hasInclude","included","filterDevStyles","needHmr","replaceDev","documentModuleId","devServer","projectRoot","serverTestPosture","clientOutDir","solidPkgsConfig","clientManifestPath","manifestPath","emittedLazyChunks","emittedLazyChunkRefs","isClientBuild","resolveLazyModuleUrls","placeholderRe","match","resolutions","exec","relativeId","placeholder","injectSsrModuleId","mainPlugin","crawlFrameworkPkgs","viteUserConfig","isFrameworkPkgByJson","pkgJson","exports","nestedDeps","userTest","userSetupFiles","browser","inline","jestDomImport","dedupe","refresh","disabled","rolldownOptions","jsx","conditions","isSsrTargetWebworker","defaultClientConditions","defaultServerConditions","externalConditions","defaultExternalConditions","lastErrorTime","origSend","args","payload","Date","now","hotUpdate","modules","getModulesByFile","moduleParsed","depId","dynamicallyImportedIds","cleanId","emitFile","preserveSignature","_base","outputOptions","ref","getFileName","transformOptions","currentFileExtension","extensionsToWatch","allExtensions","extension","moduleId","inNodeModules","shouldBeProcessedWithTypescript","extensionName","extensionOptions","typescript","plugins","isDocumentShell","needRefresh","declineHmr","babelUserOptions","nativeFilename","compiler","lazyResult","transformLazyAsync","refreshResult","transformRefreshAsync","bundler","fixRender","granular","importSource","babelBaseOptions","sourceFileName","ast","sourceMaps","configFile","babelrc","parserOpts","supportOptions","mergeAndConcat","supportResult","transformAsync","finalCode","documentPath","clientBuiltFirst","clientBuild","hasInput","otherOrchestrator"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;;;AAIA;AACA;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ACO,QAAQ,CAACnP,MAAM,EAAE,IAAIuD,GAAG,CAAC,CAACnE,EAAE,CAAE,CAAC,CAAC,EACpDuQ,UACF,CAAC;QAED,OAAO;AACL;AACA;AACA;UACApL,IAAI,EAAE,CAACD,MAAM,CAACC,IAAI,IAAI,EAAE,IAAImM,wBAAwB,CAAC7F,IAAI,CAAC;UAC1D1G,GAAG,EAAEG,MAAM,CAACH;SACb;AACH,MAAA;AACA,MAAA,OAAO,IAAI;AACb,IAAA;GACD,EACD,GAAG+M,YAAY,CAChB;AACH;;AChtBO,MAAM8B,gBAAgB,GAAG,yBAAyB;AAClD,MAAMC,iBAAiB,GAAG,8BAA8B;AAExD,SAASC,uBAAuBA,GAAW;EAChD,OAAO,CACL,CAAA,iCAAA,EAAoCF,gBAAgB,CAAA,EAAA,CAAI,EACxD,CAAA,kBAAA,CAAoB,CACrB,CAAC5N,IAAI,CAAC,IAAI,CAAC;AACd;;ACRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AA4BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAgMA;AACA;AACA;AACA;AACA;AACO,MAAM+N,cAAc,GAAG,2BAA2B;AACzD,MAAM3F,UAAU,GAAG2F,cAAc;AACjC;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,sBAAsB,GAAG,yBAAyB;AACxD;AACA;AACA;AACA;AACA,MAAMC,UAAU,GAAG,oBAAoB;AACvC,MAAMC,aAAa,GAAG,8BAA8B;AACpD,MAAMC,sBAAsB,GAAG,IAAI,GAAGD,aAAa;AACnD;AACA;AACA;AACA,MAAME,eAAe,GAAG,oCAAoC;AAC5D,MAAMC,eAAe,GAAG,oCAAoC;AAC5D,MAAMC,WAAW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