dinou 9.0.2 → 9.0.3

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 (37) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +503 -9883
  3. package/dinou/bun/build.js +38 -1
  4. package/{cli.js → dinou/cli.js} +8 -7
  5. package/dinou/cloudflare/build.js +37 -0
  6. package/dinou/core/build-static-pages.js +15 -7
  7. package/dinou/core/cache-revalidate.js +909 -151
  8. package/dinou/core/cache-slot.js +728 -97
  9. package/dinou/core/client-webpack.jsx +60 -9
  10. package/dinou/core/client.jsx +60 -9
  11. package/dinou/core/edge-ssr.js +33 -5
  12. package/dinou/core/generate-static.js +109 -47
  13. package/dinou/core/get-jsx.js +333 -329
  14. package/dinou/core/handler.js +2983 -2343
  15. package/dinou/core/layout-functions.js +102 -1
  16. package/dinou/core/ppr-context.js +256 -105
  17. package/dinou/core/ppr-runtime.js +540 -267
  18. package/dinou/core/render-jsx-to-client-jsx.js +131 -71
  19. package/dinou/core/slot.js +246 -33
  20. package/dinou/core/storage-adapter.js +117 -11
  21. package/dinou/deno/build.js +38 -1
  22. package/dinou/deno/seed-kv.js +43 -11
  23. package/dinou/esbuild/helpers-esbuild/swc-disk-cache.js +242 -225
  24. package/dinou/esbuild/plugins-esbuild/server-functions-plugin.js +253 -226
  25. package/dinou/esbuild/react-refresh/esm-hmr/client.js +209 -209
  26. package/dinou/node/build.js +2 -2
  27. package/dinou/node/bundle-dual-engine.js +2 -0
  28. package/dinou/node/dev.js +2853 -2704
  29. package/dinou/package.json +5 -2
  30. package/dinou/rollup/react-refresh/esm-hmr/client.js +220 -220
  31. package/dinou/rollup/rollup-plugins/rollup-plugin-server-functions.js +182 -160
  32. package/dinou/server.d.ts +25 -11
  33. package/dinou/server.js +5 -0
  34. package/dinou/webpack/loaders/server-functions-loader.js +101 -94
  35. package/dinou/webpack/webpack.config.js +9 -4
  36. package/eject.js +219 -223
  37. package/package.json +2 -2
@@ -1,267 +1,540 @@
1
- // dinou/core/ppr-runtime.js
2
- // Dinou Partial Prerendering (PPR) Runtime Streaming Resume Engine.
3
- // Sends the pre-rendered shell immediately (0ms TTFB) and progressively
4
- // streams dynamic Suspense holes as they resolve over the same HTTP connection.
5
- // Designed for the Dual-Bundle architecture (Pass A: RSC, Pass B: SSR).
6
-
7
- import React from "react";
8
- import { renderRSCStream } from "./rsc-renderer.js";
9
- import { getClientManifest } from "./manifest-provider.js";
10
- import { requestStorage, setCurrentContext } from "./request-context.js";
11
- import getJSX from "./get-jsx.js";
12
-
13
- /**
14
- * Traverses a React JSX element tree to find Suspense boundaries,
15
- * evaluates their dynamic children, and streams replacement chunks.
16
- *
17
- * @param {object} node - Root JSX node (layout + page)
18
- * @param {Array<string|object>} expectedHoles - Holes registered at build time
19
- * @param {WritableStreamDefaultWriter} writer - Response stream writer
20
- * @param {TextEncoder} encoder - Text encoder
21
- * @param {object} platformContext - Dinou platform context (containing renderHtmlStream)
22
- * @param {boolean} isDevelopment - Dev mode flag
23
- */
24
- async function streamDynamicHoles(
25
- node,
26
- expectedHoles,
27
- writer,
28
- encoder,
29
- platformContext,
30
- isDevelopment = false
31
- ) {
32
- let holeIndex = 0;
33
- const holePromises = [];
34
-
35
- const knownHoleIds = new Set(
36
- (expectedHoles || []).map((h) => (typeof h === "object" ? h.id : h))
37
- );
38
-
39
- const clientManifest = getClientManifest();
40
-
41
- function isClientComponent(type) {
42
- if (!type) return false;
43
- return (
44
- type.$$typeof === Symbol.for("react.client.reference") ||
45
- Boolean(type.$$id) ||
46
- Boolean(type.filepath)
47
- );
48
- }
49
-
50
- async function traverse(current) {
51
- if (!current) return;
52
-
53
- // Handle Client Component: do NOT execute, only traverse children
54
- if (isClientComponent(current?.type) || current?.$$typeof === Symbol.for("react.client.reference")) {
55
- if (current?.props?.children) {
56
- await traverse(current.props.children);
57
- }
58
- return;
59
- }
60
-
61
- // Handle React Server Component function
62
- if (typeof current?.type === "function") {
63
- try {
64
- const evaluated = await current.type(current.props || {});
65
- await traverse(evaluated);
66
- } catch (err) {
67
- console.error("[Dinou PPR] Error evaluating component in hole traversal:", err);
68
- }
69
- return;
70
- }
71
-
72
- // Handle React.forward_ref
73
- if (
74
- typeof current?.type === "object" &&
75
- current.type !== null &&
76
- current.type.$$typeof === Symbol.for("react.forward_ref")
77
- ) {
78
- try {
79
- const rendered = current.type.render(current.props || {}, current.ref);
80
- await traverse(rendered);
81
- } catch (err) {
82
- console.error("[Dinou PPR] Error evaluating forward_ref in hole traversal:", err);
83
- }
84
- return;
85
- }
86
-
87
- // Handle React.Suspense
88
- if (
89
- current?.type === Symbol.for("react.suspense") ||
90
- current?.type === React.Suspense
91
- ) {
92
- holeIndex++;
93
- const currentHoleId = `ppr-hole-${holeIndex}`;
94
-
95
- // Check if this boundary was registered as a dynamic hole
96
- const shouldStream =
97
- knownHoleIds.size === 0 || knownHoleIds.has(currentHoleId);
98
-
99
- if (shouldStream) {
100
- const children = current.props?.children;
101
- const promise = (async () => {
102
- try {
103
- let html = "";
104
- if (platformContext && platformContext.renderHtmlStream) {
105
- const rscStream = renderRSCStream(children, clientManifest, { runtime: "edge" });
106
- const htmlStream = await platformContext.renderHtmlStream(rscStream, {
107
- bootstrapModules: [],
108
- });
109
- html = await new Response(htmlStream).text();
110
- }
111
-
112
- const chunk = `\n<template id="ppr-content-${currentHoleId}">${html}</template>\n<script>(function(){var c=document.getElementById("ppr-content-${currentHoleId}");if(!c)return;var b=document.getElementById("B:${holeIndex - 1}");var t=document.querySelector('[data-ppr-hole="${currentHoleId}"]')||(b?b.nextElementSibling:null);try{if(t){t.replaceWith(c.content?c.content:...c.childNodes);}}finally{c.remove();}})();</script>\n`;
113
- await writer.write(encoder.encode(chunk));
114
- } catch (holeErr) {
115
- console.error(`[Dinou PPR] Error resolving dynamic hole ${currentHoleId}:`, holeErr);
116
- const errMsg = isDevelopment
117
- ? (holeErr?.message || "Unknown dynamic error")
118
- : "Error loading dynamic content";
119
- const errChunk = `\n<template id="ppr-content-${currentHoleId}"><div style="color:#e11d48;padding:8px 12px;background:#fff1f2;border:1px solid #fecdd3;border-radius:6px;font-size:0.875rem;font-family:system-ui,sans-serif;">[PPR Error: ${errMsg}]</div></template>\n<script>(function(){var c=document.getElementById("ppr-content-${currentHoleId}");if(!c)return;var b=document.getElementById("B:${holeIndex - 1}");var t=document.querySelector('[data-ppr-hole="${currentHoleId}"]')||(b?b.nextElementSibling:null);try{if(t){t.replaceWith(c.content?c.content:...c.childNodes);}}finally{c.remove();}})();</script>\n`;
120
- await writer.write(encoder.encode(errChunk));
121
- }
122
- })();
123
- holePromises.push(promise);
124
- }
125
- return;
126
- }
127
-
128
- // Handle Arrays (children)
129
- if (Array.isArray(current)) {
130
- for (const item of current) {
131
- await traverse(item);
132
- }
133
- return;
134
- }
135
-
136
- // Traverse children props
137
- if (current?.props?.children) {
138
- await traverse(current.props.children);
139
- }
140
- }
141
-
142
- await traverse(node);
143
- await Promise.all(holePromises);
144
- }
145
-
146
- /**
147
- * Handles PPR Runtime Streaming Resume.
148
- * Immediately flushes shellPrelude to the client, then resolves dynamic holes in parallel.
149
- */
150
- async function handlePprResume({
151
- reqPath,
152
- queryObj,
153
- simReq,
154
- bridge,
155
- platformContext,
156
- rootContext,
157
- cachedItem,
158
- metadata,
159
- isDevelopment,
160
- getDiscoveredLayouts,
161
- createRequestContext,
162
- copyCustomContextProperties,
163
- }) {
164
- let shellHtml = cachedItem.content;
165
- if (typeof shellHtml === "string") {
166
- if (!shellHtml.includes("window.__DINOU_LAYOUTS__")) {
167
- const knownLayouts = typeof getDiscoveredLayouts === "function" ? getDiscoveredLayouts() : {};
168
- shellHtml = shellHtml.replace(
169
- "</head>",
170
- `<script>window.__DINOU_LAYOUTS__=${JSON.stringify(knownLayouts)};</script></head>`
171
- );
172
- }
173
- shellHtml = shellHtml.replace(
174
- /window\.__DINOU_USE_STATIC__\s*=\s*true;?/g,
175
- "window.__DINOU_USE_STATIC__ = false; window.__DINOU_PPR__ = true;"
176
- );
177
- if (!shellHtml.includes("window.__DINOU_PPR__")) {
178
- shellHtml = shellHtml.replace(
179
- "</head>",
180
- `<script>window.__DINOU_USE_STATIC__ = false; window.__DINOU_PPR__ = true;</script></head>`
181
- );
182
- }
183
- }
184
-
185
- // Separate shell into prelude (up to </body>) and postlude
186
- const lowerHtml = shellHtml.toLowerCase();
187
- const bodyCloseIndex = lowerHtml.lastIndexOf("</body>");
188
- let shellPrelude =
189
- bodyCloseIndex !== -1 ? shellHtml.slice(0, bodyCloseIndex) : shellHtml;
190
- let shellPostlude =
191
- bodyCloseIndex !== -1 ? shellHtml.slice(bodyCloseIndex) : "</body></html>";
192
-
193
- const { readable, writable } = new TransformStream();
194
- const writer = writable.getWriter();
195
- const encoder = new TextEncoder();
196
-
197
- // Stream dynamic holes in parallel with the prelude
198
- const resumePromise = (async () => {
199
- try {
200
- // 1. Immediately flush static shell prelude (0ms TTFB)
201
- await writer.write(encoder.encode(shellPrelude));
202
-
203
- const dynamicState = { value: true };
204
- const context = createRequestContext(simReq, bridge, platformContext, dynamicState);
205
- if (typeof copyCustomContextProperties === "function") {
206
- copyCustomContextProperties(rootContext, context);
207
- }
208
- if (typeof setCurrentContext === "function") {
209
- setCurrentContext(context);
210
- }
211
-
212
- await requestStorage.run(context, async () => {
213
- const isNotFound = { value: false };
214
- const jsx = await getJSX(
215
- reqPath,
216
- queryObj,
217
- isNotFound,
218
- isDevelopment,
219
- false
220
- );
221
-
222
- const holes = metadata?.holes || [];
223
- await streamDynamicHoles(
224
- jsx,
225
- holes,
226
- writer,
227
- encoder,
228
- platformContext,
229
- isDevelopment
230
- );
231
- });
232
- } catch (streamErr) {
233
- console.error("[Dinou PPR] Runtime streaming resume error:", streamErr);
234
- } finally {
235
- try {
236
- await writer.write(encoder.encode(shellPostlude));
237
- await writer.close();
238
- } catch (_) {}
239
- }
240
- })();
241
-
242
- if (
243
- platformContext &&
244
- platformContext.ctx &&
245
- typeof platformContext.ctx.waitUntil === "function"
246
- ) {
247
- platformContext.ctx.waitUntil(resumePromise);
248
- }
249
-
250
- const headers = new Headers(bridge.headers);
251
- headers.set("Content-Type", "text/html; charset=utf-8");
252
- headers.set("Cache-Control", "no-store, no-cache, must-revalidate");
253
-
254
- return new Response(readable, {
255
- status: metadata?.status || 200,
256
- headers,
257
- });
258
- }
259
-
260
- export {
261
- streamDynamicHoles,
262
- handlePprResume,
263
- };
264
- export default {
265
- streamDynamicHoles,
266
- handlePprResume,
267
- };
1
+ // dinou/core/ppr-runtime.js
2
+ // Dinou Partial Prerendering (PPR) Runtime Streaming Resume Engine.
3
+ // Sends the pre-rendered shell immediately (0ms TTFB) and progressively
4
+ // streams dynamic Suspense holes as they resolve over the same HTTP connection.
5
+ // Designed for the Dual-Bundle architecture (Pass A: RSC, Pass B: SSR).
6
+
7
+ import React from "react";
8
+ import { renderRSCStream } from "./rsc-renderer.js";
9
+ import { getClientManifest } from "./manifest-provider.js";
10
+ import { requestStorage, setCurrentContext } from "./request-context.js";
11
+ import getJSX from "./get-jsx.js";
12
+
13
+ function escapeHtml(str) {
14
+ return String(str)
15
+ .replace(/&/g, "&amp;")
16
+ .replace(/</g, "&lt;")
17
+ .replace(/>/g, "&gt;")
18
+ .replace(/"/g, "&quot;")
19
+ .replace(/'/g, "&#39;");
20
+ }
21
+
22
+ function isClientComponentRef(type) {
23
+ if (!type) return false;
24
+ return (
25
+ type.$$typeof === Symbol.for("react.client.reference") ||
26
+ Boolean(type.$$id) ||
27
+ Boolean(type.filepath)
28
+ );
29
+ }
30
+
31
+ /**
32
+ * Splices live dynamic <Suspense> subtrees from a live page evaluation into a
33
+ * cached PPR static shell client-JSX tree (deserialized from shell.page.json),
34
+ * keeping the static shell of the page 100% immutable across /____rsc_page____
35
+ * refreshes and soft-navigations while evaluating dynamic holes fresh.
36
+ */
37
+ async function spliceDynamicHolesIntoShell(
38
+ cachedShellTree,
39
+ livePageNodeOrFn,
40
+ startHoleIndex = 0
41
+ ) {
42
+ const knownHoleIds = new Set();
43
+ function collectKnownHoles(node) {
44
+ if (!node || typeof node !== "object") return;
45
+ if (Array.isArray(node)) {
46
+ for (const item of node) collectKnownHoles(item);
47
+ return;
48
+ }
49
+ if (node.$$typeof === Symbol.for("react.transitional.element")) {
50
+ if (node.props && typeof node.props["data-ppr-hole"] === "string") {
51
+ knownHoleIds.add(node.props["data-ppr-hole"]);
52
+ }
53
+ if (node.props && typeof node.props === "object") {
54
+ for (const val of Object.values(node.props)) {
55
+ if (val && typeof val === "object") collectKnownHoles(val);
56
+ }
57
+ }
58
+ } else {
59
+ for (const val of Object.values(node)) {
60
+ if (val && typeof val === "object") collectKnownHoles(val);
61
+ }
62
+ }
63
+ }
64
+
65
+ collectKnownHoles(cachedShellTree);
66
+ if (knownHoleIds.size === 0) {
67
+ return cachedShellTree;
68
+ }
69
+
70
+ const livePageNode =
71
+ typeof livePageNodeOrFn === "function"
72
+ ? await livePageNodeOrFn()
73
+ : livePageNodeOrFn;
74
+
75
+ let holeIndex = Number(startHoleIndex) || 0;
76
+ const liveHolesMap = new Map();
77
+
78
+ async function traverseProps(props) {
79
+ if (!props || typeof props !== "object") return;
80
+ for (const [, value] of Object.entries(props)) {
81
+ if (value && typeof value === "object") {
82
+ await traverse(value);
83
+ }
84
+ }
85
+ }
86
+
87
+ async function traverse(current) {
88
+ if (!current) return;
89
+ if (Array.isArray(current)) {
90
+ for (const item of current) {
91
+ await traverse(item);
92
+ }
93
+ return;
94
+ }
95
+ if (typeof current !== "object" || current instanceof Promise) {
96
+ return;
97
+ }
98
+ if (
99
+ isClientComponentRef(current?.type) ||
100
+ current?.$$typeof === Symbol.for("react.client.reference")
101
+ ) {
102
+ await traverseProps(current?.props);
103
+ return;
104
+ }
105
+ if (typeof current?.type === "function") {
106
+ try {
107
+ const evaluated = await current.type(current.props || {});
108
+ await traverse(evaluated);
109
+ } catch (err) {
110
+ console.error("[Dinou PPR] Error evaluating component in hole splice:", err);
111
+ }
112
+ return;
113
+ }
114
+ if (
115
+ typeof current?.type === "object" &&
116
+ current.type !== null &&
117
+ current.type.$$typeof === Symbol.for("react.forward_ref")
118
+ ) {
119
+ if (isClientComponentRef(current.type)) {
120
+ await traverseProps(current.props);
121
+ return;
122
+ }
123
+ try {
124
+ const rendered = await current.type.render(current.props || {}, current.ref);
125
+ await traverse(rendered);
126
+ } catch (err) {
127
+ console.error("[Dinou PPR] Error evaluating forward_ref in hole splice:", err);
128
+ }
129
+ return;
130
+ }
131
+ if (
132
+ typeof current?.type === "object" &&
133
+ current.type !== null &&
134
+ current.type.$$typeof === Symbol.for("react.memo")
135
+ ) {
136
+ if (isClientComponentRef(current.type)) {
137
+ await traverseProps(current.props);
138
+ return;
139
+ }
140
+ try {
141
+ const innerComp = current.type.type;
142
+ const rendered =
143
+ typeof innerComp === "function" ? await innerComp(current.props || {}) : null;
144
+ await traverse(rendered);
145
+ } catch (err) {
146
+ console.error("[Dinou PPR] Error evaluating memo in hole splice:", err);
147
+ }
148
+ return;
149
+ }
150
+ if (
151
+ current?.type === Symbol.for("react.suspense") ||
152
+ current?.type === React.Suspense
153
+ ) {
154
+ holeIndex++;
155
+ const currentHoleId = `ppr-hole-${holeIndex}`;
156
+ if (knownHoleIds.has(currentHoleId)) {
157
+ liveHolesMap.set(currentHoleId, current);
158
+ return;
159
+ }
160
+ if (current.props?.children) {
161
+ await traverse(current.props.children);
162
+ }
163
+ if (current.props?.fallback) {
164
+ await traverse(current.props.fallback);
165
+ }
166
+ return;
167
+ }
168
+ if (current?.$$typeof === Symbol.for("react.transitional.element")) {
169
+ await traverseProps(current.props);
170
+ } else {
171
+ await traverseProps(current);
172
+ }
173
+ }
174
+
175
+ await traverse(livePageNode);
176
+
177
+ function replaceHoles(node) {
178
+ if (!node || typeof node !== "object") return node;
179
+ if (Array.isArray(node)) {
180
+ return node.map((item) => replaceHoles(item));
181
+ }
182
+ if (node.$$typeof === Symbol.for("react.transitional.element")) {
183
+ const holeId = node.props && node.props["data-ppr-hole"];
184
+ if (typeof holeId === "string" && liveHolesMap.has(holeId)) {
185
+ return liveHolesMap.get(holeId);
186
+ }
187
+ if (node.props && typeof node.props === "object") {
188
+ let changed = false;
189
+ const newProps = { ...node.props };
190
+ for (const [k, v] of Object.entries(node.props)) {
191
+ if (v && typeof v === "object") {
192
+ const updated = replaceHoles(v);
193
+ if (updated !== v) {
194
+ newProps[k] = updated;
195
+ changed = true;
196
+ }
197
+ }
198
+ }
199
+ if (changed) {
200
+ if (node.key != null) newProps.key = node.key;
201
+ const children = newProps.children;
202
+ if (Array.isArray(children)) {
203
+ delete newProps.children;
204
+ return React.createElement(node.type, newProps, ...children);
205
+ }
206
+ return React.createElement(node.type, newProps);
207
+ }
208
+ }
209
+ return node;
210
+ }
211
+ let changed = false;
212
+ const clone = { ...node };
213
+ for (const [k, v] of Object.entries(node)) {
214
+ if (v && typeof v === "object") {
215
+ const updated = replaceHoles(v);
216
+ if (updated !== v) {
217
+ clone[k] = updated;
218
+ changed = true;
219
+ }
220
+ }
221
+ }
222
+ return changed ? clone : node;
223
+ }
224
+
225
+ return replaceHoles(cachedShellTree);
226
+ }
227
+
228
+ /**
229
+ * Traverses a React JSX element tree to find Suspense boundaries,
230
+ * evaluates their dynamic children, and streams replacement chunks.
231
+ *
232
+ * @param {object} node - Root JSX node (layout + page)
233
+ * @param {Array<string|object>|null} expectedHoles - Holes registered at build time
234
+ * @param {WritableStreamDefaultWriter} writer - Response stream writer
235
+ * @param {TextEncoder} encoder - Text encoder
236
+ * @param {object} platformContext - Dinou platform context (containing renderHtmlStream)
237
+ * @param {boolean} isDevelopment - Dev mode flag
238
+ */
239
+ async function streamDynamicHoles(
240
+ node,
241
+ expectedHoles,
242
+ writer,
243
+ encoder,
244
+ platformContext,
245
+ isDevelopment = false
246
+ ) {
247
+ let holeIndex = 0;
248
+ const holePromises = [];
249
+
250
+ const hasExplicitHoles = Array.isArray(expectedHoles);
251
+ const knownHoleIds = new Set(
252
+ (expectedHoles || []).map((h) => (typeof h === "object" ? h.id : h))
253
+ );
254
+
255
+ const clientManifest = getClientManifest();
256
+
257
+ async function traverseProps(props) {
258
+ if (!props || typeof props !== "object") return;
259
+ for (const [, value] of Object.entries(props)) {
260
+ if (value && typeof value === "object") {
261
+ await traverse(value);
262
+ }
263
+ }
264
+ }
265
+
266
+ async function traverse(current) {
267
+ if (!current) return;
268
+
269
+ // Handle Arrays (children)
270
+ if (Array.isArray(current)) {
271
+ for (const item of current) {
272
+ await traverse(item);
273
+ }
274
+ return;
275
+ }
276
+
277
+ if (typeof current !== "object" || current instanceof Promise) {
278
+ return;
279
+ }
280
+
281
+ // Handle Client Component: do NOT execute, only traverse props in deterministic order
282
+ if (
283
+ isClientComponentRef(current?.type) ||
284
+ current?.$$typeof === Symbol.for("react.client.reference")
285
+ ) {
286
+ await traverseProps(current?.props);
287
+ return;
288
+ }
289
+
290
+ // Handle React Server Component function
291
+ if (typeof current?.type === "function") {
292
+ try {
293
+ const evaluated = await current.type(current.props || {});
294
+ await traverse(evaluated);
295
+ } catch (err) {
296
+ console.error("[Dinou PPR] Error evaluating component in hole traversal:", err);
297
+ }
298
+ return;
299
+ }
300
+
301
+ // Handle React.forward_ref
302
+ if (
303
+ typeof current?.type === "object" &&
304
+ current.type !== null &&
305
+ current.type.$$typeof === Symbol.for("react.forward_ref")
306
+ ) {
307
+ if (isClientComponentRef(current.type)) {
308
+ await traverseProps(current.props);
309
+ return;
310
+ }
311
+ try {
312
+ const rendered = await current.type.render(current.props || {}, current.ref);
313
+ await traverse(rendered);
314
+ } catch (err) {
315
+ console.error("[Dinou PPR] Error evaluating forward_ref in hole traversal:", err);
316
+ }
317
+ return;
318
+ }
319
+
320
+ // Handle React.memo
321
+ if (
322
+ typeof current?.type === "object" &&
323
+ current.type !== null &&
324
+ current.type.$$typeof === Symbol.for("react.memo")
325
+ ) {
326
+ if (isClientComponentRef(current.type)) {
327
+ await traverseProps(current.props);
328
+ return;
329
+ }
330
+ try {
331
+ const innerComp = current.type.type;
332
+ const rendered =
333
+ typeof innerComp === "function" ? await innerComp(current.props || {}) : null;
334
+ await traverse(rendered);
335
+ } catch (err) {
336
+ console.error("[Dinou PPR] Error evaluating memo in hole traversal:", err);
337
+ }
338
+ return;
339
+ }
340
+
341
+ // Handle React.Suspense
342
+ if (
343
+ current?.type === Symbol.for("react.suspense") ||
344
+ current?.type === React.Suspense
345
+ ) {
346
+ holeIndex++;
347
+ const currentBoundaryIndex = holeIndex - 1;
348
+ const currentHoleId = `ppr-hole-${holeIndex}`;
349
+
350
+ // Check if this boundary was registered as a dynamic hole at build time
351
+ const shouldStream = hasExplicitHoles
352
+ ? knownHoleIds.has(currentHoleId)
353
+ : true;
354
+
355
+ if (shouldStream) {
356
+ const children = current.props?.children;
357
+ const promise = (async () => {
358
+ try {
359
+ let html = "";
360
+ if (platformContext && platformContext.renderHtmlStream) {
361
+ const rscStream = renderRSCStream(children, clientManifest, { runtime: "edge" });
362
+ const htmlStream = await platformContext.renderHtmlStream(rscStream, {
363
+ bootstrapModules: [],
364
+ });
365
+ html = await new Response(htmlStream).text();
366
+ }
367
+
368
+ const chunk = `\n<template id="ppr-content-${currentHoleId}">${html}</template>\n<script>(function(){var c=document.getElementById("ppr-content-${currentHoleId}");if(!c)return;var b=document.getElementById("B:${currentBoundaryIndex}");var t=document.querySelector('[data-ppr-hole="${currentHoleId}"]')||(b?b.nextElementSibling:null);try{if(t){if(c.content){t.replaceWith(c.content);}else{t.replaceWith.apply(t,Array.from(c.childNodes));}}}finally{c.remove();}})();</script>\n`;
369
+ await writer.write(encoder.encode(chunk));
370
+ } catch (holeErr) {
371
+ console.error(`[Dinou PPR] Error resolving dynamic hole ${currentHoleId}:`, holeErr);
372
+ const rawErrMsg = isDevelopment
373
+ ? (holeErr?.message || "Unknown dynamic error")
374
+ : "Error loading dynamic content";
375
+ const errMsg = escapeHtml(rawErrMsg);
376
+ const errChunk = `\n<template id="ppr-content-${currentHoleId}"><div style="color:#e11d48;padding:8px 12px;background:#fff1f2;border:1px solid #fecdd3;border-radius:6px;font-size:0.875rem;font-family:system-ui,sans-serif;">[PPR Error: ${errMsg}]</div></template>\n<script>(function(){var c=document.getElementById("ppr-content-${currentHoleId}");if(!c)return;var b=document.getElementById("B:${currentBoundaryIndex}");var t=document.querySelector('[data-ppr-hole="${currentHoleId}"]')||(b?b.nextElementSibling:null);try{if(t){if(c.content){t.replaceWith(c.content);}else{t.replaceWith.apply(t,Array.from(c.childNodes));}}}finally{c.remove();}})();</script>\n`;
377
+ await writer.write(encoder.encode(errChunk));
378
+ }
379
+ })();
380
+ holePromises.push(promise);
381
+ return;
382
+ }
383
+
384
+ // Static <Suspense> boundary: do not re-stream it, but traverse its children & fallback
385
+ // in the same order as asyncRenderJSXToClientJSX so nested dynamic <Suspense> holes are
386
+ // discovered and holeIndex remains synchronized.
387
+ if (current.props?.children) {
388
+ await traverse(current.props.children);
389
+ }
390
+ if (current.props?.fallback) {
391
+ await traverse(current.props.fallback);
392
+ }
393
+ return;
394
+ }
395
+
396
+ // Traverse host element / Fragment props or plain props object
397
+ if (current?.$$typeof === Symbol.for("react.transitional.element")) {
398
+ await traverseProps(current.props);
399
+ } else {
400
+ await traverseProps(current);
401
+ }
402
+ }
403
+
404
+ await traverse(node);
405
+ await Promise.all(holePromises);
406
+ }
407
+
408
+ /**
409
+ * Handles PPR Runtime Streaming Resume.
410
+ * Immediately flushes shellPrelude to the client, then resolves dynamic holes in parallel.
411
+ */
412
+ async function handlePprResume({
413
+ reqPath,
414
+ queryObj,
415
+ simReq,
416
+ bridge,
417
+ platformContext,
418
+ rootContext,
419
+ cachedItem,
420
+ metadata,
421
+ isDevelopment,
422
+ getDiscoveredLayouts,
423
+ createRequestContext,
424
+ copyCustomContextProperties,
425
+ }) {
426
+ let shellHtml = cachedItem.content;
427
+ if (typeof shellHtml === "string") {
428
+ if (!shellHtml.includes("window.__DINOU_LAYOUTS__")) {
429
+ const knownLayouts = typeof getDiscoveredLayouts === "function" ? getDiscoveredLayouts() : {};
430
+ shellHtml = shellHtml.replace(
431
+ "</head>",
432
+ `<script>window.__DINOU_LAYOUTS__=${JSON.stringify(knownLayouts)};</script></head>`
433
+ );
434
+ }
435
+ shellHtml = shellHtml.replace(
436
+ /window\.__DINOU_USE_STATIC__\s*=\s*true;?/g,
437
+ "window.__DINOU_USE_STATIC__ = false; window.__DINOU_PPR__ = true;"
438
+ );
439
+ if (!shellHtml.includes("window.__DINOU_PPR__")) {
440
+ shellHtml = shellHtml.replace(
441
+ "</head>",
442
+ `<script>window.__DINOU_USE_STATIC__ = false; window.__DINOU_PPR__ = true;</script></head>`
443
+ );
444
+ }
445
+ }
446
+
447
+ // Separate shell into prelude (up to </body>) and postlude
448
+ const lowerHtml = shellHtml.toLowerCase();
449
+ const bodyCloseIndex = lowerHtml.lastIndexOf("</body>");
450
+ let shellPrelude =
451
+ bodyCloseIndex !== -1 ? shellHtml.slice(0, bodyCloseIndex) : shellHtml;
452
+ let shellPostlude =
453
+ bodyCloseIndex !== -1 ? shellHtml.slice(bodyCloseIndex) : "</body></html>";
454
+
455
+ const { readable, writable } = new TransformStream();
456
+ const writer = writable.getWriter();
457
+ const encoder = new TextEncoder();
458
+
459
+ // Stream dynamic holes in parallel with the prelude
460
+ const resumePromise = (async () => {
461
+ try {
462
+ // 1. Immediately flush static shell prelude (0ms TTFB)
463
+ await writer.write(encoder.encode(shellPrelude));
464
+
465
+ const dynamicState = { value: true };
466
+ const context = createRequestContext(simReq, bridge, platformContext, dynamicState);
467
+ if (typeof copyCustomContextProperties === "function") {
468
+ copyCustomContextProperties(rootContext, context);
469
+ }
470
+ if (typeof setCurrentContext === "function") {
471
+ setCurrentContext(context);
472
+ }
473
+
474
+ await requestStorage.run(context, async () => {
475
+ const isNotFound = { value: false };
476
+ const jsx = await getJSX(
477
+ reqPath,
478
+ queryObj,
479
+ isNotFound,
480
+ isDevelopment,
481
+ false
482
+ );
483
+
484
+ let holes = Array.isArray(metadata?.holes) ? metadata.holes : null;
485
+ if ((!holes || holes.length === 0) && typeof shellPrelude === "string") {
486
+ const extracted = [
487
+ ...shellPrelude.matchAll(/data-ppr-hole="(ppr-hole-\d+)"/g),
488
+ ].map((m) => m[1]);
489
+ if (extracted.length > 0 || Array.isArray(metadata?.holes)) {
490
+ holes = extracted;
491
+ }
492
+ }
493
+
494
+ await streamDynamicHoles(
495
+ jsx,
496
+ holes,
497
+ writer,
498
+ encoder,
499
+ platformContext,
500
+ isDevelopment
501
+ );
502
+ });
503
+ } catch (streamErr) {
504
+ console.error("[Dinou PPR] Runtime streaming resume error:", streamErr);
505
+ } finally {
506
+ try {
507
+ await writer.write(encoder.encode(shellPostlude));
508
+ await writer.close();
509
+ } catch (_) {}
510
+ }
511
+ })();
512
+
513
+ if (
514
+ platformContext &&
515
+ platformContext.ctx &&
516
+ typeof platformContext.ctx.waitUntil === "function"
517
+ ) {
518
+ platformContext.ctx.waitUntil(resumePromise);
519
+ }
520
+
521
+ const headers = new Headers(bridge.headers);
522
+ headers.set("Content-Type", "text/html; charset=utf-8");
523
+ headers.set("Cache-Control", "no-store, no-cache, must-revalidate");
524
+
525
+ return new Response(readable, {
526
+ status: metadata?.status || 200,
527
+ headers,
528
+ });
529
+ }
530
+
531
+ export {
532
+ streamDynamicHoles,
533
+ handlePprResume,
534
+ spliceDynamicHolesIntoShell,
535
+ };
536
+ export default {
537
+ streamDynamicHoles,
538
+ handlePprResume,
539
+ spliceDynamicHolesIntoShell,
540
+ };