@decocms/tanstack 8.1.0-next.0 → 8.5.1

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 +111 -0
  75. package/dist/worker/index.d.ts.map +1 -0
  76. package/dist/worker/index.js +618 -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 +784 -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
@@ -1,243 +0,0 @@
1
- /**
2
- * Site Globals Wrapper
3
- *
4
- * Opt-in helper that merges sections declared in the CMS `Site` block
5
- * (`site.theme + site.global + site.pageSections`) into every page's
6
- * `resolvedSections` array.
7
- *
8
- * Without this wrapper, only `site.seo` is consumed by `cmsRouteConfig` —
9
- * the rest of the Site block is dormant CMS data. Sites that declare
10
- * theme/analytics/wishlist/help-button blocks at the site level (rather
11
- * than per-page) can opt in here to have them rendered automatically.
12
- *
13
- * @example Site's `src/routes/$.tsx`:
14
- * ```ts
15
- * import { createFileRoute, notFound } from "@tanstack/react-router";
16
- * import { cmsRouteConfig, withSiteGlobals } from "@decocms/start/routes";
17
- *
18
- * export const Route = createFileRoute("/$")({
19
- * ...withSiteGlobals(cmsRouteConfig({
20
- * siteName: "Acme",
21
- * defaultTitle: "Acme",
22
- * })),
23
- * component: ...,
24
- * });
25
- * ```
26
- */
27
-
28
- import type { MatcherContext, ResolvedSection } from "@decocms/blocks/cms";
29
- import { loadBlocks, onChange, resolvePageSections } from "@decocms/blocks/cms";
30
- import { createCacheStore, getCacheStorageContext } from "@decocms/blocks/sdk/cacheStorage";
31
-
32
- // ---------------------------------------------------------------------------
33
- // Types
34
- // ---------------------------------------------------------------------------
35
-
36
- /**
37
- * A raw site-block ref — the JSON object pulled from a `.deco/blocks/*.json`
38
- * file before block resolution. Always an object with at least
39
- * `__resolveType`; concrete props vary by block.
40
- */
41
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
42
- export type SiteGlobalRef = Record<string, any>;
43
-
44
- /** Loader output additions when site globals are merged into the page. */
45
- export interface SiteGlobalsLoaderData {
46
- /**
47
- * Raw refs (before resolution) declared in `site.theme`, `site.global`, and
48
- * `site.pageSections`. Includes refs for sections that don't resolve into
49
- * the section tree (`SKIP_RESOLVE_TYPES`) — useful for sites that need to
50
- * read site-level data (analytics IDs, manifest config, etc.) outside the
51
- * normal section render path.
52
- *
53
- * Ordering: `theme`, then `global`, then `pageSections`.
54
- */
55
- rawRefs: SiteGlobalRef[];
56
- }
57
-
58
- interface SiteBlock {
59
- theme?: SiteGlobalRef;
60
- global?: SiteGlobalRef[];
61
- pageSections?: SiteGlobalRef[];
62
- }
63
-
64
- interface CacheEntry {
65
- resolvedSections: ResolvedSection[];
66
- rawRefs: SiteGlobalRef[];
67
- expiresAt: number;
68
- }
69
-
70
- // ---------------------------------------------------------------------------
71
- // Globals resolution (cached, with onChange invalidation)
72
- // ---------------------------------------------------------------------------
73
-
74
- const DEFAULT_CACHE_TTL_MS = 5 * 60_000;
75
- const cacheTtlMs = DEFAULT_CACHE_TTL_MS;
76
-
77
- // Keyed by request path — site.global/site.pageSections can contain
78
- // path-dependent matchers (pathname, multi(ETC Segment), date, etc.), so a
79
- // single process-wide cache entry would leak one route's matched variant onto
80
- // every other route (e.g. a /section-only alert winning on "/"). Caching a
81
- // resolvedSections array per path preserves the original 5-minute SWR behavior
82
- // while keeping each route's matcher evaluation correct.
83
- const cache = createCacheStore<CacheEntry>("site-globals");
84
- const inflight = new Map<string, Promise<CacheEntry>>();
85
-
86
- onChange(() => {
87
- cache.clear();
88
- inflight.clear();
89
- });
90
-
91
- function readSiteBlock(): SiteBlock | null {
92
- const blocks = loadBlocks();
93
- // Block keys vary by site convention — try both common cases.
94
- const site = (blocks.site ?? blocks.Site) as SiteBlock | undefined;
95
- return site ?? null;
96
- }
97
-
98
- function gatherSectionRefs(site: SiteBlock): SiteGlobalRef[] {
99
- const refs: SiteGlobalRef[] = [];
100
- if (site.theme) refs.push(site.theme);
101
- if (Array.isArray(site.global)) refs.push(...site.global);
102
- if (Array.isArray(site.pageSections)) refs.push(...site.pageSections);
103
- return refs;
104
- }
105
-
106
- const EMPTY_ENTRY: CacheEntry = {
107
- resolvedSections: [],
108
- rawRefs: [],
109
- expiresAt: 0,
110
- };
111
-
112
- /**
113
- * Resolve `site.theme + site.global + site.pageSections` into a list of
114
- * `ResolvedSection`s, with in-flight dedup and 5-minute SWR caching.
115
- *
116
- * Cache is invalidated by `onChange()` from the CMS loader, so admin edits
117
- * and decofile reloads are reflected on the next request.
118
- *
119
- * Exposed as a util so sites can call it directly if they need globals
120
- * outside the route loader path (rare).
121
- */
122
- export async function resolveSiteGlobals(matcherCtx?: MatcherContext): Promise<{
123
- resolvedSections: ResolvedSection[];
124
- rawRefs: SiteGlobalRef[];
125
- }> {
126
- // Path/date/segment matchers inside site-global sections (e.g. a multivariate
127
- // `Alert` gated by a pathname matcher) must evaluate against the actual
128
- // request, and the result is cached per path so routes don't share variants.
129
- const cacheKey = cache.key(matcherCtx?.path ?? "");
130
- const now = Date.now();
131
- const cached = getCacheStorageContext()?.storage
132
- ? await cache.read(cacheKey)
133
- : cache.get(cacheKey);
134
- if (cached && cached.expiresAt > now) return cached;
135
- const inflightEntry = inflight.get(cacheKey);
136
- if (inflightEntry) return inflightEntry;
137
-
138
- const site = readSiteBlock();
139
- if (!site) {
140
- // Cache the empty result so subsequent requests don't re-walk the
141
- // block registry. `onChange` invalidation still applies — if a Site
142
- // block appears later, the listener clears `cache` and we re-check.
143
- const empty = { ...EMPTY_ENTRY, expiresAt: Date.now() + cacheTtlMs };
144
- cache.set(cacheKey, empty, empty.expiresAt);
145
- return empty;
146
- }
147
-
148
- const rawRefs = gatherSectionRefs(site);
149
- if (rawRefs.length === 0) {
150
- const empty = { ...EMPTY_ENTRY, expiresAt: Date.now() + cacheTtlMs };
151
- cache.set(cacheKey, empty, empty.expiresAt);
152
- return empty;
153
- }
154
-
155
- const p = (async () => {
156
- try {
157
- const resolvedSections = await resolvePageSections(rawRefs, matcherCtx);
158
- const entry: CacheEntry = {
159
- resolvedSections,
160
- rawRefs,
161
- expiresAt: Date.now() + cacheTtlMs,
162
- };
163
- cache.set(cacheKey, entry, entry.expiresAt);
164
- return entry;
165
- } catch (err) {
166
- console.error("[site-globals] failed to resolve:", err);
167
- // Don't cache failures — let the next request retry.
168
- return { resolvedSections: [], rawRefs, expiresAt: 0 };
169
- } finally {
170
- inflight.delete(cacheKey);
171
- }
172
- })();
173
-
174
- inflight.set(cacheKey, p);
175
- return p;
176
- }
177
-
178
- // ---------------------------------------------------------------------------
179
- // Dedupe — collapse global/pageSection components that also exist on the page
180
- // ---------------------------------------------------------------------------
181
-
182
- /**
183
- * Filter `globals` to remove sections whose `component` already appears in
184
- * `existing` (page-level sections). Page sections take precedence — globals
185
- * that conflict are dropped.
186
- *
187
- * This collapses the common case where a section like `Session` is declared
188
- * both in `site.global` and in a page's section list, which would otherwise
189
- * render twice.
190
- */
191
- export function dedupeGlobals(
192
- globals: ResolvedSection[],
193
- existing: ResolvedSection[],
194
- ): ResolvedSection[] {
195
- if (globals.length === 0) return [];
196
- const seenComponents = new Set<string>();
197
- for (const s of existing) {
198
- if (typeof s.component === "string") seenComponents.add(s.component);
199
- }
200
- const result: ResolvedSection[] = [];
201
- for (const s of globals) {
202
- if (typeof s.component === "string") {
203
- if (seenComponents.has(s.component)) continue;
204
- seenComponents.add(s.component); // also dedupe within globals (e.g. Session in both site.global AND site.pageSections)
205
- }
206
- result.push(s);
207
- }
208
- return result;
209
- }
210
-
211
- // ---------------------------------------------------------------------------
212
- // Public wrapper API (deprecated — kept for backward compat)
213
- // ---------------------------------------------------------------------------
214
-
215
- type AnyLoader = (...args: any[]) => Promise<any>;
216
-
217
- /**
218
- * @deprecated Site globals are now resolved automatically inside the
219
- * `loadCmsPage` / `loadCmsHomePage` server functions. Wrapping
220
- * `cmsRouteConfig` is a no-op — the call is kept for backward compat so
221
- * existing sites don't need to change their `routes/$.tsx` immediately.
222
- *
223
- * Previously, this wrapper called `resolveSiteGlobals()` from the route
224
- * loader, which runs **client-side** on SPA navigations. On SPA, the vite
225
- * plugin replaces `blocks.gen.ts` with `{}` in the client bundle, so
226
- * `loadBlocks()` returned a stub and globals silently dropped — see #233.
227
- *
228
- * Moving resolution into the server function makes SSR (F5) and SPA
229
- * navigations both go through the same server-side path.
230
- */
231
- export function withSiteGlobals<T extends { loader: AnyLoader }>(routeConfig: T): T {
232
- return routeConfig;
233
- }
234
-
235
- // ---------------------------------------------------------------------------
236
- // Test-only resets (not exported in public types — used by withSiteGlobals.test.ts)
237
- // ---------------------------------------------------------------------------
238
-
239
- /** @internal */
240
- export function __resetSiteGlobalsCache() {
241
- cache.clear();
242
- inflight.clear();
243
- }
@@ -1,68 +0,0 @@
1
- /**
2
- * Workers run no timers between requests: core background work (release
3
- * checks, telemetry batches) runs after the response, inside ctx.waitUntil
4
- * (hosted-publishing.mdx, hosted-releases-internals.mdx, telemetry-internals.mdx).
5
- */
6
- import { createCMS, type Loader, resetForTests } from "@decocms/blocks";
7
- import { setBlocks } from "@decocms/blocks/cms";
8
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
9
- import { createDecoWorkerEntry } from "./workerEntry";
10
-
11
- const HOOK = Symbol.for("decocms.blocks.background");
12
-
13
- beforeEach(() => {
14
- resetForTests();
15
- setBlocks({}); // the v7 path this entry still runs reads redirects from it
16
- });
17
- afterEach(() => {
18
- delete (globalThis as Record<symbol, unknown>)[HOOK];
19
- resetForTests();
20
- });
21
-
22
- function context() {
23
- const waited: Promise<unknown>[] = [];
24
- return {
25
- waited,
26
- ctx: { waitUntil: (p: Promise<unknown>) => void waited.push(p), passThroughOnException() {} },
27
- };
28
- }
29
-
30
- describe("createDecoWorkerEntry: background work", () => {
31
- it("runs a due release check after the response, inside ctx.waitUntil", async () => {
32
- const update = vi.fn(async () => ({ updated: false }));
33
- const loader: Loader = {
34
- load: async () => ({ revision: "r1", blocks: {} }),
35
- update,
36
- };
37
- const cms = createCMS({ blocks: {}, content: loader });
38
- let checkedBeforeResponse = true;
39
- const worker = createDecoWorkerEntry(
40
- {
41
- fetch: async () => {
42
- cms.forRelease();
43
- await Promise.resolve();
44
- checkedBeforeResponse = update.mock.calls.length > 0;
45
- return new Response("ok");
46
- },
47
- },
48
- { observability: false },
49
- );
50
- const { waited, ctx } = context();
51
- const response = await worker.fetch(new Request("https://example.com/"), {}, ctx);
52
- expect(await response.text()).toBe("ok");
53
- expect(checkedBeforeResponse).toBe(false);
54
- expect(waited).toHaveLength(1);
55
- await Promise.all(waited);
56
- expect(update).toHaveBeenCalledTimes(1);
57
- });
58
-
59
- it("calls waitUntil only when there's something queued", async () => {
60
- const worker = createDecoWorkerEntry(
61
- { fetch: async () => new Response("ok") },
62
- { observability: false },
63
- );
64
- const { waited, ctx } = context();
65
- await worker.fetch(new Request("https://example.com/"), {}, ctx);
66
- expect(waited).toHaveLength(0);
67
- });
68
- });
@@ -1,38 +0,0 @@
1
- /**
2
- * Runs `@decocms/blocks` background work (release checks, telemetry batches)
3
- * after each response, inside `ctx.waitUntil`. Workers run no timers between
4
- * requests, so the core's timer fallback would never fire or would be bound
5
- * to a finished request. See /next/hosted-releases-internals and
6
- * /next/telemetry-internals#sending-in-the-background.
7
- *
8
- * The hook is installed once per isolate under the `Symbol.for` key the core
9
- * looks for; its queue lives on the hook itself, so two copies of this module
10
- * share one queue.
11
- */
12
-
13
- const HOOK = Symbol.for("decocms.blocks.background");
14
-
15
- type Task = () => Promise<void>;
16
- type Hook = ((task: Task) => void) & { queue: Task[] };
17
-
18
- function hook(): Hook {
19
- const g = globalThis as unknown as Record<symbol, Hook | undefined>;
20
- const existing = g[HOOK];
21
- if (typeof existing === "function" && Array.isArray(existing.queue)) return existing;
22
- const queue: Task[] = [];
23
- const installed = Object.assign((task: Task) => void queue.push(task), { queue });
24
- g[HOOK] = installed;
25
- return installed;
26
- }
27
-
28
- /** Installs the hook (idempotent): from now on, core background work queues here. */
29
- export function installBackgroundHook(): void {
30
- hook();
31
- }
32
-
33
- /** Runs everything queued so far inside `ctx.waitUntil`. */
34
- export function runBackgroundTasks(ctx: { waitUntil(promise: Promise<unknown>): void }): void {
35
- const tasks = hook().queue.splice(0);
36
- if (tasks.length === 0) return;
37
- ctx.waitUntil(Promise.all(tasks.map((task) => task().catch(() => {}))));
38
- }
@@ -1,67 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { segmentToken } from "./cdnSegment";
3
-
4
- const BUILD = "abc123";
5
-
6
- describe("segmentToken", () => {
7
- it("produces a token for an anonymous visitor", () => {
8
- expect(segmentToken("desktop", false, BUILD)).toBeTruthy();
9
- });
10
-
11
- it("gives different segments different tokens", () => {
12
- // The whole point: the URL has to distinguish what the Worker's key
13
- // distinguishes, or a cache in front serves one visitor another's response.
14
- const tokens = ["desktop", "mobile", "desktop|r=RJ", "desktop|r=SP", "desktop|sc=3|r=RJ"].map(
15
- (s) => segmentToken(s, false, BUILD),
16
- );
17
- expect(new Set(tokens).size).toBe(tokens.length);
18
- });
19
-
20
- it("regionalized and non-regionalized visitors never share a token", () => {
21
- // This is the case that made the first version inert on real stores: region
22
- // is resolved server-side from cf.regionCode, so it MUST be in the token.
23
- expect(segmentToken("desktop", false, BUILD)).not.toBe(
24
- segmentToken("desktop|r=RJ", false, BUILD),
25
- );
26
- });
27
-
28
- it("is stable for the same segment and build", () => {
29
- // The worker verifies by recomputing, so the same input must always give
30
- // the same token — otherwise nothing would ever match.
31
- expect(segmentToken("desktop|r=RJ", false, BUILD)).toBe(
32
- segmentToken("desktop|r=RJ", false, BUILD),
33
- );
34
- });
35
-
36
- it("refuses a logged-in visitor regardless of segment precision", () => {
37
- // Personalized responses never belong in a shared entry, however exact the
38
- // key is.
39
- expect(segmentToken("desktop|auth|r=RJ", true, BUILD)).toBeNull();
40
- });
41
-
42
- it("refuses a missing or dev build hash", () => {
43
- // Without a build hash there is no way to invalidate on deploy — the cache
44
- // in front would keep serving stale code.
45
- expect(segmentToken("desktop", false, undefined)).toBeNull();
46
- expect(segmentToken("desktop", false, "")).toBeNull();
47
- expect(segmentToken("desktop", false, "dev")).toBeNull();
48
- });
49
-
50
- it("changes with the build, so a deploy invalidates it", () => {
51
- expect(segmentToken("desktop", false, "buildA")).not.toBe(
52
- segmentToken("desktop", false, "buildB"),
53
- );
54
- });
55
-
56
- it("refuses an empty segment descriptor", () => {
57
- expect(segmentToken("", false, BUILD)).toBeNull();
58
- });
59
-
60
- it("is URL-safe even when the segment carries a VTEX region id", () => {
61
- // `v2.XXXX` contains the character an earlier format used as a separator;
62
- // hashing sidesteps escaping entirely.
63
- const t = segmentToken("desktop|r=v2.ABC-123|sc=3", false, BUILD);
64
- expect(t).toMatch(/^[a-z0-9]+$/);
65
- expect(encodeURIComponent(t as string)).toBe(t);
66
- });
67
- });
@@ -1,71 +0,0 @@
1
- /**
2
- * Segment marker on `/_serverFn` URLs, so a cache in front of the Worker can
3
- * serve the response without invoking it.
4
- *
5
- * The problem: whatever sits in front (Workers Cache, a CDN rule) keys on the
6
- * raw URL. The Worker keys on a SYNTHETIC Request carrying
7
- * `__seg`/`__cf_device`/`__bot`/`__fetch`/`__abf` (`buildCacheKey` in
8
- * `./workerEntry`) — params the URL never shows. That mismatch is why the
9
- * framework stamps `CDN-Cache-Control: no-store` on public responses.
10
- *
11
- * The fix: put the segment in the URL itself, so the two keys become
12
- * equivalent.
13
- *
14
- * ## Why the SERVER issues the token
15
- *
16
- * The first version had the client derive the token from what it could see
17
- * (`navigator.userAgent`). That only ever worked on sites whose segment
18
- * reduces to device alone. A regionalized VTEX store — most of them — segments
19
- * on region too, and region is resolved from `request.cf.regionCode`, which
20
- * exists **only** on the server. The client cannot see it, so its token never
21
- * matched and the feature stayed permanently inert.
22
- *
23
- * So the server computes the token from the segment it already built, publishes
24
- * it to the page, and the client only echoes it back. The Worker still verifies
25
- * by recomputing — the marker is never trusted, so a stale or forged one just
26
- * keeps the `no-store`.
27
- *
28
- * The token is a hash rather than readable fields: `regionId` can contain the
29
- * separator (`v2.XXXX`), values would need escaping, and there is no reason to
30
- * publish a visitor's region in a URL that ends up in logs.
31
- */
32
-
33
- import { djb2Hex } from "@decocms/blocks/sdk/djb2";
34
-
35
- /** `__d` is reserved: `workerEntry` uses `?__d=` as an OTel debug flag. */
36
- export const CSEG_PARAM = "__cseg";
37
-
38
- /** Global the SSR publishes the token on, read back by `decoServerFnFetch`. */
39
- export const CSEG_GLOBAL = "__DECO_CSEG";
40
-
41
- /** RequestContext bag key the worker entry fills before rendering. */
42
- export const CSEG_BAG_KEY = "deco.cdn.segmentToken";
43
-
44
- /**
45
- * Build the token for a segment, or `null` when this request must not be
46
- * cached in front of the Worker.
47
- *
48
- * `null` — i.e. keep `no-store` — when:
49
- *
50
- * - the visitor is logged in. Personalized responses never belong in a shared
51
- * entry, no matter how precise the key is.
52
- * - there is no build hash, or it is `"dev"`. The build is part of the token
53
- * because deploying does not purge the cache in front, so the URL has to
54
- * change on its own when the bundle does.
55
- *
56
- * Everything else in the segment — device, sales channel, region, a site's own
57
- * custom dimensions — is folded INTO the token rather than rejected. That is
58
- * the difference from the first version: those are what the key needs to
59
- * distinguish, not reasons to give up on caching.
60
- */
61
- export function segmentToken(
62
- segmentDescriptor: string,
63
- loggedIn: boolean,
64
- buildHash: string | undefined,
65
- ): string | null {
66
- if (loggedIn) return null;
67
- if (!buildHash || buildHash === "dev") return null;
68
- if (!segmentDescriptor) return null;
69
-
70
- return djb2Hex(`${segmentDescriptor}|${buildHash}`);
71
- }
@@ -1,58 +0,0 @@
1
- /**
2
- * Request / Response cookie passthrough helpers for TanStack Start.
3
- *
4
- * Provides two framework-bound functions that commerce apps
5
- * (VTEX, Shopify, etc.) can plug into their cookie provider hooks
6
- * to transparently forward browser cookies to API calls and
7
- * Set-Cookie headers back to the browser.
8
- *
9
- * @example
10
- * ```ts
11
- * // setup.ts
12
- * import { getRequestCookieHeader, forwardResponseCookies } from "@decocms/start/sdk/cookiePassthrough";
13
- * import { setRequestCookieProvider, setResponseCookieForwarder } from "@decocms/apps/vtex";
14
- *
15
- * setRequestCookieProvider(getRequestCookieHeader);
16
- * setResponseCookieForwarder(forwardResponseCookies);
17
- * ```
18
- */
19
-
20
- import {
21
- getRequestHeader,
22
- getResponseHeaders,
23
- setResponseHeader,
24
- } from "@tanstack/react-start/server";
25
-
26
- /**
27
- * Returns the Cookie header from the current TanStack Start request context.
28
- * Safe to call outside a request scope (returns undefined).
29
- */
30
- export function getRequestCookieHeader(): string | undefined {
31
- try {
32
- return getRequestHeader("cookie") ?? undefined;
33
- } catch {
34
- return undefined;
35
- }
36
- }
37
-
38
- /**
39
- * Appends Set-Cookie headers to the current TanStack Start response.
40
- * Preserves any Set-Cookie headers already set by other middleware or
41
- * earlier calls, so multiple API calls in one request don't clobber
42
- * each other's cookies.
43
- *
44
- * Safe to call outside a request scope (no-op).
45
- */
46
- export function forwardResponseCookies(cookies: string[]): void {
47
- if (!cookies.length) return;
48
- try {
49
- const headers = getResponseHeaders();
50
- const existing: string[] =
51
- typeof headers.getSetCookie === "function"
52
- ? headers.getSetCookie()
53
- : [];
54
- setResponseHeader("set-cookie", [...existing, ...cookies]);
55
- } catch {
56
- // Outside request context (build time, etc.) — ignore.
57
- }
58
- }
@@ -1,77 +0,0 @@
1
- /**
2
- * Type-only marker for apps-* `invoke.ts` codegen templates (e.g.
3
- * `@decocms/apps-vtex/invoke.ts`) — NOT a real, callable createServerFn
4
- * wrapper. Deliberately does not call `createServerFn` at runtime.
5
- *
6
- * `invoke.ts` files are never imported/executed by any real site — they
7
- * are a source-of-truth that `blocks-cli`'s `generate-invoke.ts` statically
8
- * parses (via AST inspection of each `createInvokeFn(action, opts)` call
9
- * site's arguments) to emit real, literal top-level `createServerFn(...)`
10
- * declarations into each site's own `src/server/invoke.gen.ts`. This
11
- * function's ONLY job is to give those template files a correctly-typed
12
- * call site to author against.
13
- *
14
- * It must not contain a real `createServerFn(...)` call: TanStack Start's
15
- * compiler statically scans every file reachable by a site's SSR bundle for
16
- * that literal pattern and throws "createServerFn must be assigned to a
17
- * variable!" on ANY occurrence that isn't a top-level declarator — even one
18
- * inside a function body that's never actually invoked. `invoke.ts` isn't
19
- * supposed to be reachable by a site's bundler at all (it's excluded from
20
- * every apps-* package's public exports map), but Vite's `optimizeDeps`
21
- * pre-bundling has been observed sweeping it in regardless of that
22
- * exports-map restriction — so the only fully robust fix is for this file
23
- * to never contain the literal pattern the compiler is looking for, full
24
- * stop, regardless of what does or doesn't end up bundled.
25
- *
26
- * @example
27
- * ```ts
28
- * import { createInvokeFn } from "@decocms/tanstack/sdk/createInvoke";
29
- * import { addItemsToCart } from "./actions/checkout";
30
- *
31
- * export const invoke = {
32
- * vtex: {
33
- * actions: {
34
- * addItemsToCart: createInvokeFn(
35
- * (input: { orderFormId: string; orderItems: CartItem[] }) =>
36
- * addItemsToCart(input.orderFormId, input.orderItems),
37
- * { unwrap: true },
38
- * ),
39
- * },
40
- * },
41
- * };
42
- * ```
43
- *
44
- * The real, callable version of each action above only exists in the
45
- * site's generated `src/server/invoke.gen.ts` (run `npm run generate:invoke`),
46
- * which uses real top-level `createServerFn(...)` calls directly — never
47
- * this function.
48
- */
49
-
50
- export interface InvokeFnOpts {
51
- /**
52
- * When true, extracts `.data` from the result before returning.
53
- * Use for VTEX checkout functions that return VtexFetchResult<T>
54
- * (i.e. `{ data: T, setCookies: string[] }`).
55
- */
56
- unwrap?: boolean;
57
- }
58
-
59
- /**
60
- * Template-only — see the module doc comment above. Throws if actually
61
- * called at runtime, since that would mean something imported an
62
- * `invoke.ts` template file directly instead of using the site's generated
63
- * `invoke.gen.ts`, which is itself a bug worth surfacing loudly rather than
64
- * silently returning wrong behavior.
65
- */
66
- export function createInvokeFn<TInput, TOutput>(
67
- _action: (input: TInput) => Promise<TOutput>,
68
- _opts?: InvokeFnOpts,
69
- ): (ctx: { data: TInput }) => Promise<TOutput> {
70
- return () => {
71
- throw new Error(
72
- "createInvokeFn() is a codegen-time-only template marker and was never meant to be called at " +
73
- "runtime. If you're seeing this, something imported an apps-*/invoke.ts template file directly " +
74
- "instead of using the site's generated src/server/invoke.gen.ts (run `npm run generate:invoke`).",
75
- );
76
- };
77
- }