@torpor/build 1.8.5 → 1.8.6

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.
@@ -1,5 +1,6 @@
1
1
  import { t as PathTrie } from "./pathTrie-D4Ax2Mu9.mjs";
2
2
  import { t as ServerEvent } from "./ServerEvent-BY4f3RVF.mjs";
3
+ import { t as runHooks } from "./runHooks-D5p1Rh7i.mjs";
3
4
  //#region src/server/Server.ts
4
5
  /**
5
6
  * A Fetch API Request/Response server.
@@ -23,32 +24,13 @@ var Server = class {
23
24
  const match = this.match(url.pathname);
24
25
  let ev = new ServerEvent(request, match?.params, url);
25
26
  if (this.middleware.length) {
26
- let entered = 0;
27
- let response = void 0;
28
- let error = void 0;
29
- try {
30
- for (; entered < this.middleware.length && !response; entered++) {
31
- const result = await this.middleware[entered].enter?.(ev);
32
- if (result) response = result;
33
- }
34
- if (!response && match) {
35
- const result = await match.fn(ev);
36
- if (result) response = result;
37
- }
38
- } catch (e) {
39
- error = e;
40
- ev.error = e;
41
- } finally {
42
- if (response) ev.response = response;
43
- while (entered > 0) {
44
- entered--;
45
- const result = await this.middleware[entered].exit?.(ev);
46
- if (result) {
47
- response = result;
48
- ev.response = result;
49
- }
50
- }
51
- }
27
+ const { response, error } = await runHooks([{
28
+ hooks: this.middleware,
29
+ arg: ev
30
+ }], async () => {
31
+ if (!match) return void 0;
32
+ return await match.fn(ev) || void 0;
33
+ }, { event: ev });
52
34
  if (error && !response) throw error;
53
35
  } else if (match) ev.response = await match.fn(ev);
54
36
  else return new Response(null, { status: 404 });
@@ -101,4 +83,4 @@ var RouteHandler = class {
101
83
  //#endregion
102
84
  export { Server as t };
103
85
 
104
- //# sourceMappingURL=Server-C0PGzSQO.mjs.map
86
+ //# sourceMappingURL=Server-dcRbdPXf.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Server-dcRbdPXf.mjs","names":[],"sources":["../src/server/Server.ts"],"sourcesContent":["import PathTrie from \"../utils/pathTrie\";\nimport ServerEvent from \"./ServerEvent\";\nimport runHooks from \"./runHooks\";\nimport type MiddlewareFunction from \"./types/MiddlewareFunction\";\nimport type ServerFunction from \"./types/ServerFunction\";\n\n/**\n * A Fetch API Request/Response server.\n */\nexport default class Server {\n\t// TODO: We don't use any of the routes, just add(\"*\") in runDev/runBuild...\n\troutes: RouteHandler[] = [];\n\t// Match index for the routes above\n\t#trie = new PathTrie<RouteHandler>();\n\t// TODO: We only use the Vite middleware here\n\tmiddleware: MiddlewareFunction[] = [];\n\n\tconstructor() {\n\t\tthis.routes = [];\n\t\tthis.middleware = [];\n\t}\n\n\t/**\n\t * The standard Fetch API method that should work in any runtime (including\n\t * Node with polyfills).\n\t * @returns\n\t */\n\tfetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n\t\t// Use the request as-is when we were given one, so that the adapter\n\t\t// doesn't pay for constructing it twice\n\t\tconst request = input instanceof Request && !init ? input : new Request(input, init);\n\t\tconst url = new URL(request.url);\n\t\tconst match = this.match(url.pathname);\n\t\tlet ev = new ServerEvent(request, match?.params, url);\n\n\t\tif (this.middleware.length) {\n\t\t\t// Route-scoped middleware is set on server endpoints (or globally on\n\t\t\t// `site.middleware`); this list is the low-level, per-Server primitive\n\t\t\tconst { response, error } = await runHooks(\n\t\t\t\t[{ hooks: this.middleware, arg: ev }],\n\t\t\t\tasync (): Promise<Response | undefined> => {\n\t\t\t\t\tif (!match) return undefined;\n\t\t\t\t\treturn (await match.fn(ev)) || undefined;\n\t\t\t\t},\n\t\t\t\t{ event: ev },\n\t\t\t);\n\t\t\tif (error && !response) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t} else if (match) {\n\t\t\tev.response = await match.fn(ev);\n\t\t} else {\n\t\t\treturn new Response(null, { status: 404 });\n\t\t}\n\n\t\t// TODO: Should I be returning 200 if there's no response? Because it's not an error??\n\t\tev.response ??= new Response(null, { status: 200 });\n\t\tev.addHeaders();\n\n\t\treturn ev.response;\n\t};\n\n\t/**\n\t * Adds a server function at a route path.\n\t * @param path The route path pattern.\n\t * @param fn The function to call when the pattern is matched.\n\t * @returns\n\t */\n\tadd(path: string, fn: ServerFunction): Server {\n\t\tlet handler = new RouteHandler(path, fn);\n\t\tthis.routes.push(handler);\n\t\tthis.#trie.insert(path, handler);\n\t\tthis.#sortRoutes();\n\t\treturn this;\n\t}\n\n\tmatch(path: string): Match | undefined {\n\t\tconst found = this.#trie.match(path);\n\t\tif (found) {\n\t\t\treturn {\n\t\t\t\tfn: found.value.fn,\n\t\t\t\tparams: found.params,\n\t\t\t};\n\t\t}\n\t\tconsole.log(`Server path not found: ${path}`);\n\t}\n\n\t// TODO:\n\t//use(path: string, ...fn: MiddlewareFunction[])\n\tuse(...fn: MiddlewareFunction[]): Server {\n\t\tthis.middleware = this.middleware.concat(fn);\n\t\treturn this;\n\t}\n\n\t#sortRoutes() {\n\t\tthis.routes = this.routes.sort((a, b) => {\n\t\t\t// Sort [param]s after paths\n\t\t\t// There might be a quicker/easier way to do this\n\t\t\tfor (let i = 0; i < Math.min(a.path.length, b.path.length); i++) {\n\t\t\t\tif (a.path[i] === \"[\" && b.path[i] !== \"[\") {\n\t\t\t\t\treturn 1;\n\t\t\t\t} else if (b.path[i] === \"[\" && a.path[i] !== \"[\") {\n\t\t\t\t\treturn -1;\n\t\t\t\t} else if (a.path[i] === b.path[i]) {\n\t\t\t\t\t// Keep going...\n\t\t\t\t} else {\n\t\t\t\t\treturn a.path[i].localeCompare(b.path[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn a.path.length - b.path.length;\n\t\t});\n\t}\n}\n\nclass RouteHandler {\n\tpath: string;\n\tfn: ServerFunction;\n\n\tconstructor(path: string, fn: ServerFunction) {\n\t\tthis.path = path;\n\t\tthis.fn = fn;\n\t}\n}\n\n//class MiddlewareHandler {\n//\tpath: string;\n//\tregex: RegExp;\n//\tfn: MiddlewareFunction;\n//\n//\tconstructor(path: string, fn: MiddlewareFunction) {\n//\t\tthis.path = path;\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B;EACT,IAAI;EACJ,SAAS"}
1
+ {"version":3,"file":"Server-qn5Ws_d0.d.mts","names":[],"sources":["../src/server/types/ServerFunction.ts","../src/server/Server.ts"],"mappings":";;KAEK,kBACJ,GAAG,gBACC,8BAA8B,QAAQ;;;;;;cCKtB;;EAEpB,QAAQ;EAIR,YAAY;EAEZ;;;;;;EAUA,QAAe,OAAO,cAAc,KAAK,OAAO,gBAAc,QAAQ;;;;;;;EAyCtE,IAAI,cAAc,IAAI,iBAAiB;EAQvC,MAAM,eAAe;EAarB,OAAO,IAAI,uBAAuB;;cAyB7B;EACL;EACA,IAAI;EAEJ,YAAY,cAAc,IAAI;;UAkBrB;EACT,IAAI;EACJ,SAAS"}
package/dist/bin/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #! /usr/bin/env node
2
- import { a as loadSite, n as run, t as runOpenApi } from "../runOpenApi-AEDhan_-.mjs";
2
+ import { a as loadSite, n as run, t as runOpenApi } from "../runOpenApi-C5yMpQU1.mjs";
3
3
  //#region src/bin/index.ts
4
4
  const workingDir = process.cwd();
5
5
  if (process.argv.includes("--openapi")) {
package/dist/dev.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import { t as Server } from "./Server-C0PGzSQO.mjs";
2
- import { t as load } from "./serverEntry-DdNjmynd.mjs";
1
+ import { t as Server } from "./Server-dcRbdPXf.mjs";
2
+ import { t as load } from "./serverEntry-D1hE-Jzt.mjs";
3
3
  export { Server, load };
@@ -1,5 +1,5 @@
1
1
  import { r as serverError } from "./response-C5EZsszY.mjs";
2
- import { t as Server } from "./Server-C0PGzSQO.mjs";
2
+ import { t as Server } from "./Server-dcRbdPXf.mjs";
3
3
  import { t as flattenHeaders } from "./flattenHeaders-DM5qsSqO.mjs";
4
4
  import { existsSync, promises, realpathSync } from "node:fs";
5
5
  import fpath from "node:path";
@@ -141,4 +141,4 @@ async function sendResponse(response, res) {
141
141
  //#endregion
142
142
  export { siteEntryPaths as i, prepareTemplate as n, detectSourceMode as r, devPlugin as t };
143
143
 
144
- //# sourceMappingURL=devPlugin-CL0eu77n.mjs.map
144
+ //# sourceMappingURL=devPlugin-lLzauETn.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"devPlugin-CL0eu77n.mjs","names":["path","path","fs"],"sources":["../src/utils/entryPaths.ts","../src/run/prepareTemplate.ts","../src/run/devPlugin.ts"],"sourcesContent":["import { realpathSync } from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * Paths to the site entry files that `tb` loads from the installed\n * `@torpor/build` package, in either source (linked framework) or dist\n * (registry install) mode.\n */\nexport type SiteEntryPaths = {\n\tserverEntry: string;\n\tclientEntry: string;\n\tclientDevEntry: string;\n};\n\n/**\n * Whether tb should run the framework from its TypeScript source instead of\n * its compiled dist. This is a framework-development convenience: registry\n * installs always run dist. Source mode is enabled explicitly via the\n * TORPOR_SOURCE_DEV env var, or automatically when both `@torpor/build` and\n * `@torpor/view` are symlinked into the app from outside node_modules (as\n * workspace links and `link:` overrides do). Both packages must be linked,\n * because source mode resolves their `torpor:source` export conditions, which\n * point at src files that registry installs don't ship.\n */\nexport function detectSourceMode(siteRoot: string): boolean {\n\tif (process.env.TORPOR_SOURCE_DEV) return true;\n\tconst packages = [\"@torpor/build\", \"@torpor/view\"];\n\treturn packages.every((pkg) => {\n\t\ttry {\n\t\t\tconst dist = path.resolve(siteRoot, \"node_modules\", pkg, \"dist/index.mjs\");\n\t\t\tconst real = realpathSync(dist);\n\t\t\treturn !real.includes(\"node_modules\");\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t});\n}\n\n/**\n * The site entry files for the given mode: raw TypeScript sources when the\n * framework is linked (Vite transforms them, and edits show up without a\n * rebuild), compiled `.mjs` bundles for registry installs.\n */\nexport function siteEntryPaths(siteRoot: string, sourceMode: boolean): SiteEntryPaths {\n\tconst folder = path.resolve(\n\t\tsiteRoot,\n\t\t\"node_modules/@torpor/build\",\n\t\tsourceMode ? \"src/site\" : \"dist\",\n\t);\n\tconst ext = sourceMode ? \".ts\" : \".mjs\";\n\treturn {\n\t\tserverEntry: path.join(folder, `serverEntry${ext}`),\n\t\tclientEntry: path.join(folder, `clientEntry${ext}`),\n\t\tclientDevEntry: path.join(folder, `clientEntryDev${ext}`),\n\t};\n}\n\n/**\n * The torpor `Server` class module that a Cloudflare `_worker.ts` imports,\n * for the given mode.\n */\nexport function serverClassPath(siteRoot: string, sourceMode: boolean): string {\n\treturn path.resolve(\n\t\tsiteRoot,\n\t\t\"node_modules/@torpor/build\",\n\t\tsourceMode ? \"src/server/Server.ts\" : \"dist/server/Server.mjs\",\n\t);\n}\n","export default function prepareTemplate(\n\ttemplate: string,\n\tclientScript: string,\n\tclientDevScript?: string,\n): string {\n\tlet result = template;\n\n\t// Put %COMPONENT_HEAD% before </head>\n\t// This is where styles will go\n\tlet headStart = result.indexOf(\"</head>\");\n\tif (headStart === -1) {\n\t\tthrow new Error(`Couldn't find <head> end tag`);\n\t}\n\tresult = result.substring(0, headStart) + \"%COMPONENT_HEAD%\" + result.substring(headStart);\n\n\t// Put %COMPONENT_BODY% inside <div id=\"app\"></div>\n\t// This is where the component's HTML will go\n\tlet divMatchStart = regexIndexOf(result, /<div\\s+id=(\"app\"|'app'|app)[\\s>]/);\n\tif (divMatchStart === -1) {\n\t\tthrow new Error(`Couldn't find <div id=\"app\"></div>`);\n\t}\n\tlet bodyStart = result.indexOf(\">\", divMatchStart) + 1;\n\tlet bodyEnd = result.indexOf(\"</div>\", bodyStart);\n\tif (bodyEnd === -1) {\n\t\tthrow new Error(`Couldn't find <div id=\"app\"></div>`);\n\t}\n\tresult = result.substring(0, bodyStart) + \"%COMPONENT_BODY%\" + result.substring(bodyEnd);\n\n\t// Add the clientEntry script at the very end, for hydrating and navigating\n\tif (clientDevScript) {\n\t\tresult += `<script type=\"module\" src=\"${clientDevScript}\"></script>`;\n\t}\n\tresult += `<script type=\"module\" src=\"${clientScript}\"></script>`;\n\n\treturn result;\n}\n\n// From https://stackoverflow.com/a/274094\nfunction regexIndexOf(string: string, regex: RegExp, position?: number) {\n\tvar indexOf = string.substring(position || 0).search(regex);\n\treturn indexOf >= 0 ? indexOf + (position || 0) : indexOf;\n}\n","import { type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { existsSync, promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport { type Plugin, type ViteDevServer } from \"vite\";\nimport { serverError } from \"../response.ts\";\nimport Server from \"../server/Server.ts\";\nimport flattenHeaders from \"../server/connect/flattenHeaders.ts\";\nimport type Site from \"../site/Site.ts\";\nimport { siteEntryPaths } from \"../utils/entryPaths\";\nimport prepareTemplate from \"./prepareTemplate.ts\";\n\ntype ReqHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>;\n\n/**\n * The default Node-runtime dev plugin. Reads `src/site.html`, sets up a torpor\n * `Server` whose catch-all route renders via `vite.ssrLoadModule`, and registers\n * a Connect middleware (after Vite's own middlewares) that bridges Node\n * req/res to the torpor Server's fetch handler.\n *\n * Adapters that need a different runtime (e.g. workerd) provide their own\n * `dev()` plugin instead.\n */\nexport default function devPlugin(site: Site, sourceMode = false): Plugin {\n\treturn {\n\t\tname: \"torpor-dev\",\n\t\tconfigureServer(vite) {\n\t\t\t// Kick off async setup immediately; the middleware awaits it so we\n\t\t\t// don't depend on whether Vite awaits configureServer itself.\n\t\t\tconst handlerPromise = createDevHandler(vite, site, sourceMode);\n\t\t\t// Return a post-hook so our middleware runs AFTER Vite's internal\n\t\t\t// middlewares (static serving, transforms, HMR), acting as the SSR\n\t\t\t// fallback.\n\t\t\treturn () => {\n\t\t\t\tvite.middlewares.use(async (req, res, next) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst handler = await handlerPromise;\n\t\t\t\t\t\tawait handler(req, res);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tnext(e as Error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t};\n\t\t},\n\t};\n}\n\nasync function createDevHandler(\n\tvite: ViteDevServer,\n\tsite: Site,\n\tsourceMode: boolean,\n): Promise<ReqHandler> {\n\tconst entries = siteEntryPaths(site.root, sourceMode);\n\tconst serverScript = entries.serverEntry;\n\n\t// Read site.html if present\n\t// It's called site.html because @torpor/build builds the site (html, routes\n\t// etc) while the user builds the app (components etc). An endpoints-only\n\t// site has no site.html, and no template is needed\n\tlet template: string | undefined;\n\tconst templateFile = path.resolve(site.root, \"src/site.html\");\n\tif (existsSync(templateFile)) {\n\t\ttemplate = await fs.readFile(templateFile, \"utf-8\");\n\n\t\t// Apply Vite HTML transforms. This injects the Vite HMR client, and also\n\t\t// applies HTML transforms from Vite plugins. Note that we only support a\n\t\t// universal transform, not individual transforms for each route\n\t\ttemplate = await vite.transformIndexHtml(\"\", template);\n\n\t\t// Prepare site.html so that we can just splice components into it\n\t\ttemplate = prepareTemplate(template, entries.clientEntry, entries.clientDevEntry);\n\t}\n\n\tconst server = new Server();\n\n\t// Every request (GET, POST, etc) goes through loadEndPoint\n\tserver.add(\"*\", async (ev) => {\n\t\ttry {\n\t\t\t// Load the server entry. ssrLoadModule automatically transforms ESM\n\t\t\t// source code to be usable in Node.js. No bundling is required, and\n\t\t\t// it provides efficient invalidation similar to HMR\n\t\t\tconst { load } = await vite.ssrLoadModule(serverScript);\n\n\t\t\t// Render the app HTML (or fetch server data etc) via serverEntry's\n\t\t\t// exported `load` function\n\t\t\treturn await load(ev, template);\n\t\t} catch (e: any) {\n\t\t\t// If an error is caught, let Vite fix the stack trace so it maps\n\t\t\t// back to your actual source code\n\t\t\tvite.ssrFixStacktrace(e);\n\t\t\treturn serverError(e);\n\t\t}\n\t});\n\n\t// Put adapter-specific functionality in the `adapter` property of\n\t// globalThis for now\n\t// @ts-ignore\n\tglobalThis.adapter = { env: process.env };\n\n\treturn async (req, res) => {\n\t\tconst request = await nodeReqToRequest(req);\n\t\tconst response = await server.fetch(request);\n\t\tawait sendResponse(response, res);\n\t};\n}\n\nasync function nodeReqToRequest(req: IncomingMessage): Promise<Request> {\n\tconst url = req.url ?? \"/\";\n\tconst host = req.headers.host ?? \"localhost\";\n\tconst protocol = \"encrypted\" in req.socket && req.socket.encrypted ? \"https\" : \"http\";\n\tconst init: RequestInit = {\n\t\tmethod: req.method,\n\t\theaders: flattenHeaders(req.headers),\n\t};\n\tif (req.method !== \"GET\" && req.method !== \"HEAD\") {\n\t\tinit.body = Readable.toWeb(req) as ReadableStream;\n\t\t// @ts-ignore duplex is required when streaming a body\n\t\tinit.duplex = \"half\";\n\t}\n\treturn new Request(`${protocol}://${host}${url}`, init);\n}\n\nasync function sendResponse(response: Response, res: ServerResponse): Promise<void> {\n\tres.statusCode = response.status;\n\tresponse.headers.forEach((value, key) => res.setHeader(key, value));\n\tif (!response.body) {\n\t\tres.end();\n\t\treturn;\n\t}\n\tReadable.fromWeb(response.body as unknown as import(\"node:stream/web\").ReadableStream).pipe(res);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwBA,SAAgB,iBAAiB,UAA2B;CAC3D,IAAI,QAAQ,IAAI,mBAAmB,OAAO;CAE1C,OAAO,CADW,iBAAiB,cACrB,CAAC,CAAC,OAAO,QAAQ;EAC9B,IAAI;GACH,MAAM,OAAOA,MAAK,QAAQ,UAAU,gBAAgB,KAAK,gBAAgB;GAEzE,OAAO,CADM,aAAa,IACf,CAAC,CAAC,SAAS,cAAc;EACrC,QAAQ;GACP,OAAO;EACR;CACD,CAAC;AACF;;;;;;AAOA,SAAgB,eAAe,UAAkB,YAAqC;CACrF,MAAM,SAASA,MAAK,QACnB,UACA,8BACA,aAAa,aAAa,MAC3B;CACA,MAAM,MAAM,aAAa,QAAQ;CACjC,OAAO;EACN,aAAaA,MAAK,KAAK,QAAQ,cAAc,KAAK;EAClD,aAAaA,MAAK,KAAK,QAAQ,cAAc,KAAK;EAClD,gBAAgBA,MAAK,KAAK,QAAQ,iBAAiB,KAAK;CACzD;AACD;;;ACvDA,SAAwB,gBACvB,UACA,cACA,iBACS;CACT,IAAI,SAAS;CAIb,IAAI,YAAY,OA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"devPlugin-lLzauETn.mjs","names":["path","path","fs"],"sources":["../src/utils/entryPaths.ts","../src/run/prepareTemplate.ts","../src/run/devPlugin.ts"],"sourcesContent":["import { realpathSync } from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * Paths to the site entry files that `tb` loads from the installed\n * `@torpor/build` package, in either source (linked framework) or dist\n * (registry install) mode.\n */\nexport type SiteEntryPaths = {\n\tserverEntry: string;\n\tclientEntry: string;\n\tclientDevEntry: string;\n};\n\n/**\n * Whether tb should run the framework from its TypeScript source instead of\n * its compiled dist. This is a framework-development convenience: registry\n * installs always run dist. Source mode is enabled explicitly via the\n * TORPOR_SOURCE_DEV env var, or automatically when both `@torpor/build` and\n * `@torpor/view` are symlinked into the app from outside node_modules (as\n * workspace links and `link:` overrides do). Both packages must be linked,\n * because source mode resolves their `torpor:source` export conditions, which\n * point at src files that registry installs don't ship.\n */\nexport function detectSourceMode(siteRoot: string): boolean {\n\tif (process.env.TORPOR_SOURCE_DEV) return true;\n\tconst packages = [\"@torpor/build\", \"@torpor/view\"];\n\treturn packages.every((pkg) => {\n\t\ttry {\n\t\t\tconst dist = path.resolve(siteRoot, \"node_modules\", pkg, \"dist/index.mjs\");\n\t\t\tconst real = realpathSync(dist);\n\t\t\treturn !real.includes(\"node_modules\");\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t});\n}\n\n/**\n * The site entry files for the given mode: raw TypeScript sources when the\n * framework is linked (Vite transforms them, and edits show up without a\n * rebuild), compiled `.mjs` bundles for registry installs.\n */\nexport function siteEntryPaths(siteRoot: string, sourceMode: boolean): SiteEntryPaths {\n\tconst folder = path.resolve(\n\t\tsiteRoot,\n\t\t\"node_modules/@torpor/build\",\n\t\tsourceMode ? \"src/site\" : \"dist\",\n\t);\n\tconst ext = sourceMode ? \".ts\" : \".mjs\";\n\treturn {\n\t\tserverEntry: path.join(folder, `serverEntry${ext}`),\n\t\tclientEntry: path.join(folder, `clientEntry${ext}`),\n\t\tclientDevEntry: path.join(folder, `clientEntryDev${ext}`),\n\t};\n}\n\n/**\n * The torpor `Server` class module that a Cloudflare `_worker.ts` imports,\n * for the given mode.\n */\nexport function serverClassPath(siteRoot: string, sourceMode: boolean): string {\n\treturn path.resolve(\n\t\tsiteRoot,\n\t\t\"node_modules/@torpor/build\",\n\t\tsourceMode ? \"src/server/Server.ts\" : \"dist/server/Server.mjs\",\n\t);\n}\n","export default function prepareTemplate(\n\ttemplate: string,\n\tclientScript: string,\n\tclientDevScript?: string,\n): string {\n\tlet result = template;\n\n\t// Put %COMPONENT_HEAD% before </head>\n\t// This is where styles will go\n\tlet headStart = result.indexOf(\"</head>\");\n\tif (headStart === -1) {\n\t\tthrow new Error(`Couldn't find <head> end tag`);\n\t}\n\tresult = result.substring(0, headStart) + \"%COMPONENT_HEAD%\" + result.substring(headStart);\n\n\t// Put %COMPONENT_BODY% inside <div id=\"app\"></div>\n\t// This is where the component's HTML will go\n\tlet divMatchStart = regexIndexOf(result, /<div\\s+id=(\"app\"|'app'|app)[\\s>]/);\n\tif (divMatchStart === -1) {\n\t\tthrow new Error(`Couldn't find <div id=\"app\"></div>`);\n\t}\n\tlet bodyStart = result.indexOf(\">\", divMatchStart) + 1;\n\tlet bodyEnd = result.indexOf(\"</div>\", bodyStart);\n\tif (bodyEnd === -1) {\n\t\tthrow new Error(`Couldn't find <div id=\"app\"></div>`);\n\t}\n\tresult = result.substring(0, bodyStart) + \"%COMPONENT_BODY%\" + result.substring(bodyEnd);\n\n\t// Add the clientEntry script at the very end, for hydrating and navigating\n\tif (clientDevScript) {\n\t\tresult += `<script type=\"module\" src=\"${clientDevScript}\"></script>`;\n\t}\n\tresult += `<script type=\"module\" src=\"${clientScript}\"></script>`;\n\n\treturn result;\n}\n\n// From https://stackoverflow.com/a/274094\nfunction regexIndexOf(string: string, regex: RegExp, position?: number) {\n\tvar indexOf = string.substring(position || 0).search(regex);\n\treturn indexOf >= 0 ? indexOf + (position || 0) : indexOf;\n}\n","import { type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { existsSync, promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport { type Plugin, type ViteDevServer } from \"vite\";\nimport { serverError } from \"../response.ts\";\nimport Server from \"../server/Server.ts\";\nimport flattenHeaders from \"../server/connect/flattenHeaders.ts\";\nimport type Site from \"../site/Site.ts\";\nimport { siteEntryPaths } from \"../utils/entryPaths\";\nimport prepareTemplate from \"./prepareTemplate.ts\";\n\ntype ReqHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>;\n\n/**\n * The default Node-runtime dev plugin. Reads `src/site.html`, sets up a torpor\n * `Server` whose catch-all route renders via `vite.ssrLoadModule`, and registers\n * a Connect middleware (after Vite's own middlewares) that bridges Node\n * req/res to the torpor Server's fetch handler.\n *\n * Adapters that need a different runtime (e.g. workerd) provide their own\n * `dev()` plugin instead.\n */\nexport default function devPlugin(site: Site, sourceMode = false): Plugin {\n\treturn {\n\t\tname: \"torpor-dev\",\n\t\tconfigureServer(vite) {\n\t\t\t// Kick off async setup immediately; the middleware awaits it so we\n\t\t\t// don't depend on whether Vite awaits configureServer itself.\n\t\t\tconst handlerPromise = createDevHandler(vite, site, sourceMode);\n\t\t\t// Return a post-hook so our middleware runs AFTER Vite's internal\n\t\t\t// middlewares (static serving, transforms, HMR), acting as the SSR\n\t\t\t// fallback.\n\t\t\treturn () => {\n\t\t\t\tvite.middlewares.use(async (req, res, next) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst handler = await handlerPromise;\n\t\t\t\t\t\tawait handler(req, res);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tnext(e as Error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t};\n\t\t},\n\t};\n}\n\nasync function createDevHandler(\n\tvite: ViteDevServer,\n\tsite: Site,\n\tsourceMode: boolean,\n): Promise<ReqHandler> {\n\tconst entries = siteEntryPaths(site.root, sourceMode);\n\tconst serverScript = entries.serverEntry;\n\n\t// Read site.html if present\n\t// It's called site.html because @torpor/build builds the site (html, routes\n\t// etc) while the user builds the app (components etc). An endpoints-only\n\t// site has no site.html, and no template is needed\n\tlet template: string | undefined;\n\tconst templateFile = path.resolve(site.root, \"src/site.html\");\n\tif (existsSync(templateFile)) {\n\t\ttemplate = await fs.readFile(templateFile, \"utf-8\");\n\n\t\t// Apply Vite HTML transforms. This injects the Vite HMR client, and also\n\t\t// applies HTML transforms from Vite plugins. Note that we only support a\n\t\t// universal transform, not individual transforms for each route\n\t\ttemplate = await vite.transformIndexHtml(\"\", template);\n\n\t\t// Prepare site.html so that we can just splice components into it\n\t\ttemplate = prepareTemplate(template, entries.clientEntry, entries.clientDevEntry);\n\t}\n\n\tconst server = new Server();\n\n\t// Every request (GET, POST, etc) goes through loadEndPoint\n\tserver.add(\"*\", async (ev) => {\n\t\ttry {\n\t\t\t// Load the server entry. ssrLoadModule automatically transforms ESM\n\t\t\t// source code to be usable in Node.js. No bundling is required, and\n\t\t\t// it provides efficient invalidation similar to HMR\n\t\t\tconst { load } = await vite.ssrLoadModule(serverScript);\n\n\t\t\t// Render the app HTML (or fetch server data etc) via serverEntry's\n\t\t\t// exported `load` function\n\t\t\treturn await load(ev, template);\n\t\t} catch (e: any) {\n\t\t\t// If an error is caught, let Vite fix the stack trace so it maps\n\t\t\t// back to your actual source code\n\t\t\tvite.ssrFixStacktrace(e);\n\t\t\treturn serverError(e);\n\t\t}\n\t});\n\n\t// Put adapter-specific functionality in the `adapter` property of\n\t// globalThis for now\n\t// @ts-ignore\n\tglobalThis.adapter = { env: process.env };\n\n\treturn async (req, res) => {\n\t\tconst request = await nodeReqToRequest(req);\n\t\tconst response = await server.fetch(request);\n\t\tawait sendResponse(response, res);\n\t};\n}\n\nasync function nodeReqToRequest(req: IncomingMessage): Promise<Request> {\n\tconst url = req.url ?? \"/\";\n\tconst host = req.headers.host ?? \"localhost\";\n\tconst protocol = \"encrypted\" in req.socket && req.socket.encrypted ? \"https\" : \"http\";\n\tconst init: RequestInit = {\n\t\tmethod: req.method,\n\t\theaders: flattenHeaders(req.headers),\n\t};\n\tif (req.method !== \"GET\" && req.method !== \"HEAD\") {\n\t\tinit.body = Readable.toWeb(req) as ReadableStream;\n\t\t// @ts-ignore duplex is required when streaming a body\n\t\tinit.duplex = \"half\";\n\t}\n\treturn new Request(`${protocol}://${host}${url}`, init);\n}\n\nasync function sendResponse(response: Response, res: ServerResponse): Promise<void> {\n\tres.statusCode = response.status;\n\tresponse.headers.forEach((value, key) => res.setHeader(key, value));\n\tif (!response.body) {\n\t\tres.end();\n\t\treturn;\n\t}\n\tReadable.fromWeb(response.body as unknown as import(\"node:stream/web\").ReadableStream).pipe(res);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwBA,SAAgB,iBAAiB,UAA2B;CAC3D,IAAI,QAAQ,IAAI,mBAAmB,OAAO;CAE1C,OAAO,CADW,iBAAiB,cACrB,CAAC,CAAC,OAAO,QAAQ;EAC9B,IAAI;GACH,MAAM,OAAOA,MAAK,QAAQ,UAAU,gBAAgB,KAAK,gBAAgB;GAEzE,OAAO,CADM,aAAa,IACf,CAAC,CAAC,SAAS,cAAc;EACrC,QAAQ;GACP,OAAO;EACR;CACD,CAAC;AACF;;;;;;AAOA,SAAgB,eAAe,UAAkB,YAAqC;CACrF,MAAM,SAASA,MAAK,QACnB,UACA,8BACA,aAAa,aAAa,MAC3B;CACA,MAAM,MAAM,aAAa,QAAQ;CACjC,OAAO;EACN,aAAaA,MAAK,KAAK,QAAQ,cAAc,KAAK;EAClD,aAAaA,MAAK,KAAK,QAAQ,cAAc,KAAK;EAClD,gBAAgBA,MAAK,KAAK,QAAQ,iBAAiB,KAAK;CACzD;AACD;;;ACvDA,SAAwB,gBACvB,UACA,cACA,iBACS;CACT,IAAI,SAAS;CAIb,IAAI,YAAY,OAAO,QAAQ,SAAS;CACxC,IAAI,cAAc,IACjB,MAAM,IAAI,MAAM,8BAA8B;CAE/C,SAAS,OAAO,UAAU,GAAG,SAAS,IAAI,qBAAqB,OAA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GED
@@ -1 +1 @@
1
- export { n as run, o as runBuild, i as runDev, t as runOpenApi, r as runPreview } from "./runOpenApi-AEDhan_-.mjs";
1
+ export { n as run, o as runBuild, i as runDev, t as runOpenApi, r as runPreview } from "./runOpenApi-C5yMpQU1.mjs";
@@ -0,0 +1,61 @@
1
+ //#region src/server/runHooks.ts
2
+ /**
3
+ * Runs hooks around a request handler — the shared implementation of the
4
+ * enter/exit machine for both middleware (site.middleware, endpoint
5
+ * middleware) and server hooks (_hook.server.ts):
6
+ *
7
+ * - enter hooks run in phase order, then list order, until one returns a
8
+ * Response (short-circuit: the handler and remaining enters are skipped)
9
+ * - the handler runs only if no enter hook responded
10
+ * - exit hooks run in reverse entry order — for the hooks that were entered,
11
+ * even when the handler or an enter hook threw
12
+ *
13
+ * Errors are captured (and set on `options.event.error`) rather than thrown,
14
+ * so `options.onError` can render an error response before the exit hooks run
15
+ * (exits inspect `ev.error` to handle it). Callers rethrow `error` when the
16
+ * result carries no response.
17
+ *
18
+ * With `options.event` (the middleware flavor), `ev.response` is kept in sync
19
+ * with the running response, and an exit hook's returned Response replaces
20
+ * it — per the `MiddlewareFunction` contract. The server-hook flavor passes
21
+ * no event, and its exits return void.
22
+ */
23
+ async function runHooks(phases, handler, options) {
24
+ const flat = phases.flatMap((phase) => phase.hooks.map((hook) => ({
25
+ hook,
26
+ arg: phase.arg
27
+ })));
28
+ let entered = 0;
29
+ let response = void 0;
30
+ let error = void 0;
31
+ const ev = options?.event;
32
+ try {
33
+ for (; entered < flat.length && !response; entered++) {
34
+ const result = await flat[entered].hook.enter?.(flat[entered].arg);
35
+ if (result) response = result;
36
+ }
37
+ if (!response) response = await handler();
38
+ } catch (e) {
39
+ error = e;
40
+ if (ev) ev.error = e;
41
+ if (options?.onError) response = await options.onError(ev, e);
42
+ } finally {
43
+ if (ev && response) ev.response = response;
44
+ while (entered > 0) {
45
+ entered--;
46
+ const result = await flat[entered].hook.exit?.(flat[entered].arg);
47
+ if (result && ev) {
48
+ response = result;
49
+ ev.response = result;
50
+ }
51
+ }
52
+ }
53
+ return {
54
+ response,
55
+ error
56
+ };
57
+ }
58
+ //#endregion
59
+ export { runHooks as t };
60
+
61
+ //# sourceMappingURL=runHooks-D5p1Rh7i.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runHooks-D5p1Rh7i.mjs","names":[],"sources":["../src/server/runHooks.ts"],"sourcesContent":["import type ServerEvent from \"./ServerEvent\";\n\n/**\n * One entry in a hook list: middleware (`MiddlewareFunction`) and server hooks\n * (`ServerHook`) are structurally identical — an optional enter and exit.\n */\ninterface Hook {\n\tenter?: (arg: any) => any;\n\texit?: (arg: any) => any;\n}\n\n/**\n * A phase of hooks around a request: a hook list plus the argument its\n * enter/exit functions take (a ServerEvent for middleware, a ServerLoadEvent\n * for server hooks). Multiple phases run their enters in order; exits run in\n * the exact reverse of entry order, across phases too.\n */\nexport interface HookPhase {\n\thooks: Hook[];\n\targ: any;\n}\n\n/**\n * Runs hooks around a request handler — the shared implementation of the\n * enter/exit machine for both middleware (site.middleware, endpoint\n * middleware) and server hooks (_hook.server.ts):\n *\n * - enter hooks run in phase order, then list order, until one returns a\n * Response (short-circuit: the handler and remaining enters are skipped)\n * - the handler runs only if no enter hook responded\n * - exit hooks run in reverse entry order — for the hooks that were entered,\n * even when the handler or an enter hook threw\n *\n * Errors are captured (and set on `options.event.error`) rather than thrown,\n * so `options.onError` can render an error response before the exit hooks run\n * (exits inspect `ev.error` to handle it). Callers rethrow `error` when the\n * result carries no response.\n *\n * With `options.event` (the middleware flavor), `ev.response` is kept in sync\n * with the running response, and an exit hook's returned Response replaces\n * it — per the `MiddlewareFunction` contract. The server-hook flavor passes\n * no event, and its exits return void.\n */\nexport default async function runHooks(\n\tphases: HookPhase[],\n\thandler: () => Promise<Response | undefined>,\n\toptions?: {\n\t\tevent?: ServerEvent;\n\t\tonError?: (ev: ServerEvent, error: unknown) => Promise<Response | undefined>;\n\t},\n): Promise<{ response: Response | undefined; error: unknown }> {\n\tconst flat = phases.flatMap((phase) => phase.hooks.map((hook) => ({ hook, arg: phase.arg })));\n\tlet entered = 0;\n\tlet response: Response | undefined = undefined;\n\tlet error: unknown = undefined;\n\tconst ev = options?.event;\n\ttry {\n\t\tfor (; entered < flat.length && !response; entered++) {\n\t\t\t// A hook returns a Response to short-circuit the request\n\t\t\tconst result = await flat[entered].hook.enter?.(flat[entered].arg);\n\t\t\tif (result) {\n\t\t\t\tresponse = result;\n\t\t\t}\n\t\t}\n\t\tif (!response) {\n\t\t\tresponse = await handler();\n\t\t}\n\t} catch (e) {\n\t\t// Exits can handle the error by returning a Response (via\n\t\t// `onError`/the caller); if none does, the caller rethrows it\n\t\terror = e;\n\t\tif (ev) {\n\t\t\tev.error = e;\n\t\t}\n\t\tif (options?.onError) {\n\t\t\tresponse = await options.onError(ev!, e);\n\t\t}\n\t} finally {\n\t\tif (ev && response) {\n\t\t\tev.response = response;\n\t\t}\n\t\t// Run exit hooks in reverse order for the hooks that were entered.\n\t\t// An exit hook can return a Response to replace the response, or to\n\t\t// handle ev.error\n\t\twhile (entered > 0) {\n\t\t\tentered--;\n\t\t\tconst result = await flat[entered].hook.exit?.(flat[entered].arg);\n\t\t\tif (result && ev) {\n\t\t\t\tresponse = result;\n\t\t\t\tev.response = result;\n\t\t\t}\n\t\t}\n\t}\n\treturn { response, error };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA2CA,eAA8B,SAC7B,QACA,SACA,SAI8D;CAC9D,MAAM,OAAO,OAAO,SAAS,UAAU,MAAM,MAAM,KAAK,UAAU;EAAE;EAAM,KAAK,MAAM;CAAI,EAAE,CAAC;CAC5F,IAAI,UAAU;CACd,IAAI,WAAiC,KAAA;CACrC,IAAI,QAAiB,KAAA;CACrB,MAAM,KAAK,SAAS;CACpB,IAAI;EACH,OAAO,UAAU,KAAK,UAAU,CAAC,UAAU,WAAW;GAErD,MAAM,SAAS,MAAM,KAAK,QAAQ,CAAC,KAAK,QAAQ,KAAK,QAAQ,CAAC,GAAG;GACjE,IAAI,QACH,WAAW;EAEb;EACA,IAAI,CAAC,UACJ,WAAW,MAAM,QAAQ;CAE3B,SAAS,GAAG;EAGX,QAAQ;EACR,IAAI,IACH,GAAG,QAAQ;EAEZ,IAAI,SAAS,SACZ,WAAW,MAAM,QAAQ,QAAQ,IAAK,CAAC;CAEzC,UAAU;EACT,IAAI,MAAM,UACT,GAAG,WAAW;EAKf,OAAO,UAAU,GAAG;GACnB;GACA,MAAM,SAAS,MAAM,KAAK,QAAQ,CAAC,KAAK,OAAO,KAAK,QAAQ,CAAC,GAAG;GAChE,IAAI,UAAU,IAAI;IACjB,WAAW;IACX,GAAG,WAAW;GACf;EACD;CACD;CACA,OAAO;EAAE;EAAU;CAAM;AAC1B"}
@@ -1,10 +1,10 @@
1
1
  import { i as normalizeOrigin, r as normalizeBasePath } from "./basePath-DQnbHc7o.mjs";
2
2
  import { i as buildOpenApiDocument, t as OPEN_API_STATE_KEY } from "./plugin-D8Www11B.mjs";
3
3
  import { r as serverError } from "./response-C5EZsszY.mjs";
4
- import { i as siteEntryPaths, n as prepareTemplate, r as detectSourceMode, t as devPlugin } from "./devPlugin-CL0eu77n.mjs";
4
+ import { i as siteEntryPaths, n as prepareTemplate, r as detectSourceMode, t as devPlugin } from "./devPlugin-lLzauETn.mjs";
5
5
  import { t as ServerEvent } from "./ServerEvent-BY4f3RVF.mjs";
6
6
  import { n as sitemapXml } from "./sitemap-4imxJVrG.mjs";
7
- import { t as Server } from "./Server-C0PGzSQO.mjs";
7
+ import { t as Server } from "./Server-dcRbdPXf.mjs";
8
8
  import { createRequire, isBuiltin } from "node:module";
9
9
  import fs, { existsSync, promises, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
10
10
  import fpath from "node:path";
@@ -1694,4 +1694,4 @@ async function runOpenApi(site, vite, outFile = "openapi.json") {
1694
1694
  //#endregion
1695
1695
  export { loadSite as a, runDev as i, run as n, runBuild as o, runPreview as r, runOpenApi as t };
1696
1696
 
1697
- //# sourceMappingURL=runOpenApi-AEDhan_-.mjs.map
1697
+ //# sourceMappingURL=runOpenApi-C5yMpQU1.mjs.map