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
@@ -10,7 +10,21 @@ import { asyncRenderJSXToClientJSX } from "./render-jsx-to-client-jsx.js";
10
10
  import { DinouCacheSlotBoundary as RawDinouCacheSlotBoundary } from "./slot.js";
11
11
  import { getContext } from "./request-context.js";
12
12
  import { getJSX } from "./get-jsx.js";
13
+ import {
14
+ isPprBuildActive,
15
+ isInsideSuspense,
16
+ deferPprSuspenseEffect,
17
+ runWithPprContext,
18
+ isInsideLayoutSegment,
19
+ isInsidePageSegment,
20
+ } from "./ppr-context.js";
13
21
  import { createRequire } from "node:module";
22
+ import { AsyncLocalStorage } from "node:async_hooks";
23
+
24
+ const slotDiscoveryStorage = new AsyncLocalStorage();
25
+ function isSlotDiscoveryActive() {
26
+ return Boolean(slotDiscoveryStorage.getStore()?.active);
27
+ }
14
28
 
15
29
  const require = createRequire(import.meta.url);
16
30
  const currentDir = path.dirname(fileURLToPath(import.meta.url));
@@ -21,6 +35,18 @@ if (!globalThis[INFLIGHT_KEY]) {
21
35
  }
22
36
  const inflightSlotRenders = globalThis[INFLIGHT_KEY];
23
37
 
38
+ const SLOT_GEN_KEY = Symbol.for("dinou.slot.render.generation");
39
+ if (!globalThis[SLOT_GEN_KEY]) {
40
+ globalThis[SLOT_GEN_KEY] = new Map();
41
+ }
42
+ const slotRenderGenerations = globalThis[SLOT_GEN_KEY];
43
+
44
+ const RECENT_FRESH_KEY = Symbol.for("dinou.slot.recent.fresh");
45
+ if (!globalThis[RECENT_FRESH_KEY]) {
46
+ globalThis[RECENT_FRESH_KEY] = new Map();
47
+ }
48
+ const recentFreshSlotRenders = globalThis[RECENT_FRESH_KEY];
49
+
24
50
  const BG_REVAL_KEY = Symbol.for("dinou.slot.background.revalidations");
25
51
  if (!globalThis[BG_REVAL_KEY]) {
26
52
  globalThis[BG_REVAL_KEY] = new Set();
@@ -33,6 +59,46 @@ if (!globalThis[SLOT_REGISTRY_KEY]) {
33
59
  }
34
60
  const slotRegistry = globalThis[SLOT_REGISTRY_KEY];
35
61
 
62
+ const DISCOVERING_SLOTS_KEY = Symbol.for("dinou.slot.discovering");
63
+ if (!globalThis[DISCOVERING_SLOTS_KEY]) {
64
+ globalThis[DISCOVERING_SLOTS_KEY] = new Set();
65
+ }
66
+ const discoveringSlots = globalThis[DISCOVERING_SLOTS_KEY];
67
+
68
+ const PRE_EVAL_ROUTES_KEY = Symbol.for("dinou.slot.preeval.routes");
69
+ if (!globalThis[PRE_EVAL_ROUTES_KEY] || !(globalThis[PRE_EVAL_ROUTES_KEY] instanceof Map)) {
70
+ globalThis[PRE_EVAL_ROUTES_KEY] = new Map();
71
+ }
72
+ const preEvaluatingRoutes = globalThis[PRE_EVAL_ROUTES_KEY];
73
+
74
+ let _registerServerRefFn = null;
75
+ function getRegisterServerReference() {
76
+ if (_registerServerRefFn) return _registerServerRefFn;
77
+ if (
78
+ typeof globalThis !== "undefined" &&
79
+ globalThis.__DINOU_EDGE_RENDERER__ &&
80
+ typeof globalThis.__DINOU_EDGE_RENDERER__.registerServerReference === "function"
81
+ ) {
82
+ _registerServerRefFn = globalThis.__DINOU_EDGE_RENDERER__.registerServerReference;
83
+ return _registerServerRefFn;
84
+ }
85
+ try {
86
+ const pkg = require("react-server-dom-webpack/server");
87
+ if (typeof pkg.registerServerReference === "function") {
88
+ _registerServerRefFn = pkg.registerServerReference;
89
+ return _registerServerRefFn;
90
+ }
91
+ } catch (e) {}
92
+ try {
93
+ const pkg = require("@roggc/react-server-dom-esm/server.node.js");
94
+ if (typeof pkg.registerServerReference === "function") {
95
+ _registerServerRefFn = pkg.registerServerReference;
96
+ return _registerServerRefFn;
97
+ }
98
+ } catch (e) {}
99
+ return null;
100
+ }
101
+
36
102
  let _DinouCacheSlotBoundary = null;
37
103
  function getCacheSlotBoundary() {
38
104
  if (!_DinouCacheSlotBoundary) {
@@ -44,10 +110,19 @@ function getCacheSlotBoundary() {
44
110
  const slotPath = path.resolve(currentDir, "slot.js");
45
111
  const fileUrl = pathToFileURL(slotPath).href;
46
112
  let regFn = null;
47
- try {
48
- const pkg = require("react-server-dom-webpack/server");
49
- regFn = pkg.registerClientReference;
50
- } catch (e) {}
113
+ if (
114
+ typeof globalThis !== "undefined" &&
115
+ globalThis.__DINOU_EDGE_RENDERER__ &&
116
+ typeof globalThis.__DINOU_EDGE_RENDERER__.registerClientReference === "function"
117
+ ) {
118
+ regFn = globalThis.__DINOU_EDGE_RENDERER__.registerClientReference;
119
+ }
120
+ if (!regFn) {
121
+ try {
122
+ const pkg = require("react-server-dom-webpack/server");
123
+ regFn = pkg.registerClientReference;
124
+ } catch (e) {}
125
+ }
51
126
  if (!regFn) {
52
127
  try {
53
128
  const pkg = require("@roggc/react-server-dom-esm/server.node.js");
@@ -74,7 +149,8 @@ function getCacheSlotBoundary() {
74
149
 
75
150
  /**
76
151
  * Serializes a resolved JSX element tree into a JSON-safe string,
77
- * preserving symbols, React 19 transitional elements, and client component references.
152
+ * preserving symbols, React 19 transitional elements, client component references,
153
+ * and server function references ("use server").
78
154
  */
79
155
  function serializeJSX(jsx) {
80
156
  return JSON.stringify(jsx, (key, value) => {
@@ -93,6 +169,17 @@ function serializeJSX(jsx) {
93
169
  async: value.$$async,
94
170
  };
95
171
  }
172
+ if (
173
+ (typeof value === "function" || typeof value === "object") &&
174
+ value !== null &&
175
+ value.$$typeof === Symbol.for("react.server.reference")
176
+ ) {
177
+ return {
178
+ __dinou_server_ref__: true,
179
+ id: value.$$id || value.name,
180
+ bound: value.$$bound || null,
181
+ };
182
+ }
96
183
  if (
97
184
  value &&
98
185
  typeof value === "object" &&
@@ -128,6 +215,26 @@ function deserializeJSX(json) {
128
215
  });
129
216
  return fakeRef;
130
217
  }
218
+ if (value.__dinou_server_ref__) {
219
+ let serverRef = function () {};
220
+ const regServerRef = getRegisterServerReference();
221
+ if (regServerRef) {
222
+ try {
223
+ serverRef = regServerRef(serverRef, value.id, null);
224
+ if (Array.isArray(value.bound) && typeof serverRef.bind === "function") {
225
+ serverRef = serverRef.bind(null, ...value.bound);
226
+ }
227
+ } catch (e) {}
228
+ }
229
+ if (serverRef.$$typeof !== Symbol.for("react.server.reference")) {
230
+ Object.defineProperties(serverRef, {
231
+ $$typeof: { value: Symbol.for("react.server.reference") },
232
+ $$id: { value: value.id },
233
+ $$bound: { value: value.bound || null },
234
+ });
235
+ }
236
+ return serverRef;
237
+ }
131
238
  }
132
239
  return value;
133
240
  });
@@ -149,11 +256,22 @@ function deserializeJSX(json) {
149
256
  props.key = node.key;
150
257
  }
151
258
  const children = props.children;
259
+ let elem;
152
260
  if (Array.isArray(children)) {
261
+ for (const ch of children) {
262
+ if (ch && typeof ch === "object" && ch._store) {
263
+ ch._store.validated = 1;
264
+ }
265
+ }
153
266
  delete props.children;
154
- return React.createElement(type, props, ...children);
267
+ elem = React.createElement(type, props, ...children);
268
+ } else {
269
+ elem = React.createElement(type, props);
270
+ }
271
+ if (elem && typeof elem === "object" && elem._store) {
272
+ elem._store.validated = 1;
155
273
  }
156
- return React.createElement(type, props);
274
+ return elem;
157
275
  }
158
276
  return node;
159
277
  }
@@ -161,6 +279,194 @@ function deserializeJSX(json) {
161
279
  return toReactElement(parsed);
162
280
  }
163
281
 
282
+ function recordSlotTagsOnContext(
283
+ tags,
284
+ inLayout = isInsideLayoutSegment(),
285
+ inPage = isInsidePageSegment()
286
+ ) {
287
+ if (!Array.isArray(tags) || tags.length === 0) return;
288
+ try {
289
+ const reqContext = getContext();
290
+ if (reqContext) {
291
+ if (!reqContext._slotTags) {
292
+ reqContext._slotTags = new Set();
293
+ }
294
+ if (!reqContext._layoutSlotTags) {
295
+ reqContext._layoutSlotTags = new Set();
296
+ }
297
+ if (!reqContext._pageSlotTags) {
298
+ reqContext._pageSlotTags = new Set();
299
+ }
300
+ for (const t of tags) {
301
+ if (!t) continue;
302
+ reqContext._slotTags.add(t);
303
+ if (inLayout) {
304
+ reqContext._layoutSlotTags.add(t);
305
+ } else if (inPage) {
306
+ reqContext._pageSlotTags.add(t);
307
+ } else if (!reqContext._layoutSlotTags.has(t)) {
308
+ reqContext._pageSlotTags.add(t);
309
+ }
310
+ }
311
+ }
312
+ } catch (e) {}
313
+ }
314
+
315
+ function commitSlotTags(tags) {
316
+ if (!Array.isArray(tags) || tags.length === 0) return;
317
+ const inLayout = isInsideLayoutSegment();
318
+ const inPage = isInsidePageSegment();
319
+ if (!deferPprSuspenseEffect(() => recordSlotTagsOnContext(tags, inLayout, inPage))) {
320
+ recordSlotTagsOnContext(tags, inLayout, inPage);
321
+ }
322
+ }
323
+
324
+ /**
325
+ * Reads a slot entry from storage, falling back to pre-rendered Edge static assets (env.ASSETS)
326
+ * when the runtime KV/Memory storage has not yet hydrated the build-time slot artifact.
327
+ */
328
+ async function getSlotFromStorage(storage, storageKey, knownTags = []) {
329
+ if (!storage) return null;
330
+ let cached = null;
331
+ try {
332
+ cached = await storage.get(storageKey);
333
+ } catch (err) {}
334
+ if (cached && cached.content) {
335
+ return cached;
336
+ }
337
+
338
+ const isDeleted =
339
+ typeof storage.isDeleted === "function" && storage.isDeleted(storageKey);
340
+ if (isDeleted) {
341
+ return null;
342
+ }
343
+
344
+ try {
345
+ const reqContext = getContext();
346
+ const assets =
347
+ reqContext?.env?.ASSETS ||
348
+ reqContext?.platformContext?.env?.ASSETS ||
349
+ reqContext?.req?.env?.ASSETS;
350
+ if (assets && typeof assets.fetch === "function") {
351
+ const cleanKey = String(storageKey || "").replace(/^\/+/, "");
352
+ const metaKey = cleanKey.endsWith("/slot.json")
353
+ ? cleanKey.slice(0, -"/slot.json".length) + "/slot.metadata.json"
354
+ : `${cleanKey}.metadata.json`;
355
+ const [slotRes, metaRes] = await Promise.all([
356
+ assets.fetch(new Request(`http://localhost/${cleanKey}`)),
357
+ assets.fetch(new Request(`http://localhost/${metaKey}`)),
358
+ ]);
359
+ if (slotRes && slotRes.status === 200) {
360
+ const ct = slotRes.headers?.get?.("content-type") || "";
361
+ const content = await slotRes.text();
362
+ if (!ct.includes("text/html") && !content.trimStart().startsWith("<")) {
363
+ let metadata = null;
364
+ if (metaRes && metaRes.status === 200) {
365
+ try {
366
+ metadata = await metaRes.json();
367
+ } catch (e) {}
368
+ }
369
+ const generatedAt = metadata?.generatedAt || 0;
370
+ const combinedTags = new Set([
371
+ ...(Array.isArray(metadata?.tags) ? metadata.tags : []),
372
+ ...(Array.isArray(knownTags) ? knownTags : []),
373
+ ]);
374
+ if (typeof storage.getTagInvalidatedAt === "function") {
375
+ for (const t of combinedTags) {
376
+ const invAt = storage.getTagInvalidatedAt(t);
377
+ if (invAt > 0 && invAt >= generatedAt) {
378
+ return null;
379
+ }
380
+ }
381
+ }
382
+ cached = { content, metadata };
383
+ await storage.set(cleanKey, content, metadata);
384
+ return cached;
385
+ }
386
+ }
387
+ }
388
+ } catch (e) {}
389
+
390
+ return cached;
391
+ }
392
+
393
+ /**
394
+ * Traverses a deserialized JSX tree from a cached outer slot and refreshes
395
+ * any nested <DinouCacheSlot> boundaries so inner slot invalidations are
396
+ * respected even when the outer slot hits its cache.
397
+ */
398
+ async function refreshNestedSlotsInTree(node, currentSlotId, options = {}) {
399
+ if (node == null || typeof node !== "object") return node;
400
+ if (isSlotDiscoveryActive()) return node;
401
+
402
+ if (Array.isArray(node)) {
403
+ return Promise.all(
404
+ node.map((item) => refreshNestedSlotsInTree(item, currentSlotId, options))
405
+ );
406
+ }
407
+
408
+ if (node.$$typeof === Symbol.for("react.transitional.element")) {
409
+ const nestedSlotId = node.props && node.props.__dinou_slot__;
410
+ if (nestedSlotId && nestedSlotId !== currentSlotId) {
411
+ const nestedTags = Array.isArray(node.props.tags) ? node.props.tags : [];
412
+ commitSlotTags(Array.from(new Set([nestedSlotId, ...nestedTags].filter(Boolean))));
413
+ if (!slotRegistry.has(nestedSlotId) && slotRegistry.has(currentSlotId)) {
414
+ const parentEntry = slotRegistry.get(currentSlotId);
415
+ if (parentEntry && typeof parentEntry.discover === "function") {
416
+ await parentEntry.discover();
417
+ }
418
+ }
419
+ let currentPath = options.currentPath;
420
+ if (!currentPath) {
421
+ try {
422
+ currentPath = getContext()?.req?.path;
423
+ } catch (e) {}
424
+ }
425
+ const freshInner = await getSlotJSX(nestedSlotId, {
426
+ ...options,
427
+ currentPath,
428
+ skipHostRevalidate: true,
429
+ });
430
+ if (freshInner !== null) {
431
+ const refreshedInner = await refreshNestedSlotsInTree(
432
+ freshInner,
433
+ nestedSlotId,
434
+ options
435
+ );
436
+ const newProps = { ...node.props };
437
+ if (node.key != null) newProps.key = node.key;
438
+ delete newProps.children;
439
+ return React.createElement(node.type, newProps, refreshedInner);
440
+ }
441
+ }
442
+
443
+ if (node.props && typeof node.props === "object") {
444
+ let changed = false;
445
+ const newProps = { ...node.props };
446
+ for (const [k, v] of Object.entries(node.props)) {
447
+ if (v && typeof v === "object") {
448
+ const updated = await refreshNestedSlotsInTree(v, currentSlotId, options);
449
+ if (updated !== v) {
450
+ newProps[k] = updated;
451
+ changed = true;
452
+ }
453
+ }
454
+ }
455
+ if (changed) {
456
+ if (node.key != null) newProps.key = node.key;
457
+ const children = newProps.children;
458
+ if (Array.isArray(children)) {
459
+ delete newProps.children;
460
+ return React.createElement(node.type, newProps, ...children);
461
+ }
462
+ return React.createElement(node.type, newProps);
463
+ }
464
+ }
465
+ }
466
+
467
+ return node;
468
+ }
469
+
164
470
  /**
165
471
  * DinouCacheSlot component.
166
472
  *
@@ -184,36 +490,89 @@ async function DinouCacheSlot(props) {
184
490
  : tag
185
491
  ? [tag]
186
492
  : [];
493
+ const slotTagsToCommit = Array.from(new Set([slotId, ...allTags].filter(Boolean)));
187
494
 
188
495
  const storageKey = `slots/${slotId}/slot.json`;
189
496
  const storage = getStorageAdapter();
497
+ const isNoCache = revalidate === 0;
190
498
 
191
- function wrapWithBoundary(content) {
499
+ function wrapWithBoundary(content, alreadyRendered = false) {
192
500
  const Boundary = getCacheSlotBoundary();
193
501
  if (!Boundary) return content;
194
- return React.createElement(Boundary, { id: slotId }, content);
502
+ const elem = React.createElement(
503
+ Boundary,
504
+ { id: slotId, tags: allTags, __dinou_slot__: slotId },
505
+ content
506
+ );
507
+ if (alreadyRendered) {
508
+ return Object.defineProperties(
509
+ Object.create(Object.getPrototypeOf(elem)),
510
+ {
511
+ ...Object.getOwnPropertyDescriptors(elem),
512
+ __clientJsxAlreadyRendered: {
513
+ value: true,
514
+ enumerable: false,
515
+ configurable: true,
516
+ },
517
+ }
518
+ );
519
+ }
520
+ return elem;
195
521
  }
196
522
 
197
- // Register in slotRegistry for on-demand endpoint re-rendering
523
+ // Register in slotRegistry for on-demand endpoint re-rendering and nested slot discovery
198
524
  slotRegistry.set(slotId, {
199
525
  render: async () => {
200
526
  const childElement = typeof children === "function" ? await children() : children;
201
527
  return await asyncRenderJSXToClientJSX(childElement);
202
528
  },
529
+ discover: async () => {
530
+ if (discoveringSlots.has(slotId)) return;
531
+ discoveringSlots.add(slotId);
532
+ try {
533
+ await slotDiscoveryStorage.run({ active: true }, async () => {
534
+ const childElement = typeof children === "function" ? await children() : children;
535
+ await asyncRenderJSXToClientJSX(childElement);
536
+ });
537
+ } catch (e) {
538
+ } finally {
539
+ discoveringSlots.delete(slotId);
540
+ }
541
+ },
203
542
  tags: allTags,
204
543
  revalidate: typeof revalidate === "number" ? revalidate : undefined,
205
544
  });
206
545
 
207
- if (!storage) {
208
- const directContent = typeof children === "function" ? await children() : children;
209
- return wrapWithBoundary(directContent);
546
+ // When running inside a nested slot discovery pass, recursively discover any child slots
547
+ if (isSlotDiscoveryActive() && !discoveringSlots.has(slotId)) {
548
+ const ownEntry = slotRegistry.get(slotId);
549
+ if (ownEntry && typeof ownEntry.discover === "function") {
550
+ await ownEntry.discover();
551
+ }
552
+ }
553
+
554
+ if (!storage || isNoCache) {
555
+ const childElement = typeof children === "function" ? await children() : children;
556
+ const directContent = await asyncRenderJSXToClientJSX(childElement);
557
+ commitSlotTags(slotTagsToCommit);
558
+ return wrapWithBoundary(directContent, true);
210
559
  }
211
560
 
212
561
  // 1. Check if cached in storage
213
- let cached = null;
214
- try {
215
- cached = await storage.get(storageKey);
216
- } catch (err) {}
562
+ let cached = await getSlotFromStorage(storage, storageKey, allTags);
563
+
564
+ // During a PPR static shell build, if a slot is inside a <Suspense> boundary
565
+ // and was only cached at runtime (not part of the static shell), do not short-circuit
566
+ // from disk so any dynamic request access (cookies/headers/query) inside the slot still
567
+ // triggers PPR postpone.
568
+ if (
569
+ isPprBuildActive() &&
570
+ isInsideSuspense() &&
571
+ cached &&
572
+ !cached.metadata?.inStaticShell
573
+ ) {
574
+ cached = null;
575
+ }
217
576
 
218
577
  const now = Date.now();
219
578
  if (cached && cached.content) {
@@ -226,6 +585,13 @@ async function DinouCacheSlot(props) {
226
585
  ? meta.revalidate
227
586
  : undefined;
228
587
 
588
+ if (revalidateSeconds === 0) {
589
+ const childElement = typeof children === "function" ? await children() : children;
590
+ const directContent = await asyncRenderJSXToClientJSX(childElement);
591
+ commitSlotTags(slotTagsToCommit);
592
+ return wrapWithBoundary(directContent, true);
593
+ }
594
+
229
595
  const isExpired =
230
596
  typeof revalidateSeconds === "number" &&
231
597
  revalidateSeconds > 0 &&
@@ -234,69 +600,52 @@ async function DinouCacheSlot(props) {
234
600
  if (!isExpired) {
235
601
  try {
236
602
  const restored = deserializeJSX(cached.content);
237
- return wrapWithBoundary(restored);
238
- } catch (err) {}
239
- } else {
240
- // Stale-While-Revalidate
241
- try {
242
- const staleJSX = deserializeJSX(cached.content);
243
-
244
- if (!backgroundRevalidations.has(storageKey)) {
245
- backgroundRevalidations.add(storageKey);
246
- const bgPromise = (async () => {
247
- try {
248
- const childElement = typeof children === "function" ? await children() : children;
249
- const resolved = await asyncRenderJSXToClientJSX(childElement);
250
- const serialized = serializeJSX(resolved);
251
- await storage.set(storageKey, serialized, {
252
- tags: allTags,
253
- revalidate: revalidateSeconds,
254
- generatedAt: Date.now(),
255
- slotId,
256
- });
257
- } catch (e) {
258
- console.error(`[DinouCacheSlot] Background revalidation failed for slot "${slotId}":`, e);
259
- } finally {
260
- backgroundRevalidations.delete(storageKey);
261
- }
262
- })();
263
-
264
- try {
265
- const reqContext = getContext();
266
- const ctx = reqContext?.ctx || reqContext?.platformContext?.ctx || reqContext?.req?.ctx;
267
- if (ctx && typeof ctx.waitUntil === "function") {
268
- ctx.waitUntil(bgPromise);
269
- }
270
- } catch (e) {}
271
- }
272
-
273
- return wrapWithBoundary(staleJSX);
603
+ const withRefreshedNested = await refreshNestedSlotsInTree(restored, slotId);
604
+ commitSlotTags(slotTagsToCommit);
605
+ return wrapWithBoundary(withRefreshedNested, false);
274
606
  } catch (err) {}
275
607
  }
276
608
  }
277
609
 
278
- // 2. Cache MISS or expired without usable stale content: Deduplicate synchronous render
610
+ // 2. Cache MISS or expired TTL: Deduplicate synchronous render
279
611
  if (inflightSlotRenders.has(storageKey)) {
280
612
  try {
281
613
  const deduped = await inflightSlotRenders.get(storageKey);
282
- return wrapWithBoundary(deduped);
614
+ commitSlotTags(slotTagsToCommit);
615
+ return wrapWithBoundary(deduped, true);
283
616
  } catch (e) {}
284
617
  }
285
618
 
619
+ const inPprSuspense = isPprBuildActive() && isInsideSuspense();
620
+ const isPprShellBuild = isPprBuildActive();
621
+
286
622
  const renderPromise = (async () => {
287
623
  const childElement = typeof children === "function" ? await children() : children;
288
624
  const resolved = await asyncRenderJSXToClientJSX(childElement);
289
625
  const serialized = serializeJSX(resolved);
290
626
 
291
- try {
292
- await storage.set(storageKey, serialized, {
293
- tags: allTags,
294
- revalidate: typeof revalidate === "number" ? revalidate : undefined,
295
- generatedAt: Date.now(),
296
- slotId,
297
- });
298
- } catch (err) {
299
- console.error(`[DinouCacheSlot] Failed to write cache for slot "${slotId}":`, err);
627
+ const slotMeta = {
628
+ tags: allTags,
629
+ revalidate: typeof revalidate === "number" ? revalidate : undefined,
630
+ generatedAt: Date.now(),
631
+ slotId,
632
+ inStaticShell: Boolean(isPprShellBuild || cached?.metadata?.inStaticShell),
633
+ };
634
+
635
+ const persistSlot = async () => {
636
+ try {
637
+ await storage.set(storageKey, serialized, slotMeta);
638
+ } catch (err) {
639
+ console.error(`[DinouCacheSlot] Failed to write cache for slot "${slotId}":`, err);
640
+ }
641
+ };
642
+
643
+ if (inPprSuspense) {
644
+ if (!deferPprSuspenseEffect(persistSlot)) {
645
+ await persistSlot();
646
+ }
647
+ } else {
648
+ await persistSlot();
300
649
  }
301
650
 
302
651
  return deserializeJSX(serialized);
@@ -305,94 +654,376 @@ async function DinouCacheSlot(props) {
305
654
  inflightSlotRenders.set(storageKey, renderPromise);
306
655
  try {
307
656
  const fresh = await renderPromise;
308
- return wrapWithBoundary(fresh);
657
+ commitSlotTags(slotTagsToCommit);
658
+ return wrapWithBoundary(fresh, true);
309
659
  } finally {
310
660
  inflightSlotRenders.delete(storageKey);
311
661
  }
312
662
  }
313
663
 
664
+ /**
665
+ * Resolves a slot ID or tag to its canonical slotId using slotRegistry or storage metadata.
666
+ */
667
+ async function resolveCanonicalSlotId(slotIdOrTag, storage) {
668
+ if (slotRegistry.has(slotIdOrTag)) {
669
+ return slotIdOrTag;
670
+ }
671
+ for (const [regId, entry] of slotRegistry.entries()) {
672
+ if (Array.isArray(entry.tags) && entry.tags.includes(slotIdOrTag)) {
673
+ return regId;
674
+ }
675
+ }
676
+ if (storage) {
677
+ try {
678
+ const direct = await getSlotFromStorage(storage, `slots/${slotIdOrTag}/slot.json`);
679
+ if (direct && direct.content) {
680
+ return slotIdOrTag;
681
+ }
682
+ if (typeof storage.keys === "function") {
683
+ const keys = await storage.keys("slots/");
684
+ for (const rawKey of keys) {
685
+ const key = String(rawKey || "").replace(/\\/g, "/");
686
+ if (key.endsWith("/slot.json") || key.endsWith("/slot.metadata.json")) {
687
+ const item = await storage.get(key);
688
+ let meta = item?.metadata;
689
+ if (!meta && key.endsWith("/slot.metadata.json") && item?.content) {
690
+ try {
691
+ meta = JSON.parse(item.content);
692
+ } catch (e) {}
693
+ }
694
+ if (meta && Array.isArray(meta.tags) && meta.tags.includes(slotIdOrTag)) {
695
+ if (meta.slotId) return meta.slotId;
696
+ const match = key.match(/^slots\/([^/]+)\//);
697
+ if (match) return match[1];
698
+ }
699
+ }
700
+ }
701
+ }
702
+ } catch (e) {}
703
+ }
704
+ return slotIdOrTag;
705
+ }
706
+
314
707
  /**
315
708
  * Resolves a slot's JSX tree for the granular /____rsc_slot____/:id endpoint.
316
709
  */
317
710
  async function getSlotJSX(slotId, options = {}) {
318
711
  const storage = getStorageAdapter();
319
- const storageKey = `slots/${slotId}/slot.json`;
712
+ let targetId = await resolveCanonicalSlotId(slotId, storage);
713
+ let storageKey = `slots/${targetId}/slot.json`;
320
714
 
321
- // 1. Check storage cache
322
- let cached = null;
323
- if (storage) {
715
+ const reqUrlEarly = String(options.req?.url || "");
716
+ const qIdxEarly = reqUrlEarly.indexOf("?");
717
+ const queryKeyEarly = qIdxEarly !== -1 ? reqUrlEarly.slice(qIdxEarly) : "";
718
+ const earlyStampedeKey = `${storageKey}::${queryKeyEarly}`;
719
+ const earlyInflightKey = options.fresh ? earlyStampedeKey : storageKey;
720
+
721
+ if (inflightSlotRenders.has(earlyInflightKey)) {
324
722
  try {
325
- cached = await storage.get(storageKey);
723
+ const deduped = await inflightSlotRenders.get(earlyInflightKey);
724
+ return await refreshNestedSlotsInTree(deduped, targetId, options);
326
725
  } catch (e) {}
327
726
  }
328
727
 
728
+ if (options.fresh && recentFreshSlotRenders.has(earlyStampedeKey)) {
729
+ const recent = recentFreshSlotRenders.get(earlyStampedeKey);
730
+ if (recent && Date.now() - recent.timestamp < 500 && recent.serialized) {
731
+ recent.timestamp = Date.now();
732
+ const restored = deserializeJSX(recent.serialized);
733
+ return await refreshNestedSlotsInTree(restored, targetId, options);
734
+ }
735
+ recentFreshSlotRenders.delete(earlyStampedeKey);
736
+ }
737
+
738
+ // 1. Check storage cache
739
+ let cached = await getSlotFromStorage(storage, storageKey);
740
+
741
+ const regEntryInitial = slotRegistry.get(targetId);
329
742
  const now = Date.now();
330
743
  if (cached && cached.content) {
331
744
  const meta = cached.metadata || {};
332
745
  const generatedAt = meta.generatedAt || 0;
333
746
  const revalidateSeconds =
334
- typeof meta.revalidate === "number" ? meta.revalidate : undefined;
747
+ typeof regEntryInitial?.revalidate === "number"
748
+ ? regEntryInitial.revalidate
749
+ : typeof meta.revalidate === "number"
750
+ ? meta.revalidate
751
+ : undefined;
335
752
 
753
+ const isNoCache = revalidateSeconds === 0;
336
754
  const isExpired =
337
- typeof revalidateSeconds === "number" &&
338
- revalidateSeconds > 0 &&
339
- now > generatedAt + revalidateSeconds * 1000;
755
+ isNoCache ||
756
+ (typeof revalidateSeconds === "number" &&
757
+ revalidateSeconds > 0 &&
758
+ now > generatedAt + revalidateSeconds * 1000);
340
759
 
341
760
  if (!isExpired && !options.fresh) {
342
761
  try {
343
- return deserializeJSX(cached.content);
762
+ const restored = deserializeJSX(cached.content);
763
+ return await refreshNestedSlotsInTree(restored, targetId, options);
344
764
  } catch (e) {}
345
765
  }
346
766
  }
347
767
 
348
- // 2. If missing from storage (e.g. was invalidated) or expired or forced fresh:
349
- if (!slotRegistry.has(slotId) && options.currentPath) {
350
- try {
351
- const isNotFound = { value: false };
352
- await getJSX(options.currentPath, {}, isNotFound, false, false, { segment: "page" });
353
- } catch (e) {
354
- console.warn(`[getSlotJSX] Could not pre-evaluate route "${options.currentPath}" to register slot "${slotId}":`, e);
768
+ async function discoverFromRegisteredSlots() {
769
+ const attempted = new Set();
770
+ let progressed = true;
771
+ while (!slotRegistry.has(targetId) && progressed) {
772
+ progressed = false;
773
+ for (const [regKey, entry] of Array.from(slotRegistry.entries())) {
774
+ if (attempted.has(regKey)) continue;
775
+ attempted.add(regKey);
776
+ progressed = true;
777
+ if (typeof entry.discover === "function") {
778
+ await entry.discover();
779
+ targetId = await resolveCanonicalSlotId(slotId, storage);
780
+ if (slotRegistry.has(targetId)) return;
781
+ }
782
+ }
783
+ }
784
+ }
785
+
786
+ // 2. First try discovering nested slots from already-registered outer slots
787
+ if (!slotRegistry.has(targetId)) {
788
+ await discoverFromRegisteredSlots();
789
+ }
790
+
791
+ // 3. If still not in slotRegistry (e.g., cold server start), pre-evaluate the route once
792
+ if (!slotRegistry.has(targetId) && options.currentPath) {
793
+ if (preEvaluatingRoutes.has(options.currentPath)) {
794
+ try {
795
+ await preEvaluatingRoutes.get(options.currentPath);
796
+ } catch (e) {}
797
+ targetId = await resolveCanonicalSlotId(slotId, storage);
798
+ } else {
799
+ const preEvalPromise = (async () => {
800
+ try {
801
+ const isNotFound = { value: false };
802
+ await runWithPprContext({ isPpr: true }, async () => {
803
+ await slotDiscoveryStorage.run({ active: true }, async () => {
804
+ const pageJsx = await getJSX(options.currentPath, {}, isNotFound, false, false, {
805
+ segment: "page",
806
+ });
807
+ if (pageJsx) {
808
+ await asyncRenderJSXToClientJSX(pageJsx);
809
+ }
810
+ const resolvedId = await resolveCanonicalSlotId(slotId, storage);
811
+
812
+ if (!slotRegistry.has(resolvedId)) {
813
+ const fullJsx = await getJSX(options.currentPath, {}, isNotFound, false, false);
814
+ if (fullJsx) {
815
+ await asyncRenderJSXToClientJSX(fullJsx);
816
+ }
817
+ }
818
+ });
819
+ });
820
+ } catch (e) {
821
+ console.warn(
822
+ `[getSlotJSX] Could not pre-evaluate route "${options.currentPath}" to register slot "${slotId}":`,
823
+ e
824
+ );
825
+ } finally {
826
+ preEvaluatingRoutes.delete(options.currentPath);
827
+ }
828
+ })();
829
+ preEvaluatingRoutes.set(options.currentPath, preEvalPromise);
830
+ await preEvalPromise;
831
+ targetId = await resolveCanonicalSlotId(slotId, storage);
832
+ }
833
+
834
+ if (!slotRegistry.has(targetId)) {
835
+ await discoverFromRegisteredSlots();
355
836
  }
356
837
  }
357
838
 
358
- if (slotRegistry.has(slotId)) {
359
- const entry = slotRegistry.get(slotId);
839
+ storageKey = `slots/${targetId}/slot.json`;
840
+
841
+ if (slotRegistry.has(targetId)) {
842
+ const entry = slotRegistry.get(targetId);
843
+ const reqUrl = String(options.req?.url || "");
844
+ const qIdx = reqUrl.indexOf("?");
845
+ const queryKey = qIdx !== -1 ? reqUrl.slice(qIdx) : "";
846
+ const stampedeKey = `${storageKey}::${queryKey}`;
847
+ const inflightKey = options.fresh ? stampedeKey : storageKey;
360
848
  try {
361
- const resolved = await entry.render();
362
- const serialized = serializeJSX(resolved);
363
- if (storage) {
364
- await storage.set(storageKey, serialized, {
365
- tags: entry.tags,
366
- revalidate: entry.revalidate,
367
- generatedAt: Date.now(),
368
- slotId,
369
- });
849
+ if (inflightSlotRenders.has(inflightKey)) {
850
+ const deduped = await inflightSlotRenders.get(inflightKey);
851
+ return await refreshNestedSlotsInTree(deduped, targetId, options);
852
+ }
853
+
854
+ if (options.fresh && recentFreshSlotRenders.has(stampedeKey)) {
855
+ const recent = recentFreshSlotRenders.get(stampedeKey);
856
+ if (recent && Date.now() - recent.timestamp < 500 && recent.serialized) {
857
+ recent.timestamp = Date.now();
858
+ const restored = deserializeJSX(recent.serialized);
859
+ return await refreshNestedSlotsInTree(restored, targetId, options);
860
+ }
861
+ recentFreshSlotRenders.delete(stampedeKey);
862
+ }
863
+
864
+ const renderGen = (slotRenderGenerations.get(storageKey) || 0) + 1;
865
+ slotRenderGenerations.set(storageKey, renderGen);
866
+ const isLatestGen = () => slotRenderGenerations.get(storageKey) === renderGen;
867
+
868
+ const renderPromise = (async () => {
869
+ const resolved = await entry.render();
870
+ const serialized = serializeJSX(resolved);
871
+ if (options.fresh && isLatestGen()) {
872
+ recentFreshSlotRenders.set(stampedeKey, {
873
+ timestamp: Date.now(),
874
+ serialized,
875
+ });
876
+ }
877
+ if (storage && entry.revalidate !== 0 && isLatestGen()) {
878
+ await storage.set(storageKey, serialized, {
879
+ tags: entry.tags,
880
+ revalidate: entry.revalidate,
881
+ generatedAt: Date.now(),
882
+ slotId: targetId,
883
+ inStaticShell: Boolean(cached?.metadata?.inStaticShell),
884
+ });
885
+ }
886
+ if (options.fresh && isLatestGen()) {
887
+ recentFreshSlotRenders.set(stampedeKey, {
888
+ timestamp: Date.now(),
889
+ serialized,
890
+ });
891
+ }
892
+ return deserializeJSX(serialized);
893
+ })();
894
+
895
+ let restored;
896
+ inflightSlotRenders.set(inflightKey, renderPromise);
897
+ try {
898
+ restored = await renderPromise;
899
+ } finally {
900
+ inflightSlotRenders.delete(inflightKey);
901
+ }
902
+
903
+ if (
904
+ storage &&
905
+ entry.revalidate !== 0 &&
906
+ !options.skipHostRevalidate &&
907
+ options.currentPath &&
908
+ isLatestGen()
909
+ ) {
910
+ try {
911
+ const cleanRouteKey = String(options.currentPath)
912
+ .split("?")[0]
913
+ .replace(/^\/+/, "")
914
+ .replace(/\/+$/, "");
915
+ const slotTagsToMatch = new Set([
916
+ targetId,
917
+ slotId,
918
+ ...(Array.isArray(entry.tags) ? entry.tags : []),
919
+ ]);
920
+ const metaKey = cleanRouteKey ? `${cleanRouteKey}/metadata.json` : "metadata.json";
921
+ const metaItem = await storage.get(metaKey);
922
+ let pageMeta = metaItem?.metadata;
923
+ if (!pageMeta && metaItem?.content) {
924
+ try {
925
+ pageMeta = JSON.parse(metaItem.content);
926
+ } catch (e) {}
927
+ }
928
+ if (
929
+ pageMeta &&
930
+ Array.isArray(pageMeta.slotTags) &&
931
+ pageMeta.slotTags.some((t) => slotTagsToMatch.has(t))
932
+ ) {
933
+ const { revalidatePage } = await import("./cache-revalidate.js");
934
+ await revalidatePage("/" + cleanRouteKey, { onlyRefreshSlots: true });
935
+ }
936
+ const segments = cleanRouteKey.split("/").filter(Boolean);
937
+ const candidateLayoutKeys = [""];
938
+ let acc = "";
939
+ for (const seg of segments) {
940
+ acc = acc ? `${acc}/${seg}` : seg;
941
+ candidateLayoutKeys.push(acc);
942
+ }
943
+ for (const lKey of candidateLayoutKeys) {
944
+ const lMetaKey = lKey ? `${lKey}/layout.metadata.json` : "layout.metadata.json";
945
+ const lItem = await storage.get(lMetaKey);
946
+ let lMeta = lItem?.metadata;
947
+ if (!lMeta && lItem?.content) {
948
+ try {
949
+ lMeta = JSON.parse(lItem.content);
950
+ } catch (e) {}
951
+ }
952
+ if (
953
+ lMeta &&
954
+ Array.isArray(lMeta.slotTags) &&
955
+ lMeta.slotTags.some((t) => slotTagsToMatch.has(t))
956
+ ) {
957
+ const { revalidateLayout } = await import("./cache-revalidate.js");
958
+ await revalidateLayout(lKey ? "/" + lKey : "/", { onlyRefreshSlots: true });
959
+ }
960
+ }
961
+ } catch (e) {}
370
962
  }
371
- return deserializeJSX(serialized);
963
+
964
+ return await refreshNestedSlotsInTree(restored, targetId, options);
372
965
  } catch (e) {
373
- console.error(`[getSlotJSX] Failed to regenerate slot "${slotId}":`, e);
966
+ console.error(`[getSlotJSX] Failed to regenerate slot "${targetId}":`, e);
374
967
  }
375
968
  }
376
969
 
377
970
  // Fallback to cached content if regeneration failed
378
971
  if (cached && cached.content) {
379
972
  try {
380
- return deserializeJSX(cached.content);
973
+ const restored = deserializeJSX(cached.content);
974
+ return await refreshNestedSlotsInTree(restored, targetId, options);
381
975
  } catch (e) {}
382
976
  }
383
977
 
384
978
  return null;
385
979
  }
386
980
 
981
+ async function hasExpiredSlots(slotTags) {
982
+ if (!Array.isArray(slotTags) || slotTags.length === 0) return false;
983
+ const storage = getStorageAdapter();
984
+ if (!storage) return false;
985
+ const now = Date.now();
986
+ const checkedIds = new Set();
987
+ for (const rawTagOrId of slotTags) {
988
+ if (!rawTagOrId) continue;
989
+ const targetId = await resolveCanonicalSlotId(rawTagOrId, storage);
990
+ if (checkedIds.has(targetId)) continue;
991
+ checkedIds.add(targetId);
992
+ const storageKey = `slots/${targetId}/slot.json`;
993
+ const cached = await getSlotFromStorage(storage, storageKey);
994
+ if (!cached || !cached.content) continue;
995
+ const meta = cached.metadata || {};
996
+ const regEntry = slotRegistry.get(targetId);
997
+ const revalidateSeconds =
998
+ typeof regEntry?.revalidate === "number"
999
+ ? regEntry.revalidate
1000
+ : typeof meta.revalidate === "number"
1001
+ ? meta.revalidate
1002
+ : undefined;
1003
+ if (
1004
+ typeof revalidateSeconds === "number" &&
1005
+ revalidateSeconds > 0 &&
1006
+ now > (meta.generatedAt || 0) + revalidateSeconds * 1000
1007
+ ) {
1008
+ return true;
1009
+ }
1010
+ }
1011
+ return false;
1012
+ }
1013
+
387
1014
  export {
388
1015
  DinouCacheSlot,
389
1016
  getSlotJSX,
390
1017
  serializeJSX,
391
1018
  deserializeJSX,
1019
+ refreshNestedSlotsInTree,
1020
+ hasExpiredSlots,
392
1021
  };
393
1022
  export default {
394
1023
  DinouCacheSlot,
395
1024
  getSlotJSX,
396
1025
  serializeJSX,
397
1026
  deserializeJSX,
1027
+ refreshNestedSlotsInTree,
1028
+ hasExpiredSlots,
398
1029
  };