@decocms/tanstack 8.1.0-next.0 → 8.4.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 (177) hide show
  1. package/README.md +79 -0
  2. package/dist/draft.d.ts +33 -0
  3. package/dist/draft.d.ts.map +1 -0
  4. package/dist/draft.js +41 -0
  5. package/dist/draft.js.map +1 -0
  6. package/dist/index.d.ts +9 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +9 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/react/DecoDocument.d.ts +61 -0
  11. package/dist/react/DecoDocument.d.ts.map +1 -0
  12. package/dist/react/DecoDocument.js +96 -0
  13. package/dist/react/DecoDocument.js.map +1 -0
  14. package/dist/react/Image.d.ts +96 -0
  15. package/dist/react/Image.d.ts.map +1 -0
  16. package/dist/react/Image.js +79 -0
  17. package/dist/react/Image.js.map +1 -0
  18. package/dist/react/index.d.ts +7 -0
  19. package/dist/react/index.d.ts.map +1 -0
  20. package/dist/react/index.js +7 -0
  21. package/dist/react/index.js.map +1 -0
  22. package/dist/react/pageValues.d.ts +10 -0
  23. package/dist/react/pageValues.d.ts.map +1 -0
  24. package/dist/react/pageValues.js +29 -0
  25. package/dist/react/pageValues.js.map +1 -0
  26. package/dist/react/scripts.d.ts +14 -0
  27. package/dist/react/scripts.d.ts.map +1 -0
  28. package/dist/react/scripts.js +96 -0
  29. package/dist/react/scripts.js.map +1 -0
  30. package/dist/router/index.d.ts +38 -0
  31. package/dist/router/index.d.ts.map +1 -0
  32. package/dist/router/index.js +60 -0
  33. package/dist/router/index.js.map +1 -0
  34. package/dist/scope/browser.d.ts +11 -0
  35. package/dist/scope/browser.d.ts.map +1 -0
  36. package/dist/scope/browser.js +8 -0
  37. package/dist/scope/browser.js.map +1 -0
  38. package/dist/scope/server.d.ts +13 -0
  39. package/dist/scope/server.d.ts.map +1 -0
  40. package/dist/scope/server.js +26 -0
  41. package/dist/scope/server.js.map +1 -0
  42. package/dist/server/index.d.ts +27 -0
  43. package/dist/server/index.d.ts.map +1 -0
  44. package/dist/server/index.js +31 -0
  45. package/dist/server/index.js.map +1 -0
  46. package/dist/shared.d.ts +26 -0
  47. package/dist/shared.d.ts.map +1 -0
  48. package/dist/shared.js +26 -0
  49. package/dist/shared.js.map +1 -0
  50. package/dist/start/index.d.ts +9 -0
  51. package/dist/start/index.d.ts.map +1 -0
  52. package/dist/start/index.js +33 -0
  53. package/dist/start/index.js.map +1 -0
  54. package/dist/studio.d.ts +28 -0
  55. package/dist/studio.d.ts.map +1 -0
  56. package/dist/studio.js +53 -0
  57. package/dist/studio.js.map +1 -0
  58. package/dist/vite/index.d.ts +15 -0
  59. package/dist/vite/index.d.ts.map +1 -0
  60. package/dist/vite/index.js +95 -0
  61. package/dist/vite/index.js.map +1 -0
  62. package/dist/worker/cacheProfiles.d.ts +43 -0
  63. package/dist/worker/cacheProfiles.d.ts.map +1 -0
  64. package/dist/worker/cacheProfiles.js +162 -0
  65. package/dist/worker/cacheProfiles.js.map +1 -0
  66. package/dist/worker/cookies.d.ts +20 -0
  67. package/dist/worker/cookies.d.ts.map +1 -0
  68. package/dist/worker/cookies.js +69 -0
  69. package/dist/worker/cookies.js.map +1 -0
  70. package/dist/worker/drafts.d.ts +59 -0
  71. package/dist/worker/drafts.d.ts.map +1 -0
  72. package/dist/worker/drafts.js +140 -0
  73. package/dist/worker/drafts.js.map +1 -0
  74. package/dist/worker/index.d.ts +107 -0
  75. package/dist/worker/index.d.ts.map +1 -0
  76. package/dist/worker/index.js +511 -0
  77. package/dist/worker/index.js.map +1 -0
  78. package/dist/worker/security.d.ts +14 -0
  79. package/dist/worker/security.d.ts.map +1 -0
  80. package/dist/worker/security.js +48 -0
  81. package/dist/worker/security.js.map +1 -0
  82. package/dist/worker/segment.d.ts +21 -0
  83. package/dist/worker/segment.d.ts.map +1 -0
  84. package/dist/worker/segment.js +43 -0
  85. package/dist/worker/segment.js.map +1 -0
  86. package/package.json +85 -37
  87. package/src/draft.ts +43 -0
  88. package/src/index.ts +8 -61
  89. package/src/react/DecoDocument.tsx +234 -0
  90. package/src/react/Image.tsx +213 -0
  91. package/src/react/index.ts +24 -0
  92. package/src/react/pageValues.ts +35 -0
  93. package/src/react/scripts.ts +98 -0
  94. package/src/router/index.ts +80 -0
  95. package/src/scope/browser.ts +18 -0
  96. package/src/scope/server.ts +37 -0
  97. package/src/server/index.ts +43 -0
  98. package/src/shared.ts +29 -0
  99. package/src/start/index.ts +31 -0
  100. package/src/studio.ts +52 -0
  101. package/src/vite/index.ts +105 -0
  102. package/src/worker/cacheProfiles.ts +180 -0
  103. package/src/worker/cookies.ts +65 -0
  104. package/src/worker/drafts.ts +157 -0
  105. package/src/worker/index.ts +648 -0
  106. package/src/worker/security.ts +63 -0
  107. package/src/worker/segment.ts +49 -0
  108. package/src/__conformance__/observability.test.ts +0 -221
  109. package/src/cms/kvBlockSource.test.ts +0 -82
  110. package/src/cms/kvBlockSource.ts +0 -68
  111. package/src/daemon/auth.ts +0 -204
  112. package/src/daemon/fs.ts +0 -238
  113. package/src/daemon/index.ts +0 -8
  114. package/src/daemon/middleware.ts +0 -156
  115. package/src/daemon/tunnel.ts +0 -129
  116. package/src/daemon/volumes.ts +0 -366
  117. package/src/daemon/watch.ts +0 -272
  118. package/src/hooks/CdnSegmentMarker.tsx +0 -38
  119. package/src/hooks/DecoPageRenderer.tsx +0 -750
  120. package/src/hooks/DecoRootLayout.tsx +0 -192
  121. package/src/hooks/DraftPreviewIndicator.test.tsx +0 -60
  122. package/src/hooks/DraftPreviewIndicator.tsx +0 -64
  123. package/src/hooks/NavigationProgress.test.tsx +0 -58
  124. package/src/hooks/NavigationProgress.tsx +0 -63
  125. package/src/hooks/PreviewProviders.test.tsx +0 -42
  126. package/src/hooks/PreviewProviders.tsx +0 -45
  127. package/src/hooks/StableOutlet.tsx +0 -30
  128. package/src/hooks/deferredObserverTiming.test.tsx +0 -91
  129. package/src/hooks/index.ts +0 -10
  130. package/src/routes/adminRoutes.test.ts +0 -99
  131. package/src/routes/adminRoutes.ts +0 -153
  132. package/src/routes/cmsRoute.test.ts +0 -267
  133. package/src/routes/cmsRoute.ts +0 -1053
  134. package/src/routes/components.tsx +0 -57
  135. package/src/routes/index.ts +0 -24
  136. package/src/routes/pageUrl.test.ts +0 -70
  137. package/src/routes/pageUrl.ts +0 -55
  138. package/src/routes/withSiteGlobals.test.ts +0 -243
  139. package/src/routes/withSiteGlobals.ts +0 -243
  140. package/src/sdk/backgroundTasks.test.ts +0 -68
  141. package/src/sdk/backgroundTasks.ts +0 -38
  142. package/src/sdk/cdnSegment.test.ts +0 -67
  143. package/src/sdk/cdnSegment.ts +0 -71
  144. package/src/sdk/cookiePassthrough.ts +0 -58
  145. package/src/sdk/createInvoke.ts +0 -77
  146. package/src/sdk/deferredSectionLoader.test.ts +0 -94
  147. package/src/sdk/deferredSectionLoader.ts +0 -46
  148. package/src/sdk/draft.test.ts +0 -341
  149. package/src/sdk/draft.ts +0 -277
  150. package/src/sdk/draftShared.ts +0 -16
  151. package/src/sdk/kvHydration.test.ts +0 -371
  152. package/src/sdk/kvHydration.ts +0 -263
  153. package/src/sdk/kvRedirects.test.ts +0 -132
  154. package/src/sdk/kvRedirects.ts +0 -125
  155. package/src/sdk/outboundHeaders.test.ts +0 -113
  156. package/src/sdk/outboundHeaders.ts +0 -81
  157. package/src/sdk/router.ts +0 -101
  158. package/src/sdk/serverFnFetch.ts +0 -59
  159. package/src/sdk/speculationRules.test.ts +0 -82
  160. package/src/sdk/speculationRules.ts +0 -136
  161. package/src/sdk/startEntry.ts +0 -31
  162. package/src/sdk/useHydrated.ts +0 -19
  163. package/src/sdk/workerEntry.cacheStorage.test.ts +0 -147
  164. package/src/sdk/workerEntry.test.ts +0 -1033
  165. package/src/sdk/workerEntry.trackingCache.test.ts +0 -328
  166. package/src/sdk/workerEntry.ts +0 -3154
  167. package/src/setupFastDeploy.ts +0 -13
  168. package/src/v8/__conformance__/delivery.test.ts +0 -100
  169. package/src/v8/binding.ts +0 -70
  170. package/src/v8/kvLoader.bundle.test.ts +0 -42
  171. package/src/v8/kvLoader.test.ts +0 -74
  172. package/src/v8/kvLoader.ts +0 -43
  173. package/src/vite/plugin-scaffold-gen.test.js +0 -106
  174. package/src/vite/plugin.js +0 -1022
  175. package/src/vite/plugin.test.js +0 -238
  176. package/src/vite/plugin.test.ts +0 -176
  177. package/tsconfig.json +0 -7
@@ -0,0 +1,648 @@
1
+ /**
2
+ * `createDecoWorker`: the Cloudflare Worker in front of TanStack Start, the way
3
+ * Deco runs every TanStack storefront. One entry, a few options, one escape
4
+ * hatch (`routes`). What every site gets, with no option:
5
+ *
6
+ * - `/deco/_liveness` answers `OK`; v7's admin paths (`/deco/*`, `/live/*`,
7
+ * `/.decofile`) answer 404.
8
+ * - Drafts: the host allowlist (`./drafts.ts`), the draft cookie, the
9
+ * `x-deco-draft` request header the page reads, and on the response
10
+ * `no-store`, `Vary: Cookie` and `noindex`. Only a real draft skips the cache.
11
+ * - The CMS redirects, before any route.
12
+ * - An edge cache (the Cloudflare Cache API) keyed by URL, device, the site's
13
+ * segment parts and `<build>.<content revision>`, with stale-while-revalidate
14
+ * and stale-if-error; logged-in, private and degraded responses never stored.
15
+ * - CDN caching of client-side navigation data whose `__cseg` token checks out;
16
+ * every other response tells the CDN `no-store`, at one exit.
17
+ * - Security headers and `frame-ancestors` for Studio; immutable fingerprinted
18
+ * assets; one `Set-Cookie` per cookie; `x-page-status`.
19
+ */
20
+ import { type CMS, matchRoute, type Redirect } from "@decocms/blocks";
21
+ import { runInScope } from "@decocms/tanstack/scope";
22
+ import { DRAFT_HEADER, draftResponseHeaders } from "../draft.ts";
23
+ import { CSEG_PARAM, DEGRADED_HEADER, PAGE_STATUS_HEADER } from "../shared.ts";
24
+ import {
25
+ type CacheProfileName,
26
+ type CacheProfileOverrides,
27
+ cacheControl,
28
+ canonicalizeServerFnPayload,
29
+ isServerFnPath,
30
+ PRIVATE_NO_CACHE,
31
+ profileOf,
32
+ resolveProfiles,
33
+ } from "./cacheProfiles.ts";
34
+ import { dedupeSetCookies, hasOnlySafeCookies, withoutSafeCookies } from "./cookies.ts";
35
+ import { decideDraft, type PreviewPolicy } from "./drafts.ts";
36
+ import { type CspOptions, htmlSecurityHeaders } from "./security.ts";
37
+ import { DEVICES, detectDevice, type Segment, segmentKey, segmentToken } from "./segment.ts";
38
+
39
+ export type {
40
+ CacheProfile,
41
+ CacheProfileName,
42
+ CacheProfileOverrides,
43
+ CacheWindow,
44
+ } from "./cacheProfiles.ts";
45
+ export { DEFAULT_CACHE_PROFILES } from "./cacheProfiles.ts";
46
+ export type { CspOptions } from "./security.ts";
47
+ export type { Device, Segment } from "./segment.ts";
48
+
49
+ /** The part of Cloudflare's `ExecutionContext` the worker uses. */
50
+ export interface ExecutionContextLike {
51
+ waitUntil(promise: Promise<unknown>): void;
52
+ passThroughOnException?(): void;
53
+ }
54
+
55
+ /**
56
+ * TanStack Start's server entry (`createServerEntry({ fetch: handler.fetch })`). The worker
57
+ * passes it the request, the Worker's env and the execution context.
58
+ */
59
+ export interface ServerEntry {
60
+ fetch(request: Request, env?: any, ctx?: any): Response | Promise<Response>;
61
+ }
62
+
63
+ /** What the edge cache did with a request (`X-Cache`). */
64
+ export type CacheDecision = "HIT" | "STALE-HIT" | "STALE-ERROR" | "MISS" | "BYPASS";
65
+
66
+ /** One page or server-function request, for `onCache`. */
67
+ export interface CacheEvent {
68
+ /** The page type (cache profile) the URL maps to. */
69
+ profile: CacheProfileName;
70
+ decision: CacheDecision;
71
+ /** Milliseconds from the request to the response's headers. */
72
+ ms: number;
73
+ status: number;
74
+ }
75
+
76
+ export interface DecoWorkerOptions<Env = unknown> {
77
+ serverEntry: ServerEntry;
78
+ /** The site's CMS: drafts, the content revision in the cache key, CMS redirects. */
79
+ cms: CMS;
80
+ /** The site's name: `<site>.deco.site` and `<site>.deco-cx.workers.dev` may preview drafts. */
81
+ site: string;
82
+ /** The build's id, in every cache key: the commit sha (`decoTanstack()` defines `__BUILD_HASH__`). */
83
+ buildHash: string;
84
+ /** Local development (`import.meta.env.DEV`): no edge cache, `no-cache` pages, loopback may frame the site. */
85
+ dev?: boolean;
86
+ /** The site's Content-Security-Policy. Studio's `frame-ancestors` is always added. */
87
+ csp?: CspOptions;
88
+ /**
89
+ * More cache-key parts for a request (a region, a sales channel, an A/B
90
+ * cohort), merged over `{ device }` (`mobile`, `tablet` or `desktop`; return
91
+ * your own `device` to merge classes). Return `"private"` for a request that
92
+ * must never share a cached response (a signed-in shopper).
93
+ */
94
+ segment?: (request: Request) => Record<string, string | undefined> | "private";
95
+ /** Changes to the default cache profiles (`DEFAULT_CACHE_PROFILES`). */
96
+ cacheProfiles?: CacheProfileOverrides;
97
+ /** Cookies a cached response may set (stripped from the stored copy). Default: `_deco_bucket`. */
98
+ safeCookies?: readonly string[];
99
+ /** Turns on `POST /_cache/purge` with `Authorization: Bearer <token>`. */
100
+ purgeToken?: (env: Env) => string | undefined;
101
+ /**
102
+ * `Link: rel=preload` hints on every HTML response the app renders. A
103
+ * `routes` response carries none: it is another origin's page (a proxied
104
+ * checkout, an A/B test's other site), and these are this app's assets.
105
+ */
106
+ preload?: { styles?: readonly string[]; fonts?: readonly string[] };
107
+ /**
108
+ * v7's `DECO_ALLOWED_PREVIEW_HOSTS`: replaces the site's declared preview
109
+ * hosts (the `CMS` block's), exact hosts with their port
110
+ * (`["localhost:5173"]` for local development); the site's Deco hosts stay
111
+ * allowed. `"none"` turns draft previews off on every host. Without it and
112
+ * without hosts in the `CMS` block, drafts preview only on the Deco hosts.
113
+ */
114
+ previewHosts?: readonly string[] | "none";
115
+ /**
116
+ * The escape hatch, after the CMS redirects and before anything else: answer
117
+ * a request yourself (a commerce proxy, a sitemap, an A/B route) or return
118
+ * `null` to let the worker serve it. The request carries the checked draft.
119
+ * Its response leaves like any other (security headers, `CDN-Cache-Control`)
120
+ * but without the `preload` hints.
121
+ */
122
+ routes?: (
123
+ request: Request,
124
+ env: Env,
125
+ ctx: ExecutionContextLike,
126
+ ) => Response | null | undefined | Promise<Response | null | undefined>;
127
+ /** Called once per page or server-function request (D3: no exporter is built in). */
128
+ onCache?: (event: CacheEvent) => void;
129
+ }
130
+
131
+ export interface DecoWorker<Env> {
132
+ fetch(request: Request, env: Env, ctx: ExecutionContextLike): Promise<Response>;
133
+ }
134
+
135
+ const LIVENESS_PATH = "/deco/_liveness";
136
+ /** v7's admin protocol paths: v8 sites serve none of them. */
137
+ const REMOVED_ADMIN_PATHS = ["/deco/", "/live/", "/.decofile"];
138
+ const PURGE_PATH = "/_cache/purge";
139
+ const BYPASS_PATHS = ["/_build"];
140
+ const STATIC_PATHS = ["/fonts/"];
141
+ const FINGERPRINTED_ASSET_RE = /(?:\/_build)?\/assets\/.*-[a-zA-Z0-9_-]{8,}\.\w+$/;
142
+ /** Query parameters that never change a page, left out of its cache key (v7's list). */
143
+ const TRACKING_PARAMS = new Set([
144
+ "utm_source",
145
+ "utm_medium",
146
+ "utm_campaign",
147
+ "utm_term",
148
+ "utm_content",
149
+ "utmi_campaign",
150
+ "utmi_page",
151
+ "utmi_part",
152
+ "fbclid",
153
+ "gclid",
154
+ "gclsrc",
155
+ "dclid",
156
+ "msclkid",
157
+ "twclid",
158
+ "li_fat_id",
159
+ "mc_cid",
160
+ "mc_eid",
161
+ "ttclid",
162
+ "srsltid",
163
+ ]);
164
+ const DEFAULT_SAFE_COOKIES = ["_deco_bucket"];
165
+ const STORED_AT = "X-Deco-Stored-At";
166
+ const DECISIONS = new Set<string>(["HIT", "STALE-HIT", "STALE-ERROR", "MISS", "BYPASS"]);
167
+
168
+ const isHtml = (r: Response) => (r.headers.get("content-type") ?? "").includes("text/html");
169
+
170
+ function edgeCache(): Cache | null {
171
+ return typeof caches !== "undefined"
172
+ ? ((caches as unknown as { default?: Cache }).default ?? null)
173
+ : null;
174
+ }
175
+
176
+ /** The origin's response with the page's own status (`x-page-status`) applied. */
177
+ function withPageStatus(response: Response): Response {
178
+ const status = Number(response.headers.get(PAGE_STATUS_HEADER));
179
+ if (!status || status < 200 || status > 599) return response;
180
+ const headers = new Headers(response.headers);
181
+ headers.delete(PAGE_STATUS_HEADER);
182
+ return new Response(response.body, { status, headers });
183
+ }
184
+
185
+ function isPrivateResponse(response: Response): boolean {
186
+ return /\b(private|no-store)\b/i.test(response.headers.get("cache-control") ?? "");
187
+ }
188
+
189
+ function isDegraded(response: Response): boolean {
190
+ return response.headers.get(DEGRADED_HEADER) === "true";
191
+ }
192
+
193
+ /** Adds `value` to the response's `Vary`, keeping what the origin listed. */
194
+ function appendVary(headers: Headers, value: string): void {
195
+ const current = headers.get("vary");
196
+ if (!current) headers.set("vary", value);
197
+ else if (!current.split(",").some((v) => v.trim().toLowerCase() === value.toLowerCase())) {
198
+ headers.set("vary", `${current}, ${value}`);
199
+ }
200
+ }
201
+
202
+ function mutable(response: Response): Response {
203
+ return new Response(response.body, response);
204
+ }
205
+
206
+ function bypass(response: Response, reason: string, cacheControlValue?: string): Response {
207
+ const out = mutable(response);
208
+ if (cacheControlValue) {
209
+ out.headers.set("Cache-Control", cacheControlValue);
210
+ out.headers.delete("CDN-Cache-Control");
211
+ }
212
+ out.headers.set("X-Cache", "BYPASS");
213
+ out.headers.set("X-Cache-Reason", reason);
214
+ return out;
215
+ }
216
+
217
+ export function createDecoWorker<Env = unknown>(options: DecoWorkerOptions<Env>): DecoWorker<Env> {
218
+ const { cms, serverEntry } = options;
219
+ const dev = options.dev === true;
220
+ const profiles = resolveProfiles(options.cacheProfiles);
221
+ const safeCookies = new Set(options.safeCookies ?? DEFAULT_SAFE_COOKIES);
222
+ const securityHeaders = htmlSecurityHeaders(options.csp, dev);
223
+ const policy: PreviewPolicy = { site: options.site, previewHosts: options.previewHosts };
224
+ const preloadLinks = [
225
+ ...(options.preload?.styles ?? []).map((href) => `<${href}>; rel=preload; as=style`),
226
+ ...(options.preload?.fonts ?? []).map((href) => `<${href}>; rel=preload; as=font; crossorigin`),
227
+ ];
228
+
229
+ /** `<build>.<revision>`: a published release gets new entries at once; the build alone when the revision can't be read. */
230
+ async function cacheVersion(): Promise<string> {
231
+ let revision = "";
232
+ try {
233
+ revision = await cms.forRelease().revision();
234
+ } catch {
235
+ // The content didn't load: key on the build only.
236
+ }
237
+ return [options.buildHash, revision].filter(Boolean).join(".");
238
+ }
239
+
240
+ function segmentOf(request: Request): Segment | "private" {
241
+ const base = { device: detectDevice(request.headers.get("user-agent") ?? "") };
242
+ const extra = options.segment?.(request);
243
+ if (extra === "private") return "private";
244
+ const out: Record<string, string> = { ...base };
245
+ for (const [k, v] of Object.entries(extra ?? {})) {
246
+ if (v === undefined || v === "") delete out[k];
247
+ else out[k] = v;
248
+ }
249
+ return out;
250
+ }
251
+
252
+ function cacheKey(url: URL, request: Request, version: string, segment: Segment): Request {
253
+ const key = new URL(url);
254
+ for (const name of [...key.searchParams.keys()]) {
255
+ if (TRACKING_PARAMS.has(name.toLowerCase())) key.searchParams.delete(name);
256
+ }
257
+ key.searchParams.delete(CSEG_PARAM);
258
+ const serverFn = isServerFnPath(key.pathname);
259
+ if (serverFn) {
260
+ const payload = key.searchParams.get("payload");
261
+ if (payload) key.searchParams.set("payload", canonicalizeServerFnPayload(payload));
262
+ }
263
+ if (version) key.searchParams.set("__v", version);
264
+ // Programmatic fetches (no navigation) get their own entries, as in v7.
265
+ if (!serverFn && request.headers.get("sec-fetch-dest") === "empty") {
266
+ key.searchParams.set("__fetch", "1");
267
+ }
268
+ key.searchParams.set("__seg", segmentKey(segment));
269
+ return new Request(key.toString(), { method: "GET" });
270
+ }
271
+
272
+ async function purge(request: Request, env: Env): Promise<Response> {
273
+ const token = options.purgeToken?.(env);
274
+ if (!token || request.headers.get("Authorization") !== `Bearer ${token}`) {
275
+ return new Response("Unauthorized", { status: 401 });
276
+ }
277
+ let body: { paths?: unknown; segments?: unknown };
278
+ try {
279
+ body = await request.json();
280
+ } catch {
281
+ return new Response("Invalid JSON body", { status: 400 });
282
+ }
283
+ const paths = Array.isArray(body.paths)
284
+ ? body.paths.filter((p): p is string => typeof p === "string" && p.startsWith("/"))
285
+ : [];
286
+ if (paths.length === 0) {
287
+ return new Response('Body must include "paths": ["/", "/page"]', { status: 400 });
288
+ }
289
+ // Each segment to drop: the devices by default; a site with more parts lists its own.
290
+ const segments: Segment[] = Array.isArray(body.segments)
291
+ ? body.segments.filter((s): s is Segment => !!s && typeof s === "object")
292
+ : DEVICES.map((device) => ({ device }));
293
+ const cache = edgeCache();
294
+ if (!cache) return Response.json({ purged: [], total: 0, note: "Cache API unavailable" });
295
+ const origin = new URL(request.url).origin;
296
+ // The current version's entries: older versions' keys are no longer looked up.
297
+ const version = await cacheVersion();
298
+ const purged: string[] = [];
299
+ for (const path of paths) {
300
+ for (const segment of segments) {
301
+ for (const programmatic of [false, true]) {
302
+ const url = new URL(path, origin);
303
+ const headers = programmatic ? { "sec-fetch-dest": "empty" } : undefined;
304
+ const key = cacheKey(url, new Request(url, { headers }), version, segment);
305
+ if (await cache.delete(key)) {
306
+ purged.push(`${path} (${segmentKey(segment)}${programmatic ? ", fetch" : ""})`);
307
+ }
308
+ }
309
+ }
310
+ }
311
+ return Response.json({ purged, total: purged.length });
312
+ }
313
+
314
+ // The release's redirects, read once per revision (a draft's are read each time).
315
+ let releaseRedirects: { revision: string; list: Promise<Redirect[]> } | undefined;
316
+
317
+ async function redirectsFor(pointer: string | null): Promise<Redirect[]> {
318
+ const read = async (client: ReturnType<CMS["forRelease"]>) => {
319
+ const [list] = await client.list<Redirect>("redirect");
320
+ return list ?? [];
321
+ };
322
+ if (pointer) return read(cms.forDraft(pointer));
323
+ const client = cms.forRelease();
324
+ const revision = await client.revision();
325
+ if (releaseRedirects?.revision !== revision) {
326
+ releaseRedirects = { revision, list: read(client) };
327
+ }
328
+ return releaseRedirects.list;
329
+ }
330
+
331
+ async function findRedirect(url: URL, pointer: string | null): Promise<Response | null> {
332
+ try {
333
+ const redirects = await redirectsFor(pointer);
334
+ if (!redirects.length) return null;
335
+ const match = matchRoute(url, { routes: [], redirects });
336
+ if (match.kind !== "redirect") return null;
337
+ return new Response(null, { status: match.status, headers: { Location: match.location } });
338
+ } catch {
339
+ return null; // a content error never blocks the page
340
+ }
341
+ }
342
+
343
+ interface Served {
344
+ response: Response;
345
+ profile?: CacheProfileName;
346
+ /** Answered by the site's `routes`: not this app's page, so no `preload` hints. */
347
+ routed?: true;
348
+ }
349
+
350
+ async function handle(
351
+ request: Request,
352
+ env: Env,
353
+ ctx: ExecutionContextLike,
354
+ draft: string | null,
355
+ ): Promise<Served> {
356
+ const url = new URL(request.url);
357
+ const method = request.method;
358
+ const readOnly = method === "GET" || method === "HEAD";
359
+
360
+ if (url.pathname === LIVENESS_PATH) {
361
+ return {
362
+ response: new Response("OK", {
363
+ headers: {
364
+ "Content-Type": "text/plain",
365
+ "Cache-Control": PRIVATE_NO_CACHE,
366
+ "X-Cache": "BYPASS",
367
+ },
368
+ }),
369
+ };
370
+ }
371
+ if (REMOVED_ADMIN_PATHS.some((p) => url.pathname.startsWith(p))) {
372
+ return {
373
+ response: new Response("Not Found", {
374
+ status: 404,
375
+ headers: { "Cache-Control": PRIVATE_NO_CACHE, "X-Cache": "BYPASS" },
376
+ }),
377
+ };
378
+ }
379
+ if (url.pathname === PURGE_PATH && method === "POST")
380
+ return { response: await purge(request, env) };
381
+
382
+ const asset =
383
+ FINGERPRINTED_ASSET_RE.test(url.pathname) ||
384
+ STATIC_PATHS.some((p) => url.pathname.startsWith(p));
385
+
386
+ if (
387
+ readOnly &&
388
+ !asset &&
389
+ !isServerFnPath(url.pathname) &&
390
+ !BYPASS_PATHS.some((p) => url.pathname.startsWith(p))
391
+ ) {
392
+ const redirect = await findRedirect(url, draft);
393
+ if (redirect) return { response: redirect };
394
+ }
395
+
396
+ if (options.routes) {
397
+ const routed = await options.routes(request, env, ctx);
398
+ if (routed) return { response: routed, routed: true };
399
+ }
400
+
401
+ if (asset) {
402
+ const origin = await serverEntry.fetch(request, env, ctx);
403
+ if (origin.status !== 200) return { response: origin };
404
+ if (isHtml(origin)) return { response: new Response("Not Found", { status: 404 }) };
405
+ const resp = mutable(origin);
406
+ resp.headers.set("Cache-Control", "public, max-age=31536000, immutable");
407
+ resp.headers.set("Vary", "Accept-Encoding");
408
+ return { response: resp };
409
+ }
410
+
411
+ const profileName = profileOf(url);
412
+ const profile = profiles[profileName];
413
+ const segment = segmentOf(request);
414
+ const cacheable =
415
+ method === "GET" &&
416
+ !dev &&
417
+ draft === null &&
418
+ segment !== "private" &&
419
+ !request.headers.has("authorization") &&
420
+ !BYPASS_PATHS.some((p) => url.pathname.startsWith(p));
421
+ const version = cacheable ? await cacheVersion() : "";
422
+ const token = cacheable ? segmentToken(segment as Segment, version) : null;
423
+ const origin = async (): Promise<Response> =>
424
+ withPageStatus(
425
+ await runInScope({ csegToken: token ?? undefined, draft: draft ?? undefined }, () =>
426
+ serverEntry.fetch(request, env, ctx),
427
+ ),
428
+ );
429
+
430
+ if (!cacheable) {
431
+ const resp = await origin();
432
+ if (draft !== null) {
433
+ const out = bypass(resp, "draft");
434
+ for (const [k, v] of Object.entries(draftResponseHeaders(draft))) {
435
+ if (k.toLowerCase() !== "vary") out.headers.set(k, v);
436
+ else appendVary(out.headers, v);
437
+ }
438
+ return { response: out, profile: profileName };
439
+ }
440
+ if (method !== "GET") return { response: bypass(resp, "method"), profile: profileName };
441
+ if (
442
+ segment === "private" ||
443
+ request.headers.has("authorization") ||
444
+ !profile.isPublic ||
445
+ isPrivateResponse(resp) ||
446
+ !hasOnlySafeCookies(resp, safeCookies)
447
+ ) {
448
+ return { response: bypass(resp, "private", PRIVATE_NO_CACHE), profile: profileName };
449
+ }
450
+ // `vite dev` (and the `/_build` paths): the browser revalidates every time.
451
+ return {
452
+ response: bypass(resp, dev ? "dev" : "path", dev ? "no-cache" : undefined),
453
+ profile: profileName,
454
+ };
455
+ }
456
+
457
+ const seg = segment as Segment;
458
+ const key = cacheKey(url, request, version, seg);
459
+ const cache = edgeCache();
460
+ const edge = profile.edge;
461
+ const cdnPublic =
462
+ token !== null &&
463
+ profile.isPublic &&
464
+ edge.fresh > 0 &&
465
+ isServerFnPath(url.pathname) &&
466
+ url.searchParams.get(CSEG_PARAM) === token;
467
+
468
+ const dress = (
469
+ resp: Response,
470
+ decision: CacheDecision,
471
+ extra?: Record<string, string>,
472
+ ): Response => {
473
+ const out = mutable(resp);
474
+ // Cloudflare's Cache API adds its own status to a matched response.
475
+ out.headers.delete("cf-cache-status");
476
+ out.headers.delete(STORED_AT);
477
+ out.headers.set("Cache-Control", cacheControl(profile));
478
+ out.headers.set("Vary", "Accept-Encoding");
479
+ // The CDN may keep only navigation data whose URL carries this segment's token.
480
+ out.headers.set(
481
+ "CDN-Cache-Control",
482
+ cdnPublic ? `public, max-age=${edge.fresh}` : "no-store",
483
+ );
484
+ out.headers.set("X-Cache", decision);
485
+ out.headers.set("X-Cache-Profile", profileName);
486
+ out.headers.set("X-Cache-Segment", segmentKey(seg));
487
+ if (version) out.headers.set("X-Cache-Version", version);
488
+ for (const [k, v] of Object.entries(extra ?? {})) out.headers.set(k, v);
489
+ return out;
490
+ };
491
+
492
+ const storable = (resp: Response) =>
493
+ resp.status === 200 &&
494
+ !isDegraded(resp) &&
495
+ !isPrivateResponse(resp) &&
496
+ hasOnlySafeCookies(resp, safeCookies);
497
+
498
+ const store = (resp: Response) => {
499
+ if (!cache) return;
500
+ const ttl = edge.fresh + Math.max(edge.swr, edge.sie);
501
+ const copy = resp.headers.has("set-cookie")
502
+ ? withoutSafeCookies(resp, safeCookies)
503
+ : resp.clone();
504
+ copy.headers.set("Cache-Control", `public, max-age=${ttl}`);
505
+ copy.headers.set(STORED_AT, String(Date.now()));
506
+ copy.headers.delete("CDN-Cache-Control");
507
+ ctx.waitUntil(cache.put(key, copy).catch(() => {}));
508
+ };
509
+
510
+ const ageOf = (resp: Response) => {
511
+ const storedAt = Number(resp.headers.get(STORED_AT) || "0");
512
+ return storedAt > 0 ? (Date.now() - storedAt) / 1000 : Number.POSITIVE_INFINITY;
513
+ };
514
+
515
+ let cached: Response | undefined;
516
+ if (cache && profile.isPublic && edge.fresh > 0) {
517
+ try {
518
+ cached = (await cache.match(key)) ?? undefined;
519
+ } catch {
520
+ // Cache API unavailable: a miss.
521
+ }
522
+ }
523
+
524
+ if (cached) {
525
+ const age = ageOf(cached);
526
+ if (age < edge.fresh) return { response: dress(cached, "HIT"), profile: profileName };
527
+ if (age < edge.fresh + edge.swr) {
528
+ ctx.waitUntil(
529
+ origin()
530
+ .then((fresh) => {
531
+ if (storable(fresh)) store(fresh);
532
+ })
533
+ .catch(() => {}),
534
+ );
535
+ return {
536
+ response: dress(cached, "STALE-HIT", { "X-Cache-Age": String(Math.round(age)) }),
537
+ profile: profileName,
538
+ };
539
+ }
540
+ }
541
+
542
+ const staleOnError = (reason: string, status?: number): Response | null => {
543
+ if (!cached || edge.sie <= 0) return null;
544
+ const age = ageOf(cached);
545
+ if (age >= edge.fresh + edge.sie) return null;
546
+ return dress(cached, "STALE-ERROR", {
547
+ "X-Cache-Age": String(Math.round(age)),
548
+ "X-Cache-Reason": reason,
549
+ ...(status ? { "X-Cache-Origin-Status": String(status) } : {}),
550
+ });
551
+ };
552
+
553
+ let resp: Response;
554
+ try {
555
+ resp = await origin();
556
+ } catch (error) {
557
+ const stale = staleOnError("origin-error");
558
+ if (stale) return { response: stale, profile: profileName };
559
+ throw error;
560
+ }
561
+
562
+ if (resp.status !== 200) {
563
+ if (resp.status >= 500 || resp.status === 429) {
564
+ const stale = staleOnError("origin-status", resp.status);
565
+ if (stale) return { response: stale, profile: profileName };
566
+ }
567
+ return { response: bypass(resp, `status:${resp.status}`), profile: profileName };
568
+ }
569
+ if (isDegraded(resp)) {
570
+ const stale = staleOnError("degraded");
571
+ if (stale) return { response: stale, profile: profileName };
572
+ return { response: bypass(resp, "degraded", PRIVATE_NO_CACHE), profile: profileName };
573
+ }
574
+ if (isPrivateResponse(resp) || !hasOnlySafeCookies(resp, safeCookies)) {
575
+ return { response: bypass(resp, "private-response", PRIVATE_NO_CACHE), profile: profileName };
576
+ }
577
+ if (!profile.isPublic || edge.fresh === 0) {
578
+ return {
579
+ response: bypass(resp, `profile:${profileName}`, PRIVATE_NO_CACHE),
580
+ profile: profileName,
581
+ };
582
+ }
583
+ store(resp);
584
+ return { response: dress(resp, "MISS"), profile: profileName };
585
+ }
586
+
587
+ return {
588
+ async fetch(incoming, env, ctx) {
589
+ const started = Date.now();
590
+ let decision: { pointer: string | null; setCookie: string | null } = {
591
+ pointer: null,
592
+ setCookie: null,
593
+ };
594
+ try {
595
+ decision = await decideDraft(cms, incoming, policy);
596
+ } catch {
597
+ // The settings didn't load: the request gets the release.
598
+ }
599
+ // The page reads the draft from this header; a copy from outside never counts.
600
+ let request = incoming;
601
+ if (incoming.headers.has(DRAFT_HEADER) || decision.pointer !== null) {
602
+ const headers = new Headers(incoming.headers);
603
+ headers.delete(DRAFT_HEADER);
604
+ if (decision.pointer !== null) headers.set(DRAFT_HEADER, decision.pointer);
605
+ request = new Request(incoming, { headers });
606
+ }
607
+
608
+ const served = await handle(request, env, ctx, decision.pointer);
609
+ let response = served.response;
610
+ if (response.status === 101) return response; // a WebSocket upgrade passes through untouched
611
+ response = mutable(response);
612
+
613
+ // CDN-Cache-Control is decided here, at the single exit: a response the
614
+ // worker didn't cache, or that no branch gave one, tells the CDN no-store.
615
+ if (
616
+ response.headers.get("X-Cache") === "BYPASS" ||
617
+ !response.headers.has("CDN-Cache-Control")
618
+ ) {
619
+ response.headers.set("CDN-Cache-Control", "no-store");
620
+ }
621
+ if (decision.setCookie) response.headers.append("Set-Cookie", decision.setCookie);
622
+ dedupeSetCookies(response);
623
+ if (isHtml(response)) {
624
+ for (const [k, v] of Object.entries(securityHeaders)) {
625
+ if (!response.headers.has(k)) response.headers.set(k, v);
626
+ }
627
+ if (!served.routed) {
628
+ for (const link of preloadLinks) response.headers.append("Link", link);
629
+ }
630
+ }
631
+
632
+ if (served.profile && options.onCache) {
633
+ const xCache = response.headers.get("X-Cache") ?? "BYPASS";
634
+ try {
635
+ options.onCache({
636
+ profile: served.profile,
637
+ decision: (DECISIONS.has(xCache) ? xCache : "BYPASS") as CacheDecision,
638
+ ms: Date.now() - started,
639
+ status: response.status,
640
+ });
641
+ } catch {
642
+ // A metrics hook never breaks a response.
643
+ }
644
+ }
645
+ return response;
646
+ },
647
+ };
648
+ }