@brightsideoy/kama 0.1.0-alpha.99 → 1.0.0-alpha.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.
- package/README.md +169 -0
- package/bin/cli.js +775 -251
- package/content/definitions/blocks/button.yaml +24 -0
- package/content/definitions/blocks/header.yaml +13 -0
- package/content/definitions/blocks/header_image.yaml +21 -0
- package/content/definitions/blocks/hero.yaml +28 -0
- package/content/definitions/blocks/html.yaml +13 -0
- package/content/definitions/blocks/image_card.yaml +56 -0
- package/content/definitions/blocks/single_image.yaml +27 -0
- package/content/definitions/blocks/text.yaml +15 -0
- package/content/definitions/channels/ecommerce.yaml +28 -0
- package/content/definitions/channels/website.yaml +41 -0
- package/{defaults → content}/definitions/field-sets/access.yaml +3 -5
- package/content/definitions/field-sets/channel-base.yaml +57 -0
- package/{defaults/definitions/field-sets/page-meta.yaml → content/definitions/field-sets/channel-seo.yaml} +3 -11
- package/content/definitions/field-sets/content-block.yaml +41 -0
- package/content/definitions/field-sets/page-base.yaml +44 -0
- package/content/definitions/field-sets/page-seo.yaml +34 -0
- package/{defaults → content}/definitions/field-sets/page-social.yaml +6 -8
- package/content/definitions/field-sets/schema-type.yaml +43 -0
- package/content/definitions/field-sets/tree-base.yaml +31 -0
- package/content/definitions/node-layouts/content.yml +12 -0
- package/{defaults → content}/definitions/node-layouts/landing-page.yml +8 -3
- package/{defaults → content}/definitions/node-layouts/single-column.yml +10 -5
- package/{defaults → content}/definitions/node-layouts/two-column.yml +14 -6
- package/content/definitions/nodes/address.yaml +40 -0
- package/content/definitions/nodes/article.yaml +49 -0
- package/content/definitions/nodes/event.yaml +55 -0
- package/content/definitions/nodes/external-link.yaml +29 -0
- package/content/definitions/nodes/page-skeleton.yaml +48 -0
- package/{defaults → content}/definitions/nodes/page.yaml +9 -20
- package/content/definitions/nodes/person.yaml +37 -0
- package/content/definitions/nodes/product.yaml +89 -0
- package/content/definitions/taxonomies/categories.yaml +15 -0
- package/content/definitions/taxonomies/tags.yaml +12 -0
- package/content/definitions/trees/navigation.yaml +24 -0
- package/definitions/editor/default.ts +1 -0
- package/dist/assets/index-C3LzwJjY.css +1 -0
- package/dist/assets/index-DhguVxzs.js +164 -0
- package/dist/dist-cK3xGnBZ.js +26457 -0
- package/dist/index.html +4 -2
- package/dist/index.js +24028 -7125
- package/dist/schema-compiler.js +48 -0
- package/documentation/SCHEMAS.md +182 -0
- package/package.json +20 -24
- package/schema.sql +55 -23
- package/templates/astro-starter/astro.config.mjs +27 -0
- package/templates/astro-starter/package.json.template +20 -0
- package/templates/astro-starter/public/robots.txt +23 -0
- package/templates/astro-starter/src/components/blocks/BlockRenderer.astro +134 -0
- package/templates/astro-starter/src/components/blocks/ColumnLayout.astro +67 -0
- package/templates/astro-starter/src/components/blocks/HeaderImage.astro +132 -0
- package/templates/astro-starter/src/components/blocks/Hero.astro +218 -0
- package/templates/astro-starter/src/components/blocks/HtmlBlock.astro +25 -0
- package/templates/astro-starter/src/components/blocks/ImageBlock.astro +92 -0
- package/templates/astro-starter/src/components/blocks/TextBlock.astro +15 -0
- package/templates/astro-starter/src/components/global/Breadcrumb.astro +108 -0
- package/templates/astro-starter/src/components/global/Footer.astro +50 -0
- package/templates/astro-starter/src/components/global/Header.astro +171 -0
- package/templates/astro-starter/src/components/global/MetaHead.astro +266 -0
- package/templates/astro-starter/src/components/global/NavigationMenu.astro +413 -0
- package/templates/astro-starter/src/components/ui/KamaImage.astro +172 -0
- package/templates/astro-starter/src/layouts/SkeletonLayout.astro +56 -0
- package/templates/astro-starter/src/layouts/StandardLayout.astro +62 -0
- package/templates/astro-starter/src/lib/cms.ts +217 -0
- package/templates/astro-starter/src/lib/media/kama-image-service.ts +56 -0
- package/templates/astro-starter/src/lib/media/media-proxy.ts +129 -0
- package/templates/astro-starter/src/lib/media/media-url.ts +98 -0
- package/templates/astro-starter/src/middleware.ts +435 -0
- package/templates/astro-starter/src/pages/404.astro +46 -0
- package/templates/astro-starter/src/pages/[...slug].astro +243 -0
- package/templates/astro-starter/src/pages/llms-full.txt.ts +171 -0
- package/templates/astro-starter/src/pages/llms.txt.ts +113 -0
- package/templates/astro-starter/src/pages/media/[...path].ts +14 -0
- package/templates/astro-starter/src/pages/partials/footer.astro +69 -0
- package/templates/astro-starter/src/pages/partials/nav.astro +141 -0
- package/templates/astro-starter/src/styles/standard-theme.css +157 -0
- package/templates/astro-starter/src/utils/tiptap.ts +113 -0
- package/templates/astro-starter/tsconfig.json +0 -0
- package/templates/kama-worker/index.js +19 -0
- package/templates/kama-worker/server.js +104 -0
- package/wrangler.json +22 -0
- package/defaults/definitions/blocks/button.yaml +0 -15
- package/defaults/definitions/blocks/header.yaml +0 -15
- package/defaults/definitions/blocks/header_image.yaml +0 -22
- package/defaults/definitions/blocks/hero.yaml +0 -27
- package/defaults/definitions/blocks/image_card.yaml +0 -57
- package/defaults/definitions/blocks/single_image.yaml +0 -28
- package/defaults/definitions/blocks/text.yaml +0 -16
- package/defaults/definitions/channels/ecommerce.yaml +0 -24
- package/defaults/definitions/channels/website.yaml +0 -32
- package/defaults/definitions/field-sets/channel-base.yaml +0 -31
- package/defaults/definitions/field-sets/content-block.yaml +0 -46
- package/defaults/definitions/field-sets/page-base.yaml +0 -49
- package/defaults/definitions/field-sets/tree-base.yaml +0 -31
- package/defaults/definitions/node-layouts/three-column.yml +0 -41
- package/defaults/definitions/nodes/address.yaml +0 -32
- package/defaults/definitions/nodes/article.yaml +0 -43
- package/defaults/definitions/nodes/event.yaml +0 -49
- package/defaults/definitions/nodes/external-link.yaml +0 -26
- package/defaults/definitions/nodes/person.yaml +0 -37
- package/defaults/definitions/nodes/product.yaml +0 -86
- package/defaults/definitions/trees/navigation.yaml +0 -29
- package/defaults/definitions/trees/social-links.yaml +0 -9
- package/definitions/_page.yaml +0 -52
- package/dist/assets/index-D6qQsWOj.js +0 -1392
- package/dist/assets/index-TdW5F0pX.css +0 -1
- package/dist/media/kama/2026/08/17a098c92bc54ea4b4441e531a34575b.jpg +0 -0
- package/dist/media/kama/2026/08/3e9ae457dd23461680cc699f42d07cf0.jpg +0 -0
- package/dist/media/kama/2026/08/8e5b3a2fd194459f9b962f8e12928bf0.jpg +0 -0
- package/dist/media/kama/2026/08/8ea5c21026cd4944bdf78c99fe2544a9.jpg +0 -0
- package/scripts/bundle-definitions.js +0 -176
- /package/{defaults → content}/definitions/block-layouts/three-column.yaml +0 -0
- /package/{defaults → content}/definitions/block-layouts/two-column.yaml +0 -0
- /package/{defaults → content}/definitions/field-sets/comments.yaml +0 -0
- /package/{defaults → content}/definitions/field-sets/visibility.yaml +0 -0
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
// src/middleware.ts
|
|
2
|
+
|
|
3
|
+
import { defineMiddleware } from "astro:middleware";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Safely extracts environment variables across Astro 7, Node.js, and Cloudflare Workers
|
|
7
|
+
* without triggering the `@astrojs/cloudflare` runtime.env getter exception.
|
|
8
|
+
*/
|
|
9
|
+
async function getSafeEnv(locals: any): Promise<Record<string, any>> {
|
|
10
|
+
// 1. Try native Cloudflare Workers module (Astro 5+ / workerd)
|
|
11
|
+
try {
|
|
12
|
+
// @ts-ignore
|
|
13
|
+
const cf = await import("cloudflare:workers");
|
|
14
|
+
if (cf?.env) return cf.env;
|
|
15
|
+
} catch (e) {
|
|
16
|
+
// Not running inside a Cloudflare Worker container
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// 2. Safe check for locals.runtime / cfContext (Local Node.js / Hono)
|
|
20
|
+
const runtime = locals?.runtime || locals?.cfContext;
|
|
21
|
+
if (runtime && typeof runtime === "object") {
|
|
22
|
+
if ("CMS_WORKER" in runtime || "PUBLIC_API_URL" in runtime) {
|
|
23
|
+
return runtime;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Safely check property descriptor to avoid triggering throwing getters
|
|
27
|
+
try {
|
|
28
|
+
const desc = Object.getOwnPropertyDescriptor(runtime, "env");
|
|
29
|
+
if (desc && !desc.get) {
|
|
30
|
+
return runtime.env;
|
|
31
|
+
}
|
|
32
|
+
} catch (e) {
|
|
33
|
+
// Ignore getter throws
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// 3. Fallback for standalone Node.js mode
|
|
38
|
+
return typeof process !== "undefined" ? process.env || {} : {};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export const onRequest = defineMiddleware(async (context, next) => {
|
|
42
|
+
const pathname = context.url.pathname;
|
|
43
|
+
const pathLower = pathname.toLowerCase();
|
|
44
|
+
|
|
45
|
+
// 🎯 Detect if we are previewing a draft or looking at a snapshot revision
|
|
46
|
+
const isPreview = context.url.searchParams.get("preview") === "true";
|
|
47
|
+
const hasRevision = context.url.searchParams.has("revisionId");
|
|
48
|
+
const isTimeTraveling = isPreview || hasRevision;
|
|
49
|
+
|
|
50
|
+
// 🎯 Detect Local Vite Dev Mode to bypass edge caching locally
|
|
51
|
+
const isDev = import.meta.env.DEV;
|
|
52
|
+
|
|
53
|
+
// 🎯 Safe dual-environment context extraction
|
|
54
|
+
const workerEnv = await getSafeEnv(context.locals);
|
|
55
|
+
|
|
56
|
+
// Attach to locals so Astro components (like Header.astro) don't have to re-evaluate it
|
|
57
|
+
(context.locals as any).safeEnv = workerEnv;
|
|
58
|
+
|
|
59
|
+
// 🎯 Safe ctx extraction (Fixing the runtime.ctx crash in Astro 6/7)
|
|
60
|
+
let cfContext = (context.locals as any).cfContext;
|
|
61
|
+
if (!cfContext) {
|
|
62
|
+
const runtime = (context.locals as any).runtime;
|
|
63
|
+
if (runtime && typeof runtime === "object") {
|
|
64
|
+
try {
|
|
65
|
+
const desc = Object.getOwnPropertyDescriptor(runtime, "ctx");
|
|
66
|
+
if (desc && !desc.get) {
|
|
67
|
+
cfContext = runtime.ctx;
|
|
68
|
+
}
|
|
69
|
+
} catch (e) { }
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
cfContext = cfContext || {};
|
|
73
|
+
|
|
74
|
+
const HTML_CACHE = workerEnv?.HTML_CACHE; // KV Namespace binding
|
|
75
|
+
|
|
76
|
+
// 🎯 0. INSTANT EDGE SPAM DROP (Blocks bots before hit to CMS worker/database)
|
|
77
|
+
const isSpam =
|
|
78
|
+
pathLower.includes("wp-") ||
|
|
79
|
+
pathLower.includes("wordpress") ||
|
|
80
|
+
pathLower.endsWith(".php") ||
|
|
81
|
+
pathLower === "/wp";
|
|
82
|
+
|
|
83
|
+
if (isSpam) {
|
|
84
|
+
return new Response("Not Found", { status: 404 });
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// 🎯 0B. DIRECT MEDIA PROXY VIA SERVICE BINDING
|
|
88
|
+
if (pathname.startsWith("/media/")) {
|
|
89
|
+
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");
|
|
93
|
+
const cleanApiUrl = baseApiUrl.endsWith("/") ? baseApiUrl.slice(0, -1) : baseApiUrl;
|
|
94
|
+
|
|
95
|
+
const mediaUrl = `${cleanApiUrl}${pathname}${context.url.search}`;
|
|
96
|
+
const mediaReq = new Request(mediaUrl, {
|
|
97
|
+
headers: context.request.headers
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
let mediaResponse: Response;
|
|
101
|
+
|
|
102
|
+
if (cmsWorker && typeof cmsWorker.fetch === "function") {
|
|
103
|
+
mediaResponse = await cmsWorker.fetch(mediaReq);
|
|
104
|
+
} else {
|
|
105
|
+
mediaResponse = await fetch(mediaReq);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const newHeaders = new Headers(mediaResponse.headers);
|
|
109
|
+
|
|
110
|
+
// 🎯 DEV FIX: Only apply 1-year cache on media in Production
|
|
111
|
+
if (!isDev) {
|
|
112
|
+
newHeaders.set("Cache-Control", "public, max-age=31536000, s-maxage=31536000, immutable");
|
|
113
|
+
}
|
|
114
|
+
newHeaders.set("Access-Control-Allow-Origin", "*");
|
|
115
|
+
|
|
116
|
+
return new Response(mediaResponse.body, {
|
|
117
|
+
status: mediaResponse.status,
|
|
118
|
+
statusText: mediaResponse.statusText,
|
|
119
|
+
headers: newHeaders
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// 🎯 0C. DIRECT EDGE INTERCEPT FOR CACHE PURGE ENDPOINT
|
|
124
|
+
if (pathname === "/api/purge" || pathname === "/api/purge/") {
|
|
125
|
+
if (context.request.method !== "POST") {
|
|
126
|
+
return new Response(JSON.stringify({ error: "Method Not Allowed" }), {
|
|
127
|
+
status: 405,
|
|
128
|
+
headers: { "Content-Type": "application/json" },
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const authHeader = context.request.headers.get("Authorization");
|
|
133
|
+
const expectedToken = workerEnv.CLOUDFLARE_API_TOKEN;
|
|
134
|
+
|
|
135
|
+
if (!expectedToken || authHeader !== `Bearer ${expectedToken}`) {
|
|
136
|
+
return new Response(JSON.stringify({ error: "Unauthorized Token Mismatch" }), {
|
|
137
|
+
status: 401,
|
|
138
|
+
headers: { "Content-Type": "application/json" },
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
try {
|
|
143
|
+
const body = await context.request.json();
|
|
144
|
+
const cache = typeof caches !== "undefined" && caches.default ? caches.default : null;
|
|
145
|
+
const origin = context.url.origin;
|
|
146
|
+
|
|
147
|
+
// A. Purge Workers Caching Layer (Astro cfContext)
|
|
148
|
+
if (typeof cfContext?.cache?.purge === 'function') {
|
|
149
|
+
try {
|
|
150
|
+
await cfContext.cache.purge({ purgeEverything: true });
|
|
151
|
+
console.log("✅ New Cloudflare Workers Cache Engine Purged");
|
|
152
|
+
} catch (e) {
|
|
153
|
+
console.error("❌ Failed to purge new Workers Cache Engine", e);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// B. Version-Based Instant Invalidation (0ms KV Write)
|
|
158
|
+
if (HTML_CACHE) {
|
|
159
|
+
try {
|
|
160
|
+
const now = Date.now().toString();
|
|
161
|
+
|
|
162
|
+
if (body.purge_everything) {
|
|
163
|
+
// 🎯 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}`);
|
|
169
|
+
} 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) {
|
|
173
|
+
const urlPath = new URL(targetUrl).pathname;
|
|
174
|
+
const cleanPath = urlPath.replace(/\/$/, "") || "/";
|
|
175
|
+
|
|
176
|
+
purgeTasks.push(HTML_CACHE.put(`v:${cleanPath}`, now));
|
|
177
|
+
}
|
|
178
|
+
await Promise.all(purgeTasks);
|
|
179
|
+
console.log(`✅ [Version Tagging] Updated versions for ${body.urls.length} URLs`);
|
|
180
|
+
}
|
|
181
|
+
} catch (kvErr) {
|
|
182
|
+
console.error("❌ KV Version Tagging Error:", kvErr);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// C. Global Legacy Worker Cache Purge
|
|
187
|
+
if (body.purge_everything) {
|
|
188
|
+
if (cache) {
|
|
189
|
+
const rootUrls = [
|
|
190
|
+
origin,
|
|
191
|
+
`${origin}/`
|
|
192
|
+
];
|
|
193
|
+
for (const url of rootUrls) {
|
|
194
|
+
await cache.delete(new Request(url));
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
return new Response(JSON.stringify({
|
|
199
|
+
success: true,
|
|
200
|
+
message: "All Worker Caches Purged"
|
|
201
|
+
}), {
|
|
202
|
+
status: 200,
|
|
203
|
+
headers: { "Content-Type": "application/json" },
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// D. Surgical Legacy Worker Cache Purge
|
|
208
|
+
if (Array.isArray(body.urls) && body.urls.length > 0) {
|
|
209
|
+
const results = [];
|
|
210
|
+
|
|
211
|
+
for (const targetUrl of body.urls) {
|
|
212
|
+
const cleanUrl = targetUrl.split('?')[0];
|
|
213
|
+
const urlNoSlash = cleanUrl.replace(/\/$/, "");
|
|
214
|
+
const urlWithSlash = urlNoSlash + "/";
|
|
215
|
+
const pathsToClear = [urlNoSlash, urlWithSlash];
|
|
216
|
+
|
|
217
|
+
let purged = false;
|
|
218
|
+
if (cache) {
|
|
219
|
+
for (const p of pathsToClear) {
|
|
220
|
+
const res = await cache.delete(new Request(p));
|
|
221
|
+
if (res) purged = true;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
results.push({ url: targetUrl, purged });
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return new Response(JSON.stringify({
|
|
229
|
+
success: true,
|
|
230
|
+
message: "URLs processed and version tags updated",
|
|
231
|
+
results
|
|
232
|
+
}), {
|
|
233
|
+
status: 200,
|
|
234
|
+
headers: { "Content-Type": "application/json" },
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// 🎯 E. SURGICAL DELETION FOR DELETED PAGES
|
|
239
|
+
if (Array.isArray(body.deleted_urls) && body.deleted_urls.length > 0) {
|
|
240
|
+
const results: any[] = [];
|
|
241
|
+
|
|
242
|
+
const deleteTasks = body.deleted_urls.map(async (targetUrl: string) => {
|
|
243
|
+
const urlPath = new URL(targetUrl).pathname;
|
|
244
|
+
const cleanPath = urlPath.replace(/\/$/, "") || "/";
|
|
245
|
+
|
|
246
|
+
let purgedKv = false;
|
|
247
|
+
|
|
248
|
+
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;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
await HTML_CACHE.delete(`v:${cleanPath}`);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const cleanUrl = targetUrl.split('?')[0];
|
|
264
|
+
const urlNoSlash = cleanUrl.replace(/\/$/, "");
|
|
265
|
+
const urlWithSlash = urlNoSlash + "/";
|
|
266
|
+
const pathsToClear = [urlNoSlash, urlWithSlash];
|
|
267
|
+
|
|
268
|
+
let purgedLegacy = false;
|
|
269
|
+
if (cache) {
|
|
270
|
+
for (const p of pathsToClear) {
|
|
271
|
+
const res = await cache.delete(new Request(p));
|
|
272
|
+
if (res) purgedLegacy = true;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
results.push({ url: targetUrl, purgedKv, purgedLegacy });
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
await Promise.all(deleteTasks);
|
|
280
|
+
|
|
281
|
+
return new Response(JSON.stringify({
|
|
282
|
+
success: true,
|
|
283
|
+
message: "Deleted URLs processed and KV keys permanently removed",
|
|
284
|
+
results
|
|
285
|
+
}), {
|
|
286
|
+
status: 200,
|
|
287
|
+
headers: { "Content-Type": "application/json" },
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
return new Response(JSON.stringify({ error: "Invalid payload format" }), {
|
|
292
|
+
status: 400,
|
|
293
|
+
headers: { "Content-Type": "application/json" },
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
} catch (err: any) {
|
|
297
|
+
return new Response(JSON.stringify({ error: err.message }), {
|
|
298
|
+
status: 500,
|
|
299
|
+
headers: { "Content-Type": "application/json" },
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// 🎯 1. KV STATIC "FILE" CACHE READ WITH VERSION TAGGING
|
|
305
|
+
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 "/"
|
|
308
|
+
const cleanLookupPath = pathname === "/index" || pathname === "/index/"
|
|
309
|
+
? "/"
|
|
310
|
+
: (pathname.replace(/\/$/, "") || "/");
|
|
311
|
+
|
|
312
|
+
let activeCacheKey = cleanLookupPath;
|
|
313
|
+
|
|
314
|
+
if (!isDev && isHtmlPage && HTML_CACHE && !isWarmer && !isTimeTraveling) {
|
|
315
|
+
try {
|
|
316
|
+
const [siteVer, pageVer] = await Promise.all([
|
|
317
|
+
HTML_CACHE.get("site_version"),
|
|
318
|
+
HTML_CACHE.get(`v:${cleanLookupPath}`)
|
|
319
|
+
]);
|
|
320
|
+
|
|
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"
|
|
332
|
+
}
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
} catch (e) {
|
|
336
|
+
console.warn("[Middleware] KV lookup bypass:", e);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// Process downstream SSR routes
|
|
341
|
+
const response = await next();
|
|
342
|
+
|
|
343
|
+
// 🎯 2. KV STATIC "FILE" CACHE WRITE (Save HTML under active Version Key)
|
|
344
|
+
if (
|
|
345
|
+
!isDev &&
|
|
346
|
+
isHtmlPage &&
|
|
347
|
+
HTML_CACHE &&
|
|
348
|
+
!isTimeTraveling &&
|
|
349
|
+
response.status === 200 &&
|
|
350
|
+
response.headers.get("content-type")?.includes("text/html")
|
|
351
|
+
) {
|
|
352
|
+
const htmlText = await response.clone().text();
|
|
353
|
+
|
|
354
|
+
const writeTask = (async () => {
|
|
355
|
+
if (activeCacheKey === cleanLookupPath || isWarmer) {
|
|
356
|
+
const forcedVersion = Date.now().toString();
|
|
357
|
+
|
|
358
|
+
await HTML_CACHE.put(`v:${cleanLookupPath}`, forcedVersion);
|
|
359
|
+
|
|
360
|
+
const siteVer = await HTML_CACHE.get("site_version") || "1";
|
|
361
|
+
activeCacheKey = `${cleanLookupPath}:v:${siteVer}:${forcedVersion}`;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
await HTML_CACHE.put(activeCacheKey, htmlText);
|
|
365
|
+
console.log(`✅ [Middleware] Saved HTML to KV under key: ${activeCacheKey}`);
|
|
366
|
+
})();
|
|
367
|
+
|
|
368
|
+
if (cfContext && typeof cfContext.waitUntil === 'function') {
|
|
369
|
+
cfContext.waitUntil(writeTask);
|
|
370
|
+
} else {
|
|
371
|
+
writeTask.catch((e: any) => console.error("KV write error:", e));
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// 🎯 3. SERVE LLMS & LLXML ENDPOINTS
|
|
376
|
+
if (pathname === "/llms.txt" || pathname === "/llms-full.txt") {
|
|
377
|
+
response.headers.set("Content-Type", "text/plain; charset=utf-8");
|
|
378
|
+
response.headers.set("Cache-Control", "public, max-age=3600");
|
|
379
|
+
response.headers.set("Access-Control-Allow-Origin", "*");
|
|
380
|
+
return response;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
if (pathname === "/llxml.txt") {
|
|
384
|
+
response.headers.set("Content-Type", "application/xml; charset=utf-8");
|
|
385
|
+
response.headers.set("Cache-Control", "public, max-age=3600");
|
|
386
|
+
response.headers.set("Access-Control-Allow-Origin", "*");
|
|
387
|
+
return response;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// 🎯 4. STATIC ASSET CACHING FOR COMPRESSED BUNDLES / ASSETS
|
|
391
|
+
if (!isDev) {
|
|
392
|
+
if (
|
|
393
|
+
pathname.startsWith("/_image") ||
|
|
394
|
+
pathname.startsWith("/cdn-cgi/image/") ||
|
|
395
|
+
pathname.match(/\.(png|jpg|jpeg|webp|avif|svg|gif|ico|woff2?|css|js)$/i)
|
|
396
|
+
) {
|
|
397
|
+
response.headers.set(
|
|
398
|
+
"Cache-Control",
|
|
399
|
+
"public, max-age=31536000, s-maxage=31536000, immutable"
|
|
400
|
+
);
|
|
401
|
+
response.headers.set("Access-Control-Allow-Origin", "*");
|
|
402
|
+
return response;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// 🎯 5. SECURITY HEADERS FOR HTML PAGES
|
|
407
|
+
if (response.headers.get("content-type")?.includes("text/html")) {
|
|
408
|
+
response.headers.set("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload");
|
|
409
|
+
response.headers.set("X-Content-Type-Options", "nosniff");
|
|
410
|
+
|
|
411
|
+
// 🎯 Extract origin from env dynamically
|
|
412
|
+
const cmsUrl = workerEnv?.PUBLIC_CMS_URL || workerEnv?.PUBLIC_API_URL || "http://localhost:8787";
|
|
413
|
+
let cmsOrigin = "";
|
|
414
|
+
try {
|
|
415
|
+
cmsOrigin = new URL(cmsUrl).origin;
|
|
416
|
+
} catch (e) { }
|
|
417
|
+
|
|
418
|
+
if (isDev) {
|
|
419
|
+
response.headers.set("X-Frame-Options", "ALLOWALL");
|
|
420
|
+
response.headers.set(
|
|
421
|
+
"Content-Security-Policy",
|
|
422
|
+
"default-src 'self' http: https: data: 'unsafe-inline' 'unsafe-eval'; img-src 'self' http: https: data: blob:; connect-src 'self' http: https: ws: wss:; frame-ancestors *;"
|
|
423
|
+
);
|
|
424
|
+
} else {
|
|
425
|
+
// Production headers
|
|
426
|
+
response.headers.set("Cross-Origin-Opener-Policy", "same-origin-allow-popups");
|
|
427
|
+
response.headers.set(
|
|
428
|
+
"Content-Security-Policy",
|
|
429
|
+
`default-src 'self' https: data: 'unsafe-inline' 'unsafe-eval'; img-src 'self' https: data: blob:; connect-src 'self' https:; frame-ancestors 'self' https://*.kamaengine.com https://kama.kamaengine.com ${cmsOrigin};`
|
|
430
|
+
);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
return response;
|
|
435
|
+
});
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
---
|
|
2
|
+
// src/pages/404.astro
|
|
3
|
+
import StandardLayout from "../layouts/StandardLayout.astro";
|
|
4
|
+
|
|
5
|
+
const node = {
|
|
6
|
+
title: "Page Not Found",
|
|
7
|
+
summary: "We couldn't find the page you were looking for.",
|
|
8
|
+
};
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
<StandardLayout
|
|
12
|
+
node={node}
|
|
13
|
+
isHomePage={false}
|
|
14
|
+
hasSidebar={false}
|
|
15
|
+
content={{}}
|
|
16
|
+
normalizedSlug="404"
|
|
17
|
+
headerBlocks={[]}
|
|
18
|
+
>
|
|
19
|
+
<div class="error-page">
|
|
20
|
+
<h1>404</h1>
|
|
21
|
+
<h2>Page Not Found</h2>
|
|
22
|
+
<p>Sorry, the page you are looking for doesn't exist or has been moved.</p>
|
|
23
|
+
<a href="/" class="button">Go back home</a>
|
|
24
|
+
</div>
|
|
25
|
+
</StandardLayout>
|
|
26
|
+
|
|
27
|
+
<style>
|
|
28
|
+
.error-page {
|
|
29
|
+
text-align: center;
|
|
30
|
+
padding: 100px 20px;
|
|
31
|
+
}
|
|
32
|
+
.error-page h1 {
|
|
33
|
+
font-size: 6rem;
|
|
34
|
+
margin-bottom: 0;
|
|
35
|
+
color: #0284c7;
|
|
36
|
+
}
|
|
37
|
+
.button {
|
|
38
|
+
display: inline-block;
|
|
39
|
+
margin-top: 24px;
|
|
40
|
+
padding: 12px 24px;
|
|
41
|
+
background: #0f172a;
|
|
42
|
+
color: white;
|
|
43
|
+
text-decoration: none;
|
|
44
|
+
border-radius: 4px;
|
|
45
|
+
}
|
|
46
|
+
</style>
|