@brightsideoy/kama 1.0.0-alpha.3 → 1.0.0-alpha.30

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 (111) hide show
  1. package/README.md +25 -7
  2. package/bin/cli.js +539 -359
  3. package/content/definitions/blocks/button.yaml +15 -5
  4. package/content/definitions/blocks/form.yaml +20 -0
  5. package/content/definitions/blocks/image-gallery.yaml +34 -0
  6. package/content/definitions/blocks/node-list.yaml +75 -0
  7. package/content/definitions/blocks/youtube.yaml +8 -0
  8. package/content/definitions/field-sets/access.yaml +14 -0
  9. package/content/definitions/field-sets/page-base.yaml +19 -1
  10. package/content/definitions/forms/.gitkeep +0 -0
  11. package/content/definitions/forms/contact.yaml +38 -0
  12. package/content/definitions/forms/subscription.yaml +26 -0
  13. package/content/definitions/nodes/article.yaml +19 -1
  14. package/content/definitions/taxonomies/categories.yaml +5 -2
  15. package/content/definitions/taxonomies/media-tag.yaml +15 -0
  16. package/content/definitions/taxonomies/tags.yaml +5 -2
  17. package/definitions/editor/default.ts +19 -2
  18. package/dist/assets/AssetEditor-CAvQEsBT.js +1 -0
  19. package/dist/assets/AssetEditor-CQtKSOjX.css +1 -0
  20. package/dist/assets/CmsAccordion-91I5Rx5D.css +1 -0
  21. package/dist/assets/CmsAccordion-BgdaB8QZ.js +1 -0
  22. package/dist/assets/CmsBadge-BT2jTJUu.js +1 -0
  23. package/dist/assets/CmsBadge-Ip5hXw8G.css +1 -0
  24. package/dist/assets/CmsButton-DATGQeoC.css +1 -0
  25. package/dist/assets/CmsButton-DnhPsHXA.js +1 -0
  26. package/dist/assets/CmsFieldTaxonomy-CNY3-MbD.js +1 -0
  27. package/dist/assets/CmsFieldTaxonomy-CVlKL-l2.css +1 -0
  28. package/dist/assets/CmsHelp-BO_vWABq.css +1 -0
  29. package/dist/assets/CmsHelp-DtPeURCv.js +1 -0
  30. package/dist/assets/CmsImagePreview-BhM7S_v8.js +1 -0
  31. package/dist/assets/CmsImagePreview-CujwG8r_.css +1 -0
  32. package/dist/assets/CmsPublisher-BcrQAr1m.css +1 -0
  33. package/dist/assets/CmsPublisher-DiQhfPID.js +3 -0
  34. package/dist/assets/CmsUserCenter-CAaiCweN.js +1 -0
  35. package/dist/assets/CmsUserCenter-D3OZYHD0.css +1 -0
  36. package/dist/assets/EditorSplitPreview-BfGni85I.js +1 -0
  37. package/dist/assets/EditorSplitPreview-CMoTjLW5.css +1 -0
  38. package/dist/assets/FormsWorkspace-CGs6eUjz.css +1 -0
  39. package/dist/assets/FormsWorkspace-CUK-y2dR.js +2 -0
  40. package/dist/assets/NodeContextMenu-C5RTK0sr.js +1 -0
  41. package/dist/assets/NodeContextMenu-Cj-2TvQC.css +1 -0
  42. package/dist/assets/NodeEditor-CNj66ogv.js +161 -0
  43. package/dist/assets/NodeEditor-hYW5aA6B.css +1 -0
  44. package/dist/assets/SettingsDashboard-XBOgYUn3.css +1 -0
  45. package/dist/assets/SettingsDashboard-gzHzxsIc.js +1 -0
  46. package/dist/assets/StatusPill-Dlm6uvGe.css +1 -0
  47. package/dist/assets/StatusPill-HY1gCP9c.js +1 -0
  48. package/dist/assets/TrashWorkspace-DtMgxg13.css +1 -0
  49. package/dist/assets/TrashWorkspace-t0lOrFRK.js +1 -0
  50. package/dist/assets/_plugin-vue_export-helper-BK_c4R_m.js +5 -0
  51. package/dist/assets/circle-check-CksZGUB7.js +1 -0
  52. package/dist/assets/database--QlkzG9u.js +1 -0
  53. package/dist/assets/file-U7h4eOhG.js +1 -0
  54. package/dist/assets/globe-TuZP0v6A.js +1 -0
  55. package/dist/assets/history-CIbqkRx3.js +1 -0
  56. package/dist/assets/index-0nWRArpY.js +14 -0
  57. package/dist/assets/index-C171UGo4.css +1 -0
  58. package/dist/assets/layers-BwACvD_U.js +1 -0
  59. package/dist/assets/loader-circle-DYEFqbD4.js +1 -0
  60. package/dist/assets/panel-left-close-Cpq52HZy.js +1 -0
  61. package/dist/assets/plus-7rv1C56N.js +1 -0
  62. package/dist/assets/preload-helper-BB8Wl1va.js +1 -0
  63. package/dist/assets/preload-helper-BxFQpwa9.css +1 -0
  64. package/dist/assets/rotate-ccw-DvjWccJd.js +1 -0
  65. package/dist/assets/save-Dwhm8QNL.js +1 -0
  66. package/dist/assets/schema-helpers-uuDCw8Rb.js +1 -0
  67. package/dist/assets/send-Bs4eROle.js +1 -0
  68. package/dist/assets/smartphone-i429gh5p.js +1 -0
  69. package/dist/assets/trash-2-BbKTm8cC.js +1 -0
  70. package/dist/assets/useCmsState-CDENPbKL.js +1 -0
  71. package/dist/assets/useNodes-D-Vuwq5_.js +1 -0
  72. package/dist/assets/user-DKryA1QU.js +1 -0
  73. package/dist/assets/x-DOWbsdzd.js +1 -0
  74. package/dist/build-seed.js +495 -0
  75. package/dist/{dist-cK3xGnBZ.js → dist-DKRU6nhX.js} +9254 -5762
  76. package/dist/index.html +32 -2
  77. package/dist/index.js +9179 -5689
  78. package/dist/nodemailer-Ccic7tRm-Dw2jwzbm.js +7877 -0
  79. package/dist/nodemailer-Ccic7tRm.js +7908 -0
  80. package/dist/rolldown-runtime-B0aSnxlc.js +20 -0
  81. package/dist/schema-compiler.js +1 -1
  82. package/documentation/FORMS.md +256 -0
  83. package/documentation/SCHEMAS.md +450 -119
  84. package/package.json +14 -6
  85. package/schema.sql +46 -1
  86. package/templates/astro-starter/astro-preview-dev-integration.mjs +83 -0
  87. package/templates/astro-starter/astro.config.mjs +11 -0
  88. package/templates/astro-starter/src/components/blocks/BlockRenderer.astro +17 -0
  89. package/templates/astro-starter/src/components/blocks/Form.astro +313 -0
  90. package/templates/astro-starter/src/components/blocks/HeaderImage.astro +6 -12
  91. package/templates/astro-starter/src/components/blocks/ImageBlock.astro +5 -6
  92. package/templates/astro-starter/src/components/blocks/NodeList.astro +274 -0
  93. package/templates/astro-starter/src/components/global/NavigationMenu.astro +17 -8
  94. package/templates/astro-starter/src/components/ui/KamaImage.astro +13 -5
  95. package/templates/astro-starter/src/layouts/StandardLayout.astro +4 -3
  96. package/templates/astro-starter/src/lib/cms-fetch.ts +22 -0
  97. package/templates/astro-starter/src/lib/cms.ts +18 -9
  98. package/templates/astro-starter/src/lib/media/kama-image-service.ts +15 -4
  99. package/templates/astro-starter/src/lib/media/media-proxy.ts +22 -3
  100. package/templates/astro-starter/src/lib/media/media-url.ts +17 -3
  101. package/templates/astro-starter/src/middleware.ts +199 -71
  102. package/templates/astro-starter/src/pages/[...slug].astro +122 -45
  103. package/templates/astro-starter/src/pages/api/forms/[...path].ts +57 -0
  104. package/templates/astro-starter/src/pages/api/load-nodes.ts +68 -0
  105. package/templates/astro-starter/src/pages/api/partials/node-cards.astro +98 -0
  106. package/templates/astro-starter/src/pages/partials/nav.astro +6 -5
  107. package/templates/kama-worker/index.js +22 -12
  108. package/templates/kama-worker/setup-local-db.mjs +17 -0
  109. package/wrangler.json +19 -0
  110. package/dist/assets/index-C3LzwJjY.css +0 -1
  111. package/dist/assets/index-DhguVxzs.js +0 -164
@@ -1,6 +1,7 @@
1
1
  // src/middleware.ts
2
2
 
3
3
  import { defineMiddleware } from "astro:middleware";
4
+ import { fetchCmsRequest } from "./lib/cms-fetch";
4
5
 
5
6
  /**
6
7
  * Safely extracts environment variables across Astro 7, Node.js, and Cloudflare Workers
@@ -84,40 +85,65 @@ export const onRequest = defineMiddleware(async (context, next) => {
84
85
  return new Response("Not Found", { status: 404 });
85
86
  }
86
87
 
87
- // 🎯 0B. DIRECT MEDIA PROXY VIA SERVICE BINDING
88
+ // 🎯 0B. DIRECT MEDIA PROXY VIA SERVICE BINDING WITH SURGICAL WORKER CACHING
88
89
  if (pathname.startsWith("/media/")) {
90
+ const cache = typeof caches !== "undefined" && caches.default ? caches.default : null;
91
+ // Construct a clean cache key ignoring session headers
92
+ const cacheKey = new Request(context.url.toString(), { method: "GET" });
93
+
94
+ // 1. Check surgical Worker Edge Cache for pre-encoded media (15ms HIT)
95
+ if (!isDev && cache) {
96
+ try {
97
+ const cachedResponse = await cache.match(cacheKey);
98
+ if (cachedResponse) {
99
+ return cachedResponse;
100
+ }
101
+ } catch (e) {
102
+ // Fall back to fetch if cache read fails
103
+ }
104
+ }
105
+
106
+ // 2. Cold Fetch: Pass to CMS worker for AVIF transformation
89
107
  const cmsWorker = workerEnv?.CMS_WORKER;
90
- const envApiUrl = import.meta.env?.PUBLIC_API_URL;
91
- const workerApiUrl = workerEnv?.PUBLIC_API_URL;
92
- const baseApiUrl = String(envApiUrl || workerApiUrl || "https://kama.kamaengine.com");
108
+ const envApiUrl = import.meta.env?.PUBLIC_API_URL || import.meta.env?.PUBLIC_CMS_URL;
109
+ const workerApiUrl = workerEnv?.PUBLIC_API_URL || workerEnv?.PUBLIC_CMS_URL;
110
+ const localDevApiUrl = "http://127.0.0.1:8787";
111
+ const fallbackApiUrl = isDev ? localDevApiUrl : "https://kama.kamaengine.com";
112
+ const baseApiUrl = String(
113
+ isDev && !cmsWorker
114
+ ? localDevApiUrl
115
+ : workerApiUrl || envApiUrl || fallbackApiUrl
116
+ );
93
117
  const cleanApiUrl = baseApiUrl.endsWith("/") ? baseApiUrl.slice(0, -1) : baseApiUrl;
94
118
 
95
119
  const mediaUrl = `${cleanApiUrl}${pathname}${context.url.search}`;
96
- const mediaReq = new Request(mediaUrl, {
97
- headers: context.request.headers
98
- });
99
-
100
- let mediaResponse: Response;
120
+ const mediaReq = new Request(mediaUrl, { headers: context.request.headers });
101
121
 
102
- if (cmsWorker && typeof cmsWorker.fetch === "function") {
103
- mediaResponse = await cmsWorker.fetch(mediaReq);
104
- } else {
105
- mediaResponse = await fetch(mediaReq);
106
- }
122
+ const mediaResponse = await fetchCmsRequest(mediaReq, cmsWorker);
107
123
 
108
124
  const newHeaders = new Headers(mediaResponse.headers);
109
125
 
110
- // 🎯 DEV FIX: Only apply 1-year cache on media in Production
111
126
  if (!isDev) {
112
127
  newHeaders.set("Cache-Control", "public, max-age=31536000, s-maxage=31536000, immutable");
113
128
  }
114
129
  newHeaders.set("Access-Control-Allow-Origin", "*");
115
130
 
116
- return new Response(mediaResponse.body, {
131
+ const finalResponse = new Response(mediaResponse.body, {
117
132
  status: mediaResponse.status,
118
133
  statusText: mediaResponse.statusText,
119
134
  headers: newHeaders
120
135
  });
136
+
137
+ // 3. Store ONLY successful image transformations in Worker Edge Cache
138
+ if (!isDev && cache && mediaResponse.status === 200) {
139
+ if (cfContext && typeof cfContext.waitUntil === 'function') {
140
+ cfContext.waitUntil(cache.put(cacheKey, finalResponse.clone()));
141
+ } else {
142
+ cache.put(cacheKey, finalResponse.clone()).catch(() => { });
143
+ }
144
+ }
145
+
146
+ return finalResponse;
121
147
  }
122
148
 
123
149
  // 🎯 0C. DIRECT EDGE INTERCEPT FOR CACHE PURGE ENDPOINT
@@ -130,7 +156,7 @@ export const onRequest = defineMiddleware(async (context, next) => {
130
156
  }
131
157
 
132
158
  const authHeader = context.request.headers.get("Authorization");
133
- const expectedToken = workerEnv.CLOUDFLARE_API_TOKEN;
159
+ const expectedToken = workerEnv.FRONTEND_API_SECRET || workerEnv.CLOUDFLARE_API_TOKEN;
134
160
 
135
161
  if (!expectedToken || authHeader !== `Bearer ${expectedToken}`) {
136
162
  return new Response(JSON.stringify({ error: "Unauthorized Token Mismatch" }), {
@@ -144,11 +170,21 @@ export const onRequest = defineMiddleware(async (context, next) => {
144
170
  const cache = typeof caches !== "undefined" && caches.default ? caches.default : null;
145
171
  const origin = context.url.origin;
146
172
 
173
+ if (body.purge_everything && !HTML_CACHE) {
174
+ return new Response(JSON.stringify({ success: false, error: "HTML_CACHE binding is unavailable" }), {
175
+ status: 503,
176
+ headers: { "Content-Type": "application/json" },
177
+ });
178
+ }
179
+
147
180
  // A. Purge Workers Caching Layer (Astro cfContext)
148
181
  if (typeof cfContext?.cache?.purge === 'function') {
149
182
  try {
150
- await cfContext.cache.purge({ purgeEverything: true });
151
- console.log("✅ New Cloudflare Workers Cache Engine Purged");
183
+ // 🎯 FIX: Only execute global purge if the CMS explicitly requested it!
184
+ if (body.purge_everything) {
185
+ await cfContext.cache.purge({ purgeEverything: true });
186
+ console.log("✅ New Cloudflare Workers Cache Engine Purged (Global)");
187
+ }
152
188
  } catch (e) {
153
189
  console.error("❌ Failed to purge new Workers Cache Engine", e);
154
190
  }
@@ -161,22 +197,47 @@ export const onRequest = defineMiddleware(async (context, next) => {
161
197
 
162
198
  if (body.purge_everything) {
163
199
  // 🎯 GLOBAL PURGE: Bumping site_version instantly invalidates ALL KV pages globally!
164
- await HTML_CACHE.put("site_version", now);
165
- // Ensure root alias is forced to new version
166
- await HTML_CACHE.put("v:/", now);
167
-
168
- console.log(`✅ [Version Tagging] Global site_version updated to ${now}`);
200
+ try {
201
+ await Promise.all([
202
+ HTML_CACHE.put("site_version", now),
203
+ HTML_CACHE.put("partial_version", now),
204
+ HTML_CACHE.put("v:/", now)
205
+ ]);
206
+ body.siteVersion = now;
207
+ body.partialVersion = now;
208
+ console.log(`✅ [Version Tagging] Global site_version updated to ${now}`);
209
+ } catch (kvLimitErr: any) {
210
+ console.error(`[KV Error] Global version bump failed: ${kvLimitErr.message}`);
211
+ return new Response(JSON.stringify({ success: false, error: "Failed to invalidate HTML KV cache" }), {
212
+ status: 503,
213
+ headers: { "Content-Type": "application/json" },
214
+ });
215
+ }
169
216
  } else if (Array.isArray(body.urls) && body.urls.length > 0) {
170
- // 🎯 SURGICAL PURGE: Parallel execution for page version bumps
171
- const purgeTasks = [];
172
- for (const targetUrl of body.urls) {
217
+ const cleanPaths = [...new Set(body.urls.map((targetUrl: string) => {
173
218
  const urlPath = new URL(targetUrl).pathname;
174
- const cleanPath = urlPath.replace(/\/$/, "") || "/";
175
-
176
- purgeTasks.push(HTML_CACHE.put(`v:${cleanPath}`, now));
219
+ return urlPath.replace(/\/$/, "") || "/";
220
+ }))];
221
+ const pageVersions = Object.fromEntries(cleanPaths.map(cleanPath => [cleanPath, now]));
222
+
223
+ try {
224
+ await Promise.all([
225
+ ...cleanPaths.map(cleanPath => HTML_CACHE.put(`v:${cleanPath}`, now)),
226
+ ...(body.invalidate_partials ? [HTML_CACHE.put("partial_version", now)] : [])
227
+ ]);
228
+ body.pageVersions = pageVersions;
229
+ body.siteVersion = await HTML_CACHE.get("site_version") || "1";
230
+ if (body.invalidate_partials) body.partialVersion = now;
231
+ } catch (kvLimitErr: any) {
232
+ console.error(`[KV Error] Targeted version bump failed: ${kvLimitErr.message}`);
233
+ return new Response(JSON.stringify({ success: false, error: "Failed to invalidate targeted HTML KV cache" }), {
234
+ status: 503,
235
+ headers: { "Content-Type": "application/json" },
236
+ });
177
237
  }
178
- await Promise.all(purgeTasks);
238
+
179
239
  console.log(`✅ [Version Tagging] Updated versions for ${body.urls.length} URLs`);
240
+ // CMS CacheManager will automatically send the X-Cache-Warmer requests now!
180
241
  }
181
242
  } catch (kvErr) {
182
243
  console.error("❌ KV Version Tagging Error:", kvErr);
@@ -197,7 +258,9 @@ export const onRequest = defineMiddleware(async (context, next) => {
197
258
 
198
259
  return new Response(JSON.stringify({
199
260
  success: true,
200
- message: "All Worker Caches Purged"
261
+ message: "All Worker Caches Purged",
262
+ siteVersion: body.siteVersion,
263
+ partialVersion: body.partialVersion
201
264
  }), {
202
265
  status: 200,
203
266
  headers: { "Content-Type": "application/json" },
@@ -228,7 +291,10 @@ export const onRequest = defineMiddleware(async (context, next) => {
228
291
  return new Response(JSON.stringify({
229
292
  success: true,
230
293
  message: "URLs processed and version tags updated",
231
- results
294
+ results,
295
+ pageVersions: body.pageVersions || {},
296
+ siteVersion: body.siteVersion,
297
+ partialVersion: body.partialVersion
232
298
  }), {
233
299
  status: 200,
234
300
  headers: { "Content-Type": "application/json" },
@@ -246,18 +312,21 @@ export const onRequest = defineMiddleware(async (context, next) => {
246
312
  let purgedKv = false;
247
313
 
248
314
  if (HTML_CACHE) {
249
- const [siteVer, pageVer] = await Promise.all([
250
- HTML_CACHE.get("site_version"),
251
- HTML_CACHE.get(`v:${cleanPath}`)
252
- ]);
253
-
254
- if (siteVer || pageVer) {
255
- const activeCacheKey = `${cleanPath}:v:${siteVer || "1"}:${pageVer || "1"}`;
256
- await HTML_CACHE.delete(activeCacheKey);
257
- purgedKv = true;
315
+ try {
316
+ const [siteVer, pageVer] = await Promise.all([
317
+ HTML_CACHE.get("site_version"),
318
+ HTML_CACHE.get(`v:${cleanPath}`)
319
+ ]);
320
+
321
+ if (siteVer || pageVer) {
322
+ const activeCacheKey = `${cleanPath}:v:${siteVer || "1"}:${pageVer || "1"}`;
323
+ await HTML_CACHE.delete(activeCacheKey);
324
+ purgedKv = true;
325
+ }
326
+ await HTML_CACHE.delete(`v:${cleanPath}`);
327
+ } catch (kvLimitErr: any) {
328
+ console.warn(`[KV Warning] Skipped deletion for ${cleanPath}: ${kvLimitErr.message}`);
258
329
  }
259
-
260
- await HTML_CACHE.delete(`v:${cleanPath}`);
261
330
  }
262
331
 
263
332
  const cleanUrl = targetUrl.split('?')[0];
@@ -303,34 +372,63 @@ export const onRequest = defineMiddleware(async (context, next) => {
303
372
 
304
373
  // 🎯 1. KV STATIC "FILE" CACHE READ WITH VERSION TAGGING
305
374
  const isWarmer = context.request.headers.get("X-Cache-Warmer") === "true";
306
- const isHtmlPage = !pathname.includes('.') && !pathname.startsWith('/api/');
307
- // 🎯 The ONLY way we refer to the homepage in KV is "/"
375
+ const isPartialCache = pathname.startsWith('/api/partials/');
376
+ const forcedPageVersion = isWarmer ? context.request.headers.get("X-Cache-Page-Version") : null;
377
+ const forcedSiteVersion = isWarmer ? context.request.headers.get("X-Cache-Site-Version") : null;
378
+
379
+ // 🎯 ARCHITECTURE FIX: Allow HTML partials to be edge-cached alongside regular HTML
380
+ const isHtmlPage = !pathname.includes('.') && (!pathname.startsWith('/api/') || isPartialCache);
381
+
382
+ // 🎯 ARCHITECTURE FIX: Include query string for partials so offset=6 and offset=12 have distinct cache keys
308
383
  const cleanLookupPath = pathname === "/index" || pathname === "/index/"
309
384
  ? "/"
310
- : (pathname.replace(/\/$/, "") || "/");
385
+ : (pathname.replace(/\/$/, "") || "/") + (isPartialCache ? context.url.search : "");
311
386
 
312
387
  let activeCacheKey = cleanLookupPath;
313
388
 
314
- if (!isDev && isHtmlPage && HTML_CACHE && !isWarmer && !isTimeTraveling) {
389
+ // 🎯 FIX: Retrieve the activeCacheKey versions even if it's a warmer request, so it doesn't overwrite them!
390
+ if (!isDev && isHtmlPage && HTML_CACHE && !isTimeTraveling) {
315
391
  try {
392
+ const pageVersionKey = isPartialCache ? "partial_version" : `v:${pathname.replace(/\/$/, "") || "/"}`;
393
+
316
394
  const [siteVer, pageVer] = await Promise.all([
317
- HTML_CACHE.get("site_version"),
318
- HTML_CACHE.get(`v:${cleanLookupPath}`)
395
+ isPartialCache ? Promise.resolve(null) : (forcedSiteVersion || HTML_CACHE.get("site_version")),
396
+ forcedPageVersion || HTML_CACHE.get(pageVersionKey)
319
397
  ]);
320
398
 
321
- activeCacheKey = `${cleanLookupPath}:v:${siteVer || "1"}:${pageVer || "1"}`;
322
-
323
- const cachedHtml = await HTML_CACHE.get(activeCacheKey);
324
- if (cachedHtml) {
325
- return new Response(cachedHtml, {
326
- status: 200,
327
- headers: {
328
- "Content-Type": "text/html; charset=utf-8",
329
- "X-Cache-Status": "HIT-KV-STATICFILE",
330
- "X-Cache-Key": activeCacheKey,
331
- "Cache-Control": "no-store, no-cache, must-revalidate, proxy-revalidate"
399
+ activeCacheKey = isPartialCache
400
+ ? `${cleanLookupPath}:partial:${pageVer || "1"}`
401
+ : `${cleanLookupPath}:v:${siteVer || "1"}:${pageVer || "1"}`;
402
+
403
+ // 🎯 Only serve cached HTML if it is NOT a warmer request
404
+ if (!isWarmer) {
405
+ const cachedData = await HTML_CACHE.get(activeCacheKey);
406
+ if (cachedData) {
407
+ let finalHtml = cachedData;
408
+
409
+ try {
410
+ if (cachedData.startsWith("{")) {
411
+ const parsed = JSON.parse(cachedData);
412
+ if (parsed.html) {
413
+ finalHtml = parsed.html;
414
+ }
415
+ }
416
+ } catch (jsonErr) {
417
+ // Fallback to raw HTML
332
418
  }
333
- });
419
+
420
+ return new Response(finalHtml, {
421
+ status: 200,
422
+ headers: {
423
+ "Content-Type": "text/html; charset=utf-8",
424
+ "X-Cache-Status": "HIT-KV-STATICFILE",
425
+ "X-Cache-Key": activeCacheKey,
426
+ // Prevent Cloudflare Edge from locking stale HTML in RAM.
427
+ // Force Edge to revalidate with Worker logic while keeping browser cache fresh.
428
+ "Cache-Control": "public, max-age=0, must-revalidate"
429
+ }
430
+ });
431
+ }
334
432
  }
335
433
  } catch (e) {
336
434
  console.warn("[Middleware] KV lookup bypass:", e);
@@ -343,26 +441,56 @@ export const onRequest = defineMiddleware(async (context, next) => {
343
441
  // 🎯 2. KV STATIC "FILE" CACHE WRITE (Save HTML under active Version Key)
344
442
  if (
345
443
  !isDev &&
346
- isHtmlPage &&
347
- HTML_CACHE &&
444
+ isHtmlPage && HTML_CACHE &&
348
445
  !isTimeTraveling &&
349
446
  response.status === 200 &&
350
447
  response.headers.get("content-type")?.includes("text/html")
351
448
  ) {
352
449
  const htmlText = await response.clone().text();
353
450
 
451
+ // Extract the TTL injected by Astro SSR
452
+ const kvTtlHeader = response.headers.get("X-KV-Expiration");
453
+ const kvTtl = kvTtlHeader ? parseInt(kvTtlHeader, 10) : undefined;
454
+
455
+ // Clean up the internal header so it doesn't leak to the public browser
456
+ response.headers.delete("X-KV-Expiration");
457
+
354
458
  const writeTask = (async () => {
355
- if (activeCacheKey === cleanLookupPath || isWarmer) {
459
+ // 🎯 FIX: Removed `|| isWarmer` here so warmer requests safely write to the existing activeCacheKey
460
+ if (activeCacheKey === cleanLookupPath) {
356
461
  const forcedVersion = Date.now().toString();
462
+ try {
463
+ if (isPartialCache) {
464
+ const partialVersion = await HTML_CACHE.get("partial_version") || "1";
465
+ activeCacheKey = `${cleanLookupPath}:partial:${partialVersion}`;
466
+ } else {
467
+ const pageVersion = forcedPageVersion || forcedVersion;
468
+ if (!forcedPageVersion) {
469
+ await HTML_CACHE.put(`v:${pathname.replace(/\/$/, "") || "/"}`, pageVersion);
470
+ }
471
+ const siteVer = forcedSiteVersion || await HTML_CACHE.get("site_version") || "1";
472
+ activeCacheKey = `${cleanLookupPath}:v:${siteVer}:${pageVersion}`;
473
+ }
474
+ } catch (kvLimitErr: any) {
475
+ console.warn(`[KV Warning] Could not initialize cache version key: ${kvLimitErr.message}`);
476
+ }
477
+ }
357
478
 
358
- await HTML_CACHE.put(`v:${cleanLookupPath}`, forcedVersion);
479
+ // Save TTL alongside HTML so CDN can properly cache reads
480
+ const storedTtl = kvTtl !== undefined ? Math.max(60, kvTtl) : 31536000;
481
+ const payload = JSON.stringify({ html: htmlText, ttl: storedTtl });
359
482
 
360
- const siteVer = await HTML_CACHE.get("site_version") || "1";
361
- activeCacheKey = `${cleanLookupPath}:v:${siteVer}:${forcedVersion}`;
483
+ try {
484
+ if (kvTtl !== undefined) {
485
+ await HTML_CACHE.put(activeCacheKey, payload, { expirationTtl: storedTtl });
486
+ console.log(`✅ [Middleware] Saved HTML to KV under key: ${activeCacheKey} (Expires in ${storedTtl}s)`);
487
+ } else {
488
+ await HTML_CACHE.put(activeCacheKey, payload);
489
+ console.log(`✅ [Middleware] Saved HTML to KV under key: ${activeCacheKey} (Infinite TTL)`);
490
+ }
491
+ } catch (kvLimitErr: any) {
492
+ console.warn(`[KV Warning] Skipped HTML cache save (Quota limit exceeded): ${kvLimitErr.message}`);
362
493
  }
363
-
364
- await HTML_CACHE.put(activeCacheKey, htmlText);
365
- console.log(`✅ [Middleware] Saved HTML to KV under key: ${activeCacheKey}`);
366
494
  })();
367
495
 
368
496
  if (cfContext && typeof cfContext.waitUntil === 'function') {
@@ -6,6 +6,7 @@ import SkeletonLayout from "../layouts/SkeletonLayout.astro";
6
6
  import BlockRenderer from "../components/blocks/BlockRenderer.astro";
7
7
  import Breadcrumb from "../components/global/Breadcrumb.astro";
8
8
  import { getNodeByPath, getChannelId, getTree, getTreeId } from "../lib/cms";
9
+ import { fetchCmsRequest } from "../lib/cms-fetch";
9
10
  import type { NodeResponse, TreeNode } from "../lib/cms";
10
11
 
11
12
  export const prerender = false;
@@ -26,7 +27,7 @@ Astro.response.headers.set(
26
27
  "public, no-cache, must-revalidate",
27
28
  );
28
29
 
29
- // 1. STATIC ASSET & SYSTEM ROUTE CHECK
30
+ // 1. STATIC ASSET CHECK
30
31
  const staticExts = [
31
32
  ".ico",
32
33
  ".png",
@@ -36,33 +37,13 @@ const staticExts = [
36
37
  ".txt",
37
38
  ".xml",
38
39
  ".webmanifest",
39
- ".astro",
40
- ".ts",
41
- ".tsx",
42
- ".js",
43
- ".jsx",
44
- ".css",
45
- ".map",
46
- ".json",
47
40
  ];
48
-
49
41
  const slugStr = String(slug || "");
50
- // Strip leading slashes to correctly evaluate both "src/..." and "/src/..."
51
- const cleanSlug = slugStr.replace(/^\/+/, "").toLowerCase();
52
-
53
- // Check extension regardless of slash placement
54
- const isStaticAsset = staticExts.some(ext => cleanSlug.endsWith(ext));
55
-
56
- // Block Vite client internal hits, source file paths, and node_modules
57
- const isSystemPath =
58
- cleanSlug.startsWith("src/") ||
59
- cleanSlug.startsWith("@vite/") ||
60
- cleanSlug.startsWith("node_modules/") ||
61
- cleanSlug.startsWith("users/") ||
62
- cleanSlug.includes("components/") ||
63
- cleanSlug.includes("npm-test/");
64
-
65
- if (isStaticAsset || isSystemPath) {
42
+ const isStaticAsset =
43
+ !slugStr.includes("/") &&
44
+ staticExts.some(ext => slugStr.toLowerCase().endsWith(ext));
45
+
46
+ if (isStaticAsset) {
66
47
  return new Response(null, { status: 404 });
67
48
  }
68
49
 
@@ -70,10 +51,26 @@ if (isStaticAsset || isSystemPath) {
70
51
  const safeEnv = (Astro.locals as any).safeEnv || {};
71
52
  const cmsWorker = safeEnv.CMS_WORKER;
72
53
 
54
+ // Extract environment configuration & fallback slug
55
+ const envHomeSlug = import.meta.env.PUBLIC_HOME_SLUG;
56
+ const workerHomeSlug = safeEnv.PUBLIC_HOME_SLUG;
57
+ const homeSlug = String(envHomeSlug || workerHomeSlug || "index").trim();
58
+
73
59
  const envApiUrl = import.meta.env.PUBLIC_API_URL;
74
60
  const workerApiUrl = safeEnv.PUBLIC_API_URL;
75
61
  const baseApiUrl = String(envApiUrl || workerApiUrl || "http://localhost:8787");
76
62
 
63
+ // 🎯 Safely extract the secret across both environments
64
+ const frontendApiSecret =
65
+ import.meta.env.FRONTEND_API_SECRET || safeEnv.FRONTEND_API_SECRET;
66
+ const previewSessionCookie = isTimeTraveling
67
+ ? Astro.request.headers
68
+ .get("cookie")
69
+ ?.split(";")
70
+ .map(value => value.trim())
71
+ .find(value => value.startsWith("cms_session="))
72
+ : undefined;
73
+
77
74
  const cleanApiUrl = baseApiUrl.endsWith("/")
78
75
  ? baseApiUrl.slice(0, -1)
79
76
  : baseApiUrl;
@@ -88,19 +85,21 @@ const customFetch = async (input: RequestInfo | URL, init?: RequestInit) => {
88
85
  if (revisionId) urlObj.searchParams.set("revisionId", revisionId);
89
86
  if (isPreview) urlObj.searchParams.set("preview", "true");
90
87
  urlObj.searchParams.set("_t", Date.now().toString());
91
- } else {
92
- urlObj.searchParams.set("_cb", Date.now().toString());
93
88
  }
94
89
 
95
90
  urlStr = urlObj.toString();
96
91
 
97
- const reqHeaders: Record<string, string> = {
98
- ...init?.headers,
99
- "Cache-Control": "no-cache, no-store, must-revalidate",
100
- Pragma: "no-cache",
101
- // 🎯 Direct Service Bindings require explicit header flags to bypass CMS KV cache!
102
- "X-Bypass-Cache": "true",
103
- };
92
+ const reqHeaders = new Headers(init?.headers);
93
+ if (isTimeTraveling) {
94
+ reqHeaders.set("Cache-Control", "no-cache, no-store, must-revalidate");
95
+ reqHeaders.set("Pragma", "no-cache");
96
+ reqHeaders.set("X-Bypass-Cache", "true");
97
+ }
98
+
99
+ if (frontendApiSecret) {
100
+ reqHeaders.set("Authorization", `Bearer ${frontendApiSecret}`);
101
+ }
102
+ if (previewSessionCookie) reqHeaders.set("Cookie", previewSessionCookie);
104
103
 
105
104
  const fetchOpts: RequestInit = {
106
105
  ...init,
@@ -109,10 +108,7 @@ const customFetch = async (input: RequestInfo | URL, init?: RequestInit) => {
109
108
 
110
109
  const req = new Request(urlStr, fetchOpts);
111
110
 
112
- if (cmsWorker && typeof cmsWorker.fetch === "function") {
113
- return cmsWorker.fetch(req);
114
- }
115
- return fetch(req);
111
+ return fetchCmsRequest(req, cmsWorker);
116
112
  };
117
113
 
118
114
  const channelId = getChannelId();
@@ -121,19 +117,21 @@ const treeId = getTreeId();
121
117
  // 3. PATH & CONCURRENT FETCH RESOLUTION
122
118
  const rawSlug = Array.isArray(slug) ? slug.join("/") : slugStr;
123
119
  const pathParts = rawSlug.split("/").filter(part => part.trim() !== "");
124
- const targetSlug = pathParts.join("/"); // 🎯 This is now "" for the root URL!
120
+ const requestedSlug = pathParts.join("/");
121
+
122
+ // 🎯 ONLY FIX NEEDED HERE: Pass '/' if empty so home route resolves, otherwise requestedSlug
123
+ const targetSlug = requestedSlug || "/";
125
124
 
126
125
  let pageData: NodeResponse | null = null;
127
126
  let navTree: TreeNode[] = [];
128
127
 
129
- // 🎯 Fetch Tree and Node in PARALLEL using the cache-busting customFetch
128
+ // Fetch the tree and node in parallel; only preview requests bypass API caches.
130
129
  try {
131
130
  const [treeResult, nodeResult] = await Promise.all([
132
131
  getTree(treeId, channelId, customFetch).catch(err => {
133
132
  console.error(`❌ [SSR Error] Failed to fetch tree "${treeId}":`, err);
134
133
  return [];
135
134
  }),
136
- // 🎯 We just pass the targetSlug (even if it's empty). The backend handles it!
137
135
  getNodeByPath(targetSlug, channelId, isPreview, customFetch).catch(err => {
138
136
  console.error(
139
137
  `❌ [SSR Error] Failed to fetch page data for path "${targetSlug}":`,
@@ -144,7 +142,7 @@ try {
144
142
  ]);
145
143
 
146
144
  navTree = treeResult || [];
147
- pageData = nodeResult;
145
+ pageData = nodeResult as NodeResponse | null;
148
146
  } catch (err) {
149
147
  console.error("❌ [SSR Error] Failed concurrent fetch execution:", err);
150
148
  }
@@ -156,8 +154,40 @@ if (!pageData || !pageData.node) {
156
154
  const node = pageData.node;
157
155
  const content = pageData.content || {};
158
156
 
159
- // 🎯 Vastly simplified homepage detection!
160
- const isHomePage = targetSlug === "" || node?.path === "/";
157
+ // 🎯 SMART EDGE CACHING LOGIC (API-Driven TTL)
158
+ let cacheTtl = pageData?.meta?.cacheTtl;
159
+
160
+ if (cacheTtl === undefined || cacheTtl === null) {
161
+ cacheTtl = 31536000; // Default: 1 Year (Forever)
162
+ }
163
+
164
+ cacheTtl = Math.max(60, cacheTtl);
165
+
166
+ if (isTimeTraveling) {
167
+ Astro.response.headers.set(
168
+ "Cache-Control",
169
+ "no-cache, no-store, must-revalidate",
170
+ );
171
+ } else {
172
+ Astro.response.headers.set(
173
+ "Cache-Control",
174
+ `public, max-age=0, s-maxage=${cacheTtl}, must-revalidate`,
175
+ );
176
+ Astro.response.headers.set("X-KV-Expiration", cacheTtl.toString());
177
+ }
178
+
179
+ const rootTreeSlug =
180
+ navTree && navTree.length > 0
181
+ ? navTree[0].slug || (navTree[0] as any).key
182
+ : "";
183
+
184
+ const isHomePage =
185
+ targetSlug === "/" ||
186
+ targetSlug === homeSlug ||
187
+ (rootTreeSlug && targetSlug === rootTreeSlug) ||
188
+ node?.path === "/" ||
189
+ pathParts.length === 0;
190
+
161
191
  const normalizedSlug = isHomePage ? "" : targetSlug;
162
192
 
163
193
  const headerBlocks = content?.header || [];
@@ -167,6 +197,49 @@ const hasSidebar = sidebarBlocks.length > 0;
167
197
 
168
198
  // Detect if this node is a standalone Page Skeleton
169
199
  const isSkeleton = node?.nodeType === "page-skeleton";
200
+
201
+ const hotSwapScript = `
202
+ if (window !== window.top) {
203
+ window.addEventListener("message", async event => {
204
+ if (event.source === window.parent && event.data && event.data.type === "kama-preview-update") {
205
+ try {
206
+ const currentScrollY = window.scrollY;
207
+ let newHtml = event.data.html;
208
+ if (typeof newHtml !== "string" && typeof event.data.url === "string") {
209
+ const response = await fetch(event.data.url, { cache: "no-store" });
210
+ if (!response.ok) throw new Error("Preview refresh failed (" + response.status + ").");
211
+ newHtml = await response.text();
212
+ }
213
+ if (typeof newHtml !== "string") return;
214
+ const newDoc = new DOMParser().parseFromString(newHtml, "text/html");
215
+
216
+ newDoc.body
217
+ .querySelectorAll("script, style, link, meta, noscript")
218
+ .forEach(el => el.remove());
219
+
220
+ const preserveTags = ["SCRIPT", "STYLE", "LINK", "META", "NOSCRIPT"];
221
+
222
+ Array.from(document.body.children).forEach(child => {
223
+ if (!preserveTags.includes(child.tagName.toUpperCase())) {
224
+ child.remove();
225
+ }
226
+ });
227
+
228
+ const referenceNode = document.body.firstChild;
229
+ Array.from(newDoc.body.children).forEach(child => {
230
+ if (!preserveTags.includes(child.tagName.toUpperCase())) {
231
+ document.body.insertBefore(child.cloneNode(true), referenceNode);
232
+ }
233
+ });
234
+
235
+ window.scrollTo(0, currentScrollY);
236
+ } catch (err) {
237
+ console.error("[KAMA Preview] Failed to hot-swap HTML:", err);
238
+ }
239
+ }
240
+ });
241
+ }
242
+ `;
170
243
  ---
171
244
 
172
245
  {
@@ -179,6 +252,8 @@ const isSkeleton = node?.nodeType === "page-skeleton";
179
252
  isHomePage={isHomePage}
180
253
  >
181
254
  <BlockRenderer blocks={mainBlocks} contentMap={content} region="main" />
255
+
256
+ {isPreview && <script is:inline set:html={hotSwapScript} />}
182
257
  </SkeletonLayout>
183
258
  ) : (
184
259
  <StandardLayout
@@ -238,6 +313,8 @@ const isSkeleton = node?.nodeType === "page-skeleton";
238
313
  </aside>
239
314
  )}
240
315
  </div>
316
+
317
+ {isPreview && <script is:inline set:html={hotSwapScript} />}
241
318
  </StandardLayout>
242
319
  )
243
320
  }