dinou 9.0.2 → 9.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +379 -9742
  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/bailout-proxy.js +2 -2
  7. package/dinou/core/build-static-pages.js +17 -7
  8. package/dinou/core/cache-revalidate.js +977 -152
  9. package/dinou/core/cache-slot.js +848 -103
  10. package/dinou/core/client-webpack.jsx +60 -9
  11. package/dinou/core/client.jsx +60 -9
  12. package/dinou/core/edge-ssr.js +33 -5
  13. package/dinou/core/generate-static.js +109 -47
  14. package/dinou/core/get-jsx.js +35 -27
  15. package/dinou/core/handler.js +786 -54
  16. package/dinou/core/layout-functions.js +102 -1
  17. package/dinou/core/no-dynamic.js +25 -0
  18. package/dinou/core/ppr-context.js +293 -10
  19. package/dinou/core/ppr-runtime.js +373 -37
  20. package/dinou/core/render-jsx-to-client-jsx.js +205 -74
  21. package/dinou/core/slot.js +246 -33
  22. package/dinou/core/storage-adapter.js +117 -11
  23. package/dinou/deno/build.js +38 -1
  24. package/dinou/deno/seed-kv.js +43 -11
  25. package/dinou/esbuild/helpers-esbuild/swc-disk-cache.js +242 -225
  26. package/dinou/esbuild/plugins-esbuild/server-functions-plugin.js +253 -226
  27. package/dinou/esbuild/react-refresh/esm-hmr/client.js +209 -209
  28. package/dinou/index.d.ts +10 -0
  29. package/dinou/index.js +3 -0
  30. package/dinou/node/build.js +2 -2
  31. package/dinou/node/bundle-dual-engine.js +2 -0
  32. package/dinou/node/dev.js +2853 -2704
  33. package/dinou/package.json +4 -1
  34. package/dinou/rollup/react-refresh/esm-hmr/client.js +220 -220
  35. package/dinou/rollup/rollup-plugins/rollup-plugin-server-functions.js +182 -160
  36. package/dinou/server.d.ts +65 -12
  37. package/dinou/server.js +11 -0
  38. package/dinou/webpack/loaders/server-functions-loader.js +101 -94
  39. package/dinou/webpack/webpack.config.js +9 -4
  40. package/eject.js +219 -223
  41. package/package.json +2 -2
@@ -23,7 +23,7 @@ import { getFilePathAndDynamicParams } from "./get-file-path-and-dynamic-params.
23
23
  import getJSX from "./get-jsx.js";
24
24
  import { getErrorJSX } from "./get-error-jsx.js";
25
25
  import importModule from "./import-module.js";
26
- import { resolveLayoutFunctionsConfig } from "./layout-functions.js";
26
+ import { resolveLayoutFunctionsConfig, getActiveLayoutChain } from "./layout-functions.js";
27
27
  import { revalidating, regenerating, inFlightGenerations } from "./revalidating.js";
28
28
  import { generatingISG } from "./generating-isg.js";
29
29
  import { requestStorage, setCurrentContext } from "./request-context.js";
@@ -38,11 +38,24 @@ import { pipeRSC, renderRSCStream, isEdgeRuntime } from "./rsc-renderer.js";
38
38
  import { getStorageAdapter, setStorageAdapter } from "./storage-adapter.js";
39
39
  import { createBailoutProxy } from "./bailout-proxy.js";
40
40
  import getAssetFromManifest from "./get-asset-from-manifest.js";
41
- import { handlePprResume } from "./ppr-runtime.js";
41
+ import { handlePprResume, spliceDynamicHolesIntoShell } from "./ppr-runtime.js";
42
42
  import { resolveModulePpr } from "./resolve-module-ppr.js";
43
43
  import { getDinouConfig as loadDinouConfig } from "./load-dinou-config.js";
44
- import { getSlotJSX } from "./cache-slot.js";
45
- import { runWithPprContext, getRegisteredHoles } from "./ppr-context.js";
44
+ import {
45
+ getSlotJSX,
46
+ serializeJSX,
47
+ deserializeJSX,
48
+ refreshNestedSlotsInTree,
49
+ hasExpiredSlots,
50
+ } from "./cache-slot.js";
51
+ import {
52
+ runWithPprContext,
53
+ getRegisteredHoles,
54
+ resetPprHoles,
55
+ getPprHoleCounter,
56
+ runInPageSegment,
57
+ runInLayoutSegment,
58
+ } from "./ppr-context.js";
46
59
  import { asyncRenderJSXToClientJSX } from "./render-jsx-to-client-jsx.js";
47
60
 
48
61
  // Load Dinou configuration and plugins
@@ -107,7 +120,7 @@ if (typeof globalThis !== "undefined" && globalThis.__DINOU_CONFIG__) {
107
120
  function copyCustomContextProperties(source, target) {
108
121
  if (!source || !target) return;
109
122
  for (const key of Object.keys(source)) {
110
- if (!["req", "res", "env", "ctx"].includes(key)) {
123
+ if (!["req", "res", "env", "ctx", "platformContext", "_markDynamic"].includes(key)) {
111
124
  target[key] = source[key];
112
125
  }
113
126
  }
@@ -137,7 +150,11 @@ const botGarbagePatterns = [
137
150
  /\.log$/i,
138
151
  ];
139
152
 
140
- const isDynamic = new Map();
153
+ const IS_DYNAMIC_MAP_KEY = Symbol.for("dinou.isDynamic.map");
154
+ if (!globalThis[IS_DYNAMIC_MAP_KEY]) {
155
+ globalThis[IS_DYNAMIC_MAP_KEY] = new Map();
156
+ }
157
+ const isDynamic = globalThis[IS_DYNAMIC_MAP_KEY];
141
158
  const pageFunctionsConfigCache = new Map();
142
159
 
143
160
  async function resolvePprForRoute(pagePath, pageFunctionsModule, reqSegments, queryObj) {
@@ -400,6 +417,11 @@ function getDiscoveredLayouts() {
400
417
  if (!discovered.includes(clean)) {
401
418
  discovered.push(clean);
402
419
  }
420
+ } else if (vfs[key]?.type === "file" && /(?:^|\/)no_layout$/.test(key)) {
421
+ const clean = "!" + key.replace(/^\/?src\/?/, "").replace(/\/?no_layout$/, "");
422
+ if (!discovered.includes(clean)) {
423
+ discovered.push(clean);
424
+ }
403
425
  }
404
426
  }
405
427
  }
@@ -433,6 +455,8 @@ function getDiscoveredLayouts() {
433
455
  find(path.join(dir, entry.name), rel ? `${rel}/${entry.name}` : entry.name);
434
456
  } else if (/^layout\.[jt]sx?$/.test(entry.name)) {
435
457
  discovered.push(rel);
458
+ } else if (entry.name === "no_layout") {
459
+ discovered.push("!" + rel);
436
460
  }
437
461
  }
438
462
  }
@@ -445,6 +469,86 @@ function getDiscoveredLayouts() {
445
469
  return discovered;
446
470
  }
447
471
 
472
+ async function readMetaFromStorage(storage, metaKey, fallbackKey = null, platformContext = null, requestUrl = null) {
473
+ if (storage) {
474
+ try {
475
+ const metaItem = await storage.get(metaKey);
476
+ if (metaItem) {
477
+ if (metaItem.metadata && typeof metaItem.metadata === "object" && metaItem.metadata.generatedAt) {
478
+ return metaItem.metadata;
479
+ }
480
+ if (typeof metaItem.content === "string" && metaItem.content.trim().startsWith("{")) {
481
+ return JSON.parse(metaItem.content);
482
+ }
483
+ }
484
+ if (fallbackKey) {
485
+ const fbItem = await storage.get(fallbackKey);
486
+ if (fbItem && fbItem.metadata && typeof fbItem.metadata === "object" && fbItem.metadata.generatedAt) {
487
+ return fbItem.metadata;
488
+ }
489
+ }
490
+ } catch (e) {}
491
+ }
492
+ if (
493
+ platformContext &&
494
+ platformContext.env &&
495
+ platformContext.env.ASSETS &&
496
+ requestUrl &&
497
+ !(storage && typeof storage.isDeleted === "function" && storage.isDeleted(metaKey))
498
+ ) {
499
+ try {
500
+ const metaRes = await platformContext.env.ASSETS.fetch(new Request(new URL(`/${metaKey}`, requestUrl)));
501
+ if (metaRes && metaRes.status === 200) {
502
+ const text = await metaRes.text();
503
+ if (text && text.trim().startsWith("{")) {
504
+ const parsed = JSON.parse(text);
505
+ if (storage) {
506
+ await storage.set(metaKey, text);
507
+ }
508
+ return parsed;
509
+ }
510
+ }
511
+ } catch (e) {}
512
+ }
513
+ return null;
514
+ }
515
+
516
+ async function readRscFromStorage(storage, rscKey, platformContext = null, requestUrl = null) {
517
+ if (storage) {
518
+ try {
519
+ const item = await storage.get(rscKey);
520
+ if (item && typeof item.content === "string" && item.content.length > 0 && !item.content.trimStart().startsWith("<")) {
521
+ return item.content;
522
+ }
523
+ } catch (e) {}
524
+ }
525
+ if (
526
+ platformContext &&
527
+ platformContext.env &&
528
+ platformContext.env.ASSETS &&
529
+ requestUrl &&
530
+ !(storage && typeof storage.isDeleted === "function" && storage.isDeleted(rscKey))
531
+ ) {
532
+ try {
533
+ const assetRes = await platformContext.env.ASSETS.fetch(new Request(new URL(`/${rscKey}`, requestUrl)));
534
+ if (assetRes && assetRes.status === 200) {
535
+ const text = await assetRes.text();
536
+ if (text && !text.trimStart().startsWith("<")) {
537
+ if (storage) {
538
+ await storage.set(rscKey, text);
539
+ }
540
+ return text;
541
+ }
542
+ }
543
+ } catch (e) {}
544
+ }
545
+ return "";
546
+ }
547
+
548
+ function __noopMarker() {
549
+ return discovered;
550
+ }
551
+
448
552
  /**
449
553
  * Bridges Node.js style response methods to a WHATWG Web Response.
450
554
  */
@@ -782,6 +886,7 @@ function createRequestContext(simReq, resBridge, platformContext = {}, dynamicSt
782
886
  env: platformContext.env || {},
783
887
  ctx: platformContext.ctx || null,
784
888
  platformContext,
889
+ _markDynamic: markDynamic,
785
890
  };
786
891
 
787
892
  if (dinouConfig.plugins && Array.isArray(dinouConfig.plugins)) {
@@ -870,6 +975,9 @@ function createServerFunctionContext(simReq, resBridge, platformContext = {}) {
870
975
  resBridge.write(`D:{"type":"cookie","cookie":${JSON.stringify(cookieStr)}}\n`);
871
976
  },
872
977
  },
978
+ env: platformContext.env || {},
979
+ ctx: platformContext.ctx || null,
980
+ platformContext,
873
981
  };
874
982
  setCurrentContext(context);
875
983
  return context;
@@ -882,6 +990,14 @@ function createServerFunctionContext(simReq, resBridge, platformContext = {}) {
882
990
  * @returns {Promise<Response>}
883
991
  */
884
992
  async function handleRequest(request, platformContext = {}) {
993
+ if (typeof globalThis !== "undefined") {
994
+ if (platformContext?.renderHtmlStream) {
995
+ globalThis.__DINOU_RENDER_HTML_STREAM__ = platformContext.renderHtmlStream;
996
+ }
997
+ if (platformContext?.env) {
998
+ globalThis.__DINOU_ENV__ = platformContext.env;
999
+ }
1000
+ }
885
1001
  const url = new URL(request.url);
886
1002
  const pathname = url.pathname;
887
1003
 
@@ -916,6 +1032,10 @@ async function handleRequest(request, platformContext = {}) {
916
1032
  }
917
1033
  const cookiesObj = parseCookieHeader(headersObj["cookie"] || "");
918
1034
  const queryObj = Object.fromEntries(url.searchParams.entries());
1035
+ const internalBuildId = queryObj.____build_id____;
1036
+ const internalRefreshVersion = queryObj.____v____;
1037
+ delete queryObj.____build_id____;
1038
+ delete queryObj.____v____;
919
1039
 
920
1040
  const simReq = {
921
1041
  path: pathname,
@@ -1228,7 +1348,7 @@ async function handleRequest(request, platformContext = {}) {
1228
1348
  if (!isDynamic.has(cleanPath)) {
1229
1349
  isDynamic.set(cleanPath, { value: false });
1230
1350
  }
1231
- const dynamicState = isDynamic.get(cleanPath);
1351
+ const dynamicState = isLayoutReq ? { value: false } : isDynamic.get(cleanPath);
1232
1352
 
1233
1353
  const reqPath = cleanPath.endsWith("/") ? cleanPath : cleanPath + "/";
1234
1354
  let isPathBlocked = false;
@@ -1254,7 +1374,7 @@ async function handleRequest(request, platformContext = {}) {
1254
1374
  isPathBlocked = pageConfig.isPathBlocked;
1255
1375
  }
1256
1376
 
1257
- const nonBuildIdQueryKeys = Object.keys(queryObj).filter((k) => k !== "buildId");
1377
+ const nonBuildIdQueryKeys = Object.keys(queryObj);
1258
1378
  const hasQueryParams = nonBuildIdQueryKeys.length > 0;
1259
1379
 
1260
1380
  const targetFileName = isLayoutReq
@@ -1267,31 +1387,149 @@ async function handleRequest(request, platformContext = {}) {
1267
1387
 
1268
1388
  let isRoutePpr = false;
1269
1389
  let currentGeneratedAt = null;
1270
- try {
1271
- const metaFileName = isLayoutReq ? "layout.metadata.json" : "metadata.json";
1272
- const metadataPath = path.join(".dinou/dist2", cleanPath, metaFileName);
1273
- if (existsSync(metadataPath)) {
1274
- const metaObj = JSON.parse(readFileSync(metadataPath, "utf8"));
1275
- currentGeneratedAt = metaObj.generatedAt || null;
1276
- if (metaObj.ppr) {
1277
- isRoutePpr = true;
1390
+ let leafLayoutSuspenseCount = 0;
1391
+ if (!isDevelopment && isEdgeRuntime(platformContext)) {
1392
+ const storage = getStorageAdapter();
1393
+ const cleanRel = cleanPath.replace(/^\/+/, "").replace(/\/+$/, "");
1394
+ try {
1395
+ const activeChain = getActiveLayoutChain(reqSegments, queryObj, srcFolder, {
1396
+ ignoreNoLayout: isLayoutReq,
1397
+ });
1398
+ if (activeChain.length > 0) {
1399
+ for (const entry of activeChain) {
1400
+ const lMetaKey = entry.cleanLayoutKey ? `${entry.cleanLayoutKey}/layout.metadata.json` : "layout.metadata.json";
1401
+ const lRscKey = entry.cleanLayoutKey ? `${entry.cleanLayoutKey}/layout.rsc` : "layout.rsc";
1402
+ const lMeta = await readMetaFromStorage(storage, lMetaKey, lRscKey, platformContext, request.url);
1403
+ entry.generatedAt = Number(lMeta?.generatedAt || 0);
1404
+ entry.suspenseCount = Number(lMeta?.suspenseCount || 0);
1405
+ entry.revalidate = lMeta?.revalidate;
1406
+ entry.slotTags = Array.isArray(lMeta?.slotTags) ? lMeta.slotTags : [];
1407
+ }
1408
+ if (!platformContext?.isSSG && !isOld && !dynamicState.value) {
1409
+ for (let i = activeChain.length - 1; i >= 0; i--) {
1410
+ const entry = activeChain[i];
1411
+ const isLayoutTtlExpired =
1412
+ typeof entry.revalidate === "number" &&
1413
+ entry.revalidate >= 1 &&
1414
+ entry.generatedAt > 0 &&
1415
+ Date.now() > entry.generatedAt + entry.revalidate * 1000;
1416
+ const isLayoutSlotTtlExpired =
1417
+ !isLayoutTtlExpired &&
1418
+ entry.slotTags.length > 0 &&
1419
+ (await hasExpiredSlots(entry.slotTags));
1420
+ const maxAncestorGen =
1421
+ i < activeChain.length - 1
1422
+ ? Math.max(0, ...activeChain.slice(i + 1).map((l) => l.generatedAt || 0))
1423
+ : 0;
1424
+ const isAncestorNewer = entry.generatedAt > 0 && maxAncestorGen > entry.generatedAt;
1425
+ if (isLayoutSlotTtlExpired && !isLayoutTtlExpired && !(isLayoutReq && isAncestorNewer)) {
1426
+ const layoutSlotRevalKey = `layout-slot:${entry.layoutRoutePath}`;
1427
+ const layoutSlotRevalPromise = (async () => {
1428
+ if (regenerating.has(layoutSlotRevalKey)) return;
1429
+ regenerating.add(layoutSlotRevalKey);
1430
+ try {
1431
+ const { revalidateLayout } = await import("./cache-revalidate.js");
1432
+ await revalidateLayout(entry.layoutRoutePath, { onlyRefreshSlots: true });
1433
+ } catch (err) {
1434
+ console.error(`❌ [Slot ISR] Error refreshing layout slots for ${entry.layoutRoutePath}:`, err);
1435
+ } finally {
1436
+ regenerating.delete(layoutSlotRevalKey);
1437
+ }
1438
+ })();
1439
+ if (platformContext && platformContext.ctx && typeof platformContext.ctx.waitUntil === "function") {
1440
+ platformContext.ctx.waitUntil(layoutSlotRevalPromise);
1441
+ }
1442
+ } else if (isLayoutTtlExpired || (isLayoutReq && isAncestorNewer)) {
1443
+ const { revalidateLayout } = await import("./cache-revalidate.js");
1444
+ await revalidateLayout(entry.layoutRoutePath, {});
1445
+ const lMetaKey = entry.cleanLayoutKey
1446
+ ? `${entry.cleanLayoutKey}/layout.metadata.json`
1447
+ : "layout.metadata.json";
1448
+ const lRscKey = entry.cleanLayoutKey
1449
+ ? `${entry.cleanLayoutKey}/layout.rsc`
1450
+ : "layout.rsc";
1451
+ const refreshedMeta = await readMetaFromStorage(
1452
+ storage,
1453
+ lMetaKey,
1454
+ lRscKey,
1455
+ platformContext,
1456
+ request.url
1457
+ );
1458
+ if (refreshedMeta?.generatedAt) {
1459
+ entry.generatedAt = Number(refreshedMeta.generatedAt);
1460
+ }
1461
+ if (refreshedMeta?.suspenseCount !== undefined) {
1462
+ entry.suspenseCount = Number(refreshedMeta.suspenseCount || 0);
1463
+ }
1464
+ }
1465
+ }
1466
+ }
1467
+ leafLayoutSuspenseCount = Number(activeChain[0]?.suspenseCount || 0);
1468
+ }
1469
+ } catch (e) {}
1470
+
1471
+ if (!platformContext?.isSSG) {
1472
+ const metaFileName = isLayoutReq ? "layout.metadata.json" : "metadata.json";
1473
+ const metaKey = cleanRel ? `${cleanRel}/${metaFileName}` : metaFileName;
1474
+ const rscBaseName = isLayoutReq ? "layout.rsc" : "page.rsc";
1475
+ const rscBaseKey = cleanRel ? `${cleanRel}/${rscBaseName}` : rscBaseName;
1476
+ const edgeMeta = await readMetaFromStorage(storage, metaKey, rscBaseKey, platformContext, request.url);
1477
+ if (edgeMeta) {
1478
+ currentGeneratedAt = edgeMeta.generatedAt || null;
1479
+ if (isLayoutReq) {
1480
+ if (edgeMeta.dynamic) {
1481
+ dynamicState.value = true;
1482
+ }
1483
+ if (Array.isArray(edgeMeta.holes) && edgeMeta.holes.length > 0) {
1484
+ isRoutePpr = true;
1485
+ }
1486
+ } else if (edgeMeta.ppr) {
1487
+ isRoutePpr = true;
1488
+ }
1278
1489
  }
1279
1490
  }
1280
- } catch (e) {}
1491
+ }
1492
+ if (!currentGeneratedAt && !platformContext?.isSSG) {
1493
+ try {
1494
+ const metaFileName = isLayoutReq ? "layout.metadata.json" : "metadata.json";
1495
+ const metadataPath = path.join(".dinou/dist2", cleanPath, metaFileName);
1496
+ if (existsSync(metadataPath)) {
1497
+ const metaObj = JSON.parse(readFileSync(metadataPath, "utf8"));
1498
+ currentGeneratedAt = metaObj.generatedAt || null;
1499
+ if (isLayoutReq) {
1500
+ if (metaObj.dynamic) {
1501
+ dynamicState.value = true;
1502
+ }
1503
+ if (Array.isArray(metaObj.holes) && metaObj.holes.length > 0) {
1504
+ isRoutePpr = true;
1505
+ }
1506
+ } else if (metaObj.ppr) {
1507
+ isRoutePpr = true;
1508
+ }
1509
+ }
1510
+ } catch (e) {}
1511
+ }
1281
1512
 
1282
1513
  if (!isRoutePpr) {
1283
- isRoutePpr = pageConfig?.ppr !== undefined && pageConfig?.ppr !== null
1514
+ isRoutePpr = isLayoutReq
1515
+ ? Boolean(platformContext?.isSSG && layoutConfig?.ppr)
1516
+ : pageConfig?.ppr !== undefined && pageConfig?.ppr !== null
1284
1517
  ? Boolean(pageConfig.ppr)
1285
1518
  : await resolvePprForRoute(pagePath, null, reqSegments, queryObj);
1286
1519
  }
1287
1520
 
1288
- if (!isDevelopment && !dynamicState.value && (!hasQueryParams || isStatic) && !isRoutePpr) {
1521
+ const canServeCachedRsc = isLayoutReq
1522
+ ? !isDevelopment && !platformContext?.isSSG && !dynamicState.value && !isRoutePpr
1523
+ : !isDevelopment && !platformContext?.isSSG && !dynamicState.value && (!hasQueryParams || isStatic) && !isRoutePpr;
1524
+
1525
+ if (canServeCachedRsc) {
1289
1526
  const useOld =
1290
1527
  isOld ||
1291
1528
  regenerating.has(cleanPath) ||
1292
- (queryObj.buildId &&
1529
+ (!internalRefreshVersion &&
1530
+ internalBuildId &&
1293
1531
  currentGeneratedAt &&
1294
- queryObj.buildId !== String(currentGeneratedAt));
1532
+ Number(internalBuildId) < Number(currentGeneratedAt));
1295
1533
 
1296
1534
  const actualFileName = useOld
1297
1535
  ? isLayoutReq
@@ -1328,16 +1566,67 @@ async function handleRequest(request, platformContext = {}) {
1328
1566
  const rscKey = cleanRel ? `${cleanRel}/${actualFileName}` : actualFileName;
1329
1567
  try {
1330
1568
  let cached = await storage.get(rscKey);
1569
+ if (!cached && useOld) {
1570
+ const fallbackCurrKey = cleanRel ? `${cleanRel}/${targetFileName}` : targetFileName;
1571
+ cached = await storage.get(fallbackCurrKey);
1572
+ }
1331
1573
  if (!cached && !isLayoutReq && !isPageReq) {
1332
1574
  cached = await storage.get(cleanRel ? `${cleanRel}/rsc.rsc` : "rsc.rsc");
1333
1575
  }
1334
1576
  if (cached && cached.content) {
1335
1577
  let isExpired = false;
1578
+ let isSlotOnlyExpired = false;
1336
1579
  if (isLayoutReq && cached.metadata) {
1337
1580
  const { revalidate, generatedAt } = cached.metadata;
1338
1581
  if (typeof revalidate === "number" && revalidate >= 1 && Date.now() > (generatedAt || 0) + revalidate * 1000) {
1339
1582
  isExpired = true;
1340
1583
  }
1584
+ } else if (!isLayoutReq && !useOld && !internalBuildId) {
1585
+ const pMetaKey = cleanRel ? `${cleanRel}/metadata.json` : "metadata.json";
1586
+ const pRscBaseKey = cleanRel ? `${cleanRel}/page.rsc` : "page.rsc";
1587
+ const pMeta =
1588
+ cached.metadata ||
1589
+ (await readMetaFromStorage(storage, pMetaKey, pRscBaseKey, platformContext, request.url));
1590
+ if (pMeta) {
1591
+ const pReval =
1592
+ pMeta.pageRevalidate !== undefined ? pMeta.pageRevalidate : pMeta.revalidate;
1593
+ const pGen = pMeta.pageGeneratedAt || pMeta.generatedAt || 0;
1594
+ if (typeof pReval === "number" && pReval >= 1 && pGen > 0 && Date.now() > pGen + pReval * 1000) {
1595
+ isExpired = true;
1596
+ } else if (Array.isArray(pMeta.slotTags) && pMeta.slotTags.length > 0) {
1597
+ isSlotOnlyExpired = await hasExpiredSlots(pMeta.slotTags);
1598
+ }
1599
+ }
1600
+ if (isSlotOnlyExpired && !isExpired) {
1601
+ const slotRevalKey = `slot:${cleanPath}`;
1602
+ const slotRevalPromise = (async () => {
1603
+ if (regenerating.has(slotRevalKey) || regenerating.has(cleanPath)) return;
1604
+ regenerating.add(slotRevalKey);
1605
+ try {
1606
+ const { revalidatePage } = await import("./cache-revalidate.js");
1607
+ await revalidatePage(cleanPath, { onlyRefreshSlots: true });
1608
+ } catch (err) {
1609
+ console.error(`❌ [Slot ISR] Error refreshing slots for ${cleanPath}:`, err);
1610
+ } finally {
1611
+ regenerating.delete(slotRevalKey);
1612
+ }
1613
+ })();
1614
+ if (platformContext && platformContext.ctx && typeof platformContext.ctx.waitUntil === "function") {
1615
+ platformContext.ctx.waitUntil(slotRevalPromise);
1616
+ }
1617
+ } else if (isExpired) {
1618
+ const { revalidatePage } = await import("./cache-revalidate.js");
1619
+ await revalidatePage(cleanPath, {});
1620
+ if (!dynamicState.value) {
1621
+ const refreshedCached = await storage.get(rscKey);
1622
+ if (refreshedCached && refreshedCached.content) {
1623
+ cached = refreshedCached;
1624
+ isExpired = false;
1625
+ }
1626
+ } else {
1627
+ isExpired = true;
1628
+ }
1629
+ }
1341
1630
  }
1342
1631
  if (!isExpired) {
1343
1632
  const contentStr = typeof cached.content === "string" ? cached.content : "";
@@ -1351,13 +1640,23 @@ async function handleRequest(request, platformContext = {}) {
1351
1640
  }
1352
1641
  } catch (e) {}
1353
1642
 
1354
- if (platformContext && platformContext.env && platformContext.env.ASSETS) {
1643
+ if (
1644
+ platformContext &&
1645
+ platformContext.env &&
1646
+ platformContext.env.ASSETS &&
1647
+ !(typeof storage.isDeleted === "function" && storage.isDeleted(rscKey))
1648
+ ) {
1355
1649
  try {
1356
1650
  const assetRes = await platformContext.env.ASSETS.fetch(new Request(new URL(`/${rscKey}`, request.url)));
1357
1651
  if (assetRes && assetRes.status === 200) {
1358
1652
  const contentType = assetRes.headers.get("content-type") || "";
1359
1653
  const rscContent = await assetRes.text();
1360
- if (!contentType.includes("text/html") && !rscContent.trimStart().startsWith("<")) {
1654
+ if (
1655
+ rscContent &&
1656
+ rscContent.trim().length > 0 &&
1657
+ !contentType.includes("text/html") &&
1658
+ !rscContent.trimStart().startsWith("<")
1659
+ ) {
1361
1660
  await storage.set(rscKey, rscContent);
1362
1661
  bridge.setHeader("Content-Type", "text/x-component");
1363
1662
  bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
@@ -1367,15 +1666,15 @@ async function handleRequest(request, platformContext = {}) {
1367
1666
  }
1368
1667
  } catch (e) {}
1369
1668
  }
1370
- }
1371
-
1372
- if (existsSync(payloadPath)) {
1373
- bridge.setHeader("Content-Type", "application/octet-stream");
1374
- bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
1669
+ } else if (existsSync(payloadPath)) {
1375
1670
  try {
1376
1671
  const buffer = readFileSync(payloadPath);
1377
- bridge.end(buffer);
1378
- return bridge.toResponse();
1672
+ if (buffer && buffer.length > 0) {
1673
+ bridge.setHeader("Content-Type", "application/octet-stream");
1674
+ bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
1675
+ bridge.end(buffer);
1676
+ return bridge.toResponse();
1677
+ }
1379
1678
  } catch (err) {
1380
1679
  console.error("[Dinou] Error reading RSC file:", err);
1381
1680
  return new Response("Internal Server Error", { status: 500 });
@@ -1387,7 +1686,7 @@ async function handleRequest(request, platformContext = {}) {
1387
1686
  if (layouts && Array.isArray(layouts)) {
1388
1687
  for (const [lPath, lParams] of layouts) {
1389
1688
  const lConfig = await resolveLayoutFunctionsConfig(lPath, lParams);
1390
- if (!isDevelopment && lConfig.allowISG === false) {
1689
+ if (lConfig.allowISG === false) {
1391
1690
  let isPathAllowed = false;
1392
1691
  if (lConfig.staticPathsSet) {
1393
1692
  const sortedEntries = Object.entries(lParams || {})
@@ -1402,6 +1701,10 @@ async function handleRequest(request, platformContext = {}) {
1402
1701
  isPathAllowed = lConfig.staticPathsSet.has(serializedQuery) || lConfig.staticPathsSet.has(singleValStr);
1403
1702
  }
1404
1703
  if (!isPathAllowed) {
1704
+ if (isDevelopment) {
1705
+ isPathBlocked = true;
1706
+ break;
1707
+ }
1405
1708
  const cleanReq = reqPath.replace(/^\//, "").replace(/\/$/, "");
1406
1709
  const rscPath = path.join(process.cwd(), ".dinou/dist2", cleanReq, "layout.rsc");
1407
1710
  if (!existsSync(rscPath)) {
@@ -1422,7 +1725,7 @@ async function handleRequest(request, platformContext = {}) {
1422
1725
  if (!layoutConfig) {
1423
1726
  layoutConfig = await resolveLayoutFunctionsConfig(layoutPath, layoutParams);
1424
1727
  }
1425
- if (!isDevelopment && layoutConfig.allowISG === false) {
1728
+ if (layoutConfig.allowISG === false) {
1426
1729
  let isPathAllowed = false;
1427
1730
  if (layoutConfig.staticPathsSet) {
1428
1731
  const sortedEntries = Object.entries(layoutParams || {})
@@ -1437,10 +1740,14 @@ async function handleRequest(request, platformContext = {}) {
1437
1740
  isPathAllowed = layoutConfig.staticPathsSet.has(serializedQuery) || layoutConfig.staticPathsSet.has(singleValStr);
1438
1741
  }
1439
1742
  if (!isPathAllowed) {
1440
- const cleanReq = reqPath.replace(/^\//, "").replace(/\/$/, "");
1441
- const rscPath = path.join(process.cwd(), ".dinou/dist2", cleanReq, "layout.rsc");
1442
- if (!existsSync(rscPath)) {
1743
+ if (isDevelopment) {
1443
1744
  isPathBlocked = true;
1745
+ } else {
1746
+ const cleanReq = reqPath.replace(/^\//, "").replace(/\/$/, "");
1747
+ const rscPath = path.join(process.cwd(), ".dinou/dist2", cleanReq, "layout.rsc");
1748
+ if (!existsSync(rscPath)) {
1749
+ isPathBlocked = true;
1750
+ }
1444
1751
  }
1445
1752
  }
1446
1753
  }
@@ -1465,16 +1772,130 @@ async function handleRequest(request, platformContext = {}) {
1465
1772
  isPathBlocked = pageConfig.isPathBlocked;
1466
1773
  }
1467
1774
 
1468
- const context = createRequestContext(simReq, bridge, platformContext, dynamicState);
1775
+ const rscDynamicState = isLayoutReq ? dynamicState : (isRoutePpr ? { value: false } : dynamicState);
1776
+ const context = createRequestContext(simReq, bridge, platformContext, rscDynamicState);
1469
1777
  copyCustomContextProperties(rootContext, context);
1470
1778
  const isNotFound = {};
1471
1779
  const segment = isLayoutReq ? "layout" : "page";
1472
1780
 
1473
1781
  await requestStorage.run(context, async () => {
1474
1782
  try {
1475
- const jsx = await getJSX(reqPath, queryObj, isNotFound, isDevelopment, isPathBlocked, {
1476
- segment,
1477
- });
1783
+ let jsx;
1784
+ if (platformContext?.isSSG) {
1785
+ const ssgIsPpr = isLayoutReq
1786
+ ? Boolean(isRoutePpr || (await resolvePprForRoute(null, null, reqSegments, queryObj)))
1787
+ : Boolean(isRoutePpr);
1788
+ jsx = await runWithPprContext({ isPpr: ssgIsPpr }, async () => {
1789
+ const rawJsx = await getJSX(reqPath, queryObj, isNotFound, isDevelopment, isPathBlocked, {
1790
+ segment,
1791
+ });
1792
+ const startIdx = isLayoutReq ? 0 : leafLayoutSuspenseCount;
1793
+ resetPprHoles(startIdx);
1794
+ const runSeg = isLayoutReq ? runInLayoutSegment : runInPageSegment;
1795
+ const rendered = await runSeg(() => asyncRenderJSXToClientJSX(rawJsx));
1796
+ const slotTagSet = isLayoutReq
1797
+ ? context._layoutSlotTags || context._slotTags
1798
+ : context._pageSlotTags || context._slotTags;
1799
+ if (slotTagSet && slotTagSet.size > 0) {
1800
+ bridge.setHeader("X-Dinou-Slot-Tags", JSON.stringify(Array.from(slotTagSet)));
1801
+ }
1802
+ const regHoles = getRegisteredHoles();
1803
+ if (regHoles.length > 0) {
1804
+ bridge.setHeader("X-Dinou-Ppr-Holes", JSON.stringify(regHoles));
1805
+ }
1806
+ bridge.setHeader("X-Dinou-Suspense-Count", String(getPprHoleCounter()));
1807
+ if (rscDynamicState.value) {
1808
+ bridge.setHeader("X-Dinou-Dynamic", "true");
1809
+ }
1810
+ if (rendered && isEdgeRuntime(platformContext)) {
1811
+ try {
1812
+ const storage = getStorageAdapter();
1813
+ const cleanRel = cleanPath.replace(/^\/+/, "").replace(/\/+$/, "");
1814
+ const shellPageKey = isLayoutReq ? (cleanRel ? `${cleanRel}/shell.layout.json` : "shell.layout.json") : (cleanRel ? `${cleanRel}/shell.page.json` : "shell.page.json");
1815
+ await storage.set(shellPageKey, serializeJSX(rendered));
1816
+ } catch (e) {}
1817
+ }
1818
+ return rendered;
1819
+ });
1820
+ } else if (!isDevelopment && (isPageReq || isLayoutReq) && isRoutePpr && isEdgeRuntime(platformContext)) {
1821
+ context._isPprRuntimeResume = true;
1822
+ const storage = getStorageAdapter();
1823
+ const cleanRel = cleanPath.replace(/^\/+/, "").replace(/\/+$/, "");
1824
+ if (isPageReq) {
1825
+ try {
1826
+ const pMetaKey = cleanRel ? `${cleanRel}/metadata.json` : "metadata.json";
1827
+ const pRscBaseKey = cleanRel ? `${cleanRel}/page.rsc` : "page.rsc";
1828
+ const pMeta = await readMetaFromStorage(storage, pMetaKey, pRscBaseKey, platformContext, request.url);
1829
+ if (pMeta && Array.isArray(pMeta.slotTags) && pMeta.slotTags.length > 0) {
1830
+ const isPprPageSlotExpired = await hasExpiredSlots(pMeta.slotTags);
1831
+ if (isPprPageSlotExpired) {
1832
+ const slotRevalKey = `slot:${reqPath}`;
1833
+ const slotRevalPromise = (async () => {
1834
+ if (regenerating.has(slotRevalKey) || regenerating.has(reqPath)) return;
1835
+ regenerating.add(slotRevalKey);
1836
+ try {
1837
+ const { revalidatePage } = await import("./cache-revalidate.js");
1838
+ await revalidatePage(reqPath, { onlyRefreshSlots: true });
1839
+ } catch (err) {
1840
+ console.error(`❌ [Slot ISR] Error refreshing slots for ${reqPath}:`, err);
1841
+ } finally {
1842
+ regenerating.delete(slotRevalKey);
1843
+ }
1844
+ })();
1845
+ if (platformContext && platformContext.ctx && typeof platformContext.ctx.waitUntil === "function") {
1846
+ platformContext.ctx.waitUntil(slotRevalPromise);
1847
+ }
1848
+ }
1849
+ }
1850
+ } catch (e) {}
1851
+ }
1852
+ const shellKey = isLayoutReq
1853
+ ? cleanRel
1854
+ ? `${cleanRel}/shell.layout.json`
1855
+ : "shell.layout.json"
1856
+ : cleanRel
1857
+ ? `${cleanRel}/shell.page.json`
1858
+ : "shell.page.json";
1859
+ const shellJson = await readRscFromStorage(
1860
+ storage,
1861
+ shellKey,
1862
+ platformContext,
1863
+ request.url
1864
+ );
1865
+ if (shellJson) {
1866
+ try {
1867
+ let cachedShellTree = deserializeJSX(shellJson);
1868
+ const runSeg = isLayoutReq ? runInLayoutSegment : runInPageSegment;
1869
+ const slotScope = isLayoutReq ? "__layout_shell__" : "__ppr_shell__";
1870
+ cachedShellTree = await runSeg(() =>
1871
+ refreshNestedSlotsInTree(
1872
+ cachedShellTree,
1873
+ slotScope,
1874
+ { currentPath: reqPath }
1875
+ )
1876
+ );
1877
+ jsx = await spliceDynamicHolesIntoShell(
1878
+ cachedShellTree,
1879
+ () =>
1880
+ getJSX(reqPath, queryObj, isNotFound, isDevelopment, isPathBlocked, {
1881
+ segment,
1882
+ }),
1883
+ isLayoutReq ? 0 : leafLayoutSuspenseCount
1884
+ );
1885
+ } catch (spliceErr) {
1886
+ console.warn(`[Dinou PPR] Error splicing dynamic holes for ${reqPath}:`, spliceErr);
1887
+ }
1888
+ }
1889
+ if (!jsx) {
1890
+ jsx = await getJSX(reqPath, queryObj, isNotFound, isDevelopment, isPathBlocked, {
1891
+ segment,
1892
+ });
1893
+ }
1894
+ } else {
1895
+ jsx = await getJSX(reqPath, queryObj, isNotFound, isDevelopment, isPathBlocked, {
1896
+ segment,
1897
+ });
1898
+ }
1478
1899
  if (bridge.headers.has("x-rsc-redirect") || bridge.headers.has("Location")) {
1479
1900
  return;
1480
1901
  }
@@ -1517,6 +1938,9 @@ async function handleRequest(request, platformContext = {}) {
1517
1938
  isDynamic.set(reqPath, { value: false });
1518
1939
  }
1519
1940
  const dynamicState = isDynamic.get(reqPath);
1941
+ if (platformContext?.isSSG) {
1942
+ dynamicState.value = false;
1943
+ }
1520
1944
 
1521
1945
  let { isPathBlocked, allowISGValue, isDynamicConfig, revalidate, tags, ppr: isPprConfig } = await resolvePageFunctionsConfig(
1522
1946
  pagePath,
@@ -1525,6 +1949,7 @@ async function handleRequest(request, platformContext = {}) {
1525
1949
  dynamicParams,
1526
1950
  reqPath,
1527
1951
  );
1952
+ let hasStaticDynamicConfig = Boolean(isDynamicConfig);
1528
1953
  if (isDynamicConfig) {
1529
1954
  dynamicState.value = true;
1530
1955
  }
@@ -1562,6 +1987,7 @@ async function handleRequest(request, platformContext = {}) {
1562
1987
 
1563
1988
  if (layoutConfig.isDynamic) {
1564
1989
  dynamicState.value = true;
1990
+ hasStaticDynamicConfig = true;
1565
1991
  }
1566
1992
 
1567
1993
  if (layoutConfig.allowISG === false) {
@@ -1631,7 +2057,10 @@ async function handleRequest(request, platformContext = {}) {
1631
2057
  }
1632
2058
 
1633
2059
  // 2. If not in storageAdapter, check env.ASSETS for pre-rendered build static page
1634
- if (!isDevelopment && !cachedItem && platformContext && platformContext.env && platformContext.env.ASSETS) {
2060
+ const isRouteDeletedInStorage =
2061
+ typeof storage.isDeleted === "function" &&
2062
+ (storage.isDeleted(htmlKey) || storage.isDeleted(metaKey) || (cleanPath && storage.isDeleted(cleanPath)));
2063
+ if (!isDevelopment && !cachedItem && !isRouteDeletedInStorage && platformContext && platformContext.env && platformContext.env.ASSETS) {
1635
2064
  try {
1636
2065
  const metaRes = await platformContext.env.ASSETS.fetch(new Request(new URL(`/${metaKey}`, request.url)));
1637
2066
  if (metaRes && metaRes.status === 200) {
@@ -1675,14 +2104,234 @@ async function handleRequest(request, platformContext = {}) {
1675
2104
  } catch (e) {}
1676
2105
  }
1677
2106
 
2107
+ // 2b. If PPR route shell was invalidated (e.g. by revalidateTag on a static shell slot),
2108
+ // or is a dynamic-param ISG route being visited for the first time,
2109
+ // regenerate the static shell in an isolated SSG pass before resuming dynamic holes.
2110
+ const shellHtmlKeyForCheck = cleanPath ? `${cleanPath}/shell.html` : "shell.html";
2111
+ const isShellDeletedInStorage =
2112
+ isRouteDeletedInStorage ||
2113
+ (typeof storage.isDeleted === "function" && storage.isDeleted(shellHtmlKeyForCheck));
2114
+ const hasDynamicUrlParams = Boolean(dynamicParams && Object.keys(dynamicParams).length > 0);
2115
+ if (
2116
+ !isDevelopment &&
2117
+ !cachedItem &&
2118
+ !dynamicState.value &&
2119
+ isPprConfig &&
2120
+ (isShellDeletedInStorage || (hasDynamicUrlParams && allowISGValue !== false)) &&
2121
+ !isPathBlocked &&
2122
+ queryObj.ssr_crash !== "true" &&
2123
+ !platformContext?.isSSG
2124
+ ) {
2125
+ try {
2126
+ const ssgUrl = new URL(reqPath, request.url);
2127
+ const ssgReq = new Request(ssgUrl.href, { method: "GET" });
2128
+ const ssgRes = await handleRequest(ssgReq, {
2129
+ ...platformContext,
2130
+ isSSG: true,
2131
+ });
2132
+ await ssgRes.text();
2133
+ cachedItem = await storage.get(htmlKey);
2134
+ if (!cachedItem) {
2135
+ const shellHtmlKey = cleanPath ? `${cleanPath}/shell.html` : "shell.html";
2136
+ cachedItem = await storage.get(shellHtmlKey);
2137
+ }
2138
+ } catch (e) {
2139
+ console.error(`[Dinou PPR] Error regenerating static shell for ${reqPath}:`, e);
2140
+ }
2141
+ }
2142
+
1678
2143
  // 3. If we found a cached/pre-rendered page:
1679
- if (!isDevelopment && cachedItem && !dynamicState.value && !isPathBlocked && queryObj.ssr_crash !== "true" && !platformContext?.isSSG) {
2144
+ if (!isDevelopment && cachedItem && (!dynamicState.value || cachedItem?.metadata?.ppr || isPprConfig) && !isPathBlocked && queryObj.ssr_crash !== "true" && !platformContext?.isSSG) {
2145
+ try {
2146
+ const activeLayoutChain = getActiveLayoutChain(reqSegments, queryObj, srcFolder);
2147
+ if (activeLayoutChain.length > 0) {
2148
+ for (const entry of activeLayoutChain) {
2149
+ const lMetaKey = entry.cleanLayoutKey
2150
+ ? `${entry.cleanLayoutKey}/layout.metadata.json`
2151
+ : "layout.metadata.json";
2152
+ const lRscKey = entry.cleanLayoutKey
2153
+ ? `${entry.cleanLayoutKey}/layout.rsc`
2154
+ : "layout.rsc";
2155
+ const lMeta = await readMetaFromStorage(
2156
+ storage,
2157
+ lMetaKey,
2158
+ lRscKey,
2159
+ platformContext,
2160
+ request.url
2161
+ );
2162
+ entry.generatedAt = Number(lMeta?.generatedAt || 0);
2163
+ entry.revalidate = lMeta?.revalidate;
2164
+ entry.slotTags = Array.isArray(lMeta?.slotTags) ? lMeta.slotTags : [];
2165
+ }
2166
+ for (let i = activeLayoutChain.length - 1; i >= 0; i--) {
2167
+ const entry = activeLayoutChain[i];
2168
+ const isLayoutTtlExpired =
2169
+ typeof entry.revalidate === "number" &&
2170
+ entry.revalidate >= 1 &&
2171
+ entry.generatedAt > 0 &&
2172
+ Date.now() > entry.generatedAt + entry.revalidate * 1000;
2173
+ const isLayoutSlotTtlExpired =
2174
+ !isLayoutTtlExpired &&
2175
+ entry.slotTags.length > 0 &&
2176
+ (await hasExpiredSlots(entry.slotTags));
2177
+ const maxAncestorGen =
2178
+ i < activeLayoutChain.length - 1
2179
+ ? Math.max(
2180
+ 0,
2181
+ ...activeLayoutChain.slice(i + 1).map((l) => l.generatedAt || 0)
2182
+ )
2183
+ : 0;
2184
+ const isAncestorNewer =
2185
+ entry.generatedAt > 0 && maxAncestorGen > entry.generatedAt;
2186
+ if (isLayoutSlotTtlExpired && !isLayoutTtlExpired && !isAncestorNewer) {
2187
+ const layoutSlotRevalKey = `layout-slot:${entry.layoutRoutePath}`;
2188
+ const layoutSlotRevalPromise = (async () => {
2189
+ if (regenerating.has(layoutSlotRevalKey)) return;
2190
+ regenerating.add(layoutSlotRevalKey);
2191
+ try {
2192
+ const { revalidateLayout } = await import("./cache-revalidate.js");
2193
+ await revalidateLayout(entry.layoutRoutePath, { onlyRefreshSlots: true });
2194
+ } catch (err) {
2195
+ console.error(`❌ [Slot ISR] Error refreshing layout slots for ${entry.layoutRoutePath}:`, err);
2196
+ } finally {
2197
+ regenerating.delete(layoutSlotRevalKey);
2198
+ }
2199
+ })();
2200
+ if (platformContext && platformContext.ctx && typeof platformContext.ctx.waitUntil === "function") {
2201
+ platformContext.ctx.waitUntil(layoutSlotRevalPromise);
2202
+ }
2203
+ } else if (isLayoutTtlExpired || isAncestorNewer) {
2204
+ const { revalidateLayout } = await import("./cache-revalidate.js");
2205
+ await revalidateLayout(entry.layoutRoutePath, {});
2206
+ const refreshedMeta = await readMetaFromStorage(
2207
+ storage,
2208
+ entry.cleanLayoutKey
2209
+ ? `${entry.cleanLayoutKey}/layout.metadata.json`
2210
+ : "layout.metadata.json",
2211
+ entry.cleanLayoutKey
2212
+ ? `${entry.cleanLayoutKey}/layout.rsc`
2213
+ : "layout.rsc",
2214
+ platformContext,
2215
+ request.url
2216
+ );
2217
+ if (refreshedMeta?.generatedAt) {
2218
+ entry.generatedAt = Number(refreshedMeta.generatedAt);
2219
+ }
2220
+ }
2221
+ }
2222
+ const leafLayout = activeLayoutChain[0];
2223
+ const pageGeneratedAt = Number(cachedItem.metadata?.generatedAt || 0);
2224
+ if ((leafLayout.generatedAt || 0) > pageGeneratedAt && platformContext?.renderHtmlStream) {
2225
+ const leafRscKey = leafLayout.cleanLayoutKey
2226
+ ? `${leafLayout.cleanLayoutKey}/layout.rsc`
2227
+ : "layout.rsc";
2228
+ const isPprRoute = Boolean(cachedItem?.metadata?.ppr || isPprConfig);
2229
+ const shellRscKey = cleanPath ? `${cleanPath}/shell.rsc` : "shell.rsc";
2230
+ const pageRscKey = cleanPath ? `${cleanPath}/page.rsc` : "page.rsc";
2231
+ let [layoutRscText, pageRscText] = await Promise.all([
2232
+ readRscFromStorage(storage, leafRscKey, platformContext, request.url),
2233
+ readRscFromStorage(
2234
+ storage,
2235
+ isPprRoute ? shellRscKey : pageRscKey,
2236
+ platformContext,
2237
+ request.url
2238
+ ),
2239
+ ]);
2240
+ if (!pageRscText && isPprRoute) {
2241
+ pageRscText = await readRscFromStorage(storage, pageRscKey, platformContext, request.url);
2242
+ }
2243
+ if (layoutRscText && pageRscText) {
2244
+ const encoder = new TextEncoder();
2245
+ const toStream = (str) =>
2246
+ new ReadableStream({
2247
+ start(controller) {
2248
+ controller.enqueue(encoder.encode(str));
2249
+ controller.close();
2250
+ },
2251
+ });
2252
+ const knownLayouts = getDiscoveredLayouts();
2253
+ let bootstrapScriptContent = `window.__DINOU_LAYOUTS__ = ${JSON.stringify(knownLayouts)};\n`;
2254
+ if (isPprRoute) {
2255
+ bootstrapScriptContent += "window.__DINOU_USE_STATIC__ = false;\nwindow.__DINOU_PPR__ = true;\n";
2256
+ } else {
2257
+ bootstrapScriptContent += "window.__DINOU_USE_STATIC__ = true;\n";
2258
+ }
2259
+ bootstrapScriptContent += `window.__DINOU_BUILD_ID__ = "${leafLayout.generatedAt}";\n`;
2260
+ const clientEntry = getAssetFromManifest("main.js");
2261
+ const recomposeCtx = createRequestContext(simReq, bridge, platformContext);
2262
+ copyCustomContextProperties(rootContext, recomposeCtx);
2263
+ let htmlStream;
2264
+ await requestStorage.run(recomposeCtx, async () => {
2265
+ htmlStream = await platformContext.renderHtmlStream(toStream(layoutRscText), {
2266
+ pageRscStream: toStream(pageRscText),
2267
+ bootstrapModules: [clientEntry],
2268
+ bootstrapScriptContent,
2269
+ waitForAll: true,
2270
+ });
2271
+ });
2272
+ const recomposedHtml = await new Response(htmlStream).text();
2273
+ if (recomposedHtml) {
2274
+ const updatedMeta = {
2275
+ ...(cachedItem.metadata || {}),
2276
+ pageGeneratedAt:
2277
+ cachedItem.metadata?.pageGeneratedAt ||
2278
+ cachedItem.metadata?.generatedAt,
2279
+ generatedAt: leafLayout.generatedAt,
2280
+ };
2281
+ cachedItem = {
2282
+ content: recomposedHtml,
2283
+ metadata: updatedMeta,
2284
+ };
2285
+ await storage.set(htmlKey, recomposedHtml, updatedMeta);
2286
+ if (isPprRoute) {
2287
+ const shellHtmlKey = cleanPath ? `${cleanPath}/shell.html` : "shell.html";
2288
+ await storage.set(shellHtmlKey, recomposedHtml, updatedMeta);
2289
+ }
2290
+ if (cleanPath) {
2291
+ await storage.set(cleanPath, recomposedHtml, updatedMeta);
2292
+ }
2293
+ await storage.set(metaKey, JSON.stringify(updatedMeta));
2294
+ }
2295
+ }
2296
+ }
2297
+ }
2298
+ } catch (lazyErr) {
2299
+ console.warn(`⚠️ [Dinou] Error during lazy HTML re-composition for ${reqPath}:`, lazyErr?.message || lazyErr);
2300
+ }
2301
+ if (Array.isArray(cachedItem.metadata?.slotTags) && cachedItem.metadata.slotTags.length > 0) {
2302
+ try {
2303
+ const isPageSlotTtlExpired = await hasExpiredSlots(cachedItem.metadata.slotTags);
2304
+ if (isPageSlotTtlExpired) {
2305
+ const slotRevalKey = `slot:${reqPath}`;
2306
+ const slotRevalPromise = (async () => {
2307
+ if (regenerating.has(slotRevalKey) || regenerating.has(reqPath)) return;
2308
+ regenerating.add(slotRevalKey);
2309
+ try {
2310
+ const { revalidatePage } = await import("./cache-revalidate.js");
2311
+ await revalidatePage(reqPath, { onlyRefreshSlots: true });
2312
+ } catch (slotTtlErr) {
2313
+ console.error(`❌ [Slot ISR] Error refreshing slots for ${reqPath}:`, slotTtlErr);
2314
+ } finally {
2315
+ regenerating.delete(slotRevalKey);
2316
+ }
2317
+ })();
2318
+ if (platformContext && platformContext.ctx && typeof platformContext.ctx.waitUntil === "function") {
2319
+ platformContext.ctx.waitUntil(slotRevalPromise);
2320
+ }
2321
+ }
2322
+ } catch (slotTtlErr) {}
2323
+ }
1680
2324
  const metadata = cachedItem.metadata || {};
1681
- const { revalidate, generatedAt } = metadata;
2325
+ const { generatedAt } = metadata;
2326
+ const pageOwnRevalidate =
2327
+ metadata.pageRevalidate !== undefined
2328
+ ? metadata.pageRevalidate
2329
+ : revalidate;
2330
+ const pageOwnGeneratedAt = metadata.pageGeneratedAt || generatedAt;
1682
2331
  const isExpired =
1683
- typeof revalidate === "number" &&
1684
- revalidate >= 1 &&
1685
- Date.now() > (generatedAt || 0) + revalidate * 1000;
2332
+ typeof pageOwnRevalidate === "number" &&
2333
+ pageOwnRevalidate >= 1 &&
2334
+ Date.now() > (pageOwnGeneratedAt || 0) + pageOwnRevalidate * 1000;
1686
2335
 
1687
2336
  if (isExpired) {
1688
2337
  // Trigger background revalidation on Edge!
@@ -1691,6 +2340,11 @@ async function handleRequest(request, platformContext = {}) {
1691
2340
  regenerating.add(reqPath);
1692
2341
  try {
1693
2342
  console.log(`[Edge ISR] Starting regeneration for ${reqPath}...`);
2343
+ if (metadata.ppr || isPprConfig || (platformContext && platformContext.renderHtmlStream)) {
2344
+ const { revalidatePage } = await import("./cache-revalidate.js");
2345
+ await revalidatePage(reqPath);
2346
+ return;
2347
+ }
1694
2348
  const revalBridge = new WebResponseBridge();
1695
2349
  const context = createRequestContext(simReq, revalBridge, platformContext);
1696
2350
  const isNotFound = {};
@@ -1698,7 +2352,7 @@ async function handleRequest(request, platformContext = {}) {
1698
2352
  await requestStorage.run(context, async () => {
1699
2353
  jsx = await getJSX(reqPath, queryObj, isNotFound, false, false);
1700
2354
  const clientManifest = getClientManifest();
1701
- const rscStream = renderRSCStream(jsx, clientManifest, { runtime: "edge" });
2355
+ const rscStream = requestStorage.run(context, () => renderRSCStream(jsx, clientManifest, { runtime: "edge" }));
1702
2356
  if (platformContext && platformContext.renderHtmlStream) {
1703
2357
  const [streamForSsr, streamForKv] = rscStream.tee();
1704
2358
  const [rscText, htmlStream] = await Promise.all([
@@ -1727,6 +2381,12 @@ async function handleRequest(request, platformContext = {}) {
1727
2381
  status: 200,
1728
2382
  revalidate: metadata.revalidate || 3,
1729
2383
  generatedAt: Date.now(),
2384
+ ...(Array.isArray(metadata.tags) ? { tags: metadata.tags } : {}),
2385
+ ...(context._slotTags && context._slotTags.size > 0
2386
+ ? { slotTags: Array.from(context._slotTags) }
2387
+ : Array.isArray(metadata.slotTags)
2388
+ ? { slotTags: metadata.slotTags }
2389
+ : {}),
1730
2390
  };
1731
2391
  await storage.set(htmlKey, htmlText, updatedMeta);
1732
2392
  await storage.set(metaKey, JSON.stringify(updatedMeta));
@@ -1764,6 +2424,12 @@ async function handleRequest(request, platformContext = {}) {
1764
2424
  status: 200,
1765
2425
  revalidate: metadata.revalidate || 3,
1766
2426
  generatedAt: Date.now(),
2427
+ ...(Array.isArray(metadata.tags) ? { tags: metadata.tags } : {}),
2428
+ ...(context._slotTags && context._slotTags.size > 0
2429
+ ? { slotTags: Array.from(context._slotTags) }
2430
+ : Array.isArray(metadata.slotTags)
2431
+ ? { slotTags: metadata.slotTags }
2432
+ : {}),
1767
2433
  };
1768
2434
  await storage.set(htmlKey, html, updatedMeta);
1769
2435
  await storage.set(metaKey, JSON.stringify(updatedMeta));
@@ -1831,6 +2497,9 @@ async function handleRequest(request, platformContext = {}) {
1831
2497
  if (!platformContext?.isSSG || process.env.DINOU_DEBUG) {
1832
2498
  console.log(`[Edge ISG] Processing page for ${reqPath}...`);
1833
2499
  }
2500
+ if (!hasStaticDynamicConfig) {
2501
+ dynamicState.value = false;
2502
+ }
1834
2503
  const context = createRequestContext(simReq, bridge, platformContext, dynamicState);
1835
2504
  copyCustomContextProperties(rootContext, context);
1836
2505
  const isNotFound = { value: !pagePath };
@@ -1849,6 +2518,7 @@ async function handleRequest(request, platformContext = {}) {
1849
2518
  await requestStorage.run(context, async () => {
1850
2519
  await runWithPprContext({ isPpr: true }, async () => {
1851
2520
  jsx = await getJSX(reqPath, queryObj, isNotFound, isDevelopment, !pagePath);
2521
+ resetPprHoles();
1852
2522
  jsx = await asyncRenderJSXToClientJSX(jsx);
1853
2523
  pprHoles = getRegisteredHoles();
1854
2524
  });
@@ -1892,10 +2562,13 @@ async function handleRequest(request, platformContext = {}) {
1892
2562
  }
1893
2563
  }
1894
2564
 
2565
+ const nowGen = Date.now();
1895
2566
  const genMeta = {
1896
2567
  status: isError ? 500 : isNotFound.value ? 404 : 200,
1897
- generatedAt: Date.now(),
2568
+ generatedAt: nowGen,
2569
+ pageGeneratedAt: nowGen,
1898
2570
  revalidate: combinedRevalidate,
2571
+ pageRevalidate: revalidate !== undefined ? revalidate : null,
1899
2572
  tags: tags || [],
1900
2573
  ppr: Boolean(isPprConfig),
1901
2574
  holes: pprHoles,
@@ -1905,6 +2578,7 @@ async function handleRequest(request, platformContext = {}) {
1905
2578
  },
1906
2579
  };
1907
2580
 
2581
+ const ssgPprUnwrappedBailout = Boolean(platformContext?.isSSG && isPprConfig && dynamicState.value);
1908
2582
  const shouldCacheISG =
1909
2583
  (!isDevelopment &&
1910
2584
  genMeta.status === 200 &&
@@ -1912,7 +2586,7 @@ async function handleRequest(request, platformContext = {}) {
1912
2586
  !dynamicState.value &&
1913
2587
  allowISGValue !== false &&
1914
2588
  Object.keys(queryObj).length === 0) ||
1915
- platformContext.isSSG === true;
2589
+ (platformContext.isSSG === true && !ssgPprUnwrappedBailout);
1916
2590
 
1917
2591
  if (!shouldCacheISG && inFlightKey) {
1918
2592
  inFlightGenerations.delete(inFlightKey);
@@ -1941,7 +2615,7 @@ async function handleRequest(request, platformContext = {}) {
1941
2615
  }
1942
2616
 
1943
2617
  const clientManifest = getClientManifest();
1944
- const rscStream = renderRSCStream(jsx, clientManifest, { runtime: "edge" });
2618
+ const rscStream = requestStorage.run(context, () => renderRSCStream(jsx, clientManifest, { runtime: "edge" }));
1945
2619
 
1946
2620
  if (platformContext && platformContext.renderHtmlStream) {
1947
2621
  const [streamForSsr, streamForCache] = rscStream.tee();
@@ -1951,10 +2625,14 @@ async function handleRequest(request, platformContext = {}) {
1951
2625
  bootstrapScriptContent += `window.__DINOU_LAYOUTS__ = ${JSON.stringify(knownLayouts)};\n`;
1952
2626
  if (shouldCacheISG && !isPprConfig) {
1953
2627
  bootstrapScriptContent += "window.__DINOU_USE_STATIC__ = true;\n";
2628
+ bootstrapScriptContent += `window.__DINOU_BUILD_ID__ = "${nowGen}";\n`;
1954
2629
  } else {
1955
2630
  bootstrapScriptContent += "window.__DINOU_USE_STATIC__ = false;\n";
1956
2631
  if (isPprConfig) {
1957
2632
  bootstrapScriptContent += "window.__DINOU_PPR__ = true;\n";
2633
+ if (shouldCacheISG) {
2634
+ bootstrapScriptContent += `window.__DINOU_BUILD_ID__ = "${nowGen}";\n`;
2635
+ }
1958
2636
  }
1959
2637
  }
1960
2638
  if (isDevelopment) {
@@ -2156,8 +2834,56 @@ async function handleRequest(request, platformContext = {}) {
2156
2834
  }
2157
2835
 
2158
2836
  if (fullHtml) {
2159
- if (!dynamicState.value || platformContext.isSSG === true) {
2837
+ if (!dynamicState.value || (platformContext.isSSG === true && !ssgPprUnwrappedBailout)) {
2838
+ if (platformContext.isSSG === true && !ssgPprUnwrappedBailout) dynamicState.value = false;
2839
+ for (const k of [reqPath, cleanPath, cleanPath ? `/${cleanPath}` : "/"]) {
2840
+ if (!k) continue;
2841
+ if (isDynamic.has(k)) {
2842
+ isDynamic.get(k).value = false;
2843
+ }
2844
+ }
2845
+ const pageSlotTags =
2846
+ layouts && layouts.length > 0
2847
+ ? context._pageSlotTags
2848
+ : context._pageSlotTags && context._pageSlotTags.size > 0
2849
+ ? context._pageSlotTags
2850
+ : context._slotTags;
2851
+ if (pageSlotTags && pageSlotTags.size > 0) {
2852
+ genMeta.slotTags = Array.from(pageSlotTags);
2853
+ }
2160
2854
  try {
2855
+ const pageRscKey = cleanPath ? `${cleanPath}/page.rsc` : "page.rsc";
2856
+ let pageRscText = "";
2857
+ if (context._resolvedPageClientJsx) {
2858
+ try {
2859
+ const pageStream = requestStorage.run(context, () =>
2860
+ renderRSCStream(context._resolvedPageClientJsx, clientManifest, { runtime: "edge" })
2861
+ );
2862
+ pageRscText = await new Response(pageStream).text();
2863
+ } catch (e) {}
2864
+ if (genMeta.ppr || (Array.isArray(genMeta.slotTags) && genMeta.slotTags.length > 0)) {
2865
+ try {
2866
+ const shellPageKey = cleanPath ? `${cleanPath}/shell.page.json` : "shell.page.json";
2867
+ await storage.set(shellPageKey, serializeJSX(context._resolvedPageClientJsx));
2868
+ } catch (e) {}
2869
+ }
2870
+ }
2871
+ if (!pageRscText && !platformContext?.isSSG && !genMeta.ppr) {
2872
+ try {
2873
+ const pageJsx = await requestStorage.run(context, () =>
2874
+ getJSX(reqPath, queryObj, isNotFound, false, false, { segment: "page" })
2875
+ );
2876
+ const pageStream = requestStorage.run(context, () =>
2877
+ renderRSCStream(pageJsx, clientManifest, { runtime: "edge" })
2878
+ );
2879
+ pageRscText = await new Response(pageStream).text();
2880
+ } catch (e) {
2881
+ pageRscText = rscPayload;
2882
+ }
2883
+ }
2884
+ if (pageRscText) {
2885
+ await storage.set(pageRscKey, pageRscText);
2886
+ }
2161
2887
  await storage.set(rscKey, rscPayload);
2162
2888
  await storage.set(htmlKey, fullHtml, genMeta);
2163
2889
  await storage.set(metaKey, JSON.stringify(genMeta));
@@ -2165,7 +2891,7 @@ async function handleRequest(request, platformContext = {}) {
2165
2891
  const shellHtmlKey = cleanPath ? `${cleanPath}/shell.html` : "shell.html";
2166
2892
  const shellRscKey = cleanPath ? `${cleanPath}/shell.rsc` : "shell.rsc";
2167
2893
  await storage.set(shellHtmlKey, fullHtml, genMeta);
2168
- await storage.set(shellRscKey, rscPayload, { ppr: true });
2894
+ await storage.set(shellRscKey, pageRscText || rscPayload);
2169
2895
  }
2170
2896
  if (!platformContext?.isSSG || process.env.DINOU_DEBUG) {
2171
2897
  console.log(`✅ [Edge ISG] Successfully cached ${reqPath} to KV`);
@@ -2174,6 +2900,13 @@ async function handleRequest(request, platformContext = {}) {
2174
2900
  console.error("[Edge ISG] Error caching to KV:", cacheErr);
2175
2901
  }
2176
2902
  } else {
2903
+ if (inFlightKey) {
2904
+ inFlightGenerations.delete(inFlightKey);
2905
+ }
2906
+ fullHtml = fullHtml.replace(
2907
+ "window.__DINOU_USE_STATIC__ = true;",
2908
+ "window.__DINOU_USE_STATIC__ = false;"
2909
+ );
2177
2910
  if (!platformContext?.isSSG || process.env.DINOU_DEBUG) {
2178
2911
  console.log(`ℹ️ [Edge ISG] Dynamic bailout detected during render for ${reqPath}, skipping KV cache`);
2179
2912
  }
@@ -2263,7 +2996,7 @@ async function handleRequest(request, platformContext = {}) {
2263
2996
  }
2264
2997
 
2265
2998
  // Node.js Runtime: Serve static pre-rendered HTML if available in production
2266
- if (!isDevelopment && !dynamicState.value && pagePath && !isPathBlocked) {
2999
+ if (!isDevelopment && (!dynamicState.value || isPprConfig) && pagePath && !isPathBlocked) {
2267
3000
  revalidating(reqPath, dynamicState);
2268
3001
  let htmlPathOld;
2269
3002
  if (regenerating.has(reqPath)) {
@@ -2272,7 +3005,7 @@ async function handleRequest(request, platformContext = {}) {
2272
3005
  const htmlPath = path.join(".dinou/dist2", reqPath, "index.html");
2273
3006
  const fileToRead = (htmlPathOld && existsSync(htmlPathOld)) ? htmlPathOld : htmlPath;
2274
3007
 
2275
- if (existsSync(fileToRead) && !dynamicState.value) {
3008
+ if (existsSync(fileToRead) && (!dynamicState.value || isPprConfig)) {
2276
3009
  bridge.setHeader("Content-Type", "text/html; charset=utf-8");
2277
3010
  bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
2278
3011
  let status = getStatus(reqPath);
@@ -2340,4 +3073,3 @@ export {
2340
3073
  resolvePageFunctionsConfig,
2341
3074
  };
2342
3075
  export default handleRequest;
2343
-