@decocms/tanstack 8.5.2 → 8.7.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 (86) hide show
  1. package/README.md +35 -8
  2. package/dist/assignments.d.ts +31 -0
  3. package/dist/assignments.d.ts.map +1 -0
  4. package/dist/assignments.js +61 -0
  5. package/dist/assignments.js.map +1 -0
  6. package/dist/draft.d.ts +28 -9
  7. package/dist/draft.d.ts.map +1 -1
  8. package/dist/draft.js +30 -11
  9. package/dist/draft.js.map +1 -1
  10. package/dist/index.d.ts +3 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +3 -1
  13. package/dist/index.js.map +1 -1
  14. package/dist/react/DecoDocument.d.ts.map +1 -1
  15. package/dist/react/DecoDocument.js +4 -4
  16. package/dist/react/DecoDocument.js.map +1 -1
  17. package/dist/react/pageValues.d.ts +3 -0
  18. package/dist/react/pageValues.d.ts.map +1 -1
  19. package/dist/react/pageValues.js +13 -4
  20. package/dist/react/pageValues.js.map +1 -1
  21. package/dist/scope/server.d.ts +6 -1
  22. package/dist/scope/server.d.ts.map +1 -1
  23. package/dist/scope/server.js.map +1 -1
  24. package/dist/server/index.d.ts +37 -8
  25. package/dist/server/index.d.ts.map +1 -1
  26. package/dist/server/index.js +45 -9
  27. package/dist/server/index.js.map +1 -1
  28. package/dist/shared.d.ts +5 -5
  29. package/dist/shared.js +5 -5
  30. package/dist/start/index.d.ts +3 -3
  31. package/dist/start/index.js +3 -3
  32. package/dist/visitor.d.ts +14 -0
  33. package/dist/visitor.d.ts.map +1 -0
  34. package/dist/visitor.js +14 -0
  35. package/dist/visitor.js.map +1 -0
  36. package/dist/worker/assignments.d.ts +44 -0
  37. package/dist/worker/assignments.d.ts.map +1 -0
  38. package/dist/worker/assignments.js +114 -0
  39. package/dist/worker/assignments.js.map +1 -0
  40. package/dist/worker/cache.d.ts +35 -0
  41. package/dist/worker/cache.d.ts.map +1 -0
  42. package/dist/worker/cache.js +45 -0
  43. package/dist/worker/cache.js.map +1 -0
  44. package/dist/worker/cookies.d.ts +1 -5
  45. package/dist/worker/cookies.d.ts.map +1 -1
  46. package/dist/worker/cookies.js +1 -26
  47. package/dist/worker/cookies.js.map +1 -1
  48. package/dist/worker/drafts.d.ts +54 -46
  49. package/dist/worker/drafts.d.ts.map +1 -1
  50. package/dist/worker/drafts.js +88 -88
  51. package/dist/worker/drafts.js.map +1 -1
  52. package/dist/worker/index.d.ts +82 -51
  53. package/dist/worker/index.d.ts.map +1 -1
  54. package/dist/worker/index.js +197 -372
  55. package/dist/worker/index.js.map +1 -1
  56. package/dist/worker/segment.d.ts +7 -6
  57. package/dist/worker/segment.d.ts.map +1 -1
  58. package/dist/worker/segment.js +6 -5
  59. package/dist/worker/segment.js.map +1 -1
  60. package/dist/worker/serverFn.d.ts +12 -0
  61. package/dist/worker/serverFn.d.ts.map +1 -0
  62. package/dist/worker/serverFn.js +44 -0
  63. package/dist/worker/serverFn.js.map +1 -0
  64. package/package.json +3 -3
  65. package/src/assignments.ts +77 -0
  66. package/src/draft.ts +34 -11
  67. package/src/index.ts +3 -1
  68. package/src/react/DecoDocument.tsx +20 -4
  69. package/src/react/pageValues.ts +12 -4
  70. package/src/scope/server.ts +6 -1
  71. package/src/server/index.ts +57 -12
  72. package/src/shared.ts +5 -5
  73. package/src/start/index.ts +3 -3
  74. package/src/visitor.ts +14 -0
  75. package/src/worker/assignments.ts +146 -0
  76. package/src/worker/cache.ts +61 -0
  77. package/src/worker/cookies.ts +1 -27
  78. package/src/worker/drafts.ts +113 -98
  79. package/src/worker/index.ts +276 -436
  80. package/src/worker/segment.ts +7 -7
  81. package/src/worker/serverFn.ts +36 -0
  82. package/dist/worker/cacheProfiles.d.ts +0 -43
  83. package/dist/worker/cacheProfiles.d.ts.map +0 -1
  84. package/dist/worker/cacheProfiles.js +0 -162
  85. package/dist/worker/cacheProfiles.js.map +0 -1
  86. package/src/worker/cacheProfiles.ts +0 -180
@@ -5,51 +5,72 @@
5
5
  *
6
6
  * - `/deco/_liveness` answers `OK`; v7's admin paths (`/deco/*`, `/live/*`,
7
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.
8
+ * - Versions: the host allowlist (`./drafts.ts`) for a Studio link's version
9
+ * (a draft, or a published release by its commit SHA, with the preview's
10
+ * moment and switched tests and campaigns), the draft cookie, the
11
+ * `x-deco-version` request header the page reads. A preview (any request
12
+ * with `?__draft=`, `off` included, or the draft cookie) never goes through
13
+ * `pageCache` and answers `Cache-Control: max-age=0, no-cache,
14
+ * must-revalidate`, `Vary: Cookie` and `noindex`. A link's cookie is set
15
+ * only with a response below 500; a link to a draft that can't be read
16
+ * anymore renders the release, expires the cookie and tells the page
17
+ * (`draftUnavailable`), never a 500.
11
18
  * - 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.
19
+ * - No page cache: caching is the site's (`pageCache`, the README's
20
+ * worker-entry recipe), with the helpers it needs exported here
21
+ * (`assignmentsKey`, `cacheVersion`, `isCacheable`, …).
22
+ * The worker calls `pageCache` only for a request `isCacheable` accepts,
23
+ * never for a preview (any draft signal), and adds the visitor's cookie after it, so a stored
24
+ * copy never carries one. A page request with `Authorization` is never
25
+ * handed to it and answers `private, no-cache, no-store`. A response with no
26
+ * `CDN-Cache-Control` tells the CDN `no-store`, at one exit.
17
27
  * - Security headers and `frame-ancestors` for Studio; immutable fingerprinted
18
28
  * assets; one `Set-Cookie` per cookie; `x-page-status`.
29
+ * - The visitor: on a page or server-function request, `readVisitor` from
30
+ * `@decocms/blocks/experiments` (the `deco_segment` cookie, or a new
31
+ * visitor), handed to the app on `x-deco-visitor`; the cookie is sent on a
32
+ * first visit only, never from a preview.
33
+ * - What the request's content gives it, decided once per request: each test
34
+ * and campaign on or off (`readAssignments`: `cms.client({ visitor,
35
+ * version, date, experiments, campaigns })` with the visitor and the Studio
36
+ * link's version, moment and switched tests and campaigns), handed to the
37
+ * site's `pageCache` (`page.assignments`, for its key) and to the app on
38
+ * `x-deco-assignments` (`contentClient` builds
39
+ * `cms.client({ version, experiments, campaigns })` from it, deciding
40
+ * nothing again).
19
41
  * - `http.server.request.duration` for every request, to the CMS's telemetry
20
42
  * (`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.
43
+ * method, the status class, the cache decision (the `X-Cache` the site's
44
+ * `pageCache` answered with) and the device; nothing when the CMS has no
45
+ * telemetry.
23
46
  */
24
47
  import { type CMS, matchRoute, type Redirect, type Route } from "@decocms/blocks";
48
+ import { readVisitor, serializeVisitor, type Visitor } from "@decocms/blocks/experiments";
25
49
  import { recordServerRequest } from "@decocms/blocks/metrics";
26
50
  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";
51
+ import { ASSIGNMENTS_HEADER, serializeAssignments } from "../assignments.ts";
52
+ import { draftResponseHeaders, RELEASE_CHECK_HEADER, VERSION_HEADER } from "../draft.ts";
53
+ import { PAGE_STATUS_HEADER } from "../shared.ts";
54
+ import { VISITOR_HEADER } from "../visitor.ts";
55
+ import { type RequestAssignments, readAssignments } from "./assignments.ts";
56
+ import { isCacheable } from "./cache.ts";
57
+ import { dedupeSetCookies } from "./cookies.ts";
58
+ import { type DraftDecision, decideDraft, hasDraftSignal } from "./drafts.ts";
41
59
  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";
60
+ import { type Device, detectDevice } from "./segment.ts";
61
+ import { isServerFnPath } from "./serverFn.ts";
62
+
63
+ export { CSEG_PARAM, DEGRADED_HEADER } from "../shared.ts";
64
+ export {
65
+ assignmentsKey,
66
+ liveAssignmentKeys,
67
+ type RequestAssignments,
68
+ readAssignments,
69
+ } from "./assignments.ts";
70
+ export { cacheVersion, isCacheable, requestVersion } from "./cache.ts";
51
71
  export type { CspOptions } from "./security.ts";
52
- export type { Device, Segment } from "./segment.ts";
72
+ export { type Device, detectDevice, type Segment, segmentKey, segmentToken } from "./segment.ts";
73
+ export { isServerFnPath, serverFnPagePath } from "./serverFn.ts";
53
74
 
54
75
  /** The part of Cloudflare's `ExecutionContext` the worker uses. */
55
76
  export interface ExecutionContextLike {
@@ -65,58 +86,62 @@ export interface ServerEntry {
65
86
  fetch(request: Request, env?: any, ctx?: any): Response | Promise<Response>;
66
87
  }
67
88
 
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;
89
+ /**
90
+ * A page or server-function request the site's `pageCache` may answer from
91
+ * its own cache: always one `isCacheable` accepts (a GET of the current
92
+ * release, never a preview).
93
+ */
94
+ export interface PageRequest<Env = unknown> {
95
+ /** The request as the app gets it: the visitor and the assignments on their headers. */
96
+ request: Request;
97
+ url: URL;
98
+ /** The visitor the worker read (`readVisitor`). */
99
+ visitor: Visitor;
100
+ /**
101
+ * Each test and campaign on or off for this request, as the worker decided
102
+ * them and the page renders them: key the cache on `assignmentsKey(page.assignments)`.
103
+ */
104
+ assignments: RequestAssignments;
105
+ /** The request's device class, from its user agent. */
106
+ device: Device;
107
+ env: Env;
108
+ ctx: ExecutionContextLike;
109
+ /**
110
+ * Renders the page: the app's response, with `x-page-status` applied and
111
+ * without the visitor's cookie (the worker adds it to whatever `pageCache`
112
+ * answers). `csegToken` is the `__cseg` token `DecoDocument` publishes and
113
+ * `decoServerFnFetch` sends back on the page's navigation data.
114
+ */
115
+ render(scope?: { csegToken?: string }): Promise<Response>;
79
116
  }
80
117
 
118
+ /**
119
+ * The site's page cache: answers a page from its own cache, or calls
120
+ * `page.render()`. Set `X-Cache` (`HIT`, `STALE-HIT`, `STALE-ERROR`, `MISS`)
121
+ * on the answer and the request's metric counts it.
122
+ */
123
+ export type PageCache<Env = unknown> = (page: PageRequest<Env>) => Promise<Response>;
124
+
81
125
  export interface DecoWorkerOptions<Env = unknown> {
82
126
  serverEntry: ServerEntry;
83
- /** The site's CMS: drafts, the content revision in the cache key, CMS redirects. */
127
+ /** The site's CMS: drafts, the CMS redirects, the page templates of the request metric. */
84
128
  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. */
129
+ /** Local development (`import.meta.env.DEV`): `pageCache` is never called, loopback may frame the site. */
90
130
  dev?: boolean;
91
131
  /** The site's Content-Security-Policy. Studio's `frame-ancestors` is always added. */
92
132
  csp?: CspOptions;
93
133
  /**
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).
134
+ * The site's own page cache (the example worker entry the README links), called for
135
+ * every page and server-function request `isCacheable` accepts. Without
136
+ * it nothing is cached: every request renders.
98
137
  */
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;
138
+ pageCache?: PageCache<Env>;
106
139
  /**
107
140
  * `Link: rel=preload` hints on every HTML response the app renders. A
108
141
  * `routes` response carries none: it is another origin's page (a proxied
109
142
  * checkout, an A/B test's other site), and these are this app's assets.
110
143
  */
111
144
  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
145
  /**
121
146
  * The escape hatch, after the CMS redirects and before anything else: answer
122
147
  * a request yourself (a commerce proxy, a sitemap, an A/B route) or return
@@ -129,8 +154,6 @@ export interface DecoWorkerOptions<Env = unknown> {
129
154
  env: Env,
130
155
  ctx: ExecutionContextLike,
131
156
  ) => 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
157
  }
135
158
 
136
159
  export interface DecoWorker<Env> {
@@ -140,37 +163,12 @@ export interface DecoWorker<Env> {
140
163
  const LIVENESS_PATH = "/deco/_liveness";
141
164
  /** v7's admin protocol paths: v8 sites serve none of them. */
142
165
  const REMOVED_ADMIN_PATHS = ["/deco/", "/live/", "/.decofile"];
143
- const PURGE_PATH = "/_cache/purge";
144
166
  const BYPASS_PATHS = ["/_build"];
145
167
  const STATIC_PATHS = ["/fonts/"];
146
168
  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"]);
169
+ const PRIVATE_NO_CACHE = "private, no-cache, no-store, must-revalidate";
172
170
  /** Paths the worker (or TanStack Start) serves under a fixed template, for `http.route`. */
173
- const FIXED_ROUTES = [LIVENESS_PATH, PURGE_PATH];
171
+ const FIXED_ROUTES = [LIVENESS_PATH];
174
172
  const PREFIX_ROUTES = ["/_serverFn/", "/_server/", "/_build/", "/assets/", "/fonts/"];
175
173
 
176
174
  /** The template of a path the worker knows without the content, or `null`. */
@@ -188,18 +186,19 @@ function fixedRoute(pathname: string): string | null {
188
186
  const REDIRECT_ROUTE = "redirect";
189
187
 
190
188
  /**
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.
189
+ * The cache label of `http.server.request.duration`: `DRAFT` for a preview
190
+ * (any draft signal),
191
+ * otherwise what the site's `pageCache` said in `X-Cache`. A response that
192
+ * never went through it (a redirect, the site's `routes`, an asset, a page
193
+ * without a `pageCache`) is `BYPASS` whatever `X-Cache` an upstream put on it.
195
194
  */
196
195
  function cacheLabel(
197
196
  response: Response,
198
197
  draft: boolean,
199
- served: { profile?: unknown } | undefined,
198
+ served: { cached?: true } | undefined,
200
199
  ): "HIT" | "MISS" | "BYPASS" | "DRAFT" {
201
200
  if (draft) return "DRAFT";
202
- if (!served?.profile) return "BYPASS";
201
+ if (!served?.cached) return "BYPASS";
203
202
  const xCache = response.headers.get("X-Cache");
204
203
  if (xCache === "HIT" || xCache === "STALE-HIT" || xCache === "STALE-ERROR") return "HIT";
205
204
  return xCache === "MISS" ? "MISS" : "BYPASS";
@@ -207,12 +206,6 @@ function cacheLabel(
207
206
 
208
207
  const isHtml = (r: Response) => (r.headers.get("content-type") ?? "").includes("text/html");
209
208
 
210
- function edgeCache(): Cache | null {
211
- return typeof caches !== "undefined"
212
- ? ((caches as unknown as { default?: Cache }).default ?? null)
213
- : null;
214
- }
215
-
216
209
  /** The origin's response with the page's own status (`x-page-status`) applied. */
217
210
  function withPageStatus(response: Response): Response {
218
211
  const status = Number(response.headers.get(PAGE_STATUS_HEADER));
@@ -222,14 +215,6 @@ function withPageStatus(response: Response): Response {
222
215
  return new Response(response.body, { status, headers });
223
216
  }
224
217
 
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
218
  /** Adds `value` to the response's `Vary`, keeping what the origin listed. */
234
219
  function appendVary(headers: Headers, value: string): void {
235
220
  const current = headers.get("vary");
@@ -243,124 +228,28 @@ function mutable(response: Response): Response {
243
228
  return new Response(response.body, response);
244
229
  }
245
230
 
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
231
  export function createDecoWorker<Env = unknown>(options: DecoWorkerOptions<Env>): DecoWorker<Env> {
258
232
  const { cms, serverEntry } = options;
259
233
  const dev = options.dev === true;
260
- const profiles = resolveProfiles(options.cacheProfiles);
261
- const safeCookies = new Set(options.safeCookies ?? DEFAULT_SAFE_COOKIES);
262
234
  const securityHeaders = htmlSecurityHeaders(options.csp, dev);
263
- const policy: PreviewPolicy = { site: options.site, previewHosts: options.previewHosts };
264
235
  const preloadLinks = [
265
236
  ...(options.preload?.styles ?? []).map((href) => `<${href}>; rel=preload; as=style`),
266
237
  ...(options.preload?.fonts ?? []).map((href) => `<${href}>; rel=preload; as=font; crossorigin`),
267
238
  ];
268
239
 
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
240
  // The release's redirects, read once per revision (a draft's are read each time).
355
241
  let releaseRedirects: { revision: string; list: Promise<Redirect[]> } | undefined;
356
242
 
357
- async function redirectsFor(pointer: string | null): Promise<Redirect[]> {
243
+ async function redirectsFor(
244
+ pointer: string | null,
245
+ releaseCheck: string | undefined,
246
+ ): Promise<Redirect[]> {
358
247
  const read = async (client: ReturnType<CMS["forRelease"]>) => {
359
248
  const [list] = await client.list<Redirect>("redirect");
360
249
  return list ?? [];
361
250
  };
362
- if (pointer) return read(cms.forDraft(pointer));
363
- const client = cms.forRelease();
251
+ if (pointer) return read(cms.client({ version: pointer, releaseCheck }));
252
+ const client = cms.client();
364
253
  const revision = await client.revision();
365
254
  if (releaseRedirects?.revision !== revision) {
366
255
  releaseRedirects = { revision, list: read(client) };
@@ -433,9 +322,13 @@ export function createDecoWorker<Env = unknown>(options: DecoWorkerOptions<Env>)
433
322
  }
434
323
  }
435
324
 
436
- async function findRedirect(url: URL, pointer: string | null): Promise<Response | null> {
325
+ async function findRedirect(
326
+ url: URL,
327
+ pointer: string | null,
328
+ releaseCheck: string | undefined,
329
+ ): Promise<Response | null> {
437
330
  try {
438
- const redirects = await redirectsFor(pointer);
331
+ const redirects = await redirectsFor(pointer, releaseCheck);
439
332
  if (!redirects.length) return null;
440
333
  const match = matchRoute(url, { routes: [], redirects });
441
334
  if (match.kind !== "redirect") return null;
@@ -447,19 +340,65 @@ export function createDecoWorker<Env = unknown>(options: DecoWorkerOptions<Env>)
447
340
 
448
341
  interface Served {
449
342
  response: Response;
450
- profile?: CacheProfileName;
343
+ /** Answered by the site's `pageCache`: its `X-Cache` labels the metric. */
344
+ cached?: true;
345
+ /** A fingerprinted or static asset: its own `Cache-Control`, a preview's or not. */
346
+ asset?: true;
451
347
  /** Answered by the site's `routes`: not this app's page, so no `preload` hints. */
452
348
  routed?: true;
453
349
  /** A CMS redirect. */
454
350
  redirect?: true;
351
+ /** The visitor's `deco_segment` cookie, on a first visit to the live site. */
352
+ visitorCookie?: string;
353
+ }
354
+
355
+ /**
356
+ * What a page or server-function request reads, decided once: the visitor
357
+ * (`readVisitor`: the `deco_segment` cookie, or a new visitor) on
358
+ * `x-deco-visitor`, each test and campaign on or off for it and the
359
+ * request's version (`readAssignments`) on `x-deco-assignments`, and the
360
+ * cookie to send when the visitor had no id. A preview (a draft, or an old
361
+ * release) sends no cookie: Studio is not a visitor.
362
+ */
363
+ async function withDecisions(
364
+ request: Request,
365
+ draft: DraftDecision,
366
+ ): Promise<{
367
+ request: Request;
368
+ visitor: Visitor | null;
369
+ assignments?: RequestAssignments;
370
+ visitorCookie?: string;
371
+ }> {
372
+ // TanStack Start's own build files render no content.
373
+ if (BYPASS_PATHS.some((p) => new URL(request.url).pathname.startsWith(p))) {
374
+ return { request, visitor: null };
375
+ }
376
+ const { visitor, cookie } = readVisitor(request);
377
+ // A draft's read shares the request's release check (`decideDraft`), never one of its own.
378
+ const releaseCheck = draft.version ? draft.releaseCheck : undefined;
379
+ const assignments = await readAssignments(cms, {
380
+ visitor,
381
+ ...draft.version,
382
+ ...(releaseCheck ? { releaseCheck } : {}),
383
+ });
384
+ const headers = new Headers(request.headers);
385
+ headers.set(VISITOR_HEADER, serializeVisitor(visitor));
386
+ headers.set(ASSIGNMENTS_HEADER, serializeAssignments(assignments));
387
+ const forwarded = new Request(request, { headers });
388
+ if (cookie === null || draft.version !== null) {
389
+ return { request: forwarded, visitor, assignments };
390
+ }
391
+ return { request: forwarded, visitor, assignments, visitorCookie: cookie };
455
392
  }
456
393
 
457
394
  async function handle(
458
395
  request: Request,
459
396
  env: Env,
460
397
  ctx: ExecutionContextLike,
461
- draft: string | null,
398
+ decision: DraftDecision,
399
+ preview: boolean,
462
400
  ): Promise<Served> {
401
+ const draft = decision.version?.version ?? null;
463
402
  const url = new URL(request.url);
464
403
  const method = request.method;
465
404
  const readOnly = method === "GET" || method === "HEAD";
@@ -470,7 +409,6 @@ export function createDecoWorker<Env = unknown>(options: DecoWorkerOptions<Env>)
470
409
  headers: {
471
410
  "Content-Type": "text/plain",
472
411
  "Cache-Control": PRIVATE_NO_CACHE,
473
- "X-Cache": "BYPASS",
474
412
  },
475
413
  }),
476
414
  };
@@ -479,13 +417,10 @@ export function createDecoWorker<Env = unknown>(options: DecoWorkerOptions<Env>)
479
417
  return {
480
418
  response: new Response("Not Found", {
481
419
  status: 404,
482
- headers: { "Cache-Control": PRIVATE_NO_CACHE, "X-Cache": "BYPASS" },
420
+ headers: { "Cache-Control": PRIVATE_NO_CACHE },
483
421
  }),
484
422
  };
485
423
  }
486
- if (url.pathname === PURGE_PATH && method === "POST")
487
- return { response: await purge(request, env) };
488
-
489
424
  const asset =
490
425
  FINGERPRINTED_ASSET_RE.test(url.pathname) ||
491
426
  STATIC_PATHS.some((p) => url.pathname.startsWith(p));
@@ -496,7 +431,7 @@ export function createDecoWorker<Env = unknown>(options: DecoWorkerOptions<Env>)
496
431
  !isServerFnPath(url.pathname) &&
497
432
  !BYPASS_PATHS.some((p) => url.pathname.startsWith(p))
498
433
  ) {
499
- const redirect = await findRedirect(url, draft);
434
+ const redirect = await findRedirect(url, draft, decision.releaseCheck);
500
435
  if (redirect) return { response: redirect, redirect: true };
501
436
  }
502
437
 
@@ -507,230 +442,149 @@ export function createDecoWorker<Env = unknown>(options: DecoWorkerOptions<Env>)
507
442
 
508
443
  if (asset) {
509
444
  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 }) };
445
+ if (origin.status !== 200) return { response: origin, asset: true };
446
+ if (isHtml(origin)) {
447
+ return { response: new Response("Not Found", { status: 404 }), asset: true };
448
+ }
512
449
  const resp = mutable(origin);
513
450
  resp.headers.set("Cache-Control", "public, max-age=31536000, immutable");
514
451
  resp.headers.set("Vary", "Accept-Encoding");
515
- return { response: resp };
452
+ return { response: resp, asset: true };
516
453
  }
517
454
 
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> =>
455
+ const visited = await withDecisions(request, decision);
456
+ const served = await page(visited.request, env, ctx, {
457
+ draft,
458
+ preview,
459
+ unavailable: decision.unavailable === true,
460
+ url,
461
+ visitor: visited.visitor,
462
+ assignments: visited.assignments,
463
+ });
464
+ return visited.visitorCookie === undefined
465
+ ? served
466
+ : { ...served, visitorCookie: visited.visitorCookie };
467
+ }
468
+
469
+ /**
470
+ * A page or server-function request: the site's `pageCache` when it may
471
+ * cache it, else the app. A preview (any draft signal) always renders: its
472
+ * headers are set at the exit (`serve`).
473
+ */
474
+ async function page(
475
+ request: Request,
476
+ env: Env,
477
+ ctx: ExecutionContextLike,
478
+ inputs: {
479
+ draft: string | null;
480
+ preview: boolean;
481
+ unavailable: boolean;
482
+ url: URL;
483
+ visitor: Visitor | null;
484
+ assignments: RequestAssignments | undefined;
485
+ },
486
+ ): Promise<Served> {
487
+ const { draft, preview, unavailable, url, visitor, assignments } = inputs;
488
+ const render = async (scope?: { csegToken?: string }): Promise<Response> =>
531
489
  withPageStatus(
532
- await runInScope({ csegToken: token ?? undefined, draft: draft ?? undefined }, () =>
533
- serverEntry.fetch(request, env, ctx),
490
+ await runInScope(
491
+ {
492
+ csegToken: scope?.csegToken,
493
+ draft: draft ?? undefined,
494
+ ...(unavailable ? { draftUnavailable: true } : {}),
495
+ },
496
+ () => serverEntry.fetch(request, env, ctx),
534
497
  ),
535
498
  );
536
499
 
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
- }
500
+ if (draft !== null || preview) return { response: await render() };
501
+ // A signed request's page is that caller's: no shared cache may keep it,
502
+ // whatever the app said (RFC 9111 lets one store a `public` answer to it).
503
+ if (request.headers.has("authorization")) {
504
+ const out = mutable(await render());
505
+ out.headers.set("Cache-Control", PRIVATE_NO_CACHE);
506
+ return { response: out };
647
507
  }
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
- };
508
+ if (
509
+ !options.pageCache ||
510
+ visitor === null ||
511
+ assignments === undefined ||
512
+ !isCacheable(request, { version: draft, dev })
513
+ ) {
514
+ return { response: await render() };
689
515
  }
690
- store(resp);
691
- return { response: dress(resp, "MISS"), profile: profileName };
516
+ const response = await options.pageCache({
517
+ request,
518
+ url,
519
+ visitor,
520
+ assignments,
521
+ device: detectDevice(request.headers.get("user-agent") ?? ""),
522
+ env,
523
+ ctx,
524
+ render,
525
+ });
526
+ return { response, cached: true };
692
527
  }
693
528
 
694
529
  async function serve(
695
530
  incoming: Request,
696
531
  env: Env,
697
532
  ctx: ExecutionContextLike,
698
- started: number,
699
533
  ): Promise<{ response: Response; served: Served; draft: boolean }> {
700
- let decision: { pointer: string | null; setCookie: string | null } = {
701
- pointer: null,
702
- setCookie: null,
703
- };
534
+ // Any draft signal makes the request a preview, whatever the decision.
535
+ const preview = hasDraftSignal(incoming);
536
+ let decision: DraftDecision = { version: null, setCookie: null };
704
537
  try {
705
- decision = await decideDraft(cms, incoming, policy);
538
+ decision = await decideDraft(cms, incoming);
706
539
  } catch {
707
540
  // The settings didn't load: the request gets the release.
708
541
  }
709
- // The page reads the draft from this header; a copy from outside never counts.
542
+ // The page reads the version, the visitor and the assignments from these
543
+ // headers; a copy from outside never counts.
710
544
  let request = incoming;
711
- if (incoming.headers.has(DRAFT_HEADER) || decision.pointer !== null) {
545
+ const own = [VERSION_HEADER, VISITOR_HEADER, ASSIGNMENTS_HEADER, RELEASE_CHECK_HEADER];
546
+ if (own.some((name) => incoming.headers.has(name)) || decision.version !== null) {
712
547
  const headers = new Headers(incoming.headers);
713
- headers.delete(DRAFT_HEADER);
714
- if (decision.pointer !== null) headers.set(DRAFT_HEADER, decision.pointer);
548
+ for (const name of own) headers.delete(name);
549
+ if (decision.version !== null) headers.set(VERSION_HEADER, decision.version.version);
550
+ // The page's draft reads wait for the request's release check, never one of their own.
551
+ if (decision.version !== null && decision.releaseCheck !== undefined) {
552
+ headers.set(RELEASE_CHECK_HEADER, decision.releaseCheck);
553
+ }
715
554
  request = new Request(incoming, { headers });
716
555
  }
717
556
 
718
- const served = await handle(request, env, ctx, decision.pointer);
719
- const draft = decision.pointer !== null;
557
+ const served = await handle(request, env, ctx, decision, preview);
558
+ const draft = decision.version !== null || preview;
720
559
  let response = served.response;
721
560
  // A WebSocket upgrade passes through untouched.
722
561
  if (response.status === 101) return { response, served, draft };
723
562
  response = mutable(response);
724
563
 
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
- ) {
564
+ // CDN-Cache-Control is decided here, at the single exit: a response that
565
+ // names none (the app's, the site's cache's or a route's) tells the CDN
566
+ // no-store, so only what the site chose to share is kept in front of it.
567
+ if (!response.headers.has("CDN-Cache-Control")) {
731
568
  response.headers.set("CDN-Cache-Control", "no-store");
732
569
  }
733
- if (decision.setCookie) response.headers.append("Set-Cookie", decision.setCookie);
570
+ // A preview's response is never answered from a cache: the exact header,
571
+ // whatever the app or a route said. A fingerprinted asset stays immutable.
572
+ if (preview && !served.asset) {
573
+ for (const [k, v] of Object.entries(draftResponseHeaders(true))) {
574
+ if (k.toLowerCase() !== "vary") response.headers.set(k, v);
575
+ else appendVary(response.headers, v);
576
+ }
577
+ // Nor kept by the CDN, whatever a route said: with the draft in a cookie
578
+ // a preview shares its URL with the published page.
579
+ response.headers.set("CDN-Cache-Control", "no-store");
580
+ }
581
+ // A link's cookie only with a page that rendered: a failed render never
582
+ // pins the preview to it. The cookie that ends a preview always goes.
583
+ const ending = decision.version === null;
584
+ if (decision.setCookie && (ending || response.status < 500)) {
585
+ response.headers.append("Set-Cookie", decision.setCookie);
586
+ }
587
+ if (served.visitorCookie) response.headers.append("Set-Cookie", served.visitorCookie);
734
588
  dedupeSetCookies(response);
735
589
  if (isHtml(response)) {
736
590
  for (const [k, v] of Object.entries(securityHeaders)) {
@@ -741,29 +595,15 @@ export function createDecoWorker<Env = unknown>(options: DecoWorkerOptions<Env>)
741
595
  }
742
596
  }
743
597
 
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
598
  return { response, served, draft };
758
599
  }
759
600
 
760
601
  return {
761
602
  async fetch(incoming, env, ctx) {
762
- const started = Date.now();
763
603
  const clock = performance.now();
764
604
  let result: Awaited<ReturnType<typeof serve>>;
765
605
  try {
766
- result = await serve(incoming, env, ctx, started);
606
+ result = await serve(incoming, env, ctx);
767
607
  } catch (error) {
768
608
  // The runtime answers a thrown request with a 500.
769
609
  measure(incoming, ctx, (performance.now() - clock) / 1000, 500, "BYPASS", undefined);