@decocms/tanstack 8.1.0-next.0 → 8.5.1

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