@nuxt/vite-server-nightly 4.6.0-29833429.e2a0e5da → 4.6.0-29836601.d5e5f1bd

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/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { dirname, join, relative, resolve } from "pathe";
3
- import { addTemplate, addTypeTemplate, addVitePlugin, getLayerDirectories, logger, resolvePath, tryUseNitro } from "@nuxt/kit";
3
+ import { addPlugin, addTemplate, addTypeTemplate, addVitePlugin, getLayerDirectories, logger, resolvePath, tryUseNitro } from "@nuxt/kit";
4
4
  import { bundlerDiagnostics, getServerRuntime, setServerBuild, useServerBuild } from "@nuxt/kit/internal";
5
5
  import { defu } from "defu";
6
6
  import { resolveModulePath } from "exsolve";
@@ -620,6 +620,7 @@ function addServerEntry(nuxt, serverRuntime, prerender, routeRules) {
620
620
  "",
621
621
  `export { fetch }`,
622
622
  "",
623
+ ...nuxt.options.dev ? [`export { setDevErrorContext } from ${JSON.stringify(resolve(distDir, "runtime/dev-error"))}`, ""] : [],
623
624
  `const server = import.meta.dev ? undefined : createNodeServer({ fetch, publicDir: new URL('../public/', import.meta.url) })`,
624
625
  `export default server`,
625
626
  "",
@@ -956,8 +957,15 @@ function setupDevServer(nuxt, serverEntry) {
956
957
  const html = await resolveDocument(nuxt);
957
958
  return new Response(viteServer ? await viteServer.transformIndexHtml(url, html) : html, { headers: { "content-type": "text/html;charset=utf-8" } });
958
959
  };
960
+ const errorChannel = joinURL(nuxt.options.app.baseURL, nuxt.options.devServer.errorChannel);
959
961
  const render = async (request) => {
960
- return (await viteServer.ssrLoadModule(serverEntry)).fetch(request);
962
+ const module = await viteServer.ssrLoadModule(serverEntry);
963
+ module.setDevErrorContext?.({
964
+ server: viteServer,
965
+ cwd: nuxt.options.rootDir,
966
+ channel: errorChannel
967
+ });
968
+ return module.fetch(request);
961
969
  };
962
970
  const respond = (request, url) => {
963
971
  return serverEntry && viteServer ? render(request) : shell(url);
@@ -1074,8 +1082,10 @@ function bundle(nuxt) {
1074
1082
  nuxt.options.vite.$client = client;
1075
1083
  addVitePlugin(() => [DocumentPlugin(nuxt), EntryImportMapPlugin()], { server: false });
1076
1084
  }
1077
- if (nuxt.options.dev) setupDevServer(nuxt, server?.entry);
1078
- else nuxt.hook("build:done", async () => {
1085
+ if (nuxt.options.dev) {
1086
+ addPlugin(resolve(nuxt.options.appDir, "plugins/dev-error-overlay.client"));
1087
+ setupDevServer(nuxt, server?.entry);
1088
+ } else nuxt.hook("build:done", async () => {
1079
1089
  await writeStaticOutput(nuxt, publicDir, {
1080
1090
  ssr,
1081
1091
  prerender
@@ -0,0 +1,109 @@
1
+ import process from "node:process";
2
+ import { ERROR_CHANNEL_ENV, clearErrorReport, createErrorReport, publishErrorReport, renderErrorAnsi, renderErrorPage, requestIdOf, serializeErrorCause, setErrorChannelForwarding, useErrorChannel, withErrorOverlay } from "nuxt/internal/dev-error";
3
+ import { isLoopbackAddress } from "nuxt/internal/dev/peer";
4
+ //#region src/runtime/dev-error.ts
5
+ let context;
6
+ /** Whether a dev server in front owns the channel. */
7
+ const forwarding = () => !!process.env[ERROR_CHANNEL_ENV];
8
+ setErrorChannelForwarding(forwarding);
9
+ /** Install the dev server the app renders from. */
10
+ function setDevErrorContext(next) {
11
+ context = next;
12
+ useErrorChannel().catch(() => {});
13
+ }
14
+ const THROWN_VALUE = Symbol.for("nuxt:dev:thrown");
15
+ /** Whether the app threw a bare value, which was given its status on the way here. */
16
+ function isThrownValue(error) {
17
+ return typeof error === "object" && error !== null && THROWN_VALUE in error;
18
+ }
19
+ /** Whether `pathname` is a live channel route this process serves. */
20
+ function isErrorChannelRequest(pathname) {
21
+ if (!context || forwarding()) return false;
22
+ const base = context.channel.replace(/\/$/, "");
23
+ return pathname === base || pathname.startsWith(`${base}/`);
24
+ }
25
+ /**
26
+ * Serve the live error channel: the SSE stream, report lookups and "open in editor".
27
+ *
28
+ * Trust follows the socket, since a request's origin headers are forgeable over a direct
29
+ * connection.
30
+ */
31
+ async function fetchErrorChannel(request) {
32
+ return await (await useErrorChannel()).fetchHandler(request, { trusted: isLoopbackAddress(request.ip) }) ?? new Response("Not Found", { status: 404 });
33
+ }
34
+ /**
35
+ * Build a report from the stack as raised, publish it, then rewrite the stack in place so
36
+ * every later consumer sees source positions.
37
+ */
38
+ async function observeError(error, request, options = {}) {
39
+ if (!context) return;
40
+ const report = options.expected ? void 0 : await buildReport(error).catch(() => void 0);
41
+ fixStacktraces(error, context.server);
42
+ if (report) {
43
+ const url = new URL(request.url);
44
+ await publishErrorReport(report, {
45
+ method: request.method,
46
+ url,
47
+ headers: request.headers
48
+ }).catch(() => {});
49
+ if (!forwarding()) {
50
+ const rendered = await renderErrorAnsi(report, { cwd: context.cwd }).catch(() => void 0);
51
+ console.log(`[request error] [${request.method}] ${url.pathname}${url.search}\n\n${rendered ?? String(error?.stack || error)}`);
52
+ }
53
+ }
54
+ return report;
55
+ }
56
+ async function buildReport(error) {
57
+ const { viteLoader } = await import("my-bad/vite");
58
+ return createErrorReport(error, {
59
+ cwd: context.cwd,
60
+ loaders: [viteLoader(ssrOnly(context.server), { fs: false })]
61
+ });
62
+ }
63
+ /**
64
+ * The dev server with only its SSR environment visible, since `viteLoader` maps through
65
+ * the first environment holding the file and an SSR frame belongs to the SSR transform.
66
+ */
67
+ function ssrOnly(server) {
68
+ return Object.create(server, { environments: { value: { ssr: server.environments.ssr } } });
69
+ }
70
+ /**
71
+ * Ask Vite to map the stacks of an error and its causes. It maps in place and appends to
72
+ * `message` on a stack it has already rewritten, so each one is mapped on a carrier.
73
+ */
74
+ function fixStacktraces(error, server, seen = /* @__PURE__ */ new Set()) {
75
+ if (!(error instanceof Error) || seen.has(error)) return;
76
+ seen.add(error);
77
+ if (typeof error.stack === "string") {
78
+ const carrier = { stack: error.stack };
79
+ server.ssrFixStacktrace(carrier);
80
+ if (carrier.stack) error.stack = carrier.stack;
81
+ }
82
+ fixStacktraces(error.cause, server, seen);
83
+ }
84
+ /** The error's `cause` chain, as the error page receives it in the payload. */
85
+ function errorCause(error) {
86
+ return serializeErrorCause(error?.cause);
87
+ }
88
+ /** Add the report to the error page the app rendered, a click away. */
89
+ function overlayErrorReport(html, report, request) {
90
+ return withErrorOverlay(html, report, {
91
+ cwd: context.cwd,
92
+ channel: channelPath(),
93
+ requestId: requestIdOf(request),
94
+ startMinimized: true
95
+ });
96
+ }
97
+ /** Render the report as a standalone page, for when the app cannot render its error page. */
98
+ function renderReportPage(report, request) {
99
+ return renderErrorPage(report, {
100
+ cwd: context.cwd,
101
+ channel: channelPath(),
102
+ requestId: requestIdOf(request)
103
+ });
104
+ }
105
+ function channelPath() {
106
+ return process.env[ERROR_CHANNEL_ENV] || context.channel;
107
+ }
108
+ //#endregion
109
+ export { clearErrorReport, errorCause, fetchErrorChannel, isErrorChannelRequest, isThrownValue, observeError, overlayErrorReport, renderReportPage, setDevErrorContext };
@@ -1,4 +1,6 @@
1
1
  import { fileURLToPath } from "node:url";
2
+ import { readdir } from "node:fs/promises";
3
+ import { join, relative, sep } from "node:path";
2
4
  import { serve } from "srvx/node";
3
5
  import { staticMiddleware } from "srvx/static";
4
6
  //#region src/runtime/node.ts
@@ -8,8 +10,38 @@ import { staticMiddleware } from "srvx/static";
8
10
  * The static handler comes first so a request for a hashed asset never reaches a render.
9
11
  */
10
12
  function createNodeServer(options) {
11
- const serveStatic = staticMiddleware({ dir: typeof options.publicDir === "string" ? options.publicDir : fileURLToPath(options.publicDir) });
12
- return { fetch: (request) => serveStatic(request, () => options.fetch(request)) };
13
+ const dir = typeof options.publicDir === "string" ? options.publicDir : fileURLToPath(options.publicDir);
14
+ const serveStatic = staticMiddleware({ dir });
15
+ const publicFiles = listFiles(dir);
16
+ return { fetch: async (request) => {
17
+ const files = await publicFiles;
18
+ if (!files || mayBeStaticFile(files, request)) return serveStatic(request, () => options.fetch(request));
19
+ return options.fetch(request);
20
+ } };
21
+ }
22
+ async function listFiles(dir) {
23
+ try {
24
+ const entries = await readdir(dir, {
25
+ recursive: true,
26
+ withFileTypes: true
27
+ });
28
+ const files = /* @__PURE__ */ new Set();
29
+ for (const entry of entries) if (entry.isFile()) files.add("/" + relative(dir, join(entry.parentPath, entry.name)).split(sep).join("/"));
30
+ return files;
31
+ } catch {
32
+ return;
33
+ }
34
+ }
35
+ /** Whether the request path, or one of the variants the static handler tries, is a public file. */
36
+ function mayBeStaticFile(files, request) {
37
+ let path;
38
+ try {
39
+ path = decodeURIComponent(new URL(request.url).pathname);
40
+ } catch {
41
+ return true;
42
+ }
43
+ if (path.endsWith("/")) return files.has(path + "index.html");
44
+ return files.has(path) || files.has(path + ".html") || files.has(path + "/index.html");
13
45
  }
14
46
  /** Listen for requests, using the port and host the platform environment configures. */
15
47
  function listen(server) {
@@ -45,7 +45,10 @@ function createRendererOptions(runtimeConfig, matchRouteRules, prerender) {
45
45
  hooks: () => serverHooks,
46
46
  createResponse: (body, init) => new Response(body, init),
47
47
  createError: (init) => new NuxtServerError(init),
48
- prerender
48
+ prerender,
49
+ onRenderSuccess: import.meta.dev ? () => {
50
+ import("./dev-error.mjs").then(({ clearErrorReport }) => clearErrorReport()).catch(() => {});
51
+ } : void 0
49
52
  };
50
53
  }
51
54
  /**
@@ -55,10 +58,15 @@ function createRendererOptions(runtimeConfig, matchRouteRules, prerender) {
55
58
  const PRERENDER_HINTS_HEADER = "x-nuxt-prerender";
56
59
  /**
57
60
  * A web-standard handler over the renderer: it renders the request, and renders the app's
58
- * error page for a request the render refused.
61
+ * error page for a request the render refused. In development it also serves the live
62
+ * error channel and publishes what it failed on to it.
59
63
  */
60
64
  function createFetchHandler(renderer, matchRouteRules) {
61
65
  return async function fetch(request) {
66
+ if (import.meta.dev) {
67
+ const devErrors = await import("./dev-error.mjs");
68
+ if (devErrors.isErrorChannelRequest(new URL(request.url).pathname)) return devErrors.fetchErrorChannel(request);
69
+ }
62
70
  const event = createRequestEvent(request);
63
71
  const rules = matchRouteRules(event.url.pathname);
64
72
  if (rules.redirect) return redirectResponse(event, rules.redirect, rules.headers);
@@ -129,7 +137,10 @@ function applyPrerenderHints(event, response) {
129
137
  async function renderError(renderer, request, error, event) {
130
138
  const { status, statusText, message, headers } = describeError(error);
131
139
  const url = new URL(request.url);
140
+ const devErrors = import.meta.dev ? await import("./dev-error.mjs") : void 0;
141
+ const report = devErrors ? await devErrors.observeError(error, request, { expected: status < 500 && !devErrors.isThrownValue(error) }) : void 0;
132
142
  const data = error?.data;
143
+ const stack = error?.stack;
133
144
  const errorEvent = createRequestEvent(new Request(withQuery(new URL("/__nuxt_error", url).href, {
134
145
  status: String(status),
135
146
  statusCode: String(status),
@@ -137,10 +148,15 @@ async function renderError(renderer, request, error, event) {
137
148
  statusMessage: statusText,
138
149
  message,
139
150
  url: request.url,
140
- ...data === void 0 ? {} : { data: typeof data === "string" ? data : JSON.stringify(data) }
151
+ ...data === void 0 ? {} : { data: typeof data === "string" ? data : JSON.stringify(data) },
152
+ ...import.meta.dev && stack ? { stack } : {}
141
153
  }), { headers: request.headers }));
142
154
  const state = (import.meta.prerender ? event.context.nuxt : void 0) || {};
143
155
  state["~rendering-error"] = true;
156
+ if (devErrors) {
157
+ const cause = devErrors.errorCause(error);
158
+ if (cause !== void 0) state["~error-cause"] = cause;
159
+ }
144
160
  errorEvent.context.nuxt = state;
145
161
  if (import.meta.prerender) event.context.nuxt = state;
146
162
  const rendered = await renderer.fetch(errorEvent).catch(() => null);
@@ -148,12 +164,32 @@ async function renderError(renderer, request, error, event) {
148
164
  const responseHeaders = new Headers(rendered.headers);
149
165
  for (const [name, value] of new Headers(headers)) responseHeaders.set(name, value);
150
166
  responseHeaders.set("content-type", "text/html;charset=utf-8");
167
+ if (devErrors && report && !import.meta.test) {
168
+ const html = await rendered.text();
169
+ const body = await devErrors.overlayErrorReport(html, report, request).catch(() => html);
170
+ return new Response(body, {
171
+ status,
172
+ statusText,
173
+ headers: responseHeaders
174
+ });
175
+ }
151
176
  return new Response(rendered.body, {
152
177
  status,
153
178
  statusText,
154
179
  headers: responseHeaders
155
180
  });
156
181
  }
182
+ if (devErrors && report) {
183
+ const page = await devErrors.renderReportPage(report, request).catch(() => void 0);
184
+ if (page) return new Response(page, {
185
+ status,
186
+ statusText,
187
+ headers: {
188
+ ...headers,
189
+ "content-type": "text/html;charset=utf-8"
190
+ }
191
+ });
192
+ }
157
193
  return new Response(message, {
158
194
  status,
159
195
  statusText,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nuxt/vite-server-nightly",
3
- "version": "4.6.0-29833429.e2a0e5da",
3
+ "version": "4.6.0-29836601.d5e5f1bd",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/nuxt/nuxt.git",
@@ -19,12 +19,13 @@
19
19
  "dist"
20
20
  ],
21
21
  "dependencies": {
22
- "@nuxt/kit": "npm:@nuxt/kit-nightly@4.6.0-29833429.e2a0e5da",
22
+ "@nuxt/kit": "npm:@nuxt/kit-nightly@4.6.0-29836601.d5e5f1bd",
23
23
  "clickable-path": "^0.1.1",
24
24
  "defu": "^6.1.7",
25
25
  "exsolve": "^1.1.1",
26
- "hookable": "^6.1.1",
26
+ "hookable": "^6.1.2",
27
27
  "mocked-exports": "^0.1.1",
28
+ "my-bad": "^0.2.7",
28
29
  "pathe": "^2.0.3",
29
30
  "rou3": "^0.9.2",
30
31
  "srvx": "1.0.3",
@@ -32,14 +33,14 @@
32
33
  "ultrahtml": "^1.7.0"
33
34
  },
34
35
  "devDependencies": {
35
- "@nuxt/schema": "npm:@nuxt/schema-nightly@4.6.0-29833429.e2a0e5da",
36
- "nuxt": "npm:nuxt-nightly@4.6.0-29833429.e2a0e5da",
36
+ "@nuxt/schema": "npm:@nuxt/schema-nightly@4.6.0-29836601.d5e5f1bd",
37
+ "nuxt": "npm:nuxt-nightly@4.6.0-29836601.d5e5f1bd",
37
38
  "tsdown": "0.23.0",
38
39
  "vite": "^8.3.0",
39
40
  "vitest": "5.0.1"
40
41
  },
41
42
  "peerDependencies": {
42
- "nuxt": "npm:nuxt-nightly@4.6.0-29833429.e2a0e5da",
43
+ "nuxt": "npm:nuxt-nightly@4.6.0-29836601.d5e5f1bd",
43
44
  "vite": "^8.3.0"
44
45
  },
45
46
  "engines": {