noofpi 1.2.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +20 -4
  2. package/dist/{build-25H52PWT.js → build-PFCGDPPJ.js} +5 -4
  3. package/dist/chunk-3PSMWWUB.js +68 -0
  4. package/dist/{chunk-NALDZ3PS.js → chunk-I6TFIGFO.js} +13 -5
  5. package/dist/{chunk-NX6BO7UB.js → chunk-IE3WF5XF.js} +82 -2
  6. package/dist/{chunk-UF6YTIXD.js → chunk-LL3NO5EI.js} +361 -128
  7. package/dist/{chunk-FIJJ3EGL.js → chunk-MN5PVHC5.js} +4 -0
  8. package/dist/chunk-OKNF6XDO.js +14 -0
  9. package/dist/chunk-PPUFFGCH.js +168 -0
  10. package/dist/{chunk-WX2V6EYH.js → chunk-RUNIVVFH.js} +34 -10
  11. package/dist/{chunk-2XCZWFIQ.js → chunk-X3DYEZLK.js} +1 -1
  12. package/dist/{chunk-4YOOGEOF.js → chunk-YJVMBHNL.js} +1 -1
  13. package/dist/cli.js +130 -34
  14. package/dist/{dev-CC3RXV3G.js → dev-HTWUY27O.js} +47 -59
  15. package/dist/devtools-PLUN2DYV.js +958 -0
  16. package/dist/handler-C6NnwBfC.d.ts +17 -0
  17. package/dist/index.d.ts +21 -1
  18. package/dist/index.js +2 -2
  19. package/dist/{validation-ClXd_DAW.d.ts → payload-CL6tYBin.d.ts} +2 -40
  20. package/dist/prepare-KKQ2AEBW.js +24 -0
  21. package/dist/runtime/default-app.d.ts +6 -0
  22. package/dist/runtime/entry-client.d.ts +3 -0
  23. package/dist/runtime/entry-client.js +12 -4
  24. package/dist/runtime/entry-server.d.ts +8 -0
  25. package/dist/runtime/entry-server.js +2 -2
  26. package/dist/runtime/index.d.ts +7 -8
  27. package/dist/runtime/index.js +2 -2
  28. package/dist/runtime/routes.d.ts +13 -0
  29. package/dist/runtime/silent-diagnostics.d.ts +5 -0
  30. package/dist/server/bun.d.ts +15 -0
  31. package/dist/server/bun.js +14 -11
  32. package/dist/server/index.d.ts +9 -90
  33. package/dist/server/index.js +2 -2
  34. package/dist/server/node.d.ts +20 -0
  35. package/dist/server/node.js +2 -2
  36. package/dist/{start-PARBW5KN.js → start-AJKNZRJQ.js} +11 -7
  37. package/dist/typecheck-QACZZ6FN.js +30 -0
  38. package/dist/types-B6rQOOxS.d.ts +76 -0
  39. package/dist/validation-Dwpex2JZ.d.ts +40 -0
  40. package/package.json +22 -6
  41. package/dist/chunk-KGZP2RCF.js +0 -51
  42. package/dist/devtools-KTDSD5PR.js +0 -564
@@ -266,6 +266,9 @@ function patternToRegExp(pattern) {
266
266
  ).join("/").replace(/\/\.\*$/, "(?:/.*)?");
267
267
  return new RegExp(`^${source}/?$`, "i");
268
268
  }
269
+ function matchesRoutePattern(pattern, pathname) {
270
+ return patternToRegExp(pattern).test(pathname);
271
+ }
269
272
  function validateRouteRules(rules, ssr) {
270
273
  for (const [pattern, rule] of Object.entries(rules)) {
271
274
  if (!pattern.startsWith("/"))
@@ -344,6 +347,7 @@ export {
344
347
  limitRequestBody,
345
348
  isCrossSiteWrite,
346
349
  applySecurityHeaders,
350
+ matchesRoutePattern,
347
351
  validateRouteRules,
348
352
  matchRouteRules,
349
353
  toPublicRouteRules,
@@ -0,0 +1,14 @@
1
+ // src/version.ts
2
+ import { readFileSync } from "fs";
3
+ function packageVersion() {
4
+ try {
5
+ const url = new URL("../package.json", import.meta.url);
6
+ return JSON.parse(readFileSync(url, "utf-8")).version;
7
+ } catch {
8
+ return "";
9
+ }
10
+ }
11
+
12
+ export {
13
+ packageVersion
14
+ };
@@ -0,0 +1,168 @@
1
+ // src/server/static.ts
2
+ import { stat } from "fs/promises";
3
+ import path from "path";
4
+ var MIME = {
5
+ ".html": "text/html; charset=utf-8",
6
+ ".js": "text/javascript; charset=utf-8",
7
+ ".mjs": "text/javascript; charset=utf-8",
8
+ ".css": "text/css; charset=utf-8",
9
+ ".json": "application/json; charset=utf-8",
10
+ ".svg": "image/svg+xml",
11
+ ".png": "image/png",
12
+ ".jpg": "image/jpeg",
13
+ ".jpeg": "image/jpeg",
14
+ ".gif": "image/gif",
15
+ ".webp": "image/webp",
16
+ ".avif": "image/avif",
17
+ ".ico": "image/x-icon",
18
+ ".woff": "font/woff",
19
+ ".woff2": "font/woff2",
20
+ ".txt": "text/plain; charset=utf-8",
21
+ ".xml": "application/xml; charset=utf-8",
22
+ ".map": "application/json"
23
+ };
24
+ var COMPRESSIBLE_EXTENSIONS = /* @__PURE__ */ new Set([
25
+ ".html",
26
+ ".js",
27
+ ".mjs",
28
+ ".css",
29
+ ".json",
30
+ ".svg",
31
+ ".txt",
32
+ ".xml",
33
+ ".map",
34
+ ".ico"
35
+ ]);
36
+ var ENCODINGS = [
37
+ { encoding: "br", suffix: ".br" },
38
+ { encoding: "gzip", suffix: ".gz" }
39
+ ];
40
+ function header(headers, name) {
41
+ const value = headers[name];
42
+ return Array.isArray(value) ? value.join(", ") : value;
43
+ }
44
+ function parseAcceptEncoding(value) {
45
+ const accepted = /* @__PURE__ */ new Map();
46
+ for (const part of value?.split(",") ?? []) {
47
+ const [name, ...params] = part.trim().toLowerCase().split(";");
48
+ if (!name) continue;
49
+ let q = 1;
50
+ for (const param of params) {
51
+ const match = /^\s*q\s*=\s*(\d(?:\.\d{0,3})?)\s*$/.exec(param);
52
+ if (match) q = Number(match[1]);
53
+ }
54
+ accepted.set(name.trim(), q);
55
+ }
56
+ return accepted;
57
+ }
58
+ async function pickEncoding(file, acceptEncoding) {
59
+ const accepted = parseAcceptEncoding(acceptEncoding);
60
+ if (!accepted.size) return null;
61
+ const wildcard = accepted.get("*") ?? 0;
62
+ for (const { encoding, suffix } of ENCODINGS) {
63
+ if ((accepted.get(encoding) ?? wildcard) <= 0) continue;
64
+ const info = await stat(file + suffix).catch(() => null);
65
+ if (info?.isFile()) return { encoding, file: file + suffix, info };
66
+ }
67
+ return null;
68
+ }
69
+ function weakTag(tag) {
70
+ return tag.startsWith("W/") ? tag.slice(2) : tag;
71
+ }
72
+ function matchesNoneMatch(value, etag) {
73
+ if (value.trim() === "*") return true;
74
+ return value.split(",").some((tag) => weakTag(tag.trim()) === etag);
75
+ }
76
+ var toSeconds = (ms) => Math.floor(ms / 1e3);
77
+ function isNotModified(headers, etag, mtimeMs) {
78
+ const noneMatch = header(headers, "if-none-match");
79
+ if (noneMatch !== void 0) return matchesNoneMatch(noneMatch, etag);
80
+ const since = Date.parse(header(headers, "if-modified-since") ?? "");
81
+ return !Number.isNaN(since) && toSeconds(mtimeMs) <= toSeconds(since);
82
+ }
83
+ function ifRangeHolds(headers, etag, mtimeMs) {
84
+ const value = header(headers, "if-range")?.trim();
85
+ if (!value) return true;
86
+ if (value.startsWith('"') || value.startsWith("W/")) return value === etag;
87
+ const date = Date.parse(value);
88
+ return !Number.isNaN(date) && toSeconds(date) === toSeconds(mtimeMs);
89
+ }
90
+ function parseRange(value, size) {
91
+ const match = /^bytes=(\d*)-(\d*)$/.exec(value?.trim() ?? "");
92
+ if (!match || !match[1] && !match[2]) return null;
93
+ let start;
94
+ let end;
95
+ if (!match[1]) {
96
+ const suffix = Number(match[2]);
97
+ if (suffix === 0) return "unsatisfiable";
98
+ start = Math.max(size - suffix, 0);
99
+ end = size - 1;
100
+ } else {
101
+ start = Number(match[1]);
102
+ end = match[2] ? Math.min(Number(match[2]), size - 1) : size - 1;
103
+ if (match[2] && Number(match[2]) < start) return null;
104
+ }
105
+ return start >= size ? "unsatisfiable" : { start, end };
106
+ }
107
+ async function resolveStaticFile(dir, method, rawPath, requestHeaders = {}) {
108
+ if (method !== "GET" && method !== "HEAD") return null;
109
+ let pathname;
110
+ try {
111
+ pathname = decodeURIComponent(
112
+ new URL(rawPath, "http://localhost").pathname
113
+ );
114
+ } catch {
115
+ return null;
116
+ }
117
+ const file = path.join(dir, pathname);
118
+ if (!file.startsWith(dir + path.sep) || path.basename(file) === "index.html")
119
+ return null;
120
+ const info = await stat(file).catch(() => null);
121
+ if (!info?.isFile()) return null;
122
+ const extension = path.extname(file).toLowerCase();
123
+ const compressible = COMPRESSIBLE_EXTENSIONS.has(extension);
124
+ const range = header(requestHeaders, "range");
125
+ const variant = compressible && range === void 0 ? await pickEncoding(file, header(requestHeaders, "accept-encoding")) : null;
126
+ const served = variant?.info ?? info;
127
+ const etag = `"${served.size.toString(16)}-${Math.floor(served.mtimeMs).toString(16)}"`;
128
+ const headers = {
129
+ "X-Content-Type-Options": "nosniff",
130
+ "Content-Type": MIME[extension] ?? "application/octet-stream",
131
+ "Cache-Control": pathname.startsWith("/assets/") ? "public, max-age=31536000, immutable" : "no-cache",
132
+ ETag: etag,
133
+ "Last-Modified": served.mtime.toUTCString(),
134
+ "Accept-Ranges": "bytes"
135
+ };
136
+ if (compressible) headers.Vary = "Accept-Encoding";
137
+ if (variant) headers["Content-Encoding"] = variant.encoding;
138
+ if (isNotModified(requestHeaders, etag, served.mtimeMs)) {
139
+ delete headers["Content-Type"];
140
+ return { status: 304, body: null, headers };
141
+ }
142
+ const bytes = range !== void 0 && ifRangeHolds(requestHeaders, etag, served.mtimeMs) ? parseRange(range, served.size) : null;
143
+ if (bytes === "unsatisfiable") {
144
+ headers["Content-Range"] = `bytes */${served.size}`;
145
+ headers["Content-Length"] = "0";
146
+ return { status: 416, body: null, headers };
147
+ }
148
+ if (bytes) {
149
+ headers["Content-Range"] = `bytes ${bytes.start}-${bytes.end}/${served.size}`;
150
+ headers["Content-Length"] = String(bytes.end - bytes.start + 1);
151
+ return {
152
+ status: 206,
153
+ body: { file: variant?.file ?? file, ...bytes },
154
+ headers
155
+ };
156
+ }
157
+ headers["Content-Length"] = String(served.size);
158
+ return {
159
+ status: 200,
160
+ body: { file: variant?.file ?? file },
161
+ headers
162
+ };
163
+ }
164
+
165
+ export {
166
+ COMPRESSIBLE_EXTENSIONS,
167
+ resolveStaticFile
168
+ };
@@ -1,5 +1,8 @@
1
+ import {
2
+ packageVersion
3
+ } from "./chunk-OKNF6XDO.js";
4
+
1
5
  // src/banner.ts
2
- import { readFileSync } from "fs";
3
6
  import { networkInterfaces } from "os";
4
7
  import { version as viteVersion } from "vite";
5
8
  var LOGO = ["\u2588\u2584 \u2588 \u2588\u2580\u2588 \u2588\u2580\u2588 \u2588\u2580\u2580 \u2588\u2580\u2588 \u2588", "\u2588 \u2580\u2588 \u2588\u2584\u2588 \u2588\u2584\u2588 \u2588\u2580 \u2588\u2580\u2580 \u2588"];
@@ -34,14 +37,6 @@ function gradient(text) {
34
37
  }
35
38
  return out + "\x1B[39m";
36
39
  }
37
- function packageVersion() {
38
- try {
39
- const url = new URL("../package.json", import.meta.url);
40
- return JSON.parse(readFileSync(url, "utf-8")).version;
41
- } catch {
42
- return "";
43
- }
44
- }
45
40
  function networkAddresses() {
46
41
  const addresses = [];
47
42
  for (const entries of Object.values(networkInterfaces())) {
@@ -96,7 +91,36 @@ function printBanner(options) {
96
91
  console.log(lines.join("\n"));
97
92
  }
98
93
 
94
+ // src/shortcuts.ts
95
+ import { spawn } from "child_process";
96
+ function openBrowser(url) {
97
+ const [command, args] = process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : process.platform === "darwin" ? ["open", [url]] : ["xdg-open", [url]];
98
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
99
+ child.on("error", () => console.log(` Could not open the browser: ${url}`));
100
+ child.unref();
101
+ }
102
+ function bindShortcuts(options) {
103
+ const { stdin } = process;
104
+ if (!stdin.isTTY || !process.stdout.isTTY) return false;
105
+ let closing = false;
106
+ const quit = () => {
107
+ if (closing) return;
108
+ closing = true;
109
+ options.close().finally(() => process.exit(0));
110
+ };
111
+ stdin.setRawMode(true);
112
+ stdin.setEncoding("utf-8");
113
+ stdin.resume();
114
+ stdin.on("data", (key) => {
115
+ if (key === "" || key.toLowerCase() === "q") quit();
116
+ else if (key.toLowerCase() === "b") openBrowser(options.url);
117
+ });
118
+ return true;
119
+ }
120
+
99
121
  export {
100
122
  localUrl,
101
- printBanner
123
+ printBanner,
124
+ openBrowser,
125
+ bindShortcuts
102
126
  };
@@ -24,7 +24,7 @@ import {
24
24
  matchRouteRules,
25
25
  usesFetchMode,
26
26
  usesNonce
27
- } from "./chunk-FIJJ3EGL.js";
27
+ } from "./chunk-MN5PVHC5.js";
28
28
 
29
29
  // src/server/cookies.ts
30
30
  var JAR = /* @__PURE__ */ Symbol.for("noofpi.request-cookies");
@@ -29,7 +29,7 @@ import {
29
29
  isServerRendered,
30
30
  resolveFetchMode,
31
31
  usesFetchMode
32
- } from "./chunk-FIJJ3EGL.js";
32
+ } from "./chunk-MN5PVHC5.js";
33
33
 
34
34
  // src/runtime/async-data.ts
35
35
  import {
package/dist/cli.js CHANGED
@@ -1,14 +1,85 @@
1
+ import {
2
+ packageVersion
3
+ } from "./chunk-OKNF6XDO.js";
1
4
  import {
2
5
  BUILD_PRESETS,
3
6
  assertBuildPreset,
4
7
  resolveConfig
5
- } from "./chunk-NX6BO7UB.js";
8
+ } from "./chunk-IE3WF5XF.js";
6
9
  import "./chunk-ELXCFUA4.js";
7
- import "./chunk-FIJJ3EGL.js";
10
+ import "./chunk-MN5PVHC5.js";
8
11
 
9
12
  // src/cli.ts
10
13
  import path2 from "path";
11
14
 
15
+ // src/cli-args.ts
16
+ import { parseArgs } from "util";
17
+ var COMMANDS = [
18
+ "dev",
19
+ "build",
20
+ "start",
21
+ "preview",
22
+ "prepare",
23
+ "typecheck"
24
+ ];
25
+ var CliUsageError = class extends Error {
26
+ };
27
+ function parsePort(value) {
28
+ const port = Number(value);
29
+ if (!/^\d+$/.test(value) || port > 65535)
30
+ throw new CliUsageError(
31
+ `[noofpi] --port must be an integer between 0 and 65535 (got "${value}")`
32
+ );
33
+ return port;
34
+ }
35
+ var parse = (args) => parseArgs({
36
+ args,
37
+ allowPositionals: true,
38
+ options: {
39
+ root: { type: "string" },
40
+ port: { type: "string" },
41
+ host: { type: "string" },
42
+ preset: { type: "string" },
43
+ open: { type: "boolean" },
44
+ help: { type: "boolean", short: "h" },
45
+ version: { type: "boolean", short: "v" }
46
+ }
47
+ });
48
+ function parseCliArgs(argv) {
49
+ let parsed;
50
+ try {
51
+ parsed = parse(argv);
52
+ } catch (error) {
53
+ const message = error instanceof Error ? error.message : String(error);
54
+ throw new CliUsageError(
55
+ `[noofpi] ${message.replace(/\. To specify[\s\S]*$/, "")}`
56
+ );
57
+ }
58
+ const { values, positionals } = parsed;
59
+ const [command, ...rest] = positionals;
60
+ const args = {
61
+ command: void 0,
62
+ rest,
63
+ help: values.help ?? false,
64
+ version: values.version ?? false,
65
+ open: values.open ?? false,
66
+ root: values.root,
67
+ port: values.port === void 0 ? void 0 : parsePort(values.port),
68
+ host: values.host,
69
+ preset: values.preset
70
+ };
71
+ if (command !== void 0) {
72
+ if (!COMMANDS.includes(command))
73
+ throw new CliUsageError(
74
+ `[noofpi] Unknown command "${command}" (expected ${COMMANDS.join(" | ")})`
75
+ );
76
+ args.command = command;
77
+ if (rest.length && args.command !== "typecheck" && !args.help)
78
+ throw new CliUsageError(`[noofpi] Unexpected argument "${rest[0]}"`);
79
+ }
80
+ return args;
81
+ }
82
+
12
83
  // src/load-config.ts
13
84
  import { existsSync } from "fs";
14
85
  import path from "path";
@@ -36,19 +107,23 @@ async function loadConfig(root) {
36
107
  var USAGE = `noofpi <command> [options]
37
108
 
38
109
  Commands:
39
- dev Start the dev server with live reload
40
- build Build for production into .output/
41
- start Run the production build
110
+ dev Start the dev server with live reload
111
+ build Build for production into .output/
112
+ start Run the production build
113
+ preview Build, then run the production build
114
+ prepare Generate the .noofpi/ type declarations (for a postinstall script)
115
+ typecheck Run prepare, then vue-tsc --noEmit (extra arguments go to vue-tsc after --)
42
116
 
43
117
  Options:
44
118
  --root <dir> Project root (default: current directory)
45
- --port <port> Server port
46
- --host <host> Server host
47
- --preset <name> Build target: ${BUILD_PRESETS.join(" | ")} (default: build.preset or node)`;
48
- function option(args, name) {
49
- const index = args.indexOf(name);
50
- return index === -1 ? void 0 : args[index + 1];
51
- }
119
+ --port <port> Server port (dev, start, preview)
120
+ --host <host> Server host (dev, start, preview)
121
+ --open Open the browser once the server is ready (dev, start, preview)
122
+ --preset <name> Build target: ${BUILD_PRESETS.join(" | ")} (default: build.preset or node)
123
+ preview needs a preset that \`noofpi start\` can run: node | bun | docker
124
+ -h, --help Show this help
125
+ -v, --version Show the noofpi version`;
126
+ var PREVIEW_PRESETS = ["node", "bun", "docker"];
52
127
  async function loadEnvFiles(root, mode) {
53
128
  const { loadEnv } = await import("vite");
54
129
  const env = loadEnv(mode, root, "");
@@ -56,38 +131,59 @@ async function loadEnvFiles(root, mode) {
56
131
  process.env[key] ??= value;
57
132
  }
58
133
  }
134
+ var isDevelopment = (command) => command === "dev" || command === "prepare" || command === "typecheck";
59
135
  async function main() {
60
- const [command, ...args] = process.argv.slice(2);
61
- const root = path2.resolve(option(args, "--root") ?? process.cwd());
62
- const portArg = option(args, "--port");
63
- const overrides = {
64
- port: portArg ? Number(portArg) : void 0,
65
- host: option(args, "--host")
66
- };
67
- if (command !== "dev" && command !== "build" && command !== "start") {
136
+ const args = parseCliArgs(process.argv.slice(2));
137
+ if (args.version) {
138
+ console.log(packageVersion());
139
+ return;
140
+ }
141
+ const { command } = args;
142
+ if (args.help || !command) {
68
143
  console.log(USAGE);
69
- process.exit(command ? 1 : 0);
144
+ return;
70
145
  }
71
- process.env.NODE_ENV ??= command === "dev" ? "development" : "production";
72
- await loadEnvFiles(root, command === "dev" ? "development" : "production");
146
+ const root = path2.resolve(args.root ?? process.cwd());
147
+ const overrides = { port: args.port, host: args.host, open: args.open };
148
+ const mode = isDevelopment(command) ? "development" : "production";
149
+ process.env.NODE_ENV ??= mode;
150
+ await loadEnvFiles(root, mode);
73
151
  const config = await loadConfig(root);
74
152
  if (command === "dev") {
75
- const { startDev } = await import("./dev-CC3RXV3G.js");
153
+ const { startDev } = await import("./dev-HTWUY27O.js");
76
154
  await startDev(root, config, overrides);
77
- } else if (command === "build") {
78
- const { buildApp } = await import("./build-25H52PWT.js");
79
- const preset = option(args, "--preset");
80
- await buildApp(
81
- root,
82
- config,
83
- preset ? assertBuildPreset(preset, "--preset") : void 0
84
- );
85
- } else {
86
- const { startProd } = await import("./start-PARBW5KN.js");
155
+ } else if (command === "build" || command === "preview") {
156
+ const preset = args.preset ? assertBuildPreset(args.preset, "--preset") : void 0;
157
+ if (command === "preview") {
158
+ const target = preset ?? config.build.preset;
159
+ if (!PREVIEW_PRESETS.includes(target))
160
+ throw new Error(
161
+ `[noofpi] preview can not run the "${target}" preset (use ${PREVIEW_PRESETS.join(" | ")}, or build it and serve .output/ with its own tooling)`
162
+ );
163
+ }
164
+ const { buildApp } = await import("./build-PFCGDPPJ.js");
165
+ await buildApp(root, config, preset);
166
+ if (command === "preview") {
167
+ const { startProd } = await import("./start-AJKNZRJQ.js");
168
+ await startProd(root, config, overrides);
169
+ }
170
+ } else if (command === "start") {
171
+ const { startProd } = await import("./start-AJKNZRJQ.js");
87
172
  await startProd(root, config, overrides);
173
+ } else {
174
+ const { prepareApp } = await import("./prepare-KKQ2AEBW.js");
175
+ await prepareApp(root, config);
176
+ if (command === "prepare") {
177
+ console.log("noofpi: generated .noofpi/");
178
+ } else {
179
+ const { runTypecheck } = await import("./typecheck-QACZZ6FN.js");
180
+ process.exit(await runTypecheck(root, args.rest));
181
+ }
88
182
  }
89
183
  }
90
184
  main().catch((error) => {
91
185
  console.error(error instanceof Error ? error.message : error);
186
+ if (error instanceof CliUsageError)
187
+ console.error("Run `noofpi --help` for usage.");
92
188
  process.exit(1);
93
189
  });
@@ -1,86 +1,72 @@
1
1
  import {
2
+ devErrorPage,
3
+ serializeDevErrors,
4
+ toDevError
5
+ } from "./chunk-3PSMWWUB.js";
6
+ import {
7
+ bindShortcuts,
2
8
  localUrl,
9
+ openBrowser,
3
10
  printBanner
4
- } from "./chunk-WX2V6EYH.js";
11
+ } from "./chunk-RUNIVVFH.js";
5
12
  import {
6
13
  DEV_ENTRY,
7
14
  createViteConfig,
8
15
  htmlTemplate,
9
16
  resolveCss,
10
- resolveFonts
11
- } from "./chunk-UF6YTIXD.js";
12
- import {
13
- isCloudflarePreset
14
- } from "./chunk-NX6BO7UB.js";
17
+ resolveFonts,
18
+ startPlatformProxy
19
+ } from "./chunk-LL3NO5EI.js";
20
+ import "./chunk-OKNF6XDO.js";
21
+ import "./chunk-IE3WF5XF.js";
15
22
  import {
16
23
  createHandler
17
- } from "./chunk-2XCZWFIQ.js";
24
+ } from "./chunk-X3DYEZLK.js";
18
25
  import "./chunk-MTXQR32N.js";
19
26
  import {
20
27
  sendWebResponse,
21
28
  toWebRequest
22
- } from "./chunk-NALDZ3PS.js";
23
- import "./chunk-KGZP2RCF.js";
29
+ } from "./chunk-I6TFIGFO.js";
30
+ import "./chunk-PPUFFGCH.js";
24
31
  import "./chunk-ELXCFUA4.js";
25
32
  import "./chunk-EZPJF4D4.js";
26
33
  import "./chunk-G35DW4NA.js";
27
- import "./chunk-FIJJ3EGL.js";
34
+ import "./chunk-MN5PVHC5.js";
28
35
  import "./chunk-Y3NBZ6DW.js";
29
36
 
30
37
  // src/vite/dev.ts
31
38
  import { createServer as createHttpServer } from "http";
32
- import path2 from "path";
39
+ import path from "path";
33
40
  import { createServer as createViteServer, normalizePath } from "vite";
34
41
 
35
- // src/shortcuts.ts
36
- import { spawn } from "child_process";
37
- function openBrowser(url) {
38
- const [command, args] = process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : process.platform === "darwin" ? ["open", [url]] : ["xdg-open", [url]];
39
- const child = spawn(command, args, { stdio: "ignore", detached: true });
40
- child.on("error", () => console.log(` Could not open the browser: ${url}`));
41
- child.unref();
42
+ // src/vite/dev-errors.ts
43
+ import { AsyncLocalStorage } from "async_hooks";
44
+ var scope = new AsyncLocalStorage();
45
+ function collectDevErrors(run) {
46
+ const errors = [];
47
+ return scope.run(errors, run).then((result) => ({ result, errors }));
42
48
  }
43
- function bindShortcuts(options) {
44
- const { stdin } = process;
45
- if (!stdin.isTTY || !process.stdout.isTTY) return false;
46
- let closing = false;
47
- const quit = () => {
48
- if (closing) return;
49
- closing = true;
50
- options.close().finally(() => process.exit(0));
51
- };
52
- stdin.setRawMode(true);
53
- stdin.setEncoding("utf-8");
54
- stdin.resume();
55
- stdin.on("data", (key) => {
56
- if (key === "" || key.toLowerCase() === "q") quit();
57
- else if (key.toLowerCase() === "b") openBrowser(options.url);
58
- });
59
- return true;
49
+ function recordDevError(error) {
50
+ scope.getStore()?.push(toDevError(error, "server"));
60
51
  }
61
-
62
- // src/vite/platform.ts
63
- import { existsSync } from "fs";
64
- import { createRequire } from "module";
65
- import path from "path";
66
- import { pathToFileURL } from "url";
67
- var WRANGLER_CONFIGS = ["wrangler.json", "wrangler.jsonc", "wrangler.toml"];
68
- async function startPlatformProxy(root, config) {
69
- if (!isCloudflarePreset(config.build.preset)) return void 0;
70
- let entry;
71
- try {
72
- entry = createRequire(path.join(root, "package.json")).resolve("wrangler");
73
- } catch {
74
- console.warn(
75
- "[noofpi] Cloudflare bindings are not available in dev: install wrangler (`wrangler` devDependency)"
52
+ async function withDevErrors(response, errors) {
53
+ if (!errors.length) return response;
54
+ const type = response.headers.get("content-type") ?? "";
55
+ const headers = new Headers(response.headers);
56
+ headers.delete("content-length");
57
+ if (type.includes("text/html")) {
58
+ const html = await response.text();
59
+ const script = serializeDevErrors(errors);
60
+ return new Response(
61
+ html.includes("</body>") ? html.replace("</body>", () => script + "</body>") : html + script,
62
+ { status: response.status, headers }
76
63
  );
77
- return void 0;
78
64
  }
79
- const { getPlatformProxy } = await import(pathToFileURL(entry).href);
80
- const configPath = WRANGLER_CONFIGS.map((file) => path.join(root, file)).find(
81
- existsSync
82
- );
83
- return getPlatformProxy({ configPath });
65
+ if (response.status === 500) {
66
+ headers.set("content-type", "text/html; charset=utf-8");
67
+ return new Response(devErrorPage(errors), { status: 500, headers });
68
+ }
69
+ return response;
84
70
  }
85
71
 
86
72
  // src/vite/dev.ts
@@ -105,8 +91,8 @@ async function startDev(root, config, overrides) {
105
91
  )
106
92
  );
107
93
  const stylesheets = resolveCss(root, config, fonts).map((file) => {
108
- const relative = path2.relative(root, file);
109
- const outside = relative.startsWith("..") || path2.isAbsolute(relative);
94
+ const relative = path.relative(root, file);
95
+ const outside = relative.startsWith("..") || path.isAbsolute(relative);
110
96
  const url = outside ? "/@fs/" + normalizePath(file) : "/" + normalizePath(relative);
111
97
  return url + "?direct";
112
98
  });
@@ -117,11 +103,12 @@ async function startDev(root, config, overrides) {
117
103
  onError: (error) => {
118
104
  if (error instanceof Error) vite.ssrFixStacktrace(error);
119
105
  console.error(error);
106
+ recordDevError(error);
120
107
  }
121
108
  });
122
109
  httpServer.on("request", (req, res) => {
123
110
  vite.middlewares(req, res, () => {
124
- handler(toWebRequest(req), platform?.env).then(
111
+ collectDevErrors(() => handler(toWebRequest(req), platform?.env)).then(({ result, errors }) => withDevErrors(result, errors)).then(
125
112
  (response) => sendWebResponse(res, response),
126
113
  (error) => {
127
114
  console.error(error);
@@ -142,6 +129,7 @@ async function startDev(root, config, overrides) {
142
129
  });
143
130
  const shortcuts = bindShortcuts({ url: localUrl(host, port), close });
144
131
  printBanner({ mode: "development", host, port, startedAt, shortcuts });
132
+ if (overrides.open) openBrowser(localUrl(host, port));
145
133
  return { vite, httpServer, close };
146
134
  }
147
135
  export {