vinext 0.0.25 → 0.0.26
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/README.md +6 -1
- package/dist/check.js +4 -4
- package/dist/check.js.map +1 -1
- package/dist/cli.js +32 -1
- package/dist/cli.js.map +1 -1
- package/dist/client/entry.js.map +1 -1
- package/dist/client/vinext-next-data.d.ts +22 -0
- package/dist/client/vinext-next-data.d.ts.map +1 -0
- package/dist/client/vinext-next-data.js +2 -0
- package/dist/client/vinext-next-data.js.map +1 -0
- package/dist/config/config-matchers.d.ts.map +1 -1
- package/dist/config/config-matchers.js +6 -2
- package/dist/config/config-matchers.js.map +1 -1
- package/dist/config/next-config.d.ts +31 -4
- package/dist/config/next-config.d.ts.map +1 -1
- package/dist/config/next-config.js +151 -13
- package/dist/config/next-config.js.map +1 -1
- package/dist/deploy.d.ts +11 -0
- package/dist/deploy.d.ts.map +1 -1
- package/dist/deploy.js +42 -24
- package/dist/deploy.js.map +1 -1
- package/dist/entries/app-browser-entry.d.ts +9 -0
- package/dist/entries/app-browser-entry.d.ts.map +1 -0
- package/dist/entries/app-browser-entry.js +340 -0
- package/dist/entries/app-browser-entry.js.map +1 -0
- package/dist/{server/app-dev-server.d.ts → entries/app-rsc-entry.d.ts} +4 -17
- package/dist/entries/app-rsc-entry.d.ts.map +1 -0
- package/dist/{server/app-dev-server.js → entries/app-rsc-entry.js} +360 -1205
- package/dist/entries/app-rsc-entry.js.map +1 -0
- package/dist/entries/app-ssr-entry.d.ts +8 -0
- package/dist/entries/app-ssr-entry.d.ts.map +1 -0
- package/dist/entries/app-ssr-entry.js +449 -0
- package/dist/entries/app-ssr-entry.js.map +1 -0
- package/dist/entries/pages-client-entry.d.ts +4 -0
- package/dist/entries/pages-client-entry.d.ts.map +1 -0
- package/dist/entries/pages-client-entry.js +94 -0
- package/dist/entries/pages-client-entry.js.map +1 -0
- package/dist/entries/pages-entry-helpers.d.ts +7 -0
- package/dist/entries/pages-entry-helpers.d.ts.map +1 -0
- package/dist/entries/pages-entry-helpers.js +18 -0
- package/dist/entries/pages-entry-helpers.js.map +1 -0
- package/dist/entries/pages-server-entry.d.ts +8 -0
- package/dist/entries/pages-server-entry.d.ts.map +1 -0
- package/dist/entries/pages-server-entry.js +993 -0
- package/dist/entries/pages-server-entry.js.map +1 -0
- package/dist/index.d.ts +1 -25
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +206 -1242
- package/dist/index.js.map +1 -1
- package/dist/server/instrumentation.d.ts +1 -1
- package/dist/server/instrumentation.js +1 -1
- package/dist/server/instrumentation.js.map +1 -1
- package/dist/server/middleware-codegen.d.ts +1 -1
- package/dist/server/middleware-codegen.js +1 -1
- package/dist/server/middleware-codegen.js.map +1 -1
- package/dist/server/prod-server.d.ts.map +1 -1
- package/dist/server/prod-server.js +18 -3
- package/dist/server/prod-server.js.map +1 -1
- package/dist/server/request-pipeline.d.ts +92 -0
- package/dist/server/request-pipeline.d.ts.map +1 -0
- package/dist/server/request-pipeline.js +202 -0
- package/dist/server/request-pipeline.js.map +1 -0
- package/dist/shims/constants.d.ts +120 -3
- package/dist/shims/constants.d.ts.map +1 -1
- package/dist/shims/constants.js +170 -3
- package/dist/shims/constants.js.map +1 -1
- package/dist/shims/headers.d.ts.map +1 -1
- package/dist/shims/headers.js +1 -0
- package/dist/shims/headers.js.map +1 -1
- package/dist/shims/link.d.ts.map +1 -1
- package/dist/shims/link.js +2 -2
- package/dist/shims/link.js.map +1 -1
- package/dist/shims/metadata.d.ts +7 -1
- package/dist/shims/metadata.d.ts.map +1 -1
- package/dist/shims/metadata.js +9 -3
- package/dist/shims/metadata.js.map +1 -1
- package/dist/shims/og.d.ts +6 -6
- package/dist/shims/og.js +6 -6
- package/dist/shims/og.js.map +1 -1
- package/dist/utils/project.d.ts +15 -0
- package/dist/utils/project.d.ts.map +1 -1
- package/dist/utils/project.js +48 -0
- package/dist/utils/project.js.map +1 -1
- package/package.json +1 -1
- package/dist/server/app-dev-server.d.ts.map +0 -1
- package/dist/server/app-dev-server.js.map +0 -1
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generate the virtual SSR entry module.
|
|
3
|
+
*
|
|
4
|
+
* This runs in the `ssr` Vite environment. It receives an RSC stream,
|
|
5
|
+
* deserializes it to a React tree, and renders to HTML.
|
|
6
|
+
*/
|
|
7
|
+
export function generateSsrEntry() {
|
|
8
|
+
return `
|
|
9
|
+
import { createFromReadableStream } from "@vitejs/plugin-rsc/ssr";
|
|
10
|
+
import { renderToReadableStream, renderToStaticMarkup } from "react-dom/server.edge";
|
|
11
|
+
import { setNavigationContext, ServerInsertedHTMLContext } from "next/navigation";
|
|
12
|
+
import { runWithNavigationContext as _runWithNavCtx } from "vinext/navigation-state";
|
|
13
|
+
import { safeJsonStringify } from "vinext/html";
|
|
14
|
+
import { createElement as _ssrCE } from "react";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Collect all chunks from a ReadableStream into an array of text strings.
|
|
18
|
+
* Used to capture the RSC payload for embedding in HTML.
|
|
19
|
+
* The RSC flight protocol is text-based (line-delimited key:value pairs),
|
|
20
|
+
* so we decode to text strings instead of byte arrays — this is dramatically
|
|
21
|
+
* more compact when JSON-serialized into inline <script> tags.
|
|
22
|
+
*/
|
|
23
|
+
async function collectStreamChunks(stream) {
|
|
24
|
+
const reader = stream.getReader();
|
|
25
|
+
const decoder = new TextDecoder();
|
|
26
|
+
const chunks = [];
|
|
27
|
+
while (true) {
|
|
28
|
+
const { done, value } = await reader.read();
|
|
29
|
+
if (done) break;
|
|
30
|
+
// Decode Uint8Array to text string for compact JSON serialization
|
|
31
|
+
chunks.push(decoder.decode(value, { stream: true }));
|
|
32
|
+
}
|
|
33
|
+
return chunks;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// React 19 dev-mode workaround (see VinextFlightRoot in handleSsr):
|
|
37
|
+
//
|
|
38
|
+
// In dev, Flight error decoding in react-server-dom-webpack/client.edge
|
|
39
|
+
// can hit resolveErrorDev() which (via React's dev error stack capture)
|
|
40
|
+
// expects a non-null hooks dispatcher.
|
|
41
|
+
//
|
|
42
|
+
// Vinext previously called createFromReadableStream() outside of any React render.
|
|
43
|
+
// When an RSC stream contains an error, dev-mode decoding could crash with:
|
|
44
|
+
// - "Invalid hook call"
|
|
45
|
+
// - "Cannot read properties of null (reading 'useContext')"
|
|
46
|
+
//
|
|
47
|
+
// Fix: call createFromReadableStream() lazily inside a React component render.
|
|
48
|
+
// This mirrors Next.js behavior and ensures the dispatcher is set.
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Create a TransformStream that appends RSC chunks as inline <script> tags
|
|
52
|
+
* to the HTML stream. This allows progressive hydration — the browser receives
|
|
53
|
+
* RSC data incrementally as Suspense boundaries resolve, rather than waiting
|
|
54
|
+
* for the entire RSC payload before hydration can begin.
|
|
55
|
+
*
|
|
56
|
+
* Each chunk is written as:
|
|
57
|
+
* <script>self.__VINEXT_RSC_CHUNKS__=self.__VINEXT_RSC_CHUNKS__||[];self.__VINEXT_RSC_CHUNKS__.push("...")</script>
|
|
58
|
+
*
|
|
59
|
+
* Chunks are embedded as text strings (not byte arrays) since the RSC flight
|
|
60
|
+
* protocol is text-based. The browser entry encodes them back to Uint8Array.
|
|
61
|
+
* This is ~3x more compact than the previous byte-array format.
|
|
62
|
+
*/
|
|
63
|
+
function createRscEmbedTransform(embedStream) {
|
|
64
|
+
const reader = embedStream.getReader();
|
|
65
|
+
const _decoder = new TextDecoder();
|
|
66
|
+
let done = false;
|
|
67
|
+
let pendingChunks = [];
|
|
68
|
+
let reading = false;
|
|
69
|
+
|
|
70
|
+
// Fix invalid preload "as" values in RSC Flight hint lines before
|
|
71
|
+
// they reach the client. React Flight emits HL hints with
|
|
72
|
+
// as="stylesheet" for CSS, but the HTML spec requires as="style"
|
|
73
|
+
// for <link rel="preload">. The fixPreloadAs() below only fixes the
|
|
74
|
+
// server-rendered HTML stream; this fixes the raw Flight data that
|
|
75
|
+
// gets embedded as __VINEXT_RSC_CHUNKS__ and processed client-side.
|
|
76
|
+
function fixFlightHints(text) {
|
|
77
|
+
// Flight hint format: <id>:HL["url","stylesheet"] or with options
|
|
78
|
+
return text.replace(/(\\d+:HL\\[.*?),"stylesheet"(\\]|,)/g, '$1,"style"$2');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Start reading RSC chunks in the background, accumulating them as text strings.
|
|
82
|
+
// The RSC flight protocol is text-based, so decoding to strings and embedding
|
|
83
|
+
// as JSON strings is ~3x more compact than the byte-array format.
|
|
84
|
+
async function pumpReader() {
|
|
85
|
+
if (reading) return;
|
|
86
|
+
reading = true;
|
|
87
|
+
try {
|
|
88
|
+
while (true) {
|
|
89
|
+
const result = await reader.read();
|
|
90
|
+
if (result.done) {
|
|
91
|
+
done = true;
|
|
92
|
+
break;
|
|
93
|
+
}
|
|
94
|
+
const text = _decoder.decode(result.value, { stream: true });
|
|
95
|
+
pendingChunks.push(fixFlightHints(text));
|
|
96
|
+
}
|
|
97
|
+
} catch (err) {
|
|
98
|
+
if (process.env.NODE_ENV !== "production") {
|
|
99
|
+
console.warn("[vinext] RSC embed stream read error:", err);
|
|
100
|
+
}
|
|
101
|
+
done = true;
|
|
102
|
+
}
|
|
103
|
+
reading = false;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Fire off the background reader immediately
|
|
107
|
+
const pumpPromise = pumpReader();
|
|
108
|
+
|
|
109
|
+
return {
|
|
110
|
+
/**
|
|
111
|
+
* Flush any accumulated RSC chunks as <script> tags.
|
|
112
|
+
* Called after each HTML chunk is enqueued.
|
|
113
|
+
*/
|
|
114
|
+
flush() {
|
|
115
|
+
if (pendingChunks.length === 0) return "";
|
|
116
|
+
const chunks = pendingChunks;
|
|
117
|
+
pendingChunks = [];
|
|
118
|
+
let scripts = "";
|
|
119
|
+
for (const chunk of chunks) {
|
|
120
|
+
scripts += "<script>self.__VINEXT_RSC_CHUNKS__=self.__VINEXT_RSC_CHUNKS__||[];self.__VINEXT_RSC_CHUNKS__.push(" + safeJsonStringify(chunk) + ")</script>";
|
|
121
|
+
}
|
|
122
|
+
return scripts;
|
|
123
|
+
},
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Wait for the RSC stream to fully complete and return any final
|
|
127
|
+
* script tags plus the closing signal.
|
|
128
|
+
*/
|
|
129
|
+
async finalize() {
|
|
130
|
+
await pumpPromise;
|
|
131
|
+
let scripts = this.flush();
|
|
132
|
+
// Signal that all RSC chunks have been sent.
|
|
133
|
+
// Params are already embedded in <head> — no need to include here.
|
|
134
|
+
scripts += "<script>self.__VINEXT_RSC_DONE__=true</script>";
|
|
135
|
+
return scripts;
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Render the RSC stream to HTML.
|
|
142
|
+
*
|
|
143
|
+
* @param rscStream - The RSC payload stream from the RSC environment
|
|
144
|
+
* @param navContext - Navigation context for client component SSR hooks.
|
|
145
|
+
* "use client" components like those using usePathname() need the current
|
|
146
|
+
* request URL during SSR, and they run in this SSR environment (separate
|
|
147
|
+
* from the RSC environment where the context was originally set).
|
|
148
|
+
* @param fontData - Font links and styles collected from the RSC environment.
|
|
149
|
+
* Fonts are loaded during RSC rendering (when layout calls Geist() etc.),
|
|
150
|
+
* and the data needs to be passed to SSR since they're separate module instances.
|
|
151
|
+
*/
|
|
152
|
+
export async function handleSsr(rscStream, navContext, fontData) {
|
|
153
|
+
// Wrap in a navigation ALS scope for per-request isolation in the SSR
|
|
154
|
+
// environment. The SSR environment has separate module instances from RSC,
|
|
155
|
+
// so it needs its own ALS scope.
|
|
156
|
+
return _runWithNavCtx(async () => {
|
|
157
|
+
// Set navigation context so hooks like usePathname() work during SSR
|
|
158
|
+
// of "use client" components
|
|
159
|
+
if (navContext) {
|
|
160
|
+
setNavigationContext(navContext);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// Clear any stale callbacks from previous requests
|
|
164
|
+
const { clearServerInsertedHTML, flushServerInsertedHTML, useServerInsertedHTML: _addInsertedHTML } = await import("next/navigation");
|
|
165
|
+
clearServerInsertedHTML();
|
|
166
|
+
|
|
167
|
+
try {
|
|
168
|
+
// Tee the RSC stream - one for SSR rendering, one for embedding in HTML.
|
|
169
|
+
// This ensures the browser uses the SAME RSC payload for hydration that
|
|
170
|
+
// was used to generate the HTML, avoiding hydration mismatches (React #418).
|
|
171
|
+
const [ssrStream, embedStream] = rscStream.tee();
|
|
172
|
+
|
|
173
|
+
// Create the progressive RSC embed helper — it reads the embed stream
|
|
174
|
+
// in the background and provides script tags to inject into the HTML stream.
|
|
175
|
+
const rscEmbed = createRscEmbedTransform(embedStream);
|
|
176
|
+
|
|
177
|
+
// Deserialize RSC stream back to React VDOM.
|
|
178
|
+
// IMPORTANT: Do NOT await this — createFromReadableStream returns a thenable
|
|
179
|
+
// that React's renderToReadableStream can consume progressively. By passing
|
|
180
|
+
// the unresolved thenable, React will render Suspense fallbacks (loading.tsx)
|
|
181
|
+
// immediately in the HTML shell, then stream in resolved content as RSC
|
|
182
|
+
// chunks arrive. Awaiting here would block until all async server components
|
|
183
|
+
// complete, collapsing the streaming behavior.
|
|
184
|
+
// Lazily create the Flight root inside render so React's hook dispatcher is set
|
|
185
|
+
// (avoids React 19 dev-mode resolveErrorDev() crash). VinextFlightRoot returns
|
|
186
|
+
// a thenable (not a ReactNode), which React 19 consumes via its internal
|
|
187
|
+
// thenable-as-child suspend/resume behavior. This matches Next.js's approach.
|
|
188
|
+
let flightRoot;
|
|
189
|
+
function VinextFlightRoot() {
|
|
190
|
+
if (!flightRoot) {
|
|
191
|
+
flightRoot = createFromReadableStream(ssrStream);
|
|
192
|
+
}
|
|
193
|
+
return flightRoot;
|
|
194
|
+
}
|
|
195
|
+
const root = _ssrCE(VinextFlightRoot);
|
|
196
|
+
|
|
197
|
+
// Wrap with ServerInsertedHTMLContext.Provider so libraries that use
|
|
198
|
+
// useContext(ServerInsertedHTMLContext) (Apollo Client, styled-components,
|
|
199
|
+
// etc.) get a working callback registration function during SSR.
|
|
200
|
+
// The provider value is useServerInsertedHTML — same function that direct
|
|
201
|
+
// callers use — so both paths push to the same ALS-backed callback array.
|
|
202
|
+
const ssrRoot = ServerInsertedHTMLContext
|
|
203
|
+
? _ssrCE(ServerInsertedHTMLContext.Provider, { value: _addInsertedHTML }, root)
|
|
204
|
+
: root;
|
|
205
|
+
|
|
206
|
+
// Get the bootstrap script content for the browser entry
|
|
207
|
+
const bootstrapScriptContent =
|
|
208
|
+
await import.meta.viteRsc.loadBootstrapScriptContent("index");
|
|
209
|
+
|
|
210
|
+
// djb2 hash for digest generation in the SSR environment.
|
|
211
|
+
// Matches the RSC environment's __errorDigest function.
|
|
212
|
+
function ssrErrorDigest(str) {
|
|
213
|
+
let hash = 5381;
|
|
214
|
+
for (let i = str.length - 1; i >= 0; i--) {
|
|
215
|
+
hash = (hash * 33) ^ str.charCodeAt(i);
|
|
216
|
+
}
|
|
217
|
+
return (hash >>> 0).toString();
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// Render HTML (streaming SSR)
|
|
221
|
+
// useServerInsertedHTML callbacks are registered during this render.
|
|
222
|
+
// The onError callback preserves the digest for Next.js navigation errors
|
|
223
|
+
// (redirect, notFound, forbidden, unauthorized) thrown inside Suspense
|
|
224
|
+
// boundaries during RSC streaming. Without this, React's default onError
|
|
225
|
+
// returns undefined and the digest is lost in the $RX() call, preventing
|
|
226
|
+
// client-side error boundaries from identifying the error type.
|
|
227
|
+
// In production, non-navigation errors also get a digest hash so they
|
|
228
|
+
// can be correlated with server logs without leaking details to clients.
|
|
229
|
+
const htmlStream = await renderToReadableStream(ssrRoot, {
|
|
230
|
+
bootstrapScriptContent,
|
|
231
|
+
onError(error) {
|
|
232
|
+
if (error && typeof error === "object" && "digest" in error) {
|
|
233
|
+
return String(error.digest);
|
|
234
|
+
}
|
|
235
|
+
// In production, generate a digest hash for non-navigation errors
|
|
236
|
+
if (process.env.NODE_ENV === "production" && error) {
|
|
237
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
238
|
+
const stack = error instanceof Error ? (error.stack || "") : "";
|
|
239
|
+
return ssrErrorDigest(msg + stack);
|
|
240
|
+
}
|
|
241
|
+
return undefined;
|
|
242
|
+
},
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
// Flush useServerInsertedHTML callbacks (CSS-in-JS style injection)
|
|
246
|
+
const insertedElements = flushServerInsertedHTML();
|
|
247
|
+
|
|
248
|
+
// Render the inserted elements to HTML strings
|
|
249
|
+
const { Fragment } = await import("react");
|
|
250
|
+
let insertedHTML = "";
|
|
251
|
+
for (const el of insertedElements) {
|
|
252
|
+
try {
|
|
253
|
+
insertedHTML += renderToStaticMarkup(_ssrCE(Fragment, null, el));
|
|
254
|
+
} catch {
|
|
255
|
+
// Skip elements that can't be rendered
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// Escape HTML attribute values (defense-in-depth for font URLs/types).
|
|
260
|
+
function _escAttr(s) { return s.replace(/&/g, "&").replace(/"/g, """); }
|
|
261
|
+
|
|
262
|
+
// Build font HTML from data passed from RSC environment
|
|
263
|
+
// (Fonts are loaded during RSC rendering, and RSC/SSR are separate module instances)
|
|
264
|
+
let fontHTML = "";
|
|
265
|
+
if (fontData) {
|
|
266
|
+
if (fontData.links && fontData.links.length > 0) {
|
|
267
|
+
for (const url of fontData.links) {
|
|
268
|
+
fontHTML += '<link rel="stylesheet" href="' + _escAttr(url) + '" />\\n';
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
// Emit <link rel="preload"> for local font files
|
|
272
|
+
if (fontData.preloads && fontData.preloads.length > 0) {
|
|
273
|
+
for (const preload of fontData.preloads) {
|
|
274
|
+
fontHTML += '<link rel="preload" href="' + _escAttr(preload.href) + '" as="font" type="' + _escAttr(preload.type) + '" crossorigin />\\n';
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
if (fontData.styles && fontData.styles.length > 0) {
|
|
278
|
+
fontHTML += '<style data-vinext-fonts>' + fontData.styles.join("\\n") + '</style>\\n';
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// Extract client entry module URL from bootstrapScriptContent to emit
|
|
283
|
+
// a <link rel="modulepreload"> hint. The RSC plugin formats bootstrap
|
|
284
|
+
// content as: import("URL") — we extract the URL so the browser can
|
|
285
|
+
// speculatively fetch and parse the JS module while still processing
|
|
286
|
+
// the HTML body, instead of waiting until it reaches the inline script.
|
|
287
|
+
let modulePreloadHTML = "";
|
|
288
|
+
if (bootstrapScriptContent) {
|
|
289
|
+
const m = bootstrapScriptContent.match(/import\\("([^"]+)"\\)/);
|
|
290
|
+
if (m && m[1]) {
|
|
291
|
+
modulePreloadHTML = '<link rel="modulepreload" href="' + _escAttr(m[1]) + '" />\\n';
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// Head-injected HTML: server-inserted HTML, font HTML, route params,
|
|
296
|
+
// and modulepreload hints.
|
|
297
|
+
// RSC payload is now embedded progressively via script tags in the body stream.
|
|
298
|
+
// Params are embedded eagerly in <head> so they're available before client
|
|
299
|
+
// hydration starts, avoiding the need for polling on the client.
|
|
300
|
+
const paramsScript = '<script>self.__VINEXT_RSC_PARAMS__=' + safeJsonStringify(navContext?.params || {}) + '</script>';
|
|
301
|
+
// Embed the initial navigation context (pathname + searchParams) so the
|
|
302
|
+
// browser useSyncExternalStore getServerSnapshot can return the correct
|
|
303
|
+
// value during hydration. Without this, getServerSnapshot returns "/" and
|
|
304
|
+
// React detects a mismatch against the SSR-rendered HTML.
|
|
305
|
+
// Serialise searchParams as an array of [key, value] pairs to preserve
|
|
306
|
+
// duplicate keys (e.g. ?tag=a&tag=b). Object.fromEntries() would keep
|
|
307
|
+
// only the last value, causing a hydration mismatch for multi-value params.
|
|
308
|
+
const __navPayload = { pathname: navContext?.pathname ?? '/', searchParams: navContext?.searchParams ? [...navContext.searchParams.entries()] : [] };
|
|
309
|
+
const navScript = '<script>self.__VINEXT_RSC_NAV__=' + safeJsonStringify(__navPayload) + '</script>';
|
|
310
|
+
const injectHTML = paramsScript + navScript + modulePreloadHTML + insertedHTML + fontHTML;
|
|
311
|
+
|
|
312
|
+
// Inject the collected HTML before </head> and progressively embed RSC
|
|
313
|
+
// chunks as script tags throughout the HTML body stream.
|
|
314
|
+
const decoder = new TextDecoder();
|
|
315
|
+
const encoder = new TextEncoder();
|
|
316
|
+
let injected = false;
|
|
317
|
+
|
|
318
|
+
// Fix invalid preload "as" values in server-rendered HTML.
|
|
319
|
+
// React Fizz emits <link rel="preload" as="stylesheet"> for CSS,
|
|
320
|
+
// but the HTML spec requires as="style" for <link rel="preload">.
|
|
321
|
+
// Note: fixFlightHints() in createRscEmbedTransform handles the
|
|
322
|
+
// complementary case — fixing the raw Flight stream data before
|
|
323
|
+
// it's embedded as __VINEXT_RSC_CHUNKS__ for client-side processing.
|
|
324
|
+
// See: https://html.spec.whatwg.org/multipage/links.html#link-type-preload
|
|
325
|
+
function fixPreloadAs(html) {
|
|
326
|
+
// Match <link ...rel="preload"... as="stylesheet"...> in any attribute order
|
|
327
|
+
return html.replace(/<link(?=[^>]*\\srel="preload")[^>]*>/g, function(tag) {
|
|
328
|
+
return tag.replace(' as="stylesheet"', ' as="style"');
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// Tick-buffered RSC script injection.
|
|
333
|
+
//
|
|
334
|
+
// React's renderToReadableStream (Fizz) flushes chunks synchronously
|
|
335
|
+
// within one microtask — all chunks from a single flushCompletedQueues
|
|
336
|
+
// call arrive in the same macrotask. We buffer HTML chunks as they
|
|
337
|
+
// arrive, then use setTimeout(0) to defer emitting them plus any
|
|
338
|
+
// accumulated RSC scripts to the next macrotask. This guarantees we
|
|
339
|
+
// never inject <script> tags between partial HTML chunks (which would
|
|
340
|
+
// corrupt split elements like "<linearGradi" + "ent>"), while still
|
|
341
|
+
// delivering RSC data progressively as Suspense boundaries resolve.
|
|
342
|
+
//
|
|
343
|
+
// Reference: rsc-html-stream by Devon Govett (credited by Next.js)
|
|
344
|
+
// https://github.com/devongovett/rsc-html-stream
|
|
345
|
+
let buffered = [];
|
|
346
|
+
let timeoutId = null;
|
|
347
|
+
|
|
348
|
+
const transform = new TransformStream({
|
|
349
|
+
transform(chunk, controller) {
|
|
350
|
+
const text = decoder.decode(chunk, { stream: true });
|
|
351
|
+
const fixed = fixPreloadAs(text);
|
|
352
|
+
buffered.push(fixed);
|
|
353
|
+
|
|
354
|
+
if (timeoutId !== null) return;
|
|
355
|
+
|
|
356
|
+
timeoutId = setTimeout(() => {
|
|
357
|
+
// Flush all buffered HTML chunks from this React flush cycle
|
|
358
|
+
for (const buf of buffered) {
|
|
359
|
+
if (!injected) {
|
|
360
|
+
const headEnd = buf.indexOf("</head>");
|
|
361
|
+
if (headEnd !== -1) {
|
|
362
|
+
const before = buf.slice(0, headEnd);
|
|
363
|
+
const after = buf.slice(headEnd);
|
|
364
|
+
controller.enqueue(encoder.encode(before + injectHTML + after));
|
|
365
|
+
injected = true;
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
controller.enqueue(encoder.encode(buf));
|
|
370
|
+
}
|
|
371
|
+
buffered = [];
|
|
372
|
+
|
|
373
|
+
// Now safe to inject any accumulated RSC scripts — we're between
|
|
374
|
+
// React flush cycles, so no partial HTML chunks can follow until
|
|
375
|
+
// the next macrotask.
|
|
376
|
+
const rscScripts = rscEmbed.flush();
|
|
377
|
+
if (rscScripts) {
|
|
378
|
+
controller.enqueue(encoder.encode(rscScripts));
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
timeoutId = null;
|
|
382
|
+
}, 0);
|
|
383
|
+
},
|
|
384
|
+
async flush(controller) {
|
|
385
|
+
// Cancel any pending setTimeout callback — flush() drains
|
|
386
|
+
// everything itself, so the callback would be a no-op but
|
|
387
|
+
// cancelling makes the code obviously correct.
|
|
388
|
+
if (timeoutId !== null) {
|
|
389
|
+
clearTimeout(timeoutId);
|
|
390
|
+
timeoutId = null;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// Flush any remaining buffered HTML chunks
|
|
394
|
+
for (const buf of buffered) {
|
|
395
|
+
if (!injected) {
|
|
396
|
+
const headEnd = buf.indexOf("</head>");
|
|
397
|
+
if (headEnd !== -1) {
|
|
398
|
+
const before = buf.slice(0, headEnd);
|
|
399
|
+
const after = buf.slice(headEnd);
|
|
400
|
+
controller.enqueue(encoder.encode(before + injectHTML + after));
|
|
401
|
+
injected = true;
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
controller.enqueue(encoder.encode(buf));
|
|
406
|
+
}
|
|
407
|
+
buffered = [];
|
|
408
|
+
|
|
409
|
+
if (!injected && injectHTML) {
|
|
410
|
+
controller.enqueue(encoder.encode(injectHTML));
|
|
411
|
+
}
|
|
412
|
+
// Finalize: wait for the RSC stream to complete and emit remaining
|
|
413
|
+
// chunks plus the __VINEXT_RSC_DONE__ signal.
|
|
414
|
+
const finalScripts = await rscEmbed.finalize();
|
|
415
|
+
if (finalScripts) {
|
|
416
|
+
controller.enqueue(encoder.encode(finalScripts));
|
|
417
|
+
}
|
|
418
|
+
},
|
|
419
|
+
});
|
|
420
|
+
|
|
421
|
+
return htmlStream.pipeThrough(transform);
|
|
422
|
+
} finally {
|
|
423
|
+
// Clean up so we don't leak context between requests
|
|
424
|
+
setNavigationContext(null);
|
|
425
|
+
clearServerInsertedHTML();
|
|
426
|
+
}
|
|
427
|
+
}); // end _runWithNavCtx
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
export default {
|
|
431
|
+
async fetch(request) {
|
|
432
|
+
const url = new URL(request.url);
|
|
433
|
+
if (url.pathname.startsWith("//")) {
|
|
434
|
+
return new Response("404 Not Found", { status: 404 });
|
|
435
|
+
}
|
|
436
|
+
const rscModule = await import.meta.viteRsc.loadModule("rsc", "index");
|
|
437
|
+
const result = await rscModule.default(request);
|
|
438
|
+
if (result instanceof Response) {
|
|
439
|
+
return result;
|
|
440
|
+
}
|
|
441
|
+
if (result === null || result === undefined) {
|
|
442
|
+
return new Response("Not Found", { status: 404 });
|
|
443
|
+
}
|
|
444
|
+
return new Response(String(result), { status: 200 });
|
|
445
|
+
},
|
|
446
|
+
};
|
|
447
|
+
`;
|
|
448
|
+
}
|
|
449
|
+
//# sourceMappingURL=app-ssr-entry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"app-ssr-entry.js","sourceRoot":"","sources":["../../src/entries/app-ssr-entry.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,UAAU,gBAAgB;IAC9B,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAubR,CAAC;AACF,CAAC","sourcesContent":["/**\n * Generate the virtual SSR entry module.\n *\n * This runs in the `ssr` Vite environment. It receives an RSC stream,\n * deserializes it to a React tree, and renders to HTML.\n */\nexport function generateSsrEntry(): string {\n return `\nimport { createFromReadableStream } from \"@vitejs/plugin-rsc/ssr\";\nimport { renderToReadableStream, renderToStaticMarkup } from \"react-dom/server.edge\";\nimport { setNavigationContext, ServerInsertedHTMLContext } from \"next/navigation\";\nimport { runWithNavigationContext as _runWithNavCtx } from \"vinext/navigation-state\";\nimport { safeJsonStringify } from \"vinext/html\";\nimport { createElement as _ssrCE } from \"react\";\n\n/**\n * Collect all chunks from a ReadableStream into an array of text strings.\n * Used to capture the RSC payload for embedding in HTML.\n * The RSC flight protocol is text-based (line-delimited key:value pairs),\n * so we decode to text strings instead of byte arrays — this is dramatically\n * more compact when JSON-serialized into inline <script> tags.\n */\nasync function collectStreamChunks(stream) {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n const chunks = [];\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n // Decode Uint8Array to text string for compact JSON serialization\n chunks.push(decoder.decode(value, { stream: true }));\n }\n return chunks;\n}\n\n// React 19 dev-mode workaround (see VinextFlightRoot in handleSsr):\n//\n// In dev, Flight error decoding in react-server-dom-webpack/client.edge\n// can hit resolveErrorDev() which (via React's dev error stack capture)\n// expects a non-null hooks dispatcher.\n//\n// Vinext previously called createFromReadableStream() outside of any React render.\n// When an RSC stream contains an error, dev-mode decoding could crash with:\n// - \"Invalid hook call\"\n// - \"Cannot read properties of null (reading 'useContext')\"\n//\n// Fix: call createFromReadableStream() lazily inside a React component render.\n// This mirrors Next.js behavior and ensures the dispatcher is set.\n\n/**\n * Create a TransformStream that appends RSC chunks as inline <script> tags\n * to the HTML stream. This allows progressive hydration — the browser receives\n * RSC data incrementally as Suspense boundaries resolve, rather than waiting\n * for the entire RSC payload before hydration can begin.\n *\n * Each chunk is written as:\n * <script>self.__VINEXT_RSC_CHUNKS__=self.__VINEXT_RSC_CHUNKS__||[];self.__VINEXT_RSC_CHUNKS__.push(\"...\")</script>\n *\n * Chunks are embedded as text strings (not byte arrays) since the RSC flight\n * protocol is text-based. The browser entry encodes them back to Uint8Array.\n * This is ~3x more compact than the previous byte-array format.\n */\nfunction createRscEmbedTransform(embedStream) {\n const reader = embedStream.getReader();\n const _decoder = new TextDecoder();\n let done = false;\n let pendingChunks = [];\n let reading = false;\n\n // Fix invalid preload \"as\" values in RSC Flight hint lines before\n // they reach the client. React Flight emits HL hints with\n // as=\"stylesheet\" for CSS, but the HTML spec requires as=\"style\"\n // for <link rel=\"preload\">. The fixPreloadAs() below only fixes the\n // server-rendered HTML stream; this fixes the raw Flight data that\n // gets embedded as __VINEXT_RSC_CHUNKS__ and processed client-side.\n function fixFlightHints(text) {\n // Flight hint format: <id>:HL[\"url\",\"stylesheet\"] or with options\n return text.replace(/(\\\\d+:HL\\\\[.*?),\"stylesheet\"(\\\\]|,)/g, '$1,\"style\"$2');\n }\n\n // Start reading RSC chunks in the background, accumulating them as text strings.\n // The RSC flight protocol is text-based, so decoding to strings and embedding\n // as JSON strings is ~3x more compact than the byte-array format.\n async function pumpReader() {\n if (reading) return;\n reading = true;\n try {\n while (true) {\n const result = await reader.read();\n if (result.done) {\n done = true;\n break;\n }\n const text = _decoder.decode(result.value, { stream: true });\n pendingChunks.push(fixFlightHints(text));\n }\n } catch (err) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\"[vinext] RSC embed stream read error:\", err);\n }\n done = true;\n }\n reading = false;\n }\n\n // Fire off the background reader immediately\n const pumpPromise = pumpReader();\n\n return {\n /**\n * Flush any accumulated RSC chunks as <script> tags.\n * Called after each HTML chunk is enqueued.\n */\n flush() {\n if (pendingChunks.length === 0) return \"\";\n const chunks = pendingChunks;\n pendingChunks = [];\n let scripts = \"\";\n for (const chunk of chunks) {\n scripts += \"<script>self.__VINEXT_RSC_CHUNKS__=self.__VINEXT_RSC_CHUNKS__||[];self.__VINEXT_RSC_CHUNKS__.push(\" + safeJsonStringify(chunk) + \")</script>\";\n }\n return scripts;\n },\n\n /**\n * Wait for the RSC stream to fully complete and return any final\n * script tags plus the closing signal.\n */\n async finalize() {\n await pumpPromise;\n let scripts = this.flush();\n // Signal that all RSC chunks have been sent.\n // Params are already embedded in <head> — no need to include here.\n scripts += \"<script>self.__VINEXT_RSC_DONE__=true</script>\";\n return scripts;\n },\n };\n}\n\n/**\n * Render the RSC stream to HTML.\n *\n * @param rscStream - The RSC payload stream from the RSC environment\n * @param navContext - Navigation context for client component SSR hooks.\n * \"use client\" components like those using usePathname() need the current\n * request URL during SSR, and they run in this SSR environment (separate\n * from the RSC environment where the context was originally set).\n * @param fontData - Font links and styles collected from the RSC environment.\n * Fonts are loaded during RSC rendering (when layout calls Geist() etc.),\n * and the data needs to be passed to SSR since they're separate module instances.\n */\nexport async function handleSsr(rscStream, navContext, fontData) {\n // Wrap in a navigation ALS scope for per-request isolation in the SSR\n // environment. The SSR environment has separate module instances from RSC,\n // so it needs its own ALS scope.\n return _runWithNavCtx(async () => {\n // Set navigation context so hooks like usePathname() work during SSR\n // of \"use client\" components\n if (navContext) {\n setNavigationContext(navContext);\n }\n\n // Clear any stale callbacks from previous requests\n const { clearServerInsertedHTML, flushServerInsertedHTML, useServerInsertedHTML: _addInsertedHTML } = await import(\"next/navigation\");\n clearServerInsertedHTML();\n\n try {\n // Tee the RSC stream - one for SSR rendering, one for embedding in HTML.\n // This ensures the browser uses the SAME RSC payload for hydration that\n // was used to generate the HTML, avoiding hydration mismatches (React #418).\n const [ssrStream, embedStream] = rscStream.tee();\n\n // Create the progressive RSC embed helper — it reads the embed stream\n // in the background and provides script tags to inject into the HTML stream.\n const rscEmbed = createRscEmbedTransform(embedStream);\n\n // Deserialize RSC stream back to React VDOM.\n // IMPORTANT: Do NOT await this — createFromReadableStream returns a thenable\n // that React's renderToReadableStream can consume progressively. By passing\n // the unresolved thenable, React will render Suspense fallbacks (loading.tsx)\n // immediately in the HTML shell, then stream in resolved content as RSC\n // chunks arrive. Awaiting here would block until all async server components\n // complete, collapsing the streaming behavior.\n // Lazily create the Flight root inside render so React's hook dispatcher is set\n // (avoids React 19 dev-mode resolveErrorDev() crash). VinextFlightRoot returns\n // a thenable (not a ReactNode), which React 19 consumes via its internal\n // thenable-as-child suspend/resume behavior. This matches Next.js's approach.\n let flightRoot;\n function VinextFlightRoot() {\n if (!flightRoot) {\n flightRoot = createFromReadableStream(ssrStream);\n }\n return flightRoot;\n }\n const root = _ssrCE(VinextFlightRoot);\n\n // Wrap with ServerInsertedHTMLContext.Provider so libraries that use\n // useContext(ServerInsertedHTMLContext) (Apollo Client, styled-components,\n // etc.) get a working callback registration function during SSR.\n // The provider value is useServerInsertedHTML — same function that direct\n // callers use — so both paths push to the same ALS-backed callback array.\n const ssrRoot = ServerInsertedHTMLContext\n ? _ssrCE(ServerInsertedHTMLContext.Provider, { value: _addInsertedHTML }, root)\n : root;\n\n // Get the bootstrap script content for the browser entry\n const bootstrapScriptContent =\n await import.meta.viteRsc.loadBootstrapScriptContent(\"index\");\n\n // djb2 hash for digest generation in the SSR environment.\n // Matches the RSC environment's __errorDigest function.\n function ssrErrorDigest(str) {\n let hash = 5381;\n for (let i = str.length - 1; i >= 0; i--) {\n hash = (hash * 33) ^ str.charCodeAt(i);\n }\n return (hash >>> 0).toString();\n }\n\n // Render HTML (streaming SSR)\n // useServerInsertedHTML callbacks are registered during this render.\n // The onError callback preserves the digest for Next.js navigation errors\n // (redirect, notFound, forbidden, unauthorized) thrown inside Suspense\n // boundaries during RSC streaming. Without this, React's default onError\n // returns undefined and the digest is lost in the $RX() call, preventing\n // client-side error boundaries from identifying the error type.\n // In production, non-navigation errors also get a digest hash so they\n // can be correlated with server logs without leaking details to clients.\n const htmlStream = await renderToReadableStream(ssrRoot, {\n bootstrapScriptContent,\n onError(error) {\n if (error && typeof error === \"object\" && \"digest\" in error) {\n return String(error.digest);\n }\n // In production, generate a digest hash for non-navigation errors\n if (process.env.NODE_ENV === \"production\" && error) {\n const msg = error instanceof Error ? error.message : String(error);\n const stack = error instanceof Error ? (error.stack || \"\") : \"\";\n return ssrErrorDigest(msg + stack);\n }\n return undefined;\n },\n });\n\n // Flush useServerInsertedHTML callbacks (CSS-in-JS style injection)\n const insertedElements = flushServerInsertedHTML();\n\n // Render the inserted elements to HTML strings\n const { Fragment } = await import(\"react\");\n let insertedHTML = \"\";\n for (const el of insertedElements) {\n try {\n insertedHTML += renderToStaticMarkup(_ssrCE(Fragment, null, el));\n } catch {\n // Skip elements that can't be rendered\n }\n }\n\n // Escape HTML attribute values (defense-in-depth for font URLs/types).\n function _escAttr(s) { return s.replace(/&/g, \"&\").replace(/\"/g, \""\"); }\n\n // Build font HTML from data passed from RSC environment\n // (Fonts are loaded during RSC rendering, and RSC/SSR are separate module instances)\n let fontHTML = \"\";\n if (fontData) {\n if (fontData.links && fontData.links.length > 0) {\n for (const url of fontData.links) {\n fontHTML += '<link rel=\"stylesheet\" href=\"' + _escAttr(url) + '\" />\\\\n';\n }\n }\n // Emit <link rel=\"preload\"> for local font files\n if (fontData.preloads && fontData.preloads.length > 0) {\n for (const preload of fontData.preloads) {\n fontHTML += '<link rel=\"preload\" href=\"' + _escAttr(preload.href) + '\" as=\"font\" type=\"' + _escAttr(preload.type) + '\" crossorigin />\\\\n';\n }\n }\n if (fontData.styles && fontData.styles.length > 0) {\n fontHTML += '<style data-vinext-fonts>' + fontData.styles.join(\"\\\\n\") + '</style>\\\\n';\n }\n }\n\n // Extract client entry module URL from bootstrapScriptContent to emit\n // a <link rel=\"modulepreload\"> hint. The RSC plugin formats bootstrap\n // content as: import(\"URL\") — we extract the URL so the browser can\n // speculatively fetch and parse the JS module while still processing\n // the HTML body, instead of waiting until it reaches the inline script.\n let modulePreloadHTML = \"\";\n if (bootstrapScriptContent) {\n const m = bootstrapScriptContent.match(/import\\\\(\"([^\"]+)\"\\\\)/);\n if (m && m[1]) {\n modulePreloadHTML = '<link rel=\"modulepreload\" href=\"' + _escAttr(m[1]) + '\" />\\\\n';\n }\n }\n\n // Head-injected HTML: server-inserted HTML, font HTML, route params,\n // and modulepreload hints.\n // RSC payload is now embedded progressively via script tags in the body stream.\n // Params are embedded eagerly in <head> so they're available before client\n // hydration starts, avoiding the need for polling on the client.\n const paramsScript = '<script>self.__VINEXT_RSC_PARAMS__=' + safeJsonStringify(navContext?.params || {}) + '</script>';\n // Embed the initial navigation context (pathname + searchParams) so the\n // browser useSyncExternalStore getServerSnapshot can return the correct\n // value during hydration. Without this, getServerSnapshot returns \"/\" and\n // React detects a mismatch against the SSR-rendered HTML.\n // Serialise searchParams as an array of [key, value] pairs to preserve\n // duplicate keys (e.g. ?tag=a&tag=b). Object.fromEntries() would keep\n // only the last value, causing a hydration mismatch for multi-value params.\n const __navPayload = { pathname: navContext?.pathname ?? '/', searchParams: navContext?.searchParams ? [...navContext.searchParams.entries()] : [] };\n const navScript = '<script>self.__VINEXT_RSC_NAV__=' + safeJsonStringify(__navPayload) + '</script>';\n const injectHTML = paramsScript + navScript + modulePreloadHTML + insertedHTML + fontHTML;\n\n // Inject the collected HTML before </head> and progressively embed RSC\n // chunks as script tags throughout the HTML body stream.\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n let injected = false;\n\n // Fix invalid preload \"as\" values in server-rendered HTML.\n // React Fizz emits <link rel=\"preload\" as=\"stylesheet\"> for CSS,\n // but the HTML spec requires as=\"style\" for <link rel=\"preload\">.\n // Note: fixFlightHints() in createRscEmbedTransform handles the\n // complementary case — fixing the raw Flight stream data before\n // it's embedded as __VINEXT_RSC_CHUNKS__ for client-side processing.\n // See: https://html.spec.whatwg.org/multipage/links.html#link-type-preload\n function fixPreloadAs(html) {\n // Match <link ...rel=\"preload\"... as=\"stylesheet\"...> in any attribute order\n return html.replace(/<link(?=[^>]*\\\\srel=\"preload\")[^>]*>/g, function(tag) {\n return tag.replace(' as=\"stylesheet\"', ' as=\"style\"');\n });\n }\n\n // Tick-buffered RSC script injection.\n //\n // React's renderToReadableStream (Fizz) flushes chunks synchronously\n // within one microtask — all chunks from a single flushCompletedQueues\n // call arrive in the same macrotask. We buffer HTML chunks as they\n // arrive, then use setTimeout(0) to defer emitting them plus any\n // accumulated RSC scripts to the next macrotask. This guarantees we\n // never inject <script> tags between partial HTML chunks (which would\n // corrupt split elements like \"<linearGradi\" + \"ent>\"), while still\n // delivering RSC data progressively as Suspense boundaries resolve.\n //\n // Reference: rsc-html-stream by Devon Govett (credited by Next.js)\n // https://github.com/devongovett/rsc-html-stream\n let buffered = [];\n let timeoutId = null;\n\n const transform = new TransformStream({\n transform(chunk, controller) {\n const text = decoder.decode(chunk, { stream: true });\n const fixed = fixPreloadAs(text);\n buffered.push(fixed);\n\n if (timeoutId !== null) return;\n\n timeoutId = setTimeout(() => {\n // Flush all buffered HTML chunks from this React flush cycle\n for (const buf of buffered) {\n if (!injected) {\n const headEnd = buf.indexOf(\"</head>\");\n if (headEnd !== -1) {\n const before = buf.slice(0, headEnd);\n const after = buf.slice(headEnd);\n controller.enqueue(encoder.encode(before + injectHTML + after));\n injected = true;\n continue;\n }\n }\n controller.enqueue(encoder.encode(buf));\n }\n buffered = [];\n\n // Now safe to inject any accumulated RSC scripts — we're between\n // React flush cycles, so no partial HTML chunks can follow until\n // the next macrotask.\n const rscScripts = rscEmbed.flush();\n if (rscScripts) {\n controller.enqueue(encoder.encode(rscScripts));\n }\n\n timeoutId = null;\n }, 0);\n },\n async flush(controller) {\n // Cancel any pending setTimeout callback — flush() drains\n // everything itself, so the callback would be a no-op but\n // cancelling makes the code obviously correct.\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n\n // Flush any remaining buffered HTML chunks\n for (const buf of buffered) {\n if (!injected) {\n const headEnd = buf.indexOf(\"</head>\");\n if (headEnd !== -1) {\n const before = buf.slice(0, headEnd);\n const after = buf.slice(headEnd);\n controller.enqueue(encoder.encode(before + injectHTML + after));\n injected = true;\n continue;\n }\n }\n controller.enqueue(encoder.encode(buf));\n }\n buffered = [];\n\n if (!injected && injectHTML) {\n controller.enqueue(encoder.encode(injectHTML));\n }\n // Finalize: wait for the RSC stream to complete and emit remaining\n // chunks plus the __VINEXT_RSC_DONE__ signal.\n const finalScripts = await rscEmbed.finalize();\n if (finalScripts) {\n controller.enqueue(encoder.encode(finalScripts));\n }\n },\n });\n\n return htmlStream.pipeThrough(transform);\n } finally {\n // Clean up so we don't leak context between requests\n setNavigationContext(null);\n clearServerInsertedHTML();\n }\n }); // end _runWithNavCtx\n}\n\nexport default {\n async fetch(request) {\n const url = new URL(request.url);\n if (url.pathname.startsWith(\"//\")) {\n return new Response(\"404 Not Found\", { status: 404 });\n }\n const rscModule = await import.meta.viteRsc.loadModule(\"rsc\", \"index\");\n const result = await rscModule.default(request);\n if (result instanceof Response) {\n return result;\n }\n if (result === null || result === undefined) {\n return new Response(\"Not Found\", { status: 404 });\n }\n return new Response(String(result), { status: 200 });\n },\n};\n`;\n}\n"]}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { createValidFileMatcher } from "../routing/file-matcher.js";
|
|
2
|
+
import { type ResolvedNextConfig } from "../config/next-config.js";
|
|
3
|
+
export declare function generateClientEntry(pagesDir: string, nextConfig: ResolvedNextConfig, fileMatcher: ReturnType<typeof createValidFileMatcher>): Promise<string>;
|
|
4
|
+
//# sourceMappingURL=pages-client-entry.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pages-client-entry.d.ts","sourceRoot":"","sources":["../../src/entries/pages-client-entry.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AACpE,OAAO,EAAE,KAAK,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAGnE,wBAAsB,mBAAmB,CACvC,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,kBAAkB,EAC9B,WAAW,EAAE,UAAU,CAAC,OAAO,sBAAsB,CAAC,GACrD,OAAO,CAAC,MAAM,CAAC,CAmFjB"}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pages Router client hydration entry generator.
|
|
3
|
+
*
|
|
4
|
+
* Generates the virtual client entry module (`virtual:vinext-client-entry`).
|
|
5
|
+
* This is the entry point for `vite build` (client bundle). It maps route
|
|
6
|
+
* patterns to dynamic imports of page modules so Vite code-splits each page
|
|
7
|
+
* into its own chunk. At runtime it reads __NEXT_DATA__ to determine which
|
|
8
|
+
* page to hydrate.
|
|
9
|
+
*
|
|
10
|
+
* Extracted from index.ts.
|
|
11
|
+
*/
|
|
12
|
+
import { pagesRouter, patternToNextFormat as pagesPatternToNextFormat } from "../routing/pages-router.js";
|
|
13
|
+
import { findFileWithExts } from "./pages-entry-helpers.js";
|
|
14
|
+
export async function generateClientEntry(pagesDir, nextConfig, fileMatcher) {
|
|
15
|
+
const pageRoutes = await pagesRouter(pagesDir, nextConfig?.pageExtensions, fileMatcher);
|
|
16
|
+
const appFilePath = findFileWithExts(pagesDir, "_app", fileMatcher);
|
|
17
|
+
const hasApp = appFilePath !== null;
|
|
18
|
+
// Build a map of route pattern -> dynamic import.
|
|
19
|
+
// Keys must use Next.js bracket format (e.g. "/user/[id]") to match
|
|
20
|
+
// __NEXT_DATA__.page which is set via patternToNextFormat() during SSR.
|
|
21
|
+
const loaderEntries = pageRoutes.map((r) => {
|
|
22
|
+
const absPath = r.filePath.replace(/\\/g, "/");
|
|
23
|
+
const nextFormatPattern = pagesPatternToNextFormat(r.pattern);
|
|
24
|
+
// JSON.stringify safely escapes quotes, backslashes, and special chars in
|
|
25
|
+
// both the route pattern and the absolute file path.
|
|
26
|
+
// lgtm[js/bad-code-sanitization]
|
|
27
|
+
return ` ${JSON.stringify(nextFormatPattern)}: () => import(${JSON.stringify(absPath)})`;
|
|
28
|
+
});
|
|
29
|
+
const appFileBase = appFilePath?.replace(/\\/g, "/");
|
|
30
|
+
return `
|
|
31
|
+
import React from "react";
|
|
32
|
+
import { hydrateRoot } from "react-dom/client";
|
|
33
|
+
// Eagerly import the router shim so its module-level popstate listener is
|
|
34
|
+
// registered. Without this, browser back/forward buttons do nothing because
|
|
35
|
+
// navigateClient() is never invoked on history changes.
|
|
36
|
+
import "next/router";
|
|
37
|
+
|
|
38
|
+
const pageLoaders = {
|
|
39
|
+
${loaderEntries.join(",\n")}
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
async function hydrate() {
|
|
43
|
+
const nextData = window.__NEXT_DATA__;
|
|
44
|
+
if (!nextData) {
|
|
45
|
+
console.error("[vinext] No __NEXT_DATA__ found");
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const { pageProps } = nextData.props;
|
|
50
|
+
const loader = pageLoaders[nextData.page];
|
|
51
|
+
if (!loader) {
|
|
52
|
+
console.error("[vinext] No page loader for route:", nextData.page);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const pageModule = await loader();
|
|
57
|
+
const PageComponent = pageModule.default;
|
|
58
|
+
if (!PageComponent) {
|
|
59
|
+
console.error("[vinext] Page module has no default export");
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
let element;
|
|
64
|
+
${hasApp ? `
|
|
65
|
+
try {
|
|
66
|
+
const appModule = await import(${JSON.stringify(appFileBase)});
|
|
67
|
+
const AppComponent = appModule.default;
|
|
68
|
+
window.__VINEXT_APP__ = AppComponent;
|
|
69
|
+
element = React.createElement(AppComponent, { Component: PageComponent, pageProps });
|
|
70
|
+
} catch {
|
|
71
|
+
element = React.createElement(PageComponent, pageProps);
|
|
72
|
+
}
|
|
73
|
+
` : `
|
|
74
|
+
element = React.createElement(PageComponent, pageProps);
|
|
75
|
+
`}
|
|
76
|
+
|
|
77
|
+
// Wrap with RouterContext.Provider so next/compat/router works during hydration
|
|
78
|
+
const { wrapWithRouterContext } = await import("next/router");
|
|
79
|
+
element = wrapWithRouterContext(element);
|
|
80
|
+
|
|
81
|
+
const container = document.getElementById("__next");
|
|
82
|
+
if (!container) {
|
|
83
|
+
console.error("[vinext] No #__next element found");
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const root = hydrateRoot(container, element);
|
|
88
|
+
window.__VINEXT_ROOT__ = root;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
hydrate();
|
|
92
|
+
`;
|
|
93
|
+
}
|
|
94
|
+
//# sourceMappingURL=pages-client-entry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pages-client-entry.js","sourceRoot":"","sources":["../../src/entries/pages-client-entry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,WAAW,EAAE,mBAAmB,IAAI,wBAAwB,EAAc,MAAM,4BAA4B,CAAC;AAGtH,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAE5D,MAAM,CAAC,KAAK,UAAU,mBAAmB,CACvC,QAAgB,EAChB,UAA8B,EAC9B,WAAsD;IAEtD,MAAM,UAAU,GAAG,MAAM,WAAW,CAAC,QAAQ,EAAE,UAAU,EAAE,cAAc,EAAE,WAAW,CAAC,CAAC;IAExF,MAAM,WAAW,GAAG,gBAAgB,CAAC,QAAQ,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;IACpE,MAAM,MAAM,GAAG,WAAW,KAAK,IAAI,CAAC;IAEpC,kDAAkD;IAClD,oEAAoE;IACpE,wEAAwE;IACxE,MAAM,aAAa,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC,CAAQ,EAAE,EAAE;QAChD,MAAM,OAAO,GAAG,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;QAC/C,MAAM,iBAAiB,GAAG,wBAAwB,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;QAC9D,0EAA0E;QAC1E,qDAAqD;QACrD,iCAAiC;QACjC,OAAO,KAAK,IAAI,CAAC,SAAS,CAAC,iBAAiB,CAAC,kBAAkB,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC;IAC5F,CAAC,CAAC,CAAC;IAEH,MAAM,WAAW,GAAG,WAAW,EAAE,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;IAErD,OAAO;;;;;;;;;EASP,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;IAyBvB,MAAM,CAAC,CAAC,CAAC;;qCAEwB,IAAI,CAAC,SAAS,CAAC,WAAY,CAAC;;;;;;;GAO9D,CAAC,CAAC,CAAC;;GAEH;;;;;;;;;;;;;;;;;CAiBF,CAAC;AACF,CAAC","sourcesContent":["/**\n * Pages Router client hydration entry generator.\n *\n * Generates the virtual client entry module (`virtual:vinext-client-entry`).\n * This is the entry point for `vite build` (client bundle). It maps route\n * patterns to dynamic imports of page modules so Vite code-splits each page\n * into its own chunk. At runtime it reads __NEXT_DATA__ to determine which\n * page to hydrate.\n *\n * Extracted from index.ts.\n */\nimport { pagesRouter, patternToNextFormat as pagesPatternToNextFormat, type Route } from \"../routing/pages-router.js\";\nimport { createValidFileMatcher } from \"../routing/file-matcher.js\";\nimport { type ResolvedNextConfig } from \"../config/next-config.js\";\nimport { findFileWithExts } from \"./pages-entry-helpers.js\";\n\nexport async function generateClientEntry(\n pagesDir: string,\n nextConfig: ResolvedNextConfig,\n fileMatcher: ReturnType<typeof createValidFileMatcher>,\n): Promise<string> {\n const pageRoutes = await pagesRouter(pagesDir, nextConfig?.pageExtensions, fileMatcher);\n\n const appFilePath = findFileWithExts(pagesDir, \"_app\", fileMatcher);\n const hasApp = appFilePath !== null;\n\n // Build a map of route pattern -> dynamic import.\n // Keys must use Next.js bracket format (e.g. \"/user/[id]\") to match\n // __NEXT_DATA__.page which is set via patternToNextFormat() during SSR.\n const loaderEntries = pageRoutes.map((r: Route) => {\n const absPath = r.filePath.replace(/\\\\/g, \"/\");\n const nextFormatPattern = pagesPatternToNextFormat(r.pattern);\n // JSON.stringify safely escapes quotes, backslashes, and special chars in\n // both the route pattern and the absolute file path.\n // lgtm[js/bad-code-sanitization]\n return ` ${JSON.stringify(nextFormatPattern)}: () => import(${JSON.stringify(absPath)})`;\n });\n\n const appFileBase = appFilePath?.replace(/\\\\/g, \"/\");\n\n return `\nimport React from \"react\";\nimport { hydrateRoot } from \"react-dom/client\";\n// Eagerly import the router shim so its module-level popstate listener is\n// registered. Without this, browser back/forward buttons do nothing because\n// navigateClient() is never invoked on history changes.\nimport \"next/router\";\n\nconst pageLoaders = {\n${loaderEntries.join(\",\\n\")}\n};\n\nasync function hydrate() {\n const nextData = window.__NEXT_DATA__;\n if (!nextData) {\n console.error(\"[vinext] No __NEXT_DATA__ found\");\n return;\n }\n\n const { pageProps } = nextData.props;\n const loader = pageLoaders[nextData.page];\n if (!loader) {\n console.error(\"[vinext] No page loader for route:\", nextData.page);\n return;\n }\n\n const pageModule = await loader();\n const PageComponent = pageModule.default;\n if (!PageComponent) {\n console.error(\"[vinext] Page module has no default export\");\n return;\n }\n\n let element;\n ${hasApp ? `\n try {\n const appModule = await import(${JSON.stringify(appFileBase!)});\n const AppComponent = appModule.default;\n window.__VINEXT_APP__ = AppComponent;\n element = React.createElement(AppComponent, { Component: PageComponent, pageProps });\n } catch {\n element = React.createElement(PageComponent, pageProps);\n }\n ` : `\n element = React.createElement(PageComponent, pageProps);\n `}\n\n // Wrap with RouterContext.Provider so next/compat/router works during hydration\n const { wrapWithRouterContext } = await import(\"next/router\");\n element = wrapWithRouterContext(element);\n\n const container = document.getElementById(\"__next\");\n if (!container) {\n console.error(\"[vinext] No #__next element found\");\n return;\n }\n\n const root = hydrateRoot(container, element);\n window.__VINEXT_ROOT__ = root;\n}\n\nhydrate();\n`;\n}\n"]}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createValidFileMatcher } from "../routing/file-matcher.js";
|
|
2
|
+
/**
|
|
3
|
+
* Find a file with any of the valid extensions in the given directory.
|
|
4
|
+
* Returns the first matching absolute path, or null if not found.
|
|
5
|
+
*/
|
|
6
|
+
export declare function findFileWithExts(dir: string, name: string, matcher: ReturnType<typeof createValidFileMatcher>): string | null;
|
|
7
|
+
//# sourceMappingURL=pages-entry-helpers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pages-entry-helpers.d.ts","sourceRoot":"","sources":["../../src/entries/pages-entry-helpers.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAEpE;;;GAGG;AACH,wBAAgB,gBAAgB,CAC9B,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,UAAU,CAAC,OAAO,sBAAsB,CAAC,GACjD,MAAM,GAAG,IAAI,CAMf"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared helpers used by the Pages Router entry generators.
|
|
3
|
+
*/
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
/**
|
|
7
|
+
* Find a file with any of the valid extensions in the given directory.
|
|
8
|
+
* Returns the first matching absolute path, or null if not found.
|
|
9
|
+
*/
|
|
10
|
+
export function findFileWithExts(dir, name, matcher) {
|
|
11
|
+
for (const ext of matcher.dottedExtensions) {
|
|
12
|
+
const filePath = path.join(dir, name + ext);
|
|
13
|
+
if (fs.existsSync(filePath))
|
|
14
|
+
return filePath;
|
|
15
|
+
}
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
//# sourceMappingURL=pages-entry-helpers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pages-entry-helpers.js","sourceRoot":"","sources":["../../src/entries/pages-entry-helpers.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,MAAM,SAAS,CAAC;AAGzB;;;GAGG;AACH,MAAM,UAAU,gBAAgB,CAC9B,GAAW,EACX,IAAY,EACZ,OAAkD;IAElD,KAAK,MAAM,GAAG,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;QAC3C,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,GAAG,GAAG,CAAC,CAAC;QAC5C,IAAI,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC;YAAE,OAAO,QAAQ,CAAC;IAC/C,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/**\n * Shared helpers used by the Pages Router entry generators.\n */\nimport path from \"node:path\";\nimport fs from \"node:fs\";\nimport { createValidFileMatcher } from \"../routing/file-matcher.js\";\n\n/**\n * Find a file with any of the valid extensions in the given directory.\n * Returns the first matching absolute path, or null if not found.\n */\nexport function findFileWithExts(\n dir: string,\n name: string,\n matcher: ReturnType<typeof createValidFileMatcher>,\n): string | null {\n for (const ext of matcher.dottedExtensions) {\n const filePath = path.join(dir, name + ext);\n if (fs.existsSync(filePath)) return filePath;\n }\n return null;\n}\n"]}
|