@decocms/tanstack 8.5.1 → 8.6.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 (76) 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 +9 -6
  7. package/dist/draft.d.ts.map +1 -1
  8. package/dist/draft.js +10 -7
  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/scope/server.d.ts +1 -1
  15. package/dist/scope/server.d.ts.map +1 -1
  16. package/dist/server/index.d.ts +35 -8
  17. package/dist/server/index.d.ts.map +1 -1
  18. package/dist/server/index.js +41 -9
  19. package/dist/server/index.js.map +1 -1
  20. package/dist/shared.d.ts +5 -5
  21. package/dist/shared.js +5 -5
  22. package/dist/start/index.d.ts +3 -3
  23. package/dist/start/index.js +3 -3
  24. package/dist/visitor.d.ts +14 -0
  25. package/dist/visitor.d.ts.map +1 -0
  26. package/dist/visitor.js +14 -0
  27. package/dist/visitor.js.map +1 -0
  28. package/dist/worker/assignments.d.ts +44 -0
  29. package/dist/worker/assignments.d.ts.map +1 -0
  30. package/dist/worker/assignments.js +114 -0
  31. package/dist/worker/assignments.js.map +1 -0
  32. package/dist/worker/cache.d.ts +33 -0
  33. package/dist/worker/cache.d.ts.map +1 -0
  34. package/dist/worker/cache.js +41 -0
  35. package/dist/worker/cache.js.map +1 -0
  36. package/dist/worker/cookies.d.ts +1 -5
  37. package/dist/worker/cookies.d.ts.map +1 -1
  38. package/dist/worker/cookies.js +1 -26
  39. package/dist/worker/cookies.js.map +1 -1
  40. package/dist/worker/drafts.d.ts +27 -48
  41. package/dist/worker/drafts.d.ts.map +1 -1
  42. package/dist/worker/drafts.js +33 -88
  43. package/dist/worker/drafts.js.map +1 -1
  44. package/dist/worker/index.d.ts +77 -51
  45. package/dist/worker/index.d.ts.map +1 -1
  46. package/dist/worker/index.js +141 -360
  47. package/dist/worker/index.js.map +1 -1
  48. package/dist/worker/segment.d.ts +7 -6
  49. package/dist/worker/segment.d.ts.map +1 -1
  50. package/dist/worker/segment.js +6 -5
  51. package/dist/worker/segment.js.map +1 -1
  52. package/dist/worker/serverFn.d.ts +12 -0
  53. package/dist/worker/serverFn.d.ts.map +1 -0
  54. package/dist/worker/serverFn.js +44 -0
  55. package/dist/worker/serverFn.js.map +1 -0
  56. package/package.json +3 -3
  57. package/src/assignments.ts +77 -0
  58. package/src/draft.ts +10 -7
  59. package/src/index.ts +3 -1
  60. package/src/scope/server.ts +1 -1
  61. package/src/server/index.ts +51 -12
  62. package/src/shared.ts +5 -5
  63. package/src/start/index.ts +3 -3
  64. package/src/visitor.ts +14 -0
  65. package/src/worker/assignments.ts +146 -0
  66. package/src/worker/cache.ts +57 -0
  67. package/src/worker/cookies.ts +1 -27
  68. package/src/worker/drafts.ts +38 -98
  69. package/src/worker/index.ts +213 -425
  70. package/src/worker/segment.ts +7 -7
  71. package/src/worker/serverFn.ts +36 -0
  72. package/dist/worker/cacheProfiles.d.ts +0 -43
  73. package/dist/worker/cacheProfiles.d.ts.map +0 -1
  74. package/dist/worker/cacheProfiles.js +0 -162
  75. package/dist/worker/cacheProfiles.js.map +0 -1
  76. package/src/worker/cacheProfiles.ts +0 -180
@@ -5,67 +5,69 @@
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, and on the response
12
+ * `no-store`, `Vary: Cookie` and `noindex`.
11
13
  * - 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.
14
+ * - No page cache: caching is the site's (`pageCache`, the README's
15
+ * worker-entry recipe), with the helpers it needs exported here
16
+ * (`assignmentsKey`, `cacheVersion`, `isCacheable`, …).
17
+ * The worker calls `pageCache` only for a request `isCacheable` accepts,
18
+ * never for a preview, and adds the visitor's cookie after it, so a stored
19
+ * copy never carries one. A page request with `Authorization` is never
20
+ * handed to it and answers `private, no-cache, no-store`. A response with no
21
+ * `CDN-Cache-Control` tells the CDN `no-store`, at one exit.
17
22
  * - Security headers and `frame-ancestors` for Studio; immutable fingerprinted
18
23
  * assets; one `Set-Cookie` per cookie; `x-page-status`.
24
+ * - The visitor: on a page or server-function request, `readVisitor` from
25
+ * `@decocms/blocks/experiments` (the `deco_segment` cookie, or a new
26
+ * visitor), handed to the app on `x-deco-visitor`; the cookie is sent on a
27
+ * first visit only, never from a preview.
28
+ * - What the request's content gives it, decided once per request: each test
29
+ * and campaign on or off (`readAssignments`: `cms.client({ visitor,
30
+ * version, date, experiments, campaigns })` with the visitor and the Studio
31
+ * link's version, moment and switched tests and campaigns), handed to the
32
+ * site's `pageCache` (`page.assignments`, for its key) and to the app on
33
+ * `x-deco-assignments` (`contentClient` builds
34
+ * `cms.client({ version, experiments, campaigns })` from it, deciding
35
+ * nothing again).
19
36
  * - `http.server.request.duration` for every request, to the CMS's telemetry
20
37
  * (`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.
38
+ * method, the status class, the cache decision (the `X-Cache` the site's
39
+ * `pageCache` answered with) and the device; nothing when the CMS has no
40
+ * telemetry.
23
41
  */
24
42
  import { matchRoute } from "@decocms/blocks";
43
+ import { readVisitor, serializeVisitor } from "@decocms/blocks/experiments";
25
44
  import { recordServerRequest } from "@decocms/blocks/metrics";
26
45
  import { runInScope } from "@decocms/tanstack/scope";
27
- import { DRAFT_HEADER, draftResponseHeaders } from "../draft.js";
28
- import { CSEG_PARAM, DEGRADED_HEADER, PAGE_STATUS_HEADER } from "../shared.js";
29
- import { cacheControl, canonicalizeServerFnPayload, isServerFnPath, PRIVATE_NO_CACHE, profileOf, resolveProfiles, } from "./cacheProfiles.js";
30
- import { dedupeSetCookies, hasOnlySafeCookies, withoutSafeCookies } from "./cookies.js";
46
+ import { ASSIGNMENTS_HEADER, serializeAssignments } from "../assignments.js";
47
+ import { draftResponseHeaders, VERSION_HEADER } from "../draft.js";
48
+ import { PAGE_STATUS_HEADER } from "../shared.js";
49
+ import { VISITOR_HEADER } from "../visitor.js";
50
+ import { readAssignments } from "./assignments.js";
51
+ import { isCacheable } from "./cache.js";
52
+ import { dedupeSetCookies } from "./cookies.js";
31
53
  import { decideDraft } from "./drafts.js";
32
54
  import { htmlSecurityHeaders } from "./security.js";
33
- import { DEVICES, detectDevice, segmentKey, segmentToken } from "./segment.js";
34
- export { DEFAULT_CACHE_PROFILES } from "./cacheProfiles.js";
55
+ import { detectDevice } from "./segment.js";
56
+ import { isServerFnPath } from "./serverFn.js";
57
+ export { CSEG_PARAM, DEGRADED_HEADER } from "../shared.js";
58
+ export { assignmentsKey, liveAssignmentKeys, readAssignments, } from "./assignments.js";
59
+ export { cacheVersion, isCacheable, requestVersion } from "./cache.js";
60
+ export { detectDevice, segmentKey, segmentToken } from "./segment.js";
61
+ export { isServerFnPath, serverFnPagePath } from "./serverFn.js";
35
62
  const LIVENESS_PATH = "/deco/_liveness";
36
63
  /** v7's admin protocol paths: v8 sites serve none of them. */
37
64
  const REMOVED_ADMIN_PATHS = ["/deco/", "/live/", "/.decofile"];
38
- const PURGE_PATH = "/_cache/purge";
39
65
  const BYPASS_PATHS = ["/_build"];
40
66
  const STATIC_PATHS = ["/fonts/"];
41
67
  const FINGERPRINTED_ASSET_RE = /(?:\/_build)?\/assets\/.*-[a-zA-Z0-9_-]{8,}\.\w+$/;
42
- /** Query parameters that never change a page, left out of its cache key (v7's list). */
43
- const TRACKING_PARAMS = new Set([
44
- "utm_source",
45
- "utm_medium",
46
- "utm_campaign",
47
- "utm_term",
48
- "utm_content",
49
- "utmi_campaign",
50
- "utmi_page",
51
- "utmi_part",
52
- "fbclid",
53
- "gclid",
54
- "gclsrc",
55
- "dclid",
56
- "msclkid",
57
- "twclid",
58
- "li_fat_id",
59
- "mc_cid",
60
- "mc_eid",
61
- "ttclid",
62
- "srsltid",
63
- ]);
64
- const DEFAULT_SAFE_COOKIES = ["_deco_bucket"];
65
- const STORED_AT = "X-Deco-Stored-At";
66
- const DECISIONS = new Set(["HIT", "STALE-HIT", "STALE-ERROR", "MISS", "BYPASS"]);
68
+ const PRIVATE_NO_CACHE = "private, no-cache, no-store, must-revalidate";
67
69
  /** Paths the worker (or TanStack Start) serves under a fixed template, for `http.route`. */
68
- const FIXED_ROUTES = [LIVENESS_PATH, PURGE_PATH];
70
+ const FIXED_ROUTES = [LIVENESS_PATH];
69
71
  const PREFIX_ROUTES = ["/_serverFn/", "/_server/", "/_build/", "/assets/", "/fonts/"];
70
72
  /** The template of a path the worker knows without the content, or `null`. */
71
73
  function fixedRoute(pathname) {
@@ -81,15 +83,15 @@ function fixedRoute(pathname) {
81
83
  */
82
84
  const REDIRECT_ROUTE = "redirect";
83
85
  /**
84
- * The cache label of `http.server.request.duration`: the worker's own
85
- * decision. A response that never went through the edge cache (no cache
86
- * profile: a redirect, the site's `routes`, an asset) is `BYPASS` whatever
87
- * `X-Cache` an upstream put on it.
86
+ * The cache label of `http.server.request.duration`: `DRAFT` for a preview,
87
+ * otherwise what the site's `pageCache` said in `X-Cache`. A response that
88
+ * never went through it (a redirect, the site's `routes`, an asset, a page
89
+ * without a `pageCache`) is `BYPASS` whatever `X-Cache` an upstream put on it.
88
90
  */
89
91
  function cacheLabel(response, draft, served) {
90
92
  if (draft)
91
93
  return "DRAFT";
92
- if (!served?.profile)
94
+ if (!served?.cached)
93
95
  return "BYPASS";
94
96
  const xCache = response.headers.get("X-Cache");
95
97
  if (xCache === "HIT" || xCache === "STALE-HIT" || xCache === "STALE-ERROR")
@@ -97,11 +99,6 @@ function cacheLabel(response, draft, served) {
97
99
  return xCache === "MISS" ? "MISS" : "BYPASS";
98
100
  }
99
101
  const isHtml = (r) => (r.headers.get("content-type") ?? "").includes("text/html");
100
- function edgeCache() {
101
- return typeof caches !== "undefined"
102
- ? (caches.default ?? null)
103
- : null;
104
- }
105
102
  /** The origin's response with the page's own status (`x-page-status`) applied. */
106
103
  function withPageStatus(response) {
107
104
  const status = Number(response.headers.get(PAGE_STATUS_HEADER));
@@ -111,12 +108,6 @@ function withPageStatus(response) {
111
108
  headers.delete(PAGE_STATUS_HEADER);
112
109
  return new Response(response.body, { status, headers });
113
110
  }
114
- function isPrivateResponse(response) {
115
- return /\b(private|no-store)\b/i.test(response.headers.get("cache-control") ?? "");
116
- }
117
- function isDegraded(response) {
118
- return response.headers.get(DEGRADED_HEADER) === "true";
119
- }
120
111
  /** Adds `value` to the response's `Vary`, keeping what the origin listed. */
121
112
  function appendVary(headers, value) {
122
113
  const current = headers.get("vary");
@@ -129,117 +120,14 @@ function appendVary(headers, value) {
129
120
  function mutable(response) {
130
121
  return new Response(response.body, response);
131
122
  }
132
- function bypass(response, reason, cacheControlValue) {
133
- const out = mutable(response);
134
- if (cacheControlValue) {
135
- out.headers.set("Cache-Control", cacheControlValue);
136
- out.headers.delete("CDN-Cache-Control");
137
- }
138
- out.headers.set("X-Cache", "BYPASS");
139
- out.headers.set("X-Cache-Reason", reason);
140
- return out;
141
- }
142
123
  export function createDecoWorker(options) {
143
124
  const { cms, serverEntry } = options;
144
125
  const dev = options.dev === true;
145
- const profiles = resolveProfiles(options.cacheProfiles);
146
- const safeCookies = new Set(options.safeCookies ?? DEFAULT_SAFE_COOKIES);
147
126
  const securityHeaders = htmlSecurityHeaders(options.csp, dev);
148
- const policy = { site: options.site, previewHosts: options.previewHosts };
149
127
  const preloadLinks = [
150
128
  ...(options.preload?.styles ?? []).map((href) => `<${href}>; rel=preload; as=style`),
151
129
  ...(options.preload?.fonts ?? []).map((href) => `<${href}>; rel=preload; as=font; crossorigin`),
152
130
  ];
153
- /** `<build>.<revision>`: a published release gets new entries at once; the build alone when the revision can't be read. */
154
- async function cacheVersion() {
155
- let revision = "";
156
- try {
157
- revision = await cms.forRelease().revision();
158
- }
159
- catch {
160
- // The content didn't load: key on the build only.
161
- }
162
- return [options.buildHash, revision].filter(Boolean).join(".");
163
- }
164
- function segmentOf(request) {
165
- const base = { device: detectDevice(request.headers.get("user-agent") ?? "") };
166
- const extra = options.segment?.(request);
167
- if (extra === "private")
168
- return "private";
169
- const out = { ...base };
170
- for (const [k, v] of Object.entries(extra ?? {})) {
171
- if (v === undefined || v === "")
172
- delete out[k];
173
- else
174
- out[k] = v;
175
- }
176
- return out;
177
- }
178
- function cacheKey(url, request, version, segment) {
179
- const key = new URL(url);
180
- for (const name of [...key.searchParams.keys()]) {
181
- if (TRACKING_PARAMS.has(name.toLowerCase()))
182
- key.searchParams.delete(name);
183
- }
184
- key.searchParams.delete(CSEG_PARAM);
185
- const serverFn = isServerFnPath(key.pathname);
186
- if (serverFn) {
187
- const payload = key.searchParams.get("payload");
188
- if (payload)
189
- key.searchParams.set("payload", canonicalizeServerFnPayload(payload));
190
- }
191
- if (version)
192
- key.searchParams.set("__v", version);
193
- // Programmatic fetches (no navigation) get their own entries, as in v7.
194
- if (!serverFn && request.headers.get("sec-fetch-dest") === "empty") {
195
- key.searchParams.set("__fetch", "1");
196
- }
197
- key.searchParams.set("__seg", segmentKey(segment));
198
- return new Request(key.toString(), { method: "GET" });
199
- }
200
- async function purge(request, env) {
201
- const token = options.purgeToken?.(env);
202
- if (!token || request.headers.get("Authorization") !== `Bearer ${token}`) {
203
- return new Response("Unauthorized", { status: 401 });
204
- }
205
- let body;
206
- try {
207
- body = await request.json();
208
- }
209
- catch {
210
- return new Response("Invalid JSON body", { status: 400 });
211
- }
212
- const paths = Array.isArray(body.paths)
213
- ? body.paths.filter((p) => typeof p === "string" && p.startsWith("/"))
214
- : [];
215
- if (paths.length === 0) {
216
- return new Response('Body must include "paths": ["/", "/page"]', { status: 400 });
217
- }
218
- // Each segment to drop: the devices by default; a site with more parts lists its own.
219
- const segments = Array.isArray(body.segments)
220
- ? body.segments.filter((s) => !!s && typeof s === "object")
221
- : DEVICES.map((device) => ({ device }));
222
- const cache = edgeCache();
223
- if (!cache)
224
- return Response.json({ purged: [], total: 0, note: "Cache API unavailable" });
225
- const origin = new URL(request.url).origin;
226
- // The current version's entries: older versions' keys are no longer looked up.
227
- const version = await cacheVersion();
228
- const purged = [];
229
- for (const path of paths) {
230
- for (const segment of segments) {
231
- for (const programmatic of [false, true]) {
232
- const url = new URL(path, origin);
233
- const headers = programmatic ? { "sec-fetch-dest": "empty" } : undefined;
234
- const key = cacheKey(url, new Request(url, { headers }), version, segment);
235
- if (await cache.delete(key)) {
236
- purged.push(`${path} (${segmentKey(segment)}${programmatic ? ", fetch" : ""})`);
237
- }
238
- }
239
- }
240
- }
241
- return Response.json({ purged, total: purged.length });
242
- }
243
131
  // The release's redirects, read once per revision (a draft's are read each time).
244
132
  let releaseRedirects;
245
133
  async function redirectsFor(pointer) {
@@ -248,8 +136,8 @@ export function createDecoWorker(options) {
248
136
  return list ?? [];
249
137
  };
250
138
  if (pointer)
251
- return read(cms.forDraft(pointer));
252
- const client = cms.forRelease();
139
+ return read(cms.client({ version: pointer }));
140
+ const client = cms.client();
253
141
  const revision = await client.revision();
254
142
  if (releaseRedirects?.revision !== revision) {
255
143
  releaseRedirects = { revision, list: read(client) };
@@ -323,7 +211,32 @@ export function createDecoWorker(options) {
323
211
  return null; // a content error never blocks the page
324
212
  }
325
213
  }
326
- async function handle(request, env, ctx, draft) {
214
+ /**
215
+ * What a page or server-function request reads, decided once: the visitor
216
+ * (`readVisitor`: the `deco_segment` cookie, or a new visitor) on
217
+ * `x-deco-visitor`, each test and campaign on or off for it and the
218
+ * request's version (`readAssignments`) on `x-deco-assignments`, and the
219
+ * cookie to send when the visitor had no id. A preview (a draft, or an old
220
+ * release) sends no cookie: Studio is not a visitor.
221
+ */
222
+ async function withDecisions(request, draft) {
223
+ // TanStack Start's own build files render no content.
224
+ if (BYPASS_PATHS.some((p) => new URL(request.url).pathname.startsWith(p))) {
225
+ return { request, visitor: null };
226
+ }
227
+ const { visitor, cookie } = readVisitor(request);
228
+ const assignments = await readAssignments(cms, { visitor, ...draft.version });
229
+ const headers = new Headers(request.headers);
230
+ headers.set(VISITOR_HEADER, serializeVisitor(visitor));
231
+ headers.set(ASSIGNMENTS_HEADER, serializeAssignments(assignments));
232
+ const forwarded = new Request(request, { headers });
233
+ if (cookie === null || draft.version !== null) {
234
+ return { request: forwarded, visitor, assignments };
235
+ }
236
+ return { request: forwarded, visitor, assignments, visitorCookie: cookie };
237
+ }
238
+ async function handle(request, env, ctx, decision) {
239
+ const draft = decision.version?.version ?? null;
327
240
  const url = new URL(request.url);
328
241
  const method = request.method;
329
242
  const readOnly = method === "GET" || method === "HEAD";
@@ -333,7 +246,6 @@ export function createDecoWorker(options) {
333
246
  headers: {
334
247
  "Content-Type": "text/plain",
335
248
  "Cache-Control": PRIVATE_NO_CACHE,
336
- "X-Cache": "BYPASS",
337
249
  },
338
250
  }),
339
251
  };
@@ -342,12 +254,10 @@ export function createDecoWorker(options) {
342
254
  return {
343
255
  response: new Response("Not Found", {
344
256
  status: 404,
345
- headers: { "Cache-Control": PRIVATE_NO_CACHE, "X-Cache": "BYPASS" },
257
+ headers: { "Cache-Control": PRIVATE_NO_CACHE },
346
258
  }),
347
259
  };
348
260
  }
349
- if (url.pathname === PURGE_PATH && method === "POST")
350
- return { response: await purge(request, env) };
351
261
  const asset = FINGERPRINTED_ASSET_RE.test(url.pathname) ||
352
262
  STATIC_PATHS.some((p) => url.pathname.startsWith(p));
353
263
  if (readOnly &&
@@ -374,201 +284,87 @@ export function createDecoWorker(options) {
374
284
  resp.headers.set("Vary", "Accept-Encoding");
375
285
  return { response: resp };
376
286
  }
377
- const profileName = profileOf(url);
378
- const profile = profiles[profileName];
379
- const segment = segmentOf(request);
380
- const cacheable = method === "GET" &&
381
- !dev &&
382
- draft === null &&
383
- segment !== "private" &&
384
- !request.headers.has("authorization") &&
385
- !BYPASS_PATHS.some((p) => url.pathname.startsWith(p));
386
- const version = cacheable ? await cacheVersion() : "";
387
- const token = cacheable ? segmentToken(segment, version) : null;
388
- const origin = async () => withPageStatus(await runInScope({ csegToken: token ?? undefined, draft: draft ?? undefined }, () => serverEntry.fetch(request, env, ctx)));
389
- if (!cacheable) {
390
- const resp = await origin();
391
- if (draft !== null) {
392
- const out = bypass(resp, "draft");
393
- for (const [k, v] of Object.entries(draftResponseHeaders(draft))) {
394
- if (k.toLowerCase() !== "vary")
395
- out.headers.set(k, v);
396
- else
397
- appendVary(out.headers, v);
398
- }
399
- return { response: out, profile: profileName };
400
- }
401
- if (method !== "GET")
402
- return { response: bypass(resp, "method"), profile: profileName };
403
- if (segment === "private" ||
404
- request.headers.has("authorization") ||
405
- !profile.isPublic ||
406
- isPrivateResponse(resp) ||
407
- !hasOnlySafeCookies(resp, safeCookies)) {
408
- return { response: bypass(resp, "private", PRIVATE_NO_CACHE), profile: profileName };
409
- }
410
- // `vite dev` (and the `/_build` paths): the browser revalidates every time.
411
- return {
412
- response: bypass(resp, dev ? "dev" : "path", dev ? "no-cache" : undefined),
413
- profile: profileName,
414
- };
415
- }
416
- const seg = segment;
417
- const key = cacheKey(url, request, version, seg);
418
- const cache = edgeCache();
419
- const edge = profile.edge;
420
- const cdnPublic = token !== null &&
421
- profile.isPublic &&
422
- edge.fresh > 0 &&
423
- isServerFnPath(url.pathname) &&
424
- url.searchParams.get(CSEG_PARAM) === token;
425
- const dress = (resp, decision, extra) => {
426
- const out = mutable(resp);
427
- // Cloudflare's Cache API adds its own status to a matched response.
428
- out.headers.delete("cf-cache-status");
429
- out.headers.delete(STORED_AT);
430
- out.headers.set("Cache-Control", cacheControl(profile));
431
- out.headers.set("Vary", "Accept-Encoding");
432
- // The CDN may keep only navigation data whose URL carries this segment's token.
433
- out.headers.set("CDN-Cache-Control", cdnPublic ? `public, max-age=${edge.fresh}` : "no-store");
434
- out.headers.set("X-Cache", decision);
435
- out.headers.set("X-Cache-Profile", profileName);
436
- out.headers.set("X-Cache-Segment", segmentKey(seg));
437
- if (version)
438
- out.headers.set("X-Cache-Version", version);
439
- for (const [k, v] of Object.entries(extra ?? {}))
440
- out.headers.set(k, v);
441
- return out;
442
- };
443
- const storable = (resp) => resp.status === 200 &&
444
- !isDegraded(resp) &&
445
- !isPrivateResponse(resp) &&
446
- hasOnlySafeCookies(resp, safeCookies);
447
- const store = (resp) => {
448
- if (!cache)
449
- return;
450
- const ttl = edge.fresh + Math.max(edge.swr, edge.sie);
451
- const copy = resp.headers.has("set-cookie")
452
- ? withoutSafeCookies(resp, safeCookies)
453
- : resp.clone();
454
- copy.headers.set("Cache-Control", `public, max-age=${ttl}`);
455
- copy.headers.set(STORED_AT, String(Date.now()));
456
- copy.headers.delete("CDN-Cache-Control");
457
- ctx.waitUntil(cache.put(key, copy).catch(() => { }));
458
- };
459
- const ageOf = (resp) => {
460
- const storedAt = Number(resp.headers.get(STORED_AT) || "0");
461
- return storedAt > 0 ? (Date.now() - storedAt) / 1000 : Number.POSITIVE_INFINITY;
462
- };
463
- let cached;
464
- if (cache && profile.isPublic && edge.fresh > 0) {
465
- try {
466
- cached = (await cache.match(key)) ?? undefined;
467
- }
468
- catch {
469
- // Cache API unavailable: a miss.
470
- }
471
- }
472
- if (cached) {
473
- const age = ageOf(cached);
474
- if (age < edge.fresh)
475
- return { response: dress(cached, "HIT"), profile: profileName };
476
- if (age < edge.fresh + edge.swr) {
477
- ctx.waitUntil(origin()
478
- .then((fresh) => {
479
- if (storable(fresh))
480
- store(fresh);
481
- })
482
- .catch(() => { }));
483
- return {
484
- response: dress(cached, "STALE-HIT", { "X-Cache-Age": String(Math.round(age)) }),
485
- profile: profileName,
486
- };
487
- }
488
- }
489
- const staleOnError = (reason, status) => {
490
- if (!cached || edge.sie <= 0)
491
- return null;
492
- const age = ageOf(cached);
493
- if (age >= edge.fresh + edge.sie)
494
- return null;
495
- return dress(cached, "STALE-ERROR", {
496
- "X-Cache-Age": String(Math.round(age)),
497
- "X-Cache-Reason": reason,
498
- ...(status ? { "X-Cache-Origin-Status": String(status) } : {}),
499
- });
500
- };
501
- let resp;
502
- try {
503
- resp = await origin();
504
- }
505
- catch (error) {
506
- const stale = staleOnError("origin-error");
507
- if (stale)
508
- return { response: stale, profile: profileName };
509
- throw error;
510
- }
511
- if (resp.status !== 200) {
512
- if (resp.status >= 500 || resp.status === 429) {
513
- const stale = staleOnError("origin-status", resp.status);
514
- if (stale)
515
- return { response: stale, profile: profileName };
287
+ const visited = await withDecisions(request, decision);
288
+ const served = await page(visited.request, env, ctx, draft, url, visited.visitor, visited.assignments);
289
+ return visited.visitorCookie === undefined
290
+ ? served
291
+ : { ...served, visitorCookie: visited.visitorCookie };
292
+ }
293
+ /** A page or server-function request: the site's `pageCache` when it may cache it, else the app. */
294
+ async function page(request, env, ctx, draft, url, visitor, assignments) {
295
+ const render = async (scope) => withPageStatus(await runInScope({ csegToken: scope?.csegToken, draft: draft ?? undefined }, () => serverEntry.fetch(request, env, ctx)));
296
+ if (draft !== null) {
297
+ const out = mutable(await render());
298
+ for (const [k, v] of Object.entries(draftResponseHeaders(draft))) {
299
+ if (k.toLowerCase() !== "vary")
300
+ out.headers.set(k, v);
301
+ else
302
+ appendVary(out.headers, v);
516
303
  }
517
- return { response: bypass(resp, `status:${resp.status}`), profile: profileName };
518
- }
519
- if (isDegraded(resp)) {
520
- const stale = staleOnError("degraded");
521
- if (stale)
522
- return { response: stale, profile: profileName };
523
- return { response: bypass(resp, "degraded", PRIVATE_NO_CACHE), profile: profileName };
524
- }
525
- if (isPrivateResponse(resp) || !hasOnlySafeCookies(resp, safeCookies)) {
526
- return { response: bypass(resp, "private-response", PRIVATE_NO_CACHE), profile: profileName };
527
- }
528
- if (!profile.isPublic || edge.fresh === 0) {
529
- return {
530
- response: bypass(resp, `profile:${profileName}`, PRIVATE_NO_CACHE),
531
- profile: profileName,
532
- };
533
- }
534
- store(resp);
535
- return { response: dress(resp, "MISS"), profile: profileName };
304
+ return { response: out };
305
+ }
306
+ // A signed request's page is that caller's: no shared cache may keep it,
307
+ // whatever the app said (RFC 9111 lets one store a `public` answer to it).
308
+ if (request.headers.has("authorization")) {
309
+ const out = mutable(await render());
310
+ out.headers.set("Cache-Control", PRIVATE_NO_CACHE);
311
+ return { response: out };
312
+ }
313
+ if (!options.pageCache ||
314
+ visitor === null ||
315
+ assignments === undefined ||
316
+ !isCacheable(request, { version: draft, dev })) {
317
+ return { response: await render() };
318
+ }
319
+ const response = await options.pageCache({
320
+ request,
321
+ url,
322
+ visitor,
323
+ assignments,
324
+ device: detectDevice(request.headers.get("user-agent") ?? ""),
325
+ env,
326
+ ctx,
327
+ render,
328
+ });
329
+ return { response, cached: true };
536
330
  }
537
- async function serve(incoming, env, ctx, started) {
538
- let decision = {
539
- pointer: null,
540
- setCookie: null,
541
- };
331
+ async function serve(incoming, env, ctx) {
332
+ let decision = { version: null, setCookie: null };
542
333
  try {
543
- decision = await decideDraft(cms, incoming, policy);
334
+ decision = await decideDraft(cms, incoming);
544
335
  }
545
336
  catch {
546
337
  // The settings didn't load: the request gets the release.
547
338
  }
548
- // The page reads the draft from this header; a copy from outside never counts.
339
+ // The page reads the version, the visitor and the assignments from these
340
+ // headers; a copy from outside never counts.
549
341
  let request = incoming;
550
- if (incoming.headers.has(DRAFT_HEADER) || decision.pointer !== null) {
342
+ const own = [VERSION_HEADER, VISITOR_HEADER, ASSIGNMENTS_HEADER];
343
+ if (own.some((name) => incoming.headers.has(name)) || decision.version !== null) {
551
344
  const headers = new Headers(incoming.headers);
552
- headers.delete(DRAFT_HEADER);
553
- if (decision.pointer !== null)
554
- headers.set(DRAFT_HEADER, decision.pointer);
345
+ for (const name of own)
346
+ headers.delete(name);
347
+ if (decision.version !== null)
348
+ headers.set(VERSION_HEADER, decision.version.version);
555
349
  request = new Request(incoming, { headers });
556
350
  }
557
- const served = await handle(request, env, ctx, decision.pointer);
558
- const draft = decision.pointer !== null;
351
+ const served = await handle(request, env, ctx, decision);
352
+ const draft = decision.version !== null;
559
353
  let response = served.response;
560
354
  // A WebSocket upgrade passes through untouched.
561
355
  if (response.status === 101)
562
356
  return { response, served, draft };
563
357
  response = mutable(response);
564
- // CDN-Cache-Control is decided here, at the single exit: a response the
565
- // worker didn't cache, or that no branch gave one, tells the CDN no-store.
566
- if (response.headers.get("X-Cache") === "BYPASS" ||
567
- !response.headers.has("CDN-Cache-Control")) {
358
+ // CDN-Cache-Control is decided here, at the single exit: a response that
359
+ // names none (the app's, the site's cache's or a route's) tells the CDN
360
+ // no-store, so only what the site chose to share is kept in front of it.
361
+ if (!response.headers.has("CDN-Cache-Control")) {
568
362
  response.headers.set("CDN-Cache-Control", "no-store");
569
363
  }
570
364
  if (decision.setCookie)
571
365
  response.headers.append("Set-Cookie", decision.setCookie);
366
+ if (served.visitorCookie)
367
+ response.headers.append("Set-Cookie", served.visitorCookie);
572
368
  dedupeSetCookies(response);
573
369
  if (isHtml(response)) {
574
370
  for (const [k, v] of Object.entries(securityHeaders)) {
@@ -580,29 +376,14 @@ export function createDecoWorker(options) {
580
376
  response.headers.append("Link", link);
581
377
  }
582
378
  }
583
- if (served.profile && options.onCache) {
584
- const xCache = response.headers.get("X-Cache") ?? "BYPASS";
585
- try {
586
- options.onCache({
587
- profile: served.profile,
588
- decision: (DECISIONS.has(xCache) ? xCache : "BYPASS"),
589
- ms: Date.now() - started,
590
- status: response.status,
591
- });
592
- }
593
- catch {
594
- // A metrics hook never breaks a response.
595
- }
596
- }
597
379
  return { response, served, draft };
598
380
  }
599
381
  return {
600
382
  async fetch(incoming, env, ctx) {
601
- const started = Date.now();
602
383
  const clock = performance.now();
603
384
  let result;
604
385
  try {
605
- result = await serve(incoming, env, ctx, started);
386
+ result = await serve(incoming, env, ctx);
606
387
  }
607
388
  catch (error) {
608
389
  // The runtime answers a thrown request with a 500.