@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,67 +5,74 @@
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 { matchRoute } from "@decocms/blocks";
48
+ import { readVisitor, serializeVisitor } 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.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";
31
- import { decideDraft } from "./drafts.js";
51
+ import { ASSIGNMENTS_HEADER, serializeAssignments } from "../assignments.js";
52
+ import { draftResponseHeaders, RELEASE_CHECK_HEADER, VERSION_HEADER } from "../draft.js";
53
+ import { PAGE_STATUS_HEADER } from "../shared.js";
54
+ import { VISITOR_HEADER } from "../visitor.js";
55
+ import { readAssignments } from "./assignments.js";
56
+ import { isCacheable } from "./cache.js";
57
+ import { dedupeSetCookies } from "./cookies.js";
58
+ import { decideDraft, hasDraftSignal } from "./drafts.js";
32
59
  import { htmlSecurityHeaders } from "./security.js";
33
- import { DEVICES, detectDevice, segmentKey, segmentToken } from "./segment.js";
34
- export { DEFAULT_CACHE_PROFILES } from "./cacheProfiles.js";
60
+ import { detectDevice } from "./segment.js";
61
+ import { isServerFnPath } from "./serverFn.js";
62
+ export { CSEG_PARAM, DEGRADED_HEADER } from "../shared.js";
63
+ export { assignmentsKey, liveAssignmentKeys, readAssignments, } from "./assignments.js";
64
+ export { cacheVersion, isCacheable, requestVersion } from "./cache.js";
65
+ export { detectDevice, segmentKey, segmentToken } from "./segment.js";
66
+ export { isServerFnPath, serverFnPagePath } from "./serverFn.js";
35
67
  const LIVENESS_PATH = "/deco/_liveness";
36
68
  /** v7's admin protocol paths: v8 sites serve none of them. */
37
69
  const REMOVED_ADMIN_PATHS = ["/deco/", "/live/", "/.decofile"];
38
- const PURGE_PATH = "/_cache/purge";
39
70
  const BYPASS_PATHS = ["/_build"];
40
71
  const STATIC_PATHS = ["/fonts/"];
41
72
  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"]);
73
+ const PRIVATE_NO_CACHE = "private, no-cache, no-store, must-revalidate";
67
74
  /** Paths the worker (or TanStack Start) serves under a fixed template, for `http.route`. */
68
- const FIXED_ROUTES = [LIVENESS_PATH, PURGE_PATH];
75
+ const FIXED_ROUTES = [LIVENESS_PATH];
69
76
  const PREFIX_ROUTES = ["/_serverFn/", "/_server/", "/_build/", "/assets/", "/fonts/"];
70
77
  /** The template of a path the worker knows without the content, or `null`. */
71
78
  function fixedRoute(pathname) {
@@ -81,15 +88,16 @@ function fixedRoute(pathname) {
81
88
  */
82
89
  const REDIRECT_ROUTE = "redirect";
83
90
  /**
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.
91
+ * The cache label of `http.server.request.duration`: `DRAFT` for a preview
92
+ * (any draft signal),
93
+ * otherwise what the site's `pageCache` said in `X-Cache`. A response that
94
+ * never went through it (a redirect, the site's `routes`, an asset, a page
95
+ * without a `pageCache`) is `BYPASS` whatever `X-Cache` an upstream put on it.
88
96
  */
89
97
  function cacheLabel(response, draft, served) {
90
98
  if (draft)
91
99
  return "DRAFT";
92
- if (!served?.profile)
100
+ if (!served?.cached)
93
101
  return "BYPASS";
94
102
  const xCache = response.headers.get("X-Cache");
95
103
  if (xCache === "HIT" || xCache === "STALE-HIT" || xCache === "STALE-ERROR")
@@ -97,11 +105,6 @@ function cacheLabel(response, draft, served) {
97
105
  return xCache === "MISS" ? "MISS" : "BYPASS";
98
106
  }
99
107
  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
108
  /** The origin's response with the page's own status (`x-page-status`) applied. */
106
109
  function withPageStatus(response) {
107
110
  const status = Number(response.headers.get(PAGE_STATUS_HEADER));
@@ -111,12 +114,6 @@ function withPageStatus(response) {
111
114
  headers.delete(PAGE_STATUS_HEADER);
112
115
  return new Response(response.body, { status, headers });
113
116
  }
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
117
  /** Adds `value` to the response's `Vary`, keeping what the origin listed. */
121
118
  function appendVary(headers, value) {
122
119
  const current = headers.get("vary");
@@ -129,127 +126,24 @@ function appendVary(headers, value) {
129
126
  function mutable(response) {
130
127
  return new Response(response.body, response);
131
128
  }
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
129
  export function createDecoWorker(options) {
143
130
  const { cms, serverEntry } = options;
144
131
  const dev = options.dev === true;
145
- const profiles = resolveProfiles(options.cacheProfiles);
146
- const safeCookies = new Set(options.safeCookies ?? DEFAULT_SAFE_COOKIES);
147
132
  const securityHeaders = htmlSecurityHeaders(options.csp, dev);
148
- const policy = { site: options.site, previewHosts: options.previewHosts };
149
133
  const preloadLinks = [
150
134
  ...(options.preload?.styles ?? []).map((href) => `<${href}>; rel=preload; as=style`),
151
135
  ...(options.preload?.fonts ?? []).map((href) => `<${href}>; rel=preload; as=font; crossorigin`),
152
136
  ];
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
137
  // The release's redirects, read once per revision (a draft's are read each time).
244
138
  let releaseRedirects;
245
- async function redirectsFor(pointer) {
139
+ async function redirectsFor(pointer, releaseCheck) {
246
140
  const read = async (client) => {
247
141
  const [list] = await client.list("redirect");
248
142
  return list ?? [];
249
143
  };
250
144
  if (pointer)
251
- return read(cms.forDraft(pointer));
252
- const client = cms.forRelease();
145
+ return read(cms.client({ version: pointer, releaseCheck }));
146
+ const client = cms.client();
253
147
  const revision = await client.revision();
254
148
  if (releaseRedirects?.revision !== revision) {
255
149
  releaseRedirects = { revision, list: read(client) };
@@ -309,9 +203,9 @@ export function createDecoWorker(options) {
309
203
  // A metric never breaks a response.
310
204
  }
311
205
  }
312
- async function findRedirect(url, pointer) {
206
+ async function findRedirect(url, pointer, releaseCheck) {
313
207
  try {
314
- const redirects = await redirectsFor(pointer);
208
+ const redirects = await redirectsFor(pointer, releaseCheck);
315
209
  if (!redirects.length)
316
210
  return null;
317
211
  const match = matchRoute(url, { routes: [], redirects });
@@ -323,7 +217,38 @@ export function createDecoWorker(options) {
323
217
  return null; // a content error never blocks the page
324
218
  }
325
219
  }
326
- async function handle(request, env, ctx, draft) {
220
+ /**
221
+ * What a page or server-function request reads, decided once: the visitor
222
+ * (`readVisitor`: the `deco_segment` cookie, or a new visitor) on
223
+ * `x-deco-visitor`, each test and campaign on or off for it and the
224
+ * request's version (`readAssignments`) on `x-deco-assignments`, and the
225
+ * cookie to send when the visitor had no id. A preview (a draft, or an old
226
+ * release) sends no cookie: Studio is not a visitor.
227
+ */
228
+ async function withDecisions(request, draft) {
229
+ // TanStack Start's own build files render no content.
230
+ if (BYPASS_PATHS.some((p) => new URL(request.url).pathname.startsWith(p))) {
231
+ return { request, visitor: null };
232
+ }
233
+ const { visitor, cookie } = readVisitor(request);
234
+ // A draft's read shares the request's release check (`decideDraft`), never one of its own.
235
+ const releaseCheck = draft.version ? draft.releaseCheck : undefined;
236
+ const assignments = await readAssignments(cms, {
237
+ visitor,
238
+ ...draft.version,
239
+ ...(releaseCheck ? { releaseCheck } : {}),
240
+ });
241
+ const headers = new Headers(request.headers);
242
+ headers.set(VISITOR_HEADER, serializeVisitor(visitor));
243
+ headers.set(ASSIGNMENTS_HEADER, serializeAssignments(assignments));
244
+ const forwarded = new Request(request, { headers });
245
+ if (cookie === null || draft.version !== null) {
246
+ return { request: forwarded, visitor, assignments };
247
+ }
248
+ return { request: forwarded, visitor, assignments, visitorCookie: cookie };
249
+ }
250
+ async function handle(request, env, ctx, decision, preview) {
251
+ const draft = decision.version?.version ?? null;
327
252
  const url = new URL(request.url);
328
253
  const method = request.method;
329
254
  const readOnly = method === "GET" || method === "HEAD";
@@ -333,7 +258,6 @@ export function createDecoWorker(options) {
333
258
  headers: {
334
259
  "Content-Type": "text/plain",
335
260
  "Cache-Control": PRIVATE_NO_CACHE,
336
- "X-Cache": "BYPASS",
337
261
  },
338
262
  }),
339
263
  };
@@ -342,19 +266,17 @@ export function createDecoWorker(options) {
342
266
  return {
343
267
  response: new Response("Not Found", {
344
268
  status: 404,
345
- headers: { "Cache-Control": PRIVATE_NO_CACHE, "X-Cache": "BYPASS" },
269
+ headers: { "Cache-Control": PRIVATE_NO_CACHE },
346
270
  }),
347
271
  };
348
272
  }
349
- if (url.pathname === PURGE_PATH && method === "POST")
350
- return { response: await purge(request, env) };
351
273
  const asset = FINGERPRINTED_ASSET_RE.test(url.pathname) ||
352
274
  STATIC_PATHS.some((p) => url.pathname.startsWith(p));
353
275
  if (readOnly &&
354
276
  !asset &&
355
277
  !isServerFnPath(url.pathname) &&
356
278
  !BYPASS_PATHS.some((p) => url.pathname.startsWith(p))) {
357
- const redirect = await findRedirect(url, draft);
279
+ const redirect = await findRedirect(url, draft, decision.releaseCheck);
358
280
  if (redirect)
359
281
  return { response: redirect, redirect: true };
360
282
  }
@@ -366,209 +288,127 @@ export function createDecoWorker(options) {
366
288
  if (asset) {
367
289
  const origin = await serverEntry.fetch(request, env, ctx);
368
290
  if (origin.status !== 200)
369
- return { response: origin };
370
- if (isHtml(origin))
371
- return { response: new Response("Not Found", { status: 404 }) };
291
+ return { response: origin, asset: true };
292
+ if (isHtml(origin)) {
293
+ return { response: new Response("Not Found", { status: 404 }), asset: true };
294
+ }
372
295
  const resp = mutable(origin);
373
296
  resp.headers.set("Cache-Control", "public, max-age=31536000, immutable");
374
297
  resp.headers.set("Vary", "Accept-Encoding");
375
- return { response: resp };
376
- }
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 };
516
- }
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 };
298
+ return { response: resp, asset: true };
299
+ }
300
+ const visited = await withDecisions(request, decision);
301
+ const served = await page(visited.request, env, ctx, {
302
+ draft,
303
+ preview,
304
+ unavailable: decision.unavailable === true,
305
+ url,
306
+ visitor: visited.visitor,
307
+ assignments: visited.assignments,
308
+ });
309
+ return visited.visitorCookie === undefined
310
+ ? served
311
+ : { ...served, visitorCookie: visited.visitorCookie };
536
312
  }
537
- async function serve(incoming, env, ctx, started) {
538
- let decision = {
539
- pointer: null,
540
- setCookie: null,
541
- };
313
+ /**
314
+ * A page or server-function request: the site's `pageCache` when it may
315
+ * cache it, else the app. A preview (any draft signal) always renders: its
316
+ * headers are set at the exit (`serve`).
317
+ */
318
+ async function page(request, env, ctx, inputs) {
319
+ const { draft, preview, unavailable, url, visitor, assignments } = inputs;
320
+ const render = async (scope) => withPageStatus(await runInScope({
321
+ csegToken: scope?.csegToken,
322
+ draft: draft ?? undefined,
323
+ ...(unavailable ? { draftUnavailable: true } : {}),
324
+ }, () => serverEntry.fetch(request, env, ctx)));
325
+ if (draft !== null || preview)
326
+ return { response: await render() };
327
+ // A signed request's page is that caller's: no shared cache may keep it,
328
+ // whatever the app said (RFC 9111 lets one store a `public` answer to it).
329
+ if (request.headers.has("authorization")) {
330
+ const out = mutable(await render());
331
+ out.headers.set("Cache-Control", PRIVATE_NO_CACHE);
332
+ return { response: out };
333
+ }
334
+ if (!options.pageCache ||
335
+ visitor === null ||
336
+ assignments === undefined ||
337
+ !isCacheable(request, { version: draft, dev })) {
338
+ return { response: await render() };
339
+ }
340
+ const response = await options.pageCache({
341
+ request,
342
+ url,
343
+ visitor,
344
+ assignments,
345
+ device: detectDevice(request.headers.get("user-agent") ?? ""),
346
+ env,
347
+ ctx,
348
+ render,
349
+ });
350
+ return { response, cached: true };
351
+ }
352
+ async function serve(incoming, env, ctx) {
353
+ // Any draft signal makes the request a preview, whatever the decision.
354
+ const preview = hasDraftSignal(incoming);
355
+ let decision = { version: null, setCookie: null };
542
356
  try {
543
- decision = await decideDraft(cms, incoming, policy);
357
+ decision = await decideDraft(cms, incoming);
544
358
  }
545
359
  catch {
546
360
  // The settings didn't load: the request gets the release.
547
361
  }
548
- // The page reads the draft from this header; a copy from outside never counts.
362
+ // The page reads the version, the visitor and the assignments from these
363
+ // headers; a copy from outside never counts.
549
364
  let request = incoming;
550
- if (incoming.headers.has(DRAFT_HEADER) || decision.pointer !== null) {
365
+ const own = [VERSION_HEADER, VISITOR_HEADER, ASSIGNMENTS_HEADER, RELEASE_CHECK_HEADER];
366
+ if (own.some((name) => incoming.headers.has(name)) || decision.version !== null) {
551
367
  const headers = new Headers(incoming.headers);
552
- headers.delete(DRAFT_HEADER);
553
- if (decision.pointer !== null)
554
- headers.set(DRAFT_HEADER, decision.pointer);
368
+ for (const name of own)
369
+ headers.delete(name);
370
+ if (decision.version !== null)
371
+ headers.set(VERSION_HEADER, decision.version.version);
372
+ // The page's draft reads wait for the request's release check, never one of their own.
373
+ if (decision.version !== null && decision.releaseCheck !== undefined) {
374
+ headers.set(RELEASE_CHECK_HEADER, decision.releaseCheck);
375
+ }
555
376
  request = new Request(incoming, { headers });
556
377
  }
557
- const served = await handle(request, env, ctx, decision.pointer);
558
- const draft = decision.pointer !== null;
378
+ const served = await handle(request, env, ctx, decision, preview);
379
+ const draft = decision.version !== null || preview;
559
380
  let response = served.response;
560
381
  // A WebSocket upgrade passes through untouched.
561
382
  if (response.status === 101)
562
383
  return { response, served, draft };
563
384
  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")) {
385
+ // CDN-Cache-Control is decided here, at the single exit: a response that
386
+ // names none (the app's, the site's cache's or a route's) tells the CDN
387
+ // no-store, so only what the site chose to share is kept in front of it.
388
+ if (!response.headers.has("CDN-Cache-Control")) {
568
389
  response.headers.set("CDN-Cache-Control", "no-store");
569
390
  }
570
- if (decision.setCookie)
391
+ // A preview's response is never answered from a cache: the exact header,
392
+ // whatever the app or a route said. A fingerprinted asset stays immutable.
393
+ if (preview && !served.asset) {
394
+ for (const [k, v] of Object.entries(draftResponseHeaders(true))) {
395
+ if (k.toLowerCase() !== "vary")
396
+ response.headers.set(k, v);
397
+ else
398
+ appendVary(response.headers, v);
399
+ }
400
+ // Nor kept by the CDN, whatever a route said: with the draft in a cookie
401
+ // a preview shares its URL with the published page.
402
+ response.headers.set("CDN-Cache-Control", "no-store");
403
+ }
404
+ // A link's cookie only with a page that rendered: a failed render never
405
+ // pins the preview to it. The cookie that ends a preview always goes.
406
+ const ending = decision.version === null;
407
+ if (decision.setCookie && (ending || response.status < 500)) {
571
408
  response.headers.append("Set-Cookie", decision.setCookie);
409
+ }
410
+ if (served.visitorCookie)
411
+ response.headers.append("Set-Cookie", served.visitorCookie);
572
412
  dedupeSetCookies(response);
573
413
  if (isHtml(response)) {
574
414
  for (const [k, v] of Object.entries(securityHeaders)) {
@@ -580,29 +420,14 @@ export function createDecoWorker(options) {
580
420
  response.headers.append("Link", link);
581
421
  }
582
422
  }
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
423
  return { response, served, draft };
598
424
  }
599
425
  return {
600
426
  async fetch(incoming, env, ctx) {
601
- const started = Date.now();
602
427
  const clock = performance.now();
603
428
  let result;
604
429
  try {
605
- result = await serve(incoming, env, ctx, started);
430
+ result = await serve(incoming, env, ctx);
606
431
  }
607
432
  catch (error) {
608
433
  // The runtime answers a thrown request with a 500.