@decocms/tanstack 8.1.0-next.0 → 8.4.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 (177) hide show
  1. package/README.md +79 -0
  2. package/dist/draft.d.ts +33 -0
  3. package/dist/draft.d.ts.map +1 -0
  4. package/dist/draft.js +41 -0
  5. package/dist/draft.js.map +1 -0
  6. package/dist/index.d.ts +9 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +9 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/react/DecoDocument.d.ts +61 -0
  11. package/dist/react/DecoDocument.d.ts.map +1 -0
  12. package/dist/react/DecoDocument.js +96 -0
  13. package/dist/react/DecoDocument.js.map +1 -0
  14. package/dist/react/Image.d.ts +96 -0
  15. package/dist/react/Image.d.ts.map +1 -0
  16. package/dist/react/Image.js +79 -0
  17. package/dist/react/Image.js.map +1 -0
  18. package/dist/react/index.d.ts +7 -0
  19. package/dist/react/index.d.ts.map +1 -0
  20. package/dist/react/index.js +7 -0
  21. package/dist/react/index.js.map +1 -0
  22. package/dist/react/pageValues.d.ts +10 -0
  23. package/dist/react/pageValues.d.ts.map +1 -0
  24. package/dist/react/pageValues.js +29 -0
  25. package/dist/react/pageValues.js.map +1 -0
  26. package/dist/react/scripts.d.ts +14 -0
  27. package/dist/react/scripts.d.ts.map +1 -0
  28. package/dist/react/scripts.js +96 -0
  29. package/dist/react/scripts.js.map +1 -0
  30. package/dist/router/index.d.ts +38 -0
  31. package/dist/router/index.d.ts.map +1 -0
  32. package/dist/router/index.js +60 -0
  33. package/dist/router/index.js.map +1 -0
  34. package/dist/scope/browser.d.ts +11 -0
  35. package/dist/scope/browser.d.ts.map +1 -0
  36. package/dist/scope/browser.js +8 -0
  37. package/dist/scope/browser.js.map +1 -0
  38. package/dist/scope/server.d.ts +13 -0
  39. package/dist/scope/server.d.ts.map +1 -0
  40. package/dist/scope/server.js +26 -0
  41. package/dist/scope/server.js.map +1 -0
  42. package/dist/server/index.d.ts +27 -0
  43. package/dist/server/index.d.ts.map +1 -0
  44. package/dist/server/index.js +31 -0
  45. package/dist/server/index.js.map +1 -0
  46. package/dist/shared.d.ts +26 -0
  47. package/dist/shared.d.ts.map +1 -0
  48. package/dist/shared.js +26 -0
  49. package/dist/shared.js.map +1 -0
  50. package/dist/start/index.d.ts +9 -0
  51. package/dist/start/index.d.ts.map +1 -0
  52. package/dist/start/index.js +33 -0
  53. package/dist/start/index.js.map +1 -0
  54. package/dist/studio.d.ts +28 -0
  55. package/dist/studio.d.ts.map +1 -0
  56. package/dist/studio.js +53 -0
  57. package/dist/studio.js.map +1 -0
  58. package/dist/vite/index.d.ts +15 -0
  59. package/dist/vite/index.d.ts.map +1 -0
  60. package/dist/vite/index.js +95 -0
  61. package/dist/vite/index.js.map +1 -0
  62. package/dist/worker/cacheProfiles.d.ts +43 -0
  63. package/dist/worker/cacheProfiles.d.ts.map +1 -0
  64. package/dist/worker/cacheProfiles.js +162 -0
  65. package/dist/worker/cacheProfiles.js.map +1 -0
  66. package/dist/worker/cookies.d.ts +20 -0
  67. package/dist/worker/cookies.d.ts.map +1 -0
  68. package/dist/worker/cookies.js +69 -0
  69. package/dist/worker/cookies.js.map +1 -0
  70. package/dist/worker/drafts.d.ts +59 -0
  71. package/dist/worker/drafts.d.ts.map +1 -0
  72. package/dist/worker/drafts.js +140 -0
  73. package/dist/worker/drafts.js.map +1 -0
  74. package/dist/worker/index.d.ts +107 -0
  75. package/dist/worker/index.d.ts.map +1 -0
  76. package/dist/worker/index.js +511 -0
  77. package/dist/worker/index.js.map +1 -0
  78. package/dist/worker/security.d.ts +14 -0
  79. package/dist/worker/security.d.ts.map +1 -0
  80. package/dist/worker/security.js +48 -0
  81. package/dist/worker/security.js.map +1 -0
  82. package/dist/worker/segment.d.ts +21 -0
  83. package/dist/worker/segment.d.ts.map +1 -0
  84. package/dist/worker/segment.js +43 -0
  85. package/dist/worker/segment.js.map +1 -0
  86. package/package.json +85 -37
  87. package/src/draft.ts +43 -0
  88. package/src/index.ts +8 -61
  89. package/src/react/DecoDocument.tsx +234 -0
  90. package/src/react/Image.tsx +213 -0
  91. package/src/react/index.ts +24 -0
  92. package/src/react/pageValues.ts +35 -0
  93. package/src/react/scripts.ts +98 -0
  94. package/src/router/index.ts +80 -0
  95. package/src/scope/browser.ts +18 -0
  96. package/src/scope/server.ts +37 -0
  97. package/src/server/index.ts +43 -0
  98. package/src/shared.ts +29 -0
  99. package/src/start/index.ts +31 -0
  100. package/src/studio.ts +52 -0
  101. package/src/vite/index.ts +105 -0
  102. package/src/worker/cacheProfiles.ts +180 -0
  103. package/src/worker/cookies.ts +65 -0
  104. package/src/worker/drafts.ts +157 -0
  105. package/src/worker/index.ts +648 -0
  106. package/src/worker/security.ts +63 -0
  107. package/src/worker/segment.ts +49 -0
  108. package/src/__conformance__/observability.test.ts +0 -221
  109. package/src/cms/kvBlockSource.test.ts +0 -82
  110. package/src/cms/kvBlockSource.ts +0 -68
  111. package/src/daemon/auth.ts +0 -204
  112. package/src/daemon/fs.ts +0 -238
  113. package/src/daemon/index.ts +0 -8
  114. package/src/daemon/middleware.ts +0 -156
  115. package/src/daemon/tunnel.ts +0 -129
  116. package/src/daemon/volumes.ts +0 -366
  117. package/src/daemon/watch.ts +0 -272
  118. package/src/hooks/CdnSegmentMarker.tsx +0 -38
  119. package/src/hooks/DecoPageRenderer.tsx +0 -750
  120. package/src/hooks/DecoRootLayout.tsx +0 -192
  121. package/src/hooks/DraftPreviewIndicator.test.tsx +0 -60
  122. package/src/hooks/DraftPreviewIndicator.tsx +0 -64
  123. package/src/hooks/NavigationProgress.test.tsx +0 -58
  124. package/src/hooks/NavigationProgress.tsx +0 -63
  125. package/src/hooks/PreviewProviders.test.tsx +0 -42
  126. package/src/hooks/PreviewProviders.tsx +0 -45
  127. package/src/hooks/StableOutlet.tsx +0 -30
  128. package/src/hooks/deferredObserverTiming.test.tsx +0 -91
  129. package/src/hooks/index.ts +0 -10
  130. package/src/routes/adminRoutes.test.ts +0 -99
  131. package/src/routes/adminRoutes.ts +0 -153
  132. package/src/routes/cmsRoute.test.ts +0 -267
  133. package/src/routes/cmsRoute.ts +0 -1053
  134. package/src/routes/components.tsx +0 -57
  135. package/src/routes/index.ts +0 -24
  136. package/src/routes/pageUrl.test.ts +0 -70
  137. package/src/routes/pageUrl.ts +0 -55
  138. package/src/routes/withSiteGlobals.test.ts +0 -243
  139. package/src/routes/withSiteGlobals.ts +0 -243
  140. package/src/sdk/backgroundTasks.test.ts +0 -68
  141. package/src/sdk/backgroundTasks.ts +0 -38
  142. package/src/sdk/cdnSegment.test.ts +0 -67
  143. package/src/sdk/cdnSegment.ts +0 -71
  144. package/src/sdk/cookiePassthrough.ts +0 -58
  145. package/src/sdk/createInvoke.ts +0 -77
  146. package/src/sdk/deferredSectionLoader.test.ts +0 -94
  147. package/src/sdk/deferredSectionLoader.ts +0 -46
  148. package/src/sdk/draft.test.ts +0 -341
  149. package/src/sdk/draft.ts +0 -277
  150. package/src/sdk/draftShared.ts +0 -16
  151. package/src/sdk/kvHydration.test.ts +0 -371
  152. package/src/sdk/kvHydration.ts +0 -263
  153. package/src/sdk/kvRedirects.test.ts +0 -132
  154. package/src/sdk/kvRedirects.ts +0 -125
  155. package/src/sdk/outboundHeaders.test.ts +0 -113
  156. package/src/sdk/outboundHeaders.ts +0 -81
  157. package/src/sdk/router.ts +0 -101
  158. package/src/sdk/serverFnFetch.ts +0 -59
  159. package/src/sdk/speculationRules.test.ts +0 -82
  160. package/src/sdk/speculationRules.ts +0 -136
  161. package/src/sdk/startEntry.ts +0 -31
  162. package/src/sdk/useHydrated.ts +0 -19
  163. package/src/sdk/workerEntry.cacheStorage.test.ts +0 -147
  164. package/src/sdk/workerEntry.test.ts +0 -1033
  165. package/src/sdk/workerEntry.trackingCache.test.ts +0 -328
  166. package/src/sdk/workerEntry.ts +0 -3154
  167. package/src/setupFastDeploy.ts +0 -13
  168. package/src/v8/__conformance__/delivery.test.ts +0 -100
  169. package/src/v8/binding.ts +0 -70
  170. package/src/v8/kvLoader.bundle.test.ts +0 -42
  171. package/src/v8/kvLoader.test.ts +0 -74
  172. package/src/v8/kvLoader.ts +0 -43
  173. package/src/vite/plugin-scaffold-gen.test.js +0 -106
  174. package/src/vite/plugin.js +0 -1022
  175. package/src/vite/plugin.test.js +0 -238
  176. package/src/vite/plugin.test.ts +0 -176
  177. package/tsconfig.json +0 -7
package/src/sdk/draft.ts DELETED
@@ -1,277 +0,0 @@
1
- /**
2
- * Draft preview — the TanStack Start / Cloudflare Workers binding.
3
- *
4
- * `@decocms/blocks`'s `draftSource` owns the framework-agnostic half (token
5
- * parsing, origin validation, fetch, version cache, the host allowlist). This
6
- * file binds a resolved draft to the current request and drives the cookie +
7
- * cache/indexing headers.
8
- *
9
- * ## Why this is simpler than the Next.js binding
10
- *
11
- * The Next binding (`@decocms/nextjs`'s `draft.ts`/`draftMiddleware.ts`) fights
12
- * two App Router constraints that do NOT exist here:
13
- *
14
- * 1. **Request scope.** App Router never enters an AsyncLocalStorage request
15
- * scope, so Next backs the per-request draft slot with React `cache()` and
16
- * has to await `ensureDraft` from the *page* (a layout's await does not gate
17
- * its children). TanStack already wraps every request in
18
- * `RequestContext.run(request, …)` (see `workerEntry.ts`), so the draft just
19
- * rides the request bag — `loadBlocks()` reads it back through the
20
- * dependency-injected getter registered by {@link registerDraftOverride}.
21
- *
22
- * 2. **Static-vs-dynamic rewrite.** `dynamic`/`revalidate` are static route
23
- * exports in App Router, so Next rewrites drafted requests onto an
24
- * encoded `app/%5Fdraft/…` route to escape ISR. The worker decides
25
- * cacheability per request, so a drafted request simply bypasses the edge
26
- * cache (see `requestCarriesDraft`) — no rewrite dance.
27
- *
28
- * Like Next, the whole feature is inert unless the site opts in: an allowlist
29
- * (the site block's `previewHosts`, or the `DECO_ALLOWED_PREVIEW_HOSTS`
30
- * override) must name the request's host. Upgrading the package can never be
31
- * enough to start rendering unpublished content.
32
- */
33
-
34
- import {
35
- DRAFT_COOKIE_NAME,
36
- DRAFT_QUERY_PARAM,
37
- isDraftHostAllowed,
38
- isDraftPreviewEnabled,
39
- resolveDraftForRequest,
40
- setDecoSiteHost,
41
- setDraftOverrideGetter,
42
- setDraftPreviewHosts,
43
- } from "@decocms/blocks/cms";
44
- import { RequestContext } from "@decocms/blocks/sdk/requestContext";
45
- import { DRAFT_POINTER_BAG_KEY } from "./draftShared";
46
-
47
- /** RequestContext bag key the resolved draft decofile is stashed under. */
48
- const DRAFT_BAG_KEY = "deco:draftBlocks";
49
-
50
- /**
51
- * Cookie lifetime. Short on purpose: a preview session is minutes, and a stale
52
- * pointer would keep pinning an old content version. Matches the Next binding.
53
- */
54
- const DRAFT_COOKIE_MAX_AGE = 60 * 30;
55
-
56
- // ---------------------------------------------------------------------------
57
- // Runtime binding (dependency injection into @decocms/blocks)
58
- // ---------------------------------------------------------------------------
59
-
60
- let registered = false;
61
-
62
- /**
63
- * Register the request-scoped draft getter with the runtime, once.
64
- *
65
- * `loadBlocks()` consults `getRequestDraftOverride()` as a fallback after its
66
- * own `withBlocksOverride` scope; this points that fallback at the
67
- * RequestContext bag {@link bindRequestDraft} fills. Idempotent and safe to
68
- * call at setup: outside a request scope `getBag` returns undefined, so
69
- * `loadBlocks()` behaves exactly as before.
70
- */
71
- export function registerDraftOverride(): void {
72
- if (registered) return;
73
- registered = true;
74
- setDraftOverrideGetter(
75
- () => RequestContext.getBag<Record<string, unknown>>(DRAFT_BAG_KEY) ?? null,
76
- );
77
- }
78
-
79
- /**
80
- * Install the site block's `previewHosts` as the draft-preview allowlist.
81
- *
82
- * Reads the BASE blocks (the `setBlocks()` argument / `loadBlocks()` at setup
83
- * time), never the request-time merged blocks: an allowlist readable through
84
- * the draft override could be rewritten by the very draft it gates.
85
- * `DECO_ALLOWED_PREVIEW_HOSTS` remains an operational override that replaces
86
- * this list when set. Handles both decofile shapes (`site` / `Site`), same as
87
- * `withSiteGlobals`.
88
- */
89
- export function installPreviewHostsFromBlocks(blocks: Record<string, unknown> | undefined): void {
90
- const site = (blocks?.site ?? blocks?.Site) as { previewHosts?: unknown } | undefined;
91
- if (Array.isArray(site?.previewHosts)) setDraftPreviewHosts(site.previewHosts);
92
- }
93
-
94
- /**
95
- * Register the deco-operated preview hosts inferred from the site name —
96
- * `<site>.deco.site` and `<site>.deco-cx.workers.dev` (the workers.dev deploy
97
- * URL, e.g. `acme-tanstack.deco-cx.workers.dev`) — so a signed
98
- * `?__draft=` grant previews on deco-hosted infra with zero per-site config.
99
- *
100
- * Fed from the Workers env binding `DECO_SITE_NAME`: deploy-time configuration
101
- * set by deco's hosting, trusted the same way `DECO_ALLOWED_PREVIEW_HOSTS` is —
102
- * never derived from the request. Merged ON TOP of the site block/env list
103
- * (see `setDecoSiteHost` in `@decocms/blocks`); an unset binding registers
104
- * nothing, and `DECO_ALLOWED_PREVIEW_HOSTS=none` kills the inferred hosts too.
105
- *
106
- * This inference is deliberately tanstack-only (like Fast Deploy): the
107
- * deco-operated domains only ever serve Workers deployments, and in the Next
108
- * binding flipping `isDraftPreviewEnabled()` on costs every page its
109
- * static/ISR rendering — Next sites keep the explicit opt-in.
110
- */
111
- export function installDecoSiteHostFromEnv(env: Record<string, unknown>): void {
112
- const site = env.DECO_SITE_NAME;
113
- setDecoSiteHost(typeof site === "string" ? site : undefined);
114
- }
115
-
116
- // ---------------------------------------------------------------------------
117
- // Per-request resolution + response decoration
118
- // ---------------------------------------------------------------------------
119
-
120
- /**
121
- * Read one cookie value out of a raw `Cookie:` header.
122
- *
123
- * Decodes the value — the cookie is written with `encodeURIComponent` (see
124
- * `draftCookie`), and `@decocms/blocks`'s own cookie reader decodes too, so a
125
- * cookie-carried pointer must round-trip identically or the badge's share link
126
- * would double-encode it. Decode defensively: a malformed `%` sequence
127
- * (a crafted cookie) falls back to the raw value rather than throwing and
128
- * 500-ing the request.
129
- */
130
- function readCookie(cookieHeader: string | null, name: string): string | null {
131
- if (!cookieHeader) return null;
132
- for (const part of cookieHeader.split(";")) {
133
- const eq = part.indexOf("=");
134
- if (eq === -1) continue;
135
- if (part.slice(0, eq).trim() === name) {
136
- const raw = part.slice(eq + 1).trim();
137
- try {
138
- return decodeURIComponent(raw);
139
- } catch {
140
- return raw;
141
- }
142
- }
143
- }
144
- return null;
145
- }
146
-
147
- /**
148
- * Whether a request is in draft mode — carries a live `?__draft=` param or the
149
- * navigation cookie — on a host allowed to preview.
150
- *
151
- * A pure, synchronous, network-free check (no fetch, no resolve): the worker
152
- * uses it to keep drafted requests out of the shared edge cache *before* doing
153
- * any work. Gated on `isDraftPreviewEnabled()` first, so a build without the
154
- * allowlist configured is completely unaffected — a stray `?__draft=` on a
155
- * production domain neither renders a draft nor even bypasses the cache.
156
- */
157
- export function requestCarriesDraft(request: Request, url: URL): boolean {
158
- if (!isDraftPreviewEnabled()) return false;
159
- const host = request.headers.get("x-forwarded-host") ?? request.headers.get("host");
160
- if (!isDraftHostAllowed(host)) return false;
161
- const param = url.searchParams.get(DRAFT_QUERY_PARAM);
162
- if (param === "off") return false;
163
- if (param) return true;
164
- return readCookie(request.headers.get("cookie"), DRAFT_COOKIE_NAME) !== null;
165
- }
166
-
167
- /** The cookie/header actions a drafted request implies for its response. */
168
- export interface DraftDecision {
169
- /**
170
- * The request is previewing (a pointer is present on an allowed host), so its
171
- * response must never be cached under the shared (cookie-only) URL — even if
172
- * the draft failed to resolve and the page fell back to published content.
173
- */
174
- previewing: boolean;
175
- /** Persist this pointer in the navigation cookie (set only on `?__draft=` entry). */
176
- setCookie: string | null;
177
- /** Clear the navigation cookie (`?__draft=off`). */
178
- clearCookie: boolean;
179
- }
180
-
181
- const INERT: DraftDecision = { previewing: false, setCookie: null, clearCookie: false };
182
-
183
- /**
184
- * Resolve this request's draft, if any, and bind it to the RequestContext so
185
- * every `loadBlocks()` in the render sees the merged decofile.
186
- *
187
- * Call inside `RequestContext.run`, before the page render. Returns the
188
- * cookie/header decision for the worker to apply to the final response. A
189
- * missing allowlist, disallowed host, or `?__draft=off` all short-circuit
190
- * without touching the network; a resolve failure degrades to published but
191
- * still reports `previewing: true` so the response stays uncacheable.
192
- */
193
- export async function bindRequestDraft(
194
- request: Request,
195
- fetchImpl?: typeof fetch,
196
- ): Promise<DraftDecision> {
197
- if (!isDraftPreviewEnabled()) return INERT;
198
-
199
- const url = new URL(request.url);
200
- const host = request.headers.get("x-forwarded-host") ?? request.headers.get("host");
201
- // Authoritative host gate — unlike Next, there is no separate middleware
202
- // module graph, so this single check bounds the whole feature.
203
- if (!isDraftHostAllowed(host)) return INERT;
204
-
205
- const param = url.searchParams.get(DRAFT_QUERY_PARAM);
206
- if (param === "off") return { previewing: false, setCookie: null, clearCookie: true };
207
-
208
- const cookie = readCookie(request.headers.get("cookie"), DRAFT_COOKIE_NAME);
209
- const pointer = param ?? cookie ?? null;
210
- if (!pointer) return INERT;
211
-
212
- const blocks = await resolveDraftForRequest(request, { fetchImpl });
213
- if (blocks) {
214
- RequestContext.setBag(DRAFT_BAG_KEY, blocks);
215
- // Expose the pointer to the SSR React tree so the preview badge can render
216
- // and build its share/exit links. Only when the draft actually bound —
217
- // the badge means "you're looking at draft content", matching Next.
218
- RequestContext.setBag(DRAFT_POINTER_BAG_KEY, pointer);
219
- }
220
-
221
- // Persist only on entry (`?__draft=`); in-preview navigation rides the cookie
222
- // already present.
223
- return { previewing: true, setCookie: param ?? null, clearCookie: false };
224
- }
225
-
226
- /** Build the `Set-Cookie` value for the draft navigation cookie. */
227
- function draftCookie(value: string, maxAge: number): string {
228
- // SameSite=None; Secure is mandatory for the cross-site preview iframe, and
229
- // Partitioned (CHIPS) keeps it working as browsers wind down unpartitioned
230
- // third-party cookies. HttpOnly: the pointer is read server-side only.
231
- return `${DRAFT_COOKIE_NAME}=${value}; Path=/; Max-Age=${maxAge}; HttpOnly; Secure; SameSite=None; Partitioned`;
232
- }
233
-
234
- /** Set a header defensively — some replayed responses seal their headers. */
235
- function trySet(response: Response, key: string, value: string): void {
236
- try {
237
- response.headers.set(key, value);
238
- } catch {
239
- /* sealed headers (cached replay) — best-effort */
240
- }
241
- }
242
-
243
- /**
244
- * Apply the cookie lifecycle and the cache/indexing headers a draft response
245
- * requires.
246
- *
247
- * The caching headers are the difference between a preview and a leak: with the
248
- * pointer in a cookie, a drafted response and a published one share an
249
- * identical URL, so `no-store` is what stops a CDN keyed on URL alone from
250
- * serving unpublished content to a real visitor. `Vary: Cookie` keeps any
251
- * intermediary that does respect it from mixing the two; `X-Robots-Tag` keeps a
252
- * leaked draft out of search results.
253
- */
254
- export function applyDraftCookieAndHeaders(response: Response, decision: DraftDecision): void {
255
- if (decision.clearCookie) {
256
- response.headers.append("set-cookie", draftCookie("", 0));
257
- } else if (decision.setCookie) {
258
- response.headers.append(
259
- "set-cookie",
260
- draftCookie(encodeURIComponent(decision.setCookie), DRAFT_COOKIE_MAX_AGE),
261
- );
262
- }
263
-
264
- if (decision.previewing) {
265
- trySet(response, "cache-control", "no-store, private");
266
- // Add Cookie to Vary without dropping tokens already there (e.g.
267
- // Accept-Encoding). Moot under no-store, but correct for any intermediary
268
- // that honours Vary anyway.
269
- const existingVary = response.headers.get("vary");
270
- if (!existingVary) {
271
- trySet(response, "vary", "Cookie");
272
- } else if (!/\bcookie\b/i.test(existingVary)) {
273
- trySet(response, "vary", `${existingVary}, Cookie`);
274
- }
275
- trySet(response, "x-robots-tag", "noindex, nofollow");
276
- }
277
- }
@@ -1,16 +0,0 @@
1
- /**
2
- * Client-bundle-safe constants shared by the server-side draft binding
3
- * (`./draft`, which imports the server-only `@decocms/blocks/cms`) and the
4
- * isomorphic preview-badge indicator (`../hooks/DraftPreviewIndicator`, which
5
- * must stay client-safe). Kept in their own module so the indicator never has
6
- * to import `./draft` and drag `node:async_hooks` into the browser bundle.
7
- */
8
-
9
- /** RequestContext bag key the active draft pointer is stashed under during SSR. */
10
- export const DRAFT_POINTER_BAG_KEY = "deco:draftPointer";
11
-
12
- /**
13
- * Global the SSR pass publishes the pointer on, so the client's hydration
14
- * render reads the same value (RequestContext is a no-op stub in the browser).
15
- */
16
- export const DRAFT_POINTER_GLOBAL = "__DECO_DRAFT_POINTER__";
@@ -1,371 +0,0 @@
1
- import { beforeEach, describe, expect, it, vi } from "vitest";
2
- import {
3
- computeRevision,
4
- getRevision,
5
- type KVNamespace,
6
- loadBlocks,
7
- revisionKey,
8
- setBlocks,
9
- snapshotKey,
10
- } from "@decocms/blocks/cms";
11
- import {
12
- __resetKvHydrationStateForTests,
13
- ensureBlocksHydrated,
14
- getDeploymentId,
15
- isFastDeployEnabled,
16
- maybePollRevision,
17
- } from "./kvHydration";
18
-
19
- const BUNDLED = { Site: { name: "bundled" } };
20
-
21
- /** Deployment id used across the hydration tests. */
22
- const ID = "sha-deadbeef";
23
- const SNAP = snapshotKey(ID);
24
- const REV = revisionKey(ID);
25
-
26
- /** KV stub that counts get() calls so we can assert throttling / single-load. */
27
- function makeKV(initial: Record<string, string> = {}) {
28
- const store = new Map<string, string>(Object.entries(initial));
29
- let getCalls = 0;
30
- const kv: KVNamespace = {
31
- get: (k) => {
32
- getCalls++;
33
- return Promise.resolve(store.get(k) ?? null);
34
- },
35
- put: (k, v) => {
36
- store.set(k, v);
37
- return Promise.resolve();
38
- },
39
- delete: (k) => {
40
- store.delete(k);
41
- return Promise.resolve();
42
- },
43
- };
44
- return { kv, store, getCalls: () => getCalls };
45
- }
46
-
47
- function snapshotEnv(blocks: Record<string, unknown>, extra: Record<string, unknown> = {}) {
48
- const { kv, ...rest } = makeKV({
49
- [SNAP]: JSON.stringify(blocks),
50
- [REV]: computeRevision(blocks),
51
- });
52
- // DECO_FAST_DEPLOY="1" is the explicit opt-in required alongside the binding;
53
- // DECO_DEPLOYMENT_ID scopes the read to this deployment's keyed snapshot.
54
- return {
55
- env: { DECO_KV: kv, DECO_FAST_DEPLOY: "1", DECO_DEPLOYMENT_ID: ID, ...extra },
56
- kv,
57
- ...rest,
58
- };
59
- }
60
-
61
- /** Collects ctx.waitUntil promises so tests can await background polls. */
62
- function makeCtx() {
63
- const promises: Promise<unknown>[] = [];
64
- return {
65
- ctx: { waitUntil: (p: Promise<unknown>) => promises.push(p) },
66
- settle: () => Promise.allSettled(promises),
67
- };
68
- }
69
-
70
- beforeEach(() => {
71
- __resetKvHydrationStateForTests();
72
- setBlocks({ ...BUNDLED }); // reset in-memory decofile to a known bundled state
73
- vi.restoreAllMocks();
74
- });
75
-
76
- describe("isFastDeployEnabled", () => {
77
- it("is false without a KV binding even when the flag is set", () => {
78
- expect(isFastDeployEnabled({ DECO_FAST_DEPLOY: "1" })).toBe(false);
79
- });
80
-
81
- it("is false when a non-KV value is named DECO_KV", () => {
82
- expect(isFastDeployEnabled({ DECO_KV: "some-secret-string", DECO_FAST_DEPLOY: "1" })).toBe(false);
83
- });
84
-
85
- it("is false when bound but DECO_FAST_DEPLOY is not set (explicit opt-in required)", () => {
86
- const { kv } = makeKV();
87
- expect(isFastDeployEnabled({ DECO_KV: kv })).toBe(false);
88
- });
89
-
90
- it("is true when bound AND DECO_FAST_DEPLOY=1", () => {
91
- const { kv } = makeKV();
92
- expect(isFastDeployEnabled({ DECO_KV: kv, DECO_FAST_DEPLOY: "1" })).toBe(true);
93
- });
94
-
95
- it("accepts DECO_FAST_DEPLOY=true as well", () => {
96
- const { kv } = makeKV();
97
- expect(isFastDeployEnabled({ DECO_KV: kv, DECO_FAST_DEPLOY: "true" })).toBe(true);
98
- });
99
-
100
- it("is false when DECO_FAST_DEPLOY=0 even if bound", () => {
101
- const { kv } = makeKV();
102
- expect(isFastDeployEnabled({ DECO_KV: kv, DECO_FAST_DEPLOY: "0" })).toBe(false);
103
- });
104
- });
105
-
106
- describe("ensureBlocksHydrated", () => {
107
- it("is a no-op when fast-deploy is disabled (keeps bundled blocks)", async () => {
108
- await ensureBlocksHydrated({});
109
- expect(loadBlocks()).toEqual(BUNDLED);
110
- });
111
-
112
- it("swaps the in-memory decofile with the KV snapshot", async () => {
113
- const kvBlocks = { Site: { name: "from-kv" }, "pages-home": { path: "/" } };
114
- const { env } = snapshotEnv(kvBlocks);
115
- await ensureBlocksHydrated(env);
116
- expect(loadBlocks()).toEqual(kvBlocks);
117
- expect(getRevision()).toBe(computeRevision(kvBlocks));
118
- });
119
-
120
- it("loads only once even across concurrent first requests", async () => {
121
- const kvBlocks = { Site: { name: "from-kv" } };
122
- const { env, getCalls } = snapshotEnv(kvBlocks);
123
- await Promise.all([
124
- ensureBlocksHydrated(env),
125
- ensureBlocksHydrated(env),
126
- ensureBlocksHydrated(env),
127
- ]);
128
- // SNAPSHOT + REVISION = 2 gets for a single load (not 6).
129
- expect(getCalls()).toBe(2);
130
- });
131
-
132
- it("keeps the bundled snapshot when this deployment's snapshot key is absent", async () => {
133
- const { kv } = makeKV({ [REV]: "r" }); // revision present, but no SNAPSHOT
134
- await ensureBlocksHydrated({ DECO_KV: kv, DECO_FAST_DEPLOY: "1", DECO_DEPLOYMENT_ID: ID });
135
- expect(loadBlocks()).toEqual(BUNDLED);
136
- });
137
-
138
- it("keeps bundled (never touches KV) when no deployment id resolves", async () => {
139
- const kvBlocks = { Site: { name: "from-kv" } };
140
- const { kv, getCalls } = makeKV({ [SNAP]: JSON.stringify(kvBlocks) });
141
- // Fast-deploy enabled + bound, but no DECO_DEPLOYMENT_ID / BUILD_HASH.
142
- await ensureBlocksHydrated({ DECO_KV: kv, DECO_FAST_DEPLOY: "1" });
143
- expect(loadBlocks()).toEqual(BUNDLED);
144
- expect(getCalls()).toBe(0);
145
- });
146
-
147
- it("falls back to bundled (and does not throw) when KV errors", async () => {
148
- const kv: KVNamespace = {
149
- get: () => Promise.reject(new Error("KV down")),
150
- put: () => Promise.resolve(),
151
- delete: () => Promise.resolve(),
152
- };
153
- vi.spyOn(console, "warn").mockImplementation(() => {});
154
- await expect(
155
- ensureBlocksHydrated({ DECO_KV: kv, DECO_FAST_DEPLOY: "1", DECO_DEPLOYMENT_ID: ID }),
156
- ).resolves.toBeUndefined();
157
- expect(loadBlocks()).toEqual(BUNDLED);
158
- });
159
- });
160
-
161
- describe("getDeploymentId", () => {
162
- it("prefers DECO_DEPLOYMENT_ID", () => {
163
- expect(getDeploymentId({ DECO_DEPLOYMENT_ID: "a", BUILD_HASH: "b" })).toBe("a");
164
- });
165
-
166
- it("falls back to BUILD_HASH", () => {
167
- expect(getDeploymentId({ BUILD_HASH: "b" })).toBe("b");
168
- });
169
-
170
- it("is null when nothing resolves", () => {
171
- expect(getDeploymentId({})).toBeNull();
172
- });
173
- });
174
-
175
- describe("maybePollRevision", () => {
176
- it("is a no-op before cold-start hydration has run", async () => {
177
- const { env, getCalls } = snapshotEnv({ Site: { name: "x" } });
178
- const { ctx, settle } = makeCtx();
179
- maybePollRevision(env, ctx); // kvHydrated is false
180
- await settle();
181
- expect(getCalls()).toBe(0);
182
- });
183
-
184
- it("reloads the decofile when the KV revision changed", async () => {
185
- const initial = { Site: { name: "v1" } };
186
- const { env, store } = snapshotEnv(initial);
187
- await ensureBlocksHydrated(env);
188
- expect(loadBlocks()).toEqual(initial);
189
-
190
- // Simulate a publish from another isolate: KV now holds v2.
191
- const updated = { Site: { name: "v2" }, "pages-x": { path: "/x" } };
192
- store.set(SNAP, JSON.stringify(updated));
193
- store.set(REV, computeRevision(updated));
194
-
195
- const { ctx, settle } = makeCtx();
196
- maybePollRevision(env, ctx);
197
- await settle();
198
- expect(loadBlocks()).toEqual(updated);
199
- });
200
-
201
- it("throttles to one probe per interval", async () => {
202
- const { env, getCalls } = snapshotEnv({ Site: { name: "x" } });
203
- await ensureBlocksHydrated(env);
204
- const callsAfterHydrate = getCalls();
205
-
206
- const { ctx, settle } = makeCtx();
207
- maybePollRevision(env, ctx); // fires (revision unchanged → 1 get)
208
- maybePollRevision(env, ctx); // throttled → no get
209
- maybePollRevision(env, ctx); // throttled → no get
210
- await settle();
211
-
212
- // Exactly one extra getRevision() beyond the hydrate calls.
213
- expect(getCalls()).toBe(callsAfterHydrate + 1);
214
- });
215
- });
216
-
217
- // ---------------------------------------------------------------------------
218
- // Bundles that ship no decofile (`decoVitePlugin({ fastDeploy: true })`)
219
- //
220
- // With the decofile stubbed out of the server bundle, KV is the ONLY source of
221
- // content. The "warn and serve bundled" recovery would serve an EMPTY site —
222
- // 200s with no pages, which get edge-cached and outlive the KV failure that
223
- // caused them. These assert it fails loudly instead.
224
- //
225
- // The signal is the build-time `__DECO_BLOCKS_STUBBED__` define, NOT an empty
226
- // in-memory map: draft overrides can make a stubbed bundle look populated, and
227
- // a legitimately-empty decofile would look stubbed. Both are covered below.
228
- // ---------------------------------------------------------------------------
229
- declare global {
230
- // eslint-disable-next-line no-var
231
- var __DECO_BLOCKS_STUBBED__: boolean | undefined;
232
- }
233
-
234
- /** Simulates a build made with `fastDeploy: true`. */
235
- function withStubbedBundle() {
236
- globalThis.__DECO_BLOCKS_STUBBED__ = true;
237
- }
238
-
239
- describe("ensureBlocksHydrated when the bundle ships no decofile", () => {
240
- beforeEach(() => {
241
- globalThis.__DECO_BLOCKS_STUBBED__ = undefined;
242
- });
243
-
244
- it("throws when the snapshot is missing instead of serving an empty site", async () => {
245
- withStubbedBundle();
246
- setBlocks({});
247
- const { kv } = makeKV(); // no decofile:<id> seeded
248
- const env = { DECO_KV: kv, DECO_FAST_DEPLOY: "1", DECO_DEPLOYMENT_ID: ID };
249
-
250
- await expect(ensureBlocksHydrated(env)).rejects.toThrow(/not found and this bundle ships no/);
251
- });
252
-
253
- it("throws when fast-deploy is off at runtime instead of serving {}", async () => {
254
- withStubbedBundle();
255
- setBlocks({});
256
- const { kv } = makeKV();
257
-
258
- await expect(ensureBlocksHydrated({})).rejects.toThrow(/fast-deploy is off/);
259
- await expect(ensureBlocksHydrated({ DECO_KV: kv })).rejects.toThrow(/fast-deploy is off/);
260
- });
261
-
262
- it("throws when the snapshot exists but is empty", async () => {
263
- // A seed that wrote `{}` would otherwise take the success branch, latch,
264
- // and serve the empty edge-cached site this guard exists to prevent.
265
- withStubbedBundle();
266
- setBlocks({});
267
- const { kv } = makeKV({ [SNAP]: "{}", [REV]: computeRevision({}) });
268
-
269
- await expect(
270
- ensureBlocksHydrated({ DECO_KV: kv, DECO_FAST_DEPLOY: "1", DECO_DEPLOYMENT_ID: ID }),
271
- ).rejects.toThrow(/is empty and this bundle ships no/);
272
- });
273
-
274
- it("throws when KV itself fails", async () => {
275
- withStubbedBundle();
276
- setBlocks({});
277
- const kv = {
278
- get: () => Promise.reject(new Error("KV unreachable")),
279
- put: () => Promise.resolve(),
280
- delete: () => Promise.resolve(),
281
- } as unknown as KVNamespace;
282
-
283
- await expect(
284
- ensureBlocksHydrated({ DECO_KV: kv, DECO_FAST_DEPLOY: "1", DECO_DEPLOYMENT_ID: ID }),
285
- ).rejects.toThrow(/KV unreachable/);
286
- });
287
-
288
- it("throws when no deployment id resolves", async () => {
289
- withStubbedBundle();
290
- setBlocks({});
291
- const { kv } = makeKV();
292
-
293
- await expect(ensureBlocksHydrated({ DECO_KV: kv, DECO_FAST_DEPLOY: "1" })).rejects.toThrow(
294
- /no deployment id/,
295
- );
296
- });
297
-
298
- it("is not rescued by a populated in-memory map (draft-preview overrides)", async () => {
299
- // `bindRequestDraft` composes overrides into loadBlocks() BEFORE hydration.
300
- // Inferring "has a fallback" from the map would latch here and then serve
301
- // the empty base decofile for the isolate's life.
302
- withStubbedBundle();
303
- setBlocks({ "pages-Draft": { name: "override" } });
304
- const { kv } = makeKV();
305
-
306
- await expect(
307
- ensureBlocksHydrated({ DECO_KV: kv, DECO_FAST_DEPLOY: "1", DECO_DEPLOYMENT_ID: ID }),
308
- ).rejects.toThrow(/not found and this bundle ships no/);
309
- });
310
-
311
- it("does not latch hydration on the fatal path, so the next request retries", async () => {
312
- withStubbedBundle();
313
- setBlocks({});
314
- const blocks = { Site: { name: "from-kv" } };
315
- const store = new Map<string, string>();
316
- const kv: KVNamespace = {
317
- get: (k) => Promise.resolve(store.get(k) ?? null),
318
- put: (k, v) => {
319
- store.set(k, v);
320
- return Promise.resolve();
321
- },
322
- delete: (k) => {
323
- store.delete(k);
324
- return Promise.resolve();
325
- },
326
- };
327
- const env = { DECO_KV: kv, DECO_FAST_DEPLOY: "1", DECO_DEPLOYMENT_ID: ID };
328
-
329
- // First request: snapshot absent → fatal.
330
- await expect(ensureBlocksHydrated(env)).rejects.toThrow();
331
-
332
- // Operator seeds it; the isolate must pick it up rather than stay empty.
333
- store.set(SNAP, JSON.stringify(blocks));
334
- store.set(REV, computeRevision(blocks));
335
-
336
- await expect(ensureBlocksHydrated(env)).resolves.toBeUndefined();
337
- expect(loadBlocks()).toEqual(blocks);
338
- });
339
- });
340
-
341
- describe("ensureBlocksHydrated when the bundle DOES ship a decofile (default)", () => {
342
- beforeEach(() => {
343
- globalThis.__DECO_BLOCKS_STUBBED__ = undefined;
344
- });
345
-
346
- it("warns and serves bundled when KV fails", async () => {
347
- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
348
- const kv = {
349
- get: () => Promise.reject(new Error("KV unreachable")),
350
- put: () => Promise.resolve(),
351
- delete: () => Promise.resolve(),
352
- } as unknown as KVNamespace;
353
-
354
- await expect(
355
- ensureBlocksHydrated({ DECO_KV: kv, DECO_FAST_DEPLOY: "1", DECO_DEPLOYMENT_ID: ID }),
356
- ).resolves.toBeUndefined();
357
- expect(loadBlocks()).toEqual(BUNDLED);
358
- expect(warn).toHaveBeenCalled();
359
- });
360
-
361
- it("does not 5xx a site whose bundled decofile is legitimately empty", async () => {
362
- // New site / missing blocks.gen.json. Before the build-time flag this
363
- // looked identical to a stubbed bundle and started failing requests.
364
- setBlocks({});
365
- const { kv } = makeKV(); // no snapshot seeded either
366
-
367
- await expect(
368
- ensureBlocksHydrated({ DECO_KV: kv, DECO_FAST_DEPLOY: "1", DECO_DEPLOYMENT_ID: ID }),
369
- ).resolves.toBeUndefined();
370
- });
371
- });