@decocms/tanstack 8.5.2 → 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
@@ -0,0 +1,146 @@
1
+ /**
2
+ * A request's assignments (what its content gives it), decided once by the
3
+ * worker: the version it reads (a Studio link's draft or release SHA), each
4
+ * test of the saved `experiments` block on or off for its visitor and each
5
+ * campaign of the saved `campaigns` block running or not at its date, with a
6
+ * preview's switched tests and campaigns on top. The worker hands them to the
7
+ * page (`x-deco-assignments`) and to the site's `pageCache`
8
+ * (`page.assignments`), whose key carries them (`assignmentsKey`). Two
9
+ * requests with the same assignments render the same content, so they share
10
+ * a cache entry; the visitor id itself is never in the key, or every visitor
11
+ * would miss.
12
+ *
13
+ * Blocks decides (`cms.client({ visitor, version, … })`); this only reads
14
+ * the answers. A site without either block has no assignments and keys as
15
+ * before.
16
+ */
17
+ import type { ClientOptions, CMS } from "@decocms/blocks";
18
+ import type { Assignments } from "@decocms/blocks/experiments";
19
+ import type { DecidedAssignments } from "../assignments.ts";
20
+
21
+ export interface RequestAssignments extends DecidedAssignments {
22
+ /** The version read, `null` for the current release. */
23
+ version: string | null;
24
+ }
25
+
26
+ const EXPERIMENTS = { block: "experiments", type: "split-traffic" } as const;
27
+ const CAMPAIGNS = { block: "campaigns", type: "calendar" } as const;
28
+
29
+ type Reader = ReturnType<CMS["client"]>;
30
+
31
+ /** Plain code-unit order, the same on every server and locale. */
32
+ const byCodeUnit = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
33
+
34
+ const record = (): Assignments => Object.create(null) as Assignments;
35
+
36
+ function isRecord(value: unknown): value is Record<string, unknown> {
37
+ return typeof value === "object" && value !== null && !Array.isArray(value);
38
+ }
39
+
40
+ /**
41
+ * Whether the content saves a block of `type`: listing never fails on a
42
+ * missing block, so a site without tests or campaigns reports no error.
43
+ */
44
+ async function saves(client: Reader, type: string): Promise<boolean> {
45
+ const [list] = await client.list(type);
46
+ return (list?.length ?? 0) > 0;
47
+ }
48
+
49
+ /** The saved `block` resolved, each name `true` or `false`; none when it is missing. */
50
+ async function decided(
51
+ client: Reader,
52
+ spec: { block: string; type: string },
53
+ ): Promise<Assignments> {
54
+ const out = record();
55
+ try {
56
+ if (!(await saves(client, spec.type))) return out;
57
+ const [value] = await client.resolve<unknown>(spec.block);
58
+ if (!isRecord(value)) return out;
59
+ for (const name of Object.keys(value).sort(byCodeUnit)) out[name] = value[name] === true;
60
+ } catch {
61
+ // Content that doesn't load gives no assignments.
62
+ }
63
+ return out;
64
+ }
65
+
66
+ /**
67
+ * The assignments of one request: `cms.client(options)` (the version, the
68
+ * visitor, the date and a preview's switched tests and campaigns, as
69
+ * `cms.readVersion` reads them) resolving `experiments` and `campaigns`.
70
+ * Missing blocks (or content that doesn't load) give none, never an error.
71
+ */
72
+ export async function readAssignments(
73
+ cms: Pick<CMS, "client">,
74
+ options: ClientOptions,
75
+ ): Promise<RequestAssignments> {
76
+ const version = typeof options.version === "string" ? options.version : null;
77
+ let client: Reader;
78
+ try {
79
+ client = cms.client(options);
80
+ } catch {
81
+ return { version, experiments: record(), campaigns: record() };
82
+ }
83
+ const [experiments, campaigns] = await Promise.all([
84
+ decided(client, EXPERIMENTS),
85
+ decided(client, CAMPAIGNS),
86
+ ]);
87
+ return { version, experiments, campaigns };
88
+ }
89
+
90
+ /**
91
+ * Every assignments key a live request can carry now, for a site's purge: each
92
+ * subset of the tests in the saved `experiments` block on (the empty one
93
+ * included), with the campaigns running now and with none. Previews are
94
+ * never cached, so no version. A site without either block has one: `""`.
95
+ */
96
+ export async function liveAssignmentKeys(cms: Pick<CMS, "client">): Promise<string[]> {
97
+ let client: Reader;
98
+ try {
99
+ client = cms.client();
100
+ } catch {
101
+ return [""];
102
+ }
103
+ const [saved, campaigns] = await Promise.all([
104
+ decided(client, EXPERIMENTS),
105
+ decided(client, CAMPAIGNS),
106
+ ]);
107
+ const tests = Object.keys(saved);
108
+ const running = Object.keys(campaigns).some((name) => campaigns[name] === true);
109
+ const campaignSets = running ? [campaigns, record()] : [record()];
110
+ const keys: string[] = [];
111
+ // Subsets by bitmask, tests in sorted order: 2^tests of them.
112
+ for (let mask = 0; mask < 2 ** tests.length; mask++) {
113
+ const experiments = record();
114
+ tests.forEach((name, i) => {
115
+ experiments[name] = Math.floor(mask / 2 ** i) % 2 === 1;
116
+ });
117
+ for (const set of campaignSets) {
118
+ keys.push(assignmentsKey({ version: null, experiments, campaigns: set }));
119
+ }
120
+ }
121
+ return keys;
122
+ }
123
+
124
+ /** The names that are on, sorted. */
125
+ function onNames(assignments: Readonly<Assignments>): string[] {
126
+ return Object.keys(assignments)
127
+ .filter((name) => assignments[name] === true)
128
+ .sort(byCodeUnit);
129
+ }
130
+
131
+ /**
132
+ * The assignments as one stable string for a cache key:
133
+ * `v=<version>|x=<tests on>|c=<campaigns running>`, names sorted and
134
+ * URL-encoded, empty parts left out; `""` for none. The names that are off
135
+ * aren't in it: within one content revision they are the rest.
136
+ */
137
+ export function assignmentsKey(assignments: RequestAssignments): string {
138
+ const list = (names: string[]) => names.map(encodeURIComponent).join(",");
139
+ const parts: string[] = [];
140
+ if (assignments.version) parts.push(`v=${encodeURIComponent(assignments.version)}`);
141
+ const tests = onNames(assignments.experiments);
142
+ const campaigns = onNames(assignments.campaigns);
143
+ if (tests.length) parts.push(`x=${list(tests)}`);
144
+ if (campaigns.length) parts.push(`c=${list(campaigns)}`);
145
+ return parts.join("|");
146
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * What a site needs to build its own page cache in front of the worker (the
3
+ * README's worker-entry recipe): whether a request may be cached at all, the
4
+ * version every key carries, and the version (draft or old release) a request
5
+ * renders. The worker caches nothing itself.
6
+ */
7
+ import type { CMS } from "@decocms/blocks";
8
+ import { VERSION_HEADER } from "../draft.ts";
9
+
10
+ /**
11
+ * Whether a request may be served from or stored in a shared cache at all:
12
+ * a GET of the current release (`version` `null`: never a preview, a draft
13
+ * or an old release), outside local development, without `Authorization`,
14
+ * and not one of TanStack Start's own `/_build` files. The worker calls a
15
+ * site's `pageCache` only for these.
16
+ */
17
+ export function isCacheable(
18
+ request: Pick<Request, "method" | "url" | "headers">,
19
+ inputs: { version: string | null; dev?: boolean },
20
+ ): boolean {
21
+ return (
22
+ request.method === "GET" &&
23
+ inputs.version === null &&
24
+ inputs.dev !== true &&
25
+ !request.headers.has("authorization") &&
26
+ !new URL(request.url).pathname.startsWith("/_build")
27
+ );
28
+ }
29
+
30
+ /**
31
+ * `<build>.<content revision>`, for every cache key: a new build or a
32
+ * published release gets new entries at once. The build alone when the
33
+ * revision can't be read.
34
+ */
35
+ export async function cacheVersion(
36
+ cms: Pick<CMS, "forRelease">,
37
+ buildHash: string,
38
+ ): Promise<string> {
39
+ let revision = "";
40
+ try {
41
+ revision = await cms.forRelease().revision();
42
+ } catch {
43
+ // The content didn't load: key on the build only.
44
+ }
45
+ return [buildHash, revision].filter(Boolean).join(".");
46
+ }
47
+
48
+ /**
49
+ * The version a request renders as the worker decided it (a Studio link's
50
+ * draft pointer or release SHA, after the host allowlist), from the
51
+ * `x-deco-version` header it sets; `null` for the current release. For the
52
+ * request a `routes` handler or `pageCache` gets: the worker removes any copy
53
+ * that arrives from outside.
54
+ */
55
+ export function requestVersion(request: Pick<Request, "headers">): string | null {
56
+ return request.headers.get(VERSION_HEADER) || null;
57
+ }
@@ -1,30 +1,4 @@
1
- /** Set-Cookie handling: which cookies a cached response may carry, and one header per cookie. */
2
-
3
- function cookieName(setCookie: string): string {
4
- const eq = setCookie.indexOf("=");
5
- return eq > 0 ? setCookie.slice(0, eq).trim() : "";
6
- }
7
-
8
- /** Whether every cookie the response sets is one a shared (cached) response may set. */
9
- export function hasOnlySafeCookies(response: Response, safe: ReadonlySet<string>): boolean {
10
- return response.headers.getSetCookie().every((c) => {
11
- const name = cookieName(c);
12
- return name === "" || safe.has(name);
13
- });
14
- }
15
-
16
- /** A copy for the cache without the safe cookies; the visitor still gets them. */
17
- export function withoutSafeCookies(response: Response, safe: ReadonlySet<string>): Response {
18
- const copy = response.clone();
19
- const cookies = response.headers.getSetCookie();
20
- if (cookies.length === 0) return copy;
21
- copy.headers.delete("set-cookie");
22
- for (const c of cookies) {
23
- const name = cookieName(c);
24
- if (name && !safe.has(name)) copy.headers.append("set-cookie", c);
25
- }
26
- return copy;
27
- }
1
+ /** Set-Cookie handling: one header per cookie. */
28
2
 
29
3
  /**
30
4
  * A Set-Cookie's identity: name + Domain + Path, the way the browser keys its
@@ -1,83 +1,23 @@
1
1
  /**
2
- * Which hosts may render drafts: v7's allowlist (`@decocms/blocks` 7.x
3
- * `cms/draftSource.ts`: `readAllowedHosts`, `isDraftHostAllowed`,
4
- * `isDraftPreviewEnabled`), ported as is. v7 read its override from the
5
- * `DECO_ALLOWED_PREVIEW_HOSTS` variable; here it is the `previewHosts` option.
6
- *
7
- * - The site's own preview hosts: the ones it declares, in the `CMS` block or
8
- * as `createCMS({ preview: { hosts } })` (matched as `cms.draftPointer`
9
- * matches them). A site that declares none has none, as in v7: blocks'
10
- * own default (every host) doesn't count as a declaration.
11
- * - The hosts Deco runs the site on, named after the site and always added:
12
- * `<site>.deco.site` and `<site>.deco-cx.workers.dev`, exact.
13
- * - `previewHosts: [...]` replaces the site's own list (the inferred hosts are
14
- * still added); `previewHosts: "none"` turns previews off on every host.
15
- *
16
- * Hosts compare exactly, lowercased, port included (`localhost:5173`).
2
+ * Which hosts may render drafts: the ones the CMS allows (`cms.readVersion`):
3
+ * the addresses Studio writes into the current release's metadata, plus
4
+ * `createCMS`'s `preview.hosts`; every host while the site has published no
5
+ * list, or with no `site` and no `preview.hosts`. The site declares nothing
6
+ * here (PO 2026-10-22).
17
7
  *
18
8
  * The draft itself is the capability: a host check only bounds where a draft
19
9
  * link works. A request the check refuses gets the release, never an error.
10
+ *
11
+ * What a link carries is a version, as `cms.readVersion` reads it: a draft
12
+ * pointer, or a published release's commit SHA (Studio's "Preview this
13
+ * version"), with the preview's moment and switched tests and campaigns
14
+ * (`__at`, `__test`, `__campaign`; `parseVersion` from `@decocms/blocks`).
15
+ * Both pass the same host check: a visitor on the live site never picks a
16
+ * version.
20
17
  */
21
- import { type CMS, parseDraftPointer } from "@decocms/blocks";
18
+ import { type CMS, parseVersion, type RequestVersion } from "@decocms/blocks";
22
19
  import { DRAFT_COOKIE, DRAFT_PARAM } from "../draft.ts";
23
20
 
24
- export interface PreviewPolicy {
25
- /** The site's name: `<site>.deco.site` and `<site>.deco-cx.workers.dev` may preview. */
26
- site?: string;
27
- /** Replaces the `CMS` block's preview hosts; `"none"` turns previews off everywhere. */
28
- previewHosts?: readonly string[] | "none";
29
- }
30
-
31
- /** The hosts Deco runs `site` on, which may always preview (unless previews are off). */
32
- export function inferredPreviewHosts(site: string | undefined): string[] {
33
- const s = (site ?? "").trim().toLowerCase();
34
- return s ? [`${s}.deco.site`, `${s}.deco-cx.workers.dev`] : [];
35
- }
36
-
37
- /**
38
- * Whether `host` may preview without asking the CMS: `true` (an override or
39
- * inferred host), `false` (previews off, or the override leaves it out), or
40
- * `"cms"` when only the site's declared preview hosts can say (none declared:
41
- * `false`, see {@link declaresPreviewHosts}).
42
- */
43
- export function previewHostDecision(host: string, policy: PreviewPolicy): boolean | "cms" {
44
- const override =
45
- policy.previewHosts === "none"
46
- ? ["none"]
47
- : (policy.previewHosts ?? []).map((h) => h.trim().toLowerCase()).filter(Boolean);
48
- if (override.includes("none")) return false;
49
- const h = host.trim().toLowerCase();
50
- if (h === "") return false;
51
- if (inferredPreviewHosts(policy.site).includes(h)) return true;
52
- if (policy.previewHosts !== undefined) return override.includes(h);
53
- return "cms";
54
- }
55
-
56
- /**
57
- * Whether the site declares its own preview hosts: in the `CMS` block, or as
58
- * `createCMS`'s `preview.hosts`. When it declares none, `cms.settings()`
59
- * reports blocks' default, every host (`["*"]`), which v7 never had: there,
60
- * a site without a list previewed only on its Deco hosts. The saved `CMS`
61
- * block tells an explicit `["*"]` from that default.
62
- */
63
- export async function declaresPreviewHosts(
64
- cms: Pick<CMS, "settings" | "forRelease">,
65
- ): Promise<boolean> {
66
- const { hosts } = (await cms.settings()).preview;
67
- if (hosts.length !== 1 || hosts[0] !== "*") return true;
68
- try {
69
- const [block] = await cms.forRelease().resolve<unknown>("CMS", { run: false });
70
- const preview = isRecord(block) ? block.preview : undefined;
71
- return isRecord(preview) && ("hosts" in preview || "__resolveType" in preview);
72
- } catch {
73
- return false;
74
- }
75
- }
76
-
77
- function isRecord(value: unknown): value is Record<string, unknown> {
78
- return typeof value === "object" && value !== null && !Array.isArray(value);
79
- }
80
-
81
21
  const DRAFT_OFF = "off";
82
22
 
83
23
  function draftParam(url: URL): string | null {
@@ -99,16 +39,16 @@ function readCookie(header: string | null, name: string): string | null {
99
39
  }
100
40
 
101
41
  /**
102
- * The pointer a request carries, as `@decocms/blocks` reads it: `?__draft=`
103
- * first, then the draft cookie; `null` for `?__draft=off` and for a value
104
- * that doesn't parse.
42
+ * What a request's Studio link asks for, as `@decocms/blocks` reads it:
43
+ * `?__draft=` first, then the draft cookie; `null` for `?__draft=off` and
44
+ * for a value that doesn't parse.
105
45
  */
106
- export function readDraftPointer(request: Request): string | null {
46
+ export function readDraftVersion(request: Request): RequestVersion | null {
107
47
  const param = draftParam(new URL(request.url));
108
48
  if (param === DRAFT_OFF) return null;
109
- if (param && parseDraftPointer(param) !== null) return param;
110
- const cookie = readCookie(request.headers.get("cookie"), DRAFT_COOKIE);
111
- return cookie && parseDraftPointer(cookie) !== null ? cookie : null;
49
+ const fromLink = param ? parseVersion(param) : null;
50
+ if (fromLink !== null) return fromLink;
51
+ return parseVersion(readCookie(request.headers.get("cookie"), DRAFT_COOKIE));
112
52
  }
113
53
 
114
54
  function serializeCookie(value: string, extra: string[]): string {
@@ -125,33 +65,33 @@ function serializeCookie(value: string, extra: string[]): string {
125
65
  }
126
66
 
127
67
  export interface DraftDecision {
128
- /** The draft this request renders, after the host check; `null` for the release. */
129
- pointer: string | null;
130
- /** The `Set-Cookie` the response carries: storing a draft link's pointer, or ending a preview. */
68
+ /**
69
+ * What this request's Studio link asks for, after the host check: the
70
+ * version (a draft pointer, or a release's commit SHA) and the preview's
71
+ * moment and switched tests and campaigns, in the shape of
72
+ * `cms.client()`'s options; `null` for the current release.
73
+ */
74
+ version: RequestVersion | null;
75
+ /** The `Set-Cookie` the response carries: storing a link's version, or ending a preview. */
131
76
  setCookie: string | null;
132
77
  }
133
78
 
134
- /** The draft a request renders, and the cookie its response sets, under `policy`. */
79
+ /** The version a request renders, and the cookie its response sets. */
135
80
  export async function decideDraft(
136
- cms: Pick<CMS, "draftPointer" | "settings" | "forRelease">,
81
+ cms: Pick<CMS, "readVersion">,
137
82
  request: Request,
138
- policy: PreviewPolicy,
139
83
  ): Promise<DraftDecision> {
140
84
  const url = new URL(request.url);
141
85
  const param = draftParam(url);
142
86
  // Ending a preview is allowed on any host, so a cookie set earlier always goes.
143
- if (param === DRAFT_OFF) return { pointer: null, setCookie: serializeCookie("", ["Max-Age=0"]) };
144
- const pointer = readDraftPointer(request);
145
- if (pointer === null) return { pointer: null, setCookie: null };
146
- const decision = previewHostDecision(url.host, policy);
147
- const allowed =
148
- decision === "cms"
149
- ? (await declaresPreviewHosts(cms)) && (await cms.draftPointer(request)) !== null
150
- : decision;
151
- if (!allowed) return { pointer: null, setCookie: null };
152
- const fromLink = param !== null && param === pointer;
87
+ if (param === DRAFT_OFF) return { version: null, setCookie: serializeCookie("", ["Max-Age=0"]) };
88
+ const version = readDraftVersion(request);
89
+ if (version === null) return { version: null, setCookie: null };
90
+ if ((await cms.readVersion(request)) === null) return { version: null, setCookie: null };
91
+ // The link's own value goes in the cookie, its preview parameters with it.
92
+ const fromLink = param !== null && parseVersion(param) !== null;
153
93
  return {
154
- pointer,
155
- setCookie: fromLink ? serializeCookie(encodeURIComponent(pointer), []) : null,
94
+ version,
95
+ setCookie: fromLink ? serializeCookie(encodeURIComponent(param), []) : null,
156
96
  };
157
97
  }