@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.
- package/README.md +79 -0
- package/dist/draft.d.ts +33 -0
- package/dist/draft.d.ts.map +1 -0
- package/dist/draft.js +41 -0
- package/dist/draft.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/react/DecoDocument.d.ts +61 -0
- package/dist/react/DecoDocument.d.ts.map +1 -0
- package/dist/react/DecoDocument.js +96 -0
- package/dist/react/DecoDocument.js.map +1 -0
- package/dist/react/Image.d.ts +96 -0
- package/dist/react/Image.d.ts.map +1 -0
- package/dist/react/Image.js +79 -0
- package/dist/react/Image.js.map +1 -0
- package/dist/react/index.d.ts +7 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/index.js +7 -0
- package/dist/react/index.js.map +1 -0
- package/dist/react/pageValues.d.ts +10 -0
- package/dist/react/pageValues.d.ts.map +1 -0
- package/dist/react/pageValues.js +29 -0
- package/dist/react/pageValues.js.map +1 -0
- package/dist/react/scripts.d.ts +14 -0
- package/dist/react/scripts.d.ts.map +1 -0
- package/dist/react/scripts.js +96 -0
- package/dist/react/scripts.js.map +1 -0
- package/dist/router/index.d.ts +38 -0
- package/dist/router/index.d.ts.map +1 -0
- package/dist/router/index.js +60 -0
- package/dist/router/index.js.map +1 -0
- package/dist/scope/browser.d.ts +11 -0
- package/dist/scope/browser.d.ts.map +1 -0
- package/dist/scope/browser.js +8 -0
- package/dist/scope/browser.js.map +1 -0
- package/dist/scope/server.d.ts +13 -0
- package/dist/scope/server.d.ts.map +1 -0
- package/dist/scope/server.js +26 -0
- package/dist/scope/server.js.map +1 -0
- package/dist/server/index.d.ts +27 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/index.js +31 -0
- package/dist/server/index.js.map +1 -0
- package/dist/shared.d.ts +26 -0
- package/dist/shared.d.ts.map +1 -0
- package/dist/shared.js +26 -0
- package/dist/shared.js.map +1 -0
- package/dist/start/index.d.ts +9 -0
- package/dist/start/index.d.ts.map +1 -0
- package/dist/start/index.js +33 -0
- package/dist/start/index.js.map +1 -0
- package/dist/studio.d.ts +28 -0
- package/dist/studio.d.ts.map +1 -0
- package/dist/studio.js +53 -0
- package/dist/studio.js.map +1 -0
- package/dist/vite/index.d.ts +15 -0
- package/dist/vite/index.d.ts.map +1 -0
- package/dist/vite/index.js +95 -0
- package/dist/vite/index.js.map +1 -0
- package/dist/worker/cacheProfiles.d.ts +43 -0
- package/dist/worker/cacheProfiles.d.ts.map +1 -0
- package/dist/worker/cacheProfiles.js +162 -0
- package/dist/worker/cacheProfiles.js.map +1 -0
- package/dist/worker/cookies.d.ts +20 -0
- package/dist/worker/cookies.d.ts.map +1 -0
- package/dist/worker/cookies.js +69 -0
- package/dist/worker/cookies.js.map +1 -0
- package/dist/worker/drafts.d.ts +59 -0
- package/dist/worker/drafts.d.ts.map +1 -0
- package/dist/worker/drafts.js +140 -0
- package/dist/worker/drafts.js.map +1 -0
- package/dist/worker/index.d.ts +111 -0
- package/dist/worker/index.d.ts.map +1 -0
- package/dist/worker/index.js +618 -0
- package/dist/worker/index.js.map +1 -0
- package/dist/worker/security.d.ts +14 -0
- package/dist/worker/security.d.ts.map +1 -0
- package/dist/worker/security.js +48 -0
- package/dist/worker/security.js.map +1 -0
- package/dist/worker/segment.d.ts +21 -0
- package/dist/worker/segment.d.ts.map +1 -0
- package/dist/worker/segment.js +43 -0
- package/dist/worker/segment.js.map +1 -0
- package/package.json +85 -37
- package/src/draft.ts +43 -0
- package/src/index.ts +8 -61
- package/src/react/DecoDocument.tsx +234 -0
- package/src/react/Image.tsx +213 -0
- package/src/react/index.ts +24 -0
- package/src/react/pageValues.ts +35 -0
- package/src/react/scripts.ts +98 -0
- package/src/router/index.ts +80 -0
- package/src/scope/browser.ts +18 -0
- package/src/scope/server.ts +37 -0
- package/src/server/index.ts +43 -0
- package/src/shared.ts +29 -0
- package/src/start/index.ts +31 -0
- package/src/studio.ts +52 -0
- package/src/vite/index.ts +105 -0
- package/src/worker/cacheProfiles.ts +180 -0
- package/src/worker/cookies.ts +65 -0
- package/src/worker/drafts.ts +157 -0
- package/src/worker/index.ts +784 -0
- package/src/worker/security.ts +63 -0
- package/src/worker/segment.ts +49 -0
- package/src/__conformance__/observability.test.ts +0 -221
- package/src/cms/kvBlockSource.test.ts +0 -82
- package/src/cms/kvBlockSource.ts +0 -68
- package/src/daemon/auth.ts +0 -204
- package/src/daemon/fs.ts +0 -238
- package/src/daemon/index.ts +0 -8
- package/src/daemon/middleware.ts +0 -156
- package/src/daemon/tunnel.ts +0 -129
- package/src/daemon/volumes.ts +0 -366
- package/src/daemon/watch.ts +0 -272
- package/src/hooks/CdnSegmentMarker.tsx +0 -38
- package/src/hooks/DecoPageRenderer.tsx +0 -750
- package/src/hooks/DecoRootLayout.tsx +0 -192
- package/src/hooks/DraftPreviewIndicator.test.tsx +0 -60
- package/src/hooks/DraftPreviewIndicator.tsx +0 -64
- package/src/hooks/NavigationProgress.test.tsx +0 -58
- package/src/hooks/NavigationProgress.tsx +0 -63
- package/src/hooks/PreviewProviders.test.tsx +0 -42
- package/src/hooks/PreviewProviders.tsx +0 -45
- package/src/hooks/StableOutlet.tsx +0 -30
- package/src/hooks/deferredObserverTiming.test.tsx +0 -91
- package/src/hooks/index.ts +0 -10
- package/src/routes/adminRoutes.test.ts +0 -99
- package/src/routes/adminRoutes.ts +0 -153
- package/src/routes/cmsRoute.test.ts +0 -267
- package/src/routes/cmsRoute.ts +0 -1053
- package/src/routes/components.tsx +0 -57
- package/src/routes/index.ts +0 -24
- package/src/routes/pageUrl.test.ts +0 -70
- package/src/routes/pageUrl.ts +0 -55
- package/src/routes/withSiteGlobals.test.ts +0 -243
- package/src/routes/withSiteGlobals.ts +0 -243
- package/src/sdk/backgroundTasks.test.ts +0 -68
- package/src/sdk/backgroundTasks.ts +0 -38
- package/src/sdk/cdnSegment.test.ts +0 -67
- package/src/sdk/cdnSegment.ts +0 -71
- package/src/sdk/cookiePassthrough.ts +0 -58
- package/src/sdk/createInvoke.ts +0 -77
- package/src/sdk/deferredSectionLoader.test.ts +0 -94
- package/src/sdk/deferredSectionLoader.ts +0 -46
- package/src/sdk/draft.test.ts +0 -341
- package/src/sdk/draft.ts +0 -277
- package/src/sdk/draftShared.ts +0 -16
- package/src/sdk/kvHydration.test.ts +0 -371
- package/src/sdk/kvHydration.ts +0 -263
- package/src/sdk/kvRedirects.test.ts +0 -132
- package/src/sdk/kvRedirects.ts +0 -125
- package/src/sdk/outboundHeaders.test.ts +0 -113
- package/src/sdk/outboundHeaders.ts +0 -81
- package/src/sdk/router.ts +0 -101
- package/src/sdk/serverFnFetch.ts +0 -59
- package/src/sdk/speculationRules.test.ts +0 -82
- package/src/sdk/speculationRules.ts +0 -136
- package/src/sdk/startEntry.ts +0 -31
- package/src/sdk/useHydrated.ts +0 -19
- package/src/sdk/workerEntry.cacheStorage.test.ts +0 -147
- package/src/sdk/workerEntry.test.ts +0 -1033
- package/src/sdk/workerEntry.trackingCache.test.ts +0 -328
- package/src/sdk/workerEntry.ts +0 -3154
- package/src/setupFastDeploy.ts +0 -13
- package/src/v8/__conformance__/delivery.test.ts +0 -100
- package/src/v8/binding.ts +0 -70
- package/src/v8/kvLoader.bundle.test.ts +0 -42
- package/src/v8/kvLoader.test.ts +0 -74
- package/src/v8/kvLoader.ts +0 -43
- package/src/vite/plugin-scaffold-gen.test.js +0 -106
- package/src/vite/plugin.js +0 -1022
- package/src/vite/plugin.test.js +0 -238
- package/src/vite/plugin.test.ts +0 -176
- package/tsconfig.json +0 -7
package/src/sdk/workerEntry.ts
DELETED
|
@@ -1,3154 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Factory for creating a cache-aware Cloudflare Worker entry.
|
|
3
|
-
*
|
|
4
|
-
* Wraps a TanStack Start server entry with:
|
|
5
|
-
* - Cloudflare Cache API integration (edge caching)
|
|
6
|
-
* - Device-specific cache keys (mobile/desktop split)
|
|
7
|
-
* - Per-URL cache profile detection via detectCacheProfile()
|
|
8
|
-
* - Immutable caching for fingerprinted static assets
|
|
9
|
-
* - Cache purge API endpoint
|
|
10
|
-
* - Protection against accidental caching of private/search paths
|
|
11
|
-
*
|
|
12
|
-
* @example
|
|
13
|
-
* ```ts
|
|
14
|
-
* // src/worker-entry.ts
|
|
15
|
-
* import handler, { createServerEntry } from "@tanstack/react-start/server-entry";
|
|
16
|
-
* import { createDecoWorkerEntry } from "@decocms/start/sdk/workerEntry";
|
|
17
|
-
*
|
|
18
|
-
* const serverEntry = createServerEntry({
|
|
19
|
-
* async fetch(request) {
|
|
20
|
-
* return await handler.fetch(request);
|
|
21
|
-
* },
|
|
22
|
-
* });
|
|
23
|
-
*
|
|
24
|
-
* export default createDecoWorkerEntry(serverEntry);
|
|
25
|
-
* ```
|
|
26
|
-
*/
|
|
27
|
-
|
|
28
|
-
import { draftPointer } from "@decocms/blocks";
|
|
29
|
-
import {
|
|
30
|
-
getRevision,
|
|
31
|
-
getSectionOptions,
|
|
32
|
-
isBot,
|
|
33
|
-
loadBlocks,
|
|
34
|
-
type MatcherContext,
|
|
35
|
-
onChange,
|
|
36
|
-
resolveDecoPage,
|
|
37
|
-
resolveDeferredSectionFull,
|
|
38
|
-
runSectionLoaders,
|
|
39
|
-
runSingleSectionLoader,
|
|
40
|
-
serializeRenderJson,
|
|
41
|
-
stringifyWithoutSecrets,
|
|
42
|
-
} from "@decocms/blocks/cms";
|
|
43
|
-
import { DECO_MATCHERS_OVERRIDE_PARAM } from "@decocms/blocks/matchers/override";
|
|
44
|
-
import { clearLoaderCache } from "@decocms/blocks/sdk/cachedLoader";
|
|
45
|
-
import {
|
|
46
|
-
type CacheProfileName,
|
|
47
|
-
cacheHeaders,
|
|
48
|
-
canonicalizeServerFnPayloadForCacheKey,
|
|
49
|
-
detectCacheProfile,
|
|
50
|
-
edgeCacheConfig,
|
|
51
|
-
getCacheProfile,
|
|
52
|
-
payloadHasTrackingParams,
|
|
53
|
-
serverFnPagePath,
|
|
54
|
-
} from "@decocms/blocks/sdk/cacheHeaders";
|
|
55
|
-
import {
|
|
56
|
-
bindCacheStorage,
|
|
57
|
-
type CacheStorage,
|
|
58
|
-
createWebCacheStorage,
|
|
59
|
-
getCacheStorageContext,
|
|
60
|
-
} from "@decocms/blocks/sdk/cacheStorage";
|
|
61
|
-
import { djb2Hex } from "@decocms/blocks/sdk/djb2";
|
|
62
|
-
import { isDevMode } from "@decocms/blocks/sdk/env";
|
|
63
|
-
import { parseSegmentCookie, SEGMENT_COOKIE, segmentCacheToken } from "@decocms/blocks/sdk/flags";
|
|
64
|
-
import { generateNonce, NONCE_BAG_KEY } from "@decocms/blocks/sdk/nonce";
|
|
65
|
-
import {
|
|
66
|
-
getActiveSpan,
|
|
67
|
-
logRequest,
|
|
68
|
-
recordCacheMetric,
|
|
69
|
-
recordRequestMetric,
|
|
70
|
-
setSpanAttribute,
|
|
71
|
-
withTracing,
|
|
72
|
-
} from "@decocms/blocks/sdk/observability";
|
|
73
|
-
import {
|
|
74
|
-
_setDebugSampled,
|
|
75
|
-
_setRequestTraceContext,
|
|
76
|
-
instrumentWorker,
|
|
77
|
-
type OtelOptions,
|
|
78
|
-
} from "@decocms/blocks/sdk/otel";
|
|
79
|
-
import { setRuntimeEnv } from "@decocms/blocks/sdk/otelAdapters";
|
|
80
|
-
import { parseTraceparent } from "@decocms/blocks/sdk/otelHttpTracer";
|
|
81
|
-
import {
|
|
82
|
-
loadRedirects,
|
|
83
|
-
matchExactRedirect,
|
|
84
|
-
matchPatternRedirect,
|
|
85
|
-
normalizePath,
|
|
86
|
-
type RedirectMap,
|
|
87
|
-
} from "@decocms/blocks/sdk/redirects";
|
|
88
|
-
import { RequestContext } from "@decocms/blocks/sdk/requestContext";
|
|
89
|
-
import { createResponseCache } from "@decocms/blocks/sdk/responseCache";
|
|
90
|
-
import { cleanPathForCacheKey, hasTrackingParams } from "@decocms/blocks/sdk/urlUtils";
|
|
91
|
-
import { type Device, isMobileUA } from "@decocms/blocks/sdk/useDevice";
|
|
92
|
-
import { getRenderShellConfig } from "@decocms/blocks-admin/admin/setup";
|
|
93
|
-
import { reconfigureAppsOnce } from "@decocms/blocks-admin/apps/autoconfig";
|
|
94
|
-
import { buildHtmlShell } from "@decocms/blocks-admin/sdk/htmlShell";
|
|
95
|
-
import { getAppMiddleware } from "@decocms/blocks-admin/sdk/setupApps";
|
|
96
|
-
import { installUpstreamCache } from "../v8/binding";
|
|
97
|
-
import { installBackgroundHook, runBackgroundTasks } from "./backgroundTasks";
|
|
98
|
-
import { CSEG_BAG_KEY, CSEG_PARAM, segmentToken } from "./cdnSegment";
|
|
99
|
-
import {
|
|
100
|
-
applyDraftCookieAndHeaders,
|
|
101
|
-
bindRequestDraft,
|
|
102
|
-
type DraftDecision,
|
|
103
|
-
installDecoSiteHostFromEnv,
|
|
104
|
-
installPreviewHostsFromBlocks,
|
|
105
|
-
registerDraftOverride,
|
|
106
|
-
requestCarriesDraft,
|
|
107
|
-
} from "./draft";
|
|
108
|
-
import { ensureBlocksHydrated, maybePollRevision } from "./kvHydration";
|
|
109
|
-
import { lookupExactRedirect } from "./kvRedirects";
|
|
110
|
-
import { DECO_POWERED_BY, installDefaultUserAgent } from "./outboundHeaders";
|
|
111
|
-
import { type SpeculationRulesConfig, setSpeculationRules } from "./speculationRules";
|
|
112
|
-
|
|
113
|
-
/**
|
|
114
|
-
* Build-time identifier injected by `decoVitePlugin()` (see
|
|
115
|
-
* `src/vite/plugin.js`). Falls back to `undefined` if the consuming site
|
|
116
|
-
* isn't using the plugin or the symbol wasn't `define`d at bundle time.
|
|
117
|
-
*
|
|
118
|
-
* The runtime `env.BUILD_HASH` (when explicitly set, e.g. via
|
|
119
|
-
* `wrangler deploy --var BUILD_HASH:foo`) takes precedence — see
|
|
120
|
-
* `getBuildHash()` below.
|
|
121
|
-
*/
|
|
122
|
-
declare const __DECO_BUILD_HASH__: string | undefined;
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
* The five canonical cache-decision strings stamped on the `X-Cache`
|
|
126
|
-
* response header (and on the `decision` label of `cache_*_total`
|
|
127
|
-
* metrics). Used by the request-metric label enrichment to keep label
|
|
128
|
-
* cardinality bounded — anything else (e.g. an upstream proxy that sets
|
|
129
|
-
* its own `X-Cache: random-text`) is dropped from the label.
|
|
130
|
-
*/
|
|
131
|
-
type CacheDecisionString = "HIT" | "STALE-HIT" | "STALE-ERROR" | "MISS" | "BYPASS";
|
|
132
|
-
|
|
133
|
-
function isCacheDecision(value: string | null): value is CacheDecisionString {
|
|
134
|
-
return (
|
|
135
|
-
value === "HIT" ||
|
|
136
|
-
value === "STALE-HIT" ||
|
|
137
|
-
value === "STALE-ERROR" ||
|
|
138
|
-
value === "MISS" ||
|
|
139
|
-
value === "BYPASS"
|
|
140
|
-
);
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
/**
|
|
144
|
-
* Append Link preload headers for CSS and fonts so the browser starts
|
|
145
|
-
* fetching them before parsing HTML. Only applied to HTML responses.
|
|
146
|
-
*/
|
|
147
|
-
function appendResourceHints(resp: Response): void {
|
|
148
|
-
const ct = resp.headers.get("content-type");
|
|
149
|
-
if (!ct || !ct.includes("text/html")) return;
|
|
150
|
-
const { cssHref, fontHrefs } = getRenderShellConfig();
|
|
151
|
-
if (cssHref) {
|
|
152
|
-
resp.headers.append("Link", `<${cssHref}>; rel=preload; as=style`);
|
|
153
|
-
}
|
|
154
|
-
for (const href of fontHrefs) {
|
|
155
|
-
resp.headers.append("Link", `<${href}>; rel=preload; as=font; crossorigin`);
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
// ---------------------------------------------------------------------------
|
|
160
|
-
// Types
|
|
161
|
-
// ---------------------------------------------------------------------------
|
|
162
|
-
|
|
163
|
-
/**
|
|
164
|
-
* Minimal ExecutionContext interface compatible with Cloudflare Workers.
|
|
165
|
-
* Defined here so blocks doesn't need @cloudflare/workers-types.
|
|
166
|
-
*/
|
|
167
|
-
interface WorkerExecutionContext {
|
|
168
|
-
waitUntil(promise: Promise<unknown>): void;
|
|
169
|
-
passThroughOnException(): void;
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
interface ServerEntry {
|
|
173
|
-
fetch(
|
|
174
|
-
request: Request,
|
|
175
|
-
env: Record<string, unknown>,
|
|
176
|
-
ctx: WorkerExecutionContext,
|
|
177
|
-
): Response | Promise<Response>;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/**
|
|
181
|
-
* Segment dimensions used to differentiate cache entries.
|
|
182
|
-
*
|
|
183
|
-
* The workerEntry calls `buildSegment` (if provided) to extract these
|
|
184
|
-
* from the request. Two requests with the same SegmentKey share a
|
|
185
|
-
* cache entry; different segments get different cached responses.
|
|
186
|
-
*/
|
|
187
|
-
export interface SegmentKey {
|
|
188
|
-
/**
|
|
189
|
-
* Device class derived from the request User-Agent.
|
|
190
|
-
*
|
|
191
|
-
* Accepts the full `Device` union (`"mobile" | "desktop" | "tablet"`) so
|
|
192
|
-
* that callers can pass `detectDevice(...)` directly without manual
|
|
193
|
-
* narrowing. Sites that want to share cache entries between mobile and
|
|
194
|
-
* tablet can collapse the value at the call site (e.g.
|
|
195
|
-
* `device === "tablet" ? "mobile" : device`).
|
|
196
|
-
*/
|
|
197
|
-
device: Device;
|
|
198
|
-
/** Whether the user is logged in (e.g., has a valid auth cookie). */
|
|
199
|
-
loggedIn?: boolean;
|
|
200
|
-
/** Commerce sales channel / price list. */
|
|
201
|
-
salesChannel?: string;
|
|
202
|
-
/**
|
|
203
|
-
* VTEX region ID for regionalized pricing/availability.
|
|
204
|
-
* When present, cache entries are segmented per region.
|
|
205
|
-
* Sites without regionalization should omit this field
|
|
206
|
-
* to avoid unnecessary cache fragmentation.
|
|
207
|
-
*/
|
|
208
|
-
regionId?: string;
|
|
209
|
-
/** Sorted list of active A/B flag names for cache cohort splitting. */
|
|
210
|
-
flags?: string[];
|
|
211
|
-
/**
|
|
212
|
-
* Custom cache dimensions beyond the known fields above (e.g. a
|
|
213
|
-
* store/CEP-based delivery selector). `hashSegment` serializes these
|
|
214
|
-
* automatically — unlike the known fields, there's no dedicated shorthand
|
|
215
|
-
* key, so don't reuse a name already declared above.
|
|
216
|
-
*/
|
|
217
|
-
[customField: string]: string | boolean | string[] | undefined;
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
/**
|
|
221
|
-
* Admin route handlers injected by the site's worker-entry.ts.
|
|
222
|
-
* Kept as a runtime option so the imports only exist in the SSR entry
|
|
223
|
-
* (not pulled into the client Vite build).
|
|
224
|
-
*/
|
|
225
|
-
export interface AdminHandlers {
|
|
226
|
-
handleMeta: (request: Request) => Response | Promise<Response>;
|
|
227
|
-
handleDecofileRead: () => Response;
|
|
228
|
-
handleDecofileReload: (request: Request) => Response | Promise<Response>;
|
|
229
|
-
handleRender: (request: Request) => Response | Promise<Response>;
|
|
230
|
-
corsHeaders: (request: Request) => Record<string, string>;
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
export interface DecoWorkerEntryOptions {
|
|
234
|
-
/** Choose storage once per request using the app's runtime bindings. Null disables shared storage.
|
|
235
|
-
* Omit to retain Web Cache API response caching and memory-only data caches.
|
|
236
|
-
*/
|
|
237
|
-
cacheStorage?: (env: Record<string, unknown>, request: Request) => CacheStorage | null;
|
|
238
|
-
|
|
239
|
-
/**
|
|
240
|
-
* Admin route handlers (/live/_meta, /.decofile, /live/previews).
|
|
241
|
-
* Pass the handlers from `@decocms/start/admin` here.
|
|
242
|
-
* If not provided, admin routes are not handled.
|
|
243
|
-
*/
|
|
244
|
-
admin?: AdminHandlers;
|
|
245
|
-
|
|
246
|
-
/**
|
|
247
|
-
* Override the default cache profile detection.
|
|
248
|
-
* Return `null` to fall through to the built-in detector.
|
|
249
|
-
*/
|
|
250
|
-
detectProfile?: (url: URL) => CacheProfileName | null;
|
|
251
|
-
|
|
252
|
-
/**
|
|
253
|
-
* Whether to create device-specific cache keys (mobile vs desktop).
|
|
254
|
-
* Useful when server-rendered HTML differs by device.
|
|
255
|
-
* @default true
|
|
256
|
-
*/
|
|
257
|
-
deviceSpecificKeys?: boolean;
|
|
258
|
-
|
|
259
|
-
/**
|
|
260
|
-
* Serve pages as structured per-section JSON on `?renderJson` (the mobile
|
|
261
|
-
* page-as-JSON path). Set to `false` to disable the endpoint site-wide —
|
|
262
|
-
* `?renderJson` then just renders the normal HTML page.
|
|
263
|
-
* @default true
|
|
264
|
-
*/
|
|
265
|
-
renderJson?: boolean;
|
|
266
|
-
|
|
267
|
-
/**
|
|
268
|
-
* Serve the raw resolved page as JSON on `?asJson` (legacy admin-preview
|
|
269
|
-
* path). Set to `false` to disable it site-wide.
|
|
270
|
-
* @default true
|
|
271
|
-
*/
|
|
272
|
-
asJson?: boolean;
|
|
273
|
-
|
|
274
|
-
/**
|
|
275
|
-
* Opt-in Speculation Rules API. When set, a `<script type="speculationrules">`
|
|
276
|
-
* is emitted in every page's <head> (via DecoRootLayout, so it's cache-safe)
|
|
277
|
-
* telling the browser to prerender/prefetch the next document on intent.
|
|
278
|
-
*
|
|
279
|
-
* Ships DISABLED (undefined). Only activate on sites whose analytics/pixel
|
|
280
|
-
* loaders are prerender-guarded (see ANALYTICS_SCRIPT / gtmScript in
|
|
281
|
-
* @decocms/blocks/sdk/analytics), otherwise a prerender can double-count.
|
|
282
|
-
* Scope candidates to hard-navigation links via `linkSelector` so client-
|
|
283
|
-
* routed `<Link>`s are excluded.
|
|
284
|
-
* @default undefined (disabled)
|
|
285
|
-
*/
|
|
286
|
-
speculationRules?: SpeculationRulesConfig;
|
|
287
|
-
|
|
288
|
-
/**
|
|
289
|
-
* Cross-origin access to the `?renderJson` response. It is public page data
|
|
290
|
-
* (secrets + request-derived keys are stripped), so it defaults to open.
|
|
291
|
-
* - unset (default) / `"*"` → any origin, without credentials (public API).
|
|
292
|
-
* - `string[]` → reflect a matching request Origin, *with* credentials.
|
|
293
|
-
* - `false` → no CORS headers (same-origin + native apps only).
|
|
294
|
-
*/
|
|
295
|
-
pageJsonCors?: string[] | "*" | false;
|
|
296
|
-
|
|
297
|
-
/**
|
|
298
|
-
* Build a full segment key from the incoming request.
|
|
299
|
-
*
|
|
300
|
-
* When provided, the segment key replaces the simple device-only
|
|
301
|
-
* cache key with a richer key that differentiates by login state,
|
|
302
|
-
* sales channel, and A/B flags.
|
|
303
|
-
*
|
|
304
|
-
* Logged-in segments (`loggedIn: true`) automatically bypass the
|
|
305
|
-
* cache (the response is fetched fresh every time).
|
|
306
|
-
*
|
|
307
|
-
* @example
|
|
308
|
-
* ```ts
|
|
309
|
-
* import { extractVtexContext } from "@decocms/apps/vtex/middleware";
|
|
310
|
-
*
|
|
311
|
-
* createDecoWorkerEntry(serverEntry, {
|
|
312
|
-
* buildSegment: (request) => {
|
|
313
|
-
* const vtx = extractVtexContext(request);
|
|
314
|
-
* return {
|
|
315
|
-
* device: /mobile|android|iphone/i.test(request.headers.get("user-agent") ?? "") ? "mobile" : "desktop",
|
|
316
|
-
* loggedIn: vtx.isLoggedIn,
|
|
317
|
-
* salesChannel: vtx.salesChannel,
|
|
318
|
-
* // Include regionId only if the site uses VTEX regionalization.
|
|
319
|
-
* // When present, cache entries split by region; omit it for
|
|
320
|
-
* // non-regionalized sites to maximize cache sharing.
|
|
321
|
-
* regionId: vtx.regionId ?? undefined,
|
|
322
|
-
* };
|
|
323
|
-
* },
|
|
324
|
-
* });
|
|
325
|
-
* ```
|
|
326
|
-
*/
|
|
327
|
-
buildSegment?: (request: Request) => SegmentKey;
|
|
328
|
-
|
|
329
|
-
/**
|
|
330
|
-
* Environment variable name holding the cache purge token.
|
|
331
|
-
* Set to `false` to disable the purge endpoint.
|
|
332
|
-
* @default "PURGE_TOKEN"
|
|
333
|
-
*/
|
|
334
|
-
purgeTokenEnv?: string | false;
|
|
335
|
-
/**
|
|
336
|
-
* Paths that should always bypass the edge cache, even if the
|
|
337
|
-
* profile detector would otherwise cache them.
|
|
338
|
-
* Defaults include `/_build`, `/deco/`, `/live/`, `/.decofile`.
|
|
339
|
-
*/
|
|
340
|
-
bypassPaths?: string[];
|
|
341
|
-
|
|
342
|
-
/**
|
|
343
|
-
* Additional paths (beyond the defaults) that should bypass caching.
|
|
344
|
-
* Merged with the default bypass paths.
|
|
345
|
-
*/
|
|
346
|
-
extraBypassPaths?: string[];
|
|
347
|
-
|
|
348
|
-
/**
|
|
349
|
-
* Custom HTML shell for the `/live/previews` iframe page.
|
|
350
|
-
* If not provided, a shell is generated from the render config
|
|
351
|
-
* (theme, CSS, fonts) set via setRenderShell().
|
|
352
|
-
*/
|
|
353
|
-
previewShell?: string;
|
|
354
|
-
|
|
355
|
-
/**
|
|
356
|
-
* Regex for detecting fingerprinted static assets (content-hashed filenames).
|
|
357
|
-
* Matched paths get `immutable, max-age=31536000`.
|
|
358
|
-
* @default /\/_build\/assets\/.*-[a-zA-Z0-9]{8,}\.\w+$/
|
|
359
|
-
*/
|
|
360
|
-
fingerprintedAssetPattern?: RegExp;
|
|
361
|
-
|
|
362
|
-
/**
|
|
363
|
-
* Whether to strip UTM and tracking params from cache keys.
|
|
364
|
-
* Two requests differing only in utm_source, fbclid, etc.
|
|
365
|
-
* will share the same cache entry.
|
|
366
|
-
* @default true
|
|
367
|
-
*/
|
|
368
|
-
stripTrackingParams?: boolean;
|
|
369
|
-
|
|
370
|
-
/**
|
|
371
|
-
* Optional proxy handler for commerce backend routes
|
|
372
|
-
* (checkout, account, API, login, etc.).
|
|
373
|
-
*
|
|
374
|
-
* Called early in the request pipeline — after admin routes and cache
|
|
375
|
-
* purge, but before static assets and edge cache logic. This ensures
|
|
376
|
-
* proxy requests never hit TanStack Start or the React SSR pipeline.
|
|
377
|
-
*
|
|
378
|
-
* Return a `Response` to proxy the request, or `null` to let the
|
|
379
|
-
* normal TanStack Start flow handle it.
|
|
380
|
-
*
|
|
381
|
-
* @example
|
|
382
|
-
* ```ts
|
|
383
|
-
* import { shouldProxyToVtex, proxyToVtex } from "@decocms/apps/vtex/utils/proxy";
|
|
384
|
-
*
|
|
385
|
-
* createDecoWorkerEntry(serverEntry, {
|
|
386
|
-
* proxyHandler: (request, url) => {
|
|
387
|
-
* if (shouldProxyToVtex(url.pathname)) {
|
|
388
|
-
* return proxyToVtex(request);
|
|
389
|
-
* }
|
|
390
|
-
* return null;
|
|
391
|
-
* },
|
|
392
|
-
* });
|
|
393
|
-
* ```
|
|
394
|
-
*/
|
|
395
|
-
proxyHandler?: (request: Request, url: URL) => Promise<Response | null> | Response | null;
|
|
396
|
-
|
|
397
|
-
/**
|
|
398
|
-
* Environment variable name holding a build version string.
|
|
399
|
-
* The value is appended to every cache key so each deploy gets its own
|
|
400
|
-
* cache namespace — old entries become orphaned and expire naturally,
|
|
401
|
-
* preventing stale HTML that references old CSS/JS fingerprinted filenames.
|
|
402
|
-
*
|
|
403
|
-
* Set to `false` to disable. When the env var is missing or empty,
|
|
404
|
-
* cache keys remain unversioned (backward-compatible).
|
|
405
|
-
*
|
|
406
|
-
* @default "BUILD_HASH"
|
|
407
|
-
*
|
|
408
|
-
* @example
|
|
409
|
-
* ```yaml
|
|
410
|
-
* # CI: pass git hash to wrangler
|
|
411
|
-
* - run: npx wrangler deploy --var BUILD_HASH:$(git rev-parse --short HEAD)
|
|
412
|
-
* ```
|
|
413
|
-
*/
|
|
414
|
-
cacheVersionEnv?: string | false;
|
|
415
|
-
|
|
416
|
-
/**
|
|
417
|
-
* Security headers appended to every SSR response (HTML pages).
|
|
418
|
-
* Pass `false` to disable entirely.
|
|
419
|
-
*
|
|
420
|
-
* Default headers: X-Content-Type-Options, Referrer-Policy,
|
|
421
|
-
* Permissions-Policy, X-XSS-Protection, HSTS, Cross-Origin-Opener-Policy,
|
|
422
|
-
* and a `Content-Security-Policy: frame-ancestors` directive that lets the
|
|
423
|
-
* deco admin/studio embed the storefront (see DEFAULT_FRAME_ANCESTORS_CSP).
|
|
424
|
-
*
|
|
425
|
-
* Custom entries are merged with defaults (custom values take precedence) —
|
|
426
|
-
* pass `Content-Security-Policy` here to override the default frame-ancestors.
|
|
427
|
-
*
|
|
428
|
-
* @default DEFAULT_SECURITY_HEADERS
|
|
429
|
-
*/
|
|
430
|
-
securityHeaders?: Record<string, string> | false;
|
|
431
|
-
|
|
432
|
-
/**
|
|
433
|
-
* Content Security Policy directives (report-only by default).
|
|
434
|
-
* Pass an array of directive strings which are joined with "; ".
|
|
435
|
-
* Pass `false` to omit CSP entirely.
|
|
436
|
-
*
|
|
437
|
-
* @example
|
|
438
|
-
* ```ts
|
|
439
|
-
* csp: [
|
|
440
|
-
* "default-src 'self'",
|
|
441
|
-
* "script-src 'self' 'unsafe-inline' https://www.googletagmanager.com",
|
|
442
|
-
* "img-src 'self' data: https:",
|
|
443
|
-
* ]
|
|
444
|
-
* ```
|
|
445
|
-
*/
|
|
446
|
-
csp?: string[] | false;
|
|
447
|
-
|
|
448
|
-
/**
|
|
449
|
-
* How the `csp` directives are delivered.
|
|
450
|
-
*
|
|
451
|
-
* - `"report-only"` (default): emitted as `Content-Security-Policy-Report-Only`.
|
|
452
|
-
* Browsers report violations but never block — backward-compatible, zero risk.
|
|
453
|
-
* - `"enforce"`: emitted as an enforced `Content-Security-Policy`, but ONLY on
|
|
454
|
-
* non-cacheable (`CDN-Cache-Control: no-store`) HTML responses. A fresh nonce
|
|
455
|
-
* is generated per request, threaded into every SSR inline `<script>` (via
|
|
456
|
-
* `router.options.ssr.nonce` + the deco layout components) and into the
|
|
457
|
-
* header's `script-src` (which also drops `'unsafe-inline'`). Cacheable
|
|
458
|
-
* responses stay report-only, because a per-request nonce would desync from a
|
|
459
|
-
* cached body and block every script. `'unsafe-eval'`, if present in the
|
|
460
|
-
* site's `script-src`, is left untouched — remove it explicitly in your `csp`.
|
|
461
|
-
*
|
|
462
|
-
* @default "report-only"
|
|
463
|
-
*/
|
|
464
|
-
cspMode?: "report-only" | "enforce";
|
|
465
|
-
|
|
466
|
-
/**
|
|
467
|
-
* Automatically inject Cloudflare geo data (country, region, city)
|
|
468
|
-
* as internal cookies on every request so location matchers can read
|
|
469
|
-
* them from MatcherContext.cookies. The cookies are only visible
|
|
470
|
-
* within the Worker — they are never sent to the browser.
|
|
471
|
-
*
|
|
472
|
-
* @default true
|
|
473
|
-
*/
|
|
474
|
-
autoInjectGeoCookies?: boolean;
|
|
475
|
-
|
|
476
|
-
/**
|
|
477
|
-
* Controls how Cloudflare geo data is folded into edge cache keys.
|
|
478
|
-
*
|
|
479
|
-
* - `"auto"` (default): inspects the loaded decofile on every `setBlocks()`
|
|
480
|
-
* call (startup + fast-deploy swaps). If any block is configured with
|
|
481
|
-
* `website/matchers/location.ts`, geo keying is activated at `"region"`
|
|
482
|
-
* granularity (country+state); otherwise it is set to `"off"`. `"region"`
|
|
483
|
-
* covers VTEX regionalization and most geo matchers without city-level
|
|
484
|
-
* fragmentation. Sites that need city precision should set `"city"`
|
|
485
|
-
* explicitly. No manual configuration needed for the common case.
|
|
486
|
-
* - `"city"`: full `country|region|city` key — maximum isolation for sites
|
|
487
|
-
* with city-level location matchers.
|
|
488
|
-
* - `"region"`: `country|region` — good for region/state matchers (e.g.
|
|
489
|
-
* VTEX regionalization), avoids city-level fragmentation.
|
|
490
|
-
* - `"country"`: country only.
|
|
491
|
-
* - `"off"`: no `__cf_geo` param is added and the automatic `regionId`
|
|
492
|
-
* backfill from CF geo is disabled. Use for single-catalog storefronts
|
|
493
|
-
* that do not vary content by location — recovers the full edge HIT rate.
|
|
494
|
-
*
|
|
495
|
-
* @default "auto"
|
|
496
|
-
*/
|
|
497
|
-
geoCacheKey?: "auto" | "off" | "country" | "region" | "city";
|
|
498
|
-
|
|
499
|
-
/**
|
|
500
|
-
* Cookie names considered "safe" for caching — these are public/anonymous
|
|
501
|
-
* cookies that do not carry per-user session or auth data.
|
|
502
|
-
*
|
|
503
|
-
* When a response contains ONLY safe cookies, it is still eligible for
|
|
504
|
-
* Cache API storage. The safe cookies are stripped from the cached copy
|
|
505
|
-
* but kept on the response served to the current user.
|
|
506
|
-
*
|
|
507
|
-
* If the response contains ANY cookie NOT in this list, the response
|
|
508
|
-
* bypasses caching entirely (existing behavior).
|
|
509
|
-
*
|
|
510
|
-
* @default DEFAULT_SAFE_COOKIES (vtex_is_session, vtex_is_anonymous, vtex_segment, _deco_bucket)
|
|
511
|
-
*
|
|
512
|
-
* @example
|
|
513
|
-
* ```ts
|
|
514
|
-
* createDecoWorkerEntry(serverEntry, {
|
|
515
|
-
* safeCookies: [
|
|
516
|
-
* ...DEFAULT_SAFE_COOKIES,
|
|
517
|
-
* "my_custom_analytics_cookie",
|
|
518
|
-
* ],
|
|
519
|
-
* });
|
|
520
|
-
* ```
|
|
521
|
-
*/
|
|
522
|
-
safeCookies?: string[];
|
|
523
|
-
|
|
524
|
-
/**
|
|
525
|
-
* Additional static paths (beyond fingerprinted assets) that should
|
|
526
|
-
* receive long-lived immutable cache headers.
|
|
527
|
-
*
|
|
528
|
-
* Useful for non-fingerprinted resources like fonts that live at
|
|
529
|
-
* stable URLs (e.g., `/fonts/Lato-Regular.woff2`).
|
|
530
|
-
*
|
|
531
|
-
* @default ["/fonts/"]
|
|
532
|
-
*
|
|
533
|
-
* @example
|
|
534
|
-
* ```ts
|
|
535
|
-
* createDecoWorkerEntry(serverEntry, {
|
|
536
|
-
* staticPaths: ["/fonts/", "/static/", "/images/icons/"],
|
|
537
|
-
* });
|
|
538
|
-
* ```
|
|
539
|
-
*/
|
|
540
|
-
staticPaths?: string[];
|
|
541
|
-
|
|
542
|
-
/**
|
|
543
|
-
* CDN-Cache-Control header strategy — i.e. what Cloudflare's own CDN layer is
|
|
544
|
-
* allowed to do, as distinct from the Cache API this Worker manages directly.
|
|
545
|
-
*
|
|
546
|
-
* The default is `"no-store"` because the Worker's cache key is a SYNTHETIC
|
|
547
|
-
* Request carrying `__seg`/`__cf_device`/`__cf_geo`/`__bot`/`__fetch`/`__abf`
|
|
548
|
-
* (see `buildCacheKey`), while the CDN keys on the raw URL and ignores `Vary`
|
|
549
|
-
* beyond `Accept-Encoding`. Letting the CDN cache by URL alone would serve
|
|
550
|
-
* desktop HTML to mobile, one region's to another, or a crawler's eager
|
|
551
|
-
* render to humans.
|
|
552
|
-
*
|
|
553
|
-
* - `"serverfn-segment"` (default): allow CDN caching for `/_serverFn`
|
|
554
|
-
* requests whose URL carries a verified `__cseg` marker (see
|
|
555
|
-
* `./cdnSegment` and `decoServerFnFetch`). The marker makes the CDN's key
|
|
556
|
-
* equivalent to the Worker's. HTML documents keep `no-store` — the initial
|
|
557
|
-
* navigation is a browser request with no client hook to attach a marker.
|
|
558
|
-
*
|
|
559
|
-
* This is the default because it is inert until a marker actually arrives:
|
|
560
|
-
* a client that never sends `__cseg` keeps getting `no-store`, so enabling
|
|
561
|
-
* it cannot change behaviour on its own. That is what lets a site pick the
|
|
562
|
-
* feature up from a version bump rather than a per-site change.
|
|
563
|
-
* - `"no-store"`: the CDN never caches; every request invokes the Worker.
|
|
564
|
-
* Always correct, never fast. Set this to opt OUT.
|
|
565
|
-
* - `"match-profile"`: mirror the profile's `edge.fresh` as a CDN TTL. Sound
|
|
566
|
-
* ONLY when the cache key is the raw URL — no `buildSegment`,
|
|
567
|
-
* `deviceSpecificKeys: false`, `geoCacheKey: "off"`. Since
|
|
568
|
-
* `deviceSpecificKeys` defaults to **true**, this is almost never the case;
|
|
569
|
-
* when it isn't, the option is ignored with a warning rather than silently
|
|
570
|
-
* cross-serving segments.
|
|
571
|
-
* - A function: return a CDN-Cache-Control value per profile, or `null` for
|
|
572
|
-
* no-store. You own the correctness of the key/TTL pairing.
|
|
573
|
-
*
|
|
574
|
-
* Caching HTML is deliberately not covered here. It is not a header change:
|
|
575
|
-
* whatever sits in front of the Worker has to reproduce the key above, and
|
|
576
|
-
* the initial navigation has no client hook to attach a marker to.
|
|
577
|
-
*
|
|
578
|
-
* @default "serverfn-segment"
|
|
579
|
-
*/
|
|
580
|
-
cdnCacheControl?:
|
|
581
|
-
| "no-store"
|
|
582
|
-
| "serverfn-segment"
|
|
583
|
-
| "match-profile"
|
|
584
|
-
| ((profile: CacheProfileName) => string | null);
|
|
585
|
-
/**
|
|
586
|
-
* Auto-instrumentation via `instrumentWorker` is enabled by default. The
|
|
587
|
-
* framework wraps the returned handler so that, when OTel env vars
|
|
588
|
-
* (`DECO_OTEL_*_ENDPOINT`, `DECO_OTEL_TRACES_SAMPLING_RATE`,
|
|
589
|
-
* `DECO_OTEL_LOGS_MIN_LEVEL`) are set on the Worker's `env`, telemetry
|
|
590
|
-
* starts flowing without the site having to touch its worker entry.
|
|
591
|
-
*
|
|
592
|
-
* - Pass an `OtelOptions` object to override defaults (serviceName,
|
|
593
|
-
* sampling, custom env var names, etc.).
|
|
594
|
-
* - Pass `false` to disable framework-side instrumentation entirely
|
|
595
|
-
* (e.g., when the site applies its own `instrumentWorker` wrap or
|
|
596
|
-
* uses a custom transport).
|
|
597
|
-
*
|
|
598
|
-
* When the OTel endpoint env vars are absent the wrap is effectively a
|
|
599
|
-
* no-op — no buffers, no flushes, no network calls.
|
|
600
|
-
*/
|
|
601
|
-
observability?: OtelOptions | false;
|
|
602
|
-
|
|
603
|
-
/**
|
|
604
|
-
* Default `User-Agent` for OUTBOUND `fetch` calls (loaders, commerce
|
|
605
|
-
* APIs, proxies). Cloudflare Workers sends no User-Agent at all, and
|
|
606
|
-
* UA-less requests are blocked by common WAF setups (Cloudflare managed
|
|
607
|
-
* rules / Bot Fight Mode) on partner origins. The old Deno runtime
|
|
608
|
-
* implicitly sent `Deno/x.y.z` on every outbound request, so this
|
|
609
|
-
* restores pre-migration behavior with an identifiable value.
|
|
610
|
-
*
|
|
611
|
-
* Applied only when the caller didn't set a User-Agent — app-specific
|
|
612
|
-
* UAs always win.
|
|
613
|
-
*
|
|
614
|
-
* - Pass a string to override the value (e.g. to match a partner's
|
|
615
|
-
* existing WAF allowlist during migration).
|
|
616
|
-
* - Pass `false` to leave `globalThis.fetch` untouched.
|
|
617
|
-
*
|
|
618
|
-
* @default `Deco/<version> (+https://deco.cx)` — see DECO_USER_AGENT.
|
|
619
|
-
*/
|
|
620
|
-
outboundUserAgent?: string | false;
|
|
621
|
-
}
|
|
622
|
-
|
|
623
|
-
// ---------------------------------------------------------------------------
|
|
624
|
-
// Constants
|
|
625
|
-
// ---------------------------------------------------------------------------
|
|
626
|
-
|
|
627
|
-
const PREVIEW_SHELL_SCRIPT = `(function() {
|
|
628
|
-
if (window.__DECO_LIVE_CONTROLS__) return;
|
|
629
|
-
window.__DECO_LIVE_CONTROLS__ = true;
|
|
630
|
-
addEventListener("message", function(event) {
|
|
631
|
-
var data = event.data;
|
|
632
|
-
if (!data || typeof data !== "object") return;
|
|
633
|
-
switch (data.type) {
|
|
634
|
-
case "editor::inject":
|
|
635
|
-
if (data.args && data.args.script) {
|
|
636
|
-
try { eval(data.args.script); } catch(e) { console.error("[deco] inject error:", e); }
|
|
637
|
-
}
|
|
638
|
-
break;
|
|
639
|
-
}
|
|
640
|
-
});
|
|
641
|
-
})();`;
|
|
642
|
-
|
|
643
|
-
function buildPreviewShell(): string {
|
|
644
|
-
return buildHtmlShell({ script: PREVIEW_SHELL_SCRIPT });
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
// ---------------------------------------------------------------------------
|
|
648
|
-
// Cloudflare geo cookie injection
|
|
649
|
-
// ---------------------------------------------------------------------------
|
|
650
|
-
|
|
651
|
-
/**
|
|
652
|
-
* Inject Cloudflare geo data as cookies so matchers (location.ts) can
|
|
653
|
-
* read them from MatcherContext.cookies without relying on request.cf.
|
|
654
|
-
*
|
|
655
|
-
* Call this on the incoming request before passing it to the worker entry.
|
|
656
|
-
* Only needed in production Cloudflare Workers where `request.cf` is populated.
|
|
657
|
-
*
|
|
658
|
-
* @example
|
|
659
|
-
* ```ts
|
|
660
|
-
* export default {
|
|
661
|
-
* async fetch(request, env, ctx) {
|
|
662
|
-
* return handler.fetch(injectGeoCookies(request), env, ctx);
|
|
663
|
-
* }
|
|
664
|
-
* };
|
|
665
|
-
* ```
|
|
666
|
-
*/
|
|
667
|
-
/**
|
|
668
|
-
* Returns `true` when the decofile contains at least one block whose
|
|
669
|
-
* `__resolveType` is `website/matchers/location.ts`. Used by
|
|
670
|
-
* `geoCacheKey: "auto"` to decide whether geo cache key fragmentation
|
|
671
|
-
* should be active.
|
|
672
|
-
*
|
|
673
|
-
* Matches only resolver-type references (not arbitrary string values) to
|
|
674
|
-
* avoid false positives from content/label fields that happen to mention
|
|
675
|
-
* the path.
|
|
676
|
-
*/
|
|
677
|
-
export function detectLocationMatcher(blocks: Record<string, unknown>): boolean {
|
|
678
|
-
return JSON.stringify(blocks).includes('"__resolveType":"website/matchers/location.ts"');
|
|
679
|
-
}
|
|
680
|
-
|
|
681
|
-
/**
|
|
682
|
-
* Build the `__cf_geo` cache-key fragment from Cloudflare's `request.cf`
|
|
683
|
-
* object at the requested granularity.
|
|
684
|
-
*
|
|
685
|
-
* Returns `undefined` when `granularity` is `"off"`, `cf` is absent, or no
|
|
686
|
-
* relevant fields are present.
|
|
687
|
-
*
|
|
688
|
-
* @example
|
|
689
|
-
* buildGeoCacheParam({ country: "BR", region: "São Paulo", city: "SP" }, "region")
|
|
690
|
-
* // → "BR|São Paulo"
|
|
691
|
-
*/
|
|
692
|
-
export function buildGeoCacheParam(
|
|
693
|
-
cf: Record<string, string> | undefined,
|
|
694
|
-
granularity: "off" | "country" | "region" | "city",
|
|
695
|
-
): string | undefined {
|
|
696
|
-
if (granularity === "off" || !cf) return undefined;
|
|
697
|
-
const parts: string[] = [];
|
|
698
|
-
if (cf.country) parts.push(cf.country);
|
|
699
|
-
if (granularity !== "country" && cf.region) parts.push(cf.region);
|
|
700
|
-
if (granularity === "city" && cf.city) parts.push(cf.city);
|
|
701
|
-
return parts.length ? parts.join("|") : undefined;
|
|
702
|
-
}
|
|
703
|
-
|
|
704
|
-
export function injectGeoCookies(request: Request): Request {
|
|
705
|
-
const cf = (request as unknown as { cf?: Record<string, string> }).cf;
|
|
706
|
-
if (!cf) return request;
|
|
707
|
-
|
|
708
|
-
const parts: string[] = [];
|
|
709
|
-
if (cf.region) parts.push(`__cf_geo_region=${encodeURIComponent(cf.region)}`);
|
|
710
|
-
if (cf.country) parts.push(`__cf_geo_country=${encodeURIComponent(cf.country)}`);
|
|
711
|
-
if (cf.city) parts.push(`__cf_geo_city=${encodeURIComponent(cf.city)}`);
|
|
712
|
-
if (cf.latitude) parts.push(`__cf_geo_lat=${encodeURIComponent(cf.latitude)}`);
|
|
713
|
-
if (cf.longitude) parts.push(`__cf_geo_lng=${encodeURIComponent(cf.longitude)}`);
|
|
714
|
-
if (cf.regionCode) parts.push(`__cf_geo_region_code=${encodeURIComponent(cf.regionCode)}`);
|
|
715
|
-
|
|
716
|
-
if (!parts.length) return request;
|
|
717
|
-
|
|
718
|
-
const existing = request.headers.get("cookie") ?? "";
|
|
719
|
-
const combined = existing ? `${existing}; ${parts.join("; ")}` : parts.join("; ");
|
|
720
|
-
|
|
721
|
-
// Strip CF geo headers that carry non-ASCII values (cf-region: "São Paulo",
|
|
722
|
-
// cf-ipcity: "Brasília", etc.) before building the new Request. The geo
|
|
723
|
-
// data is preserved in the __cf_geo_* cookies we just built, so callers
|
|
724
|
-
// downstream lose no information.
|
|
725
|
-
//
|
|
726
|
-
// Without this strip, the Workers runtime emits a warning on every
|
|
727
|
-
// request because the new Request inherits these UTF-8 headers from the
|
|
728
|
-
// inbound request:
|
|
729
|
-
//
|
|
730
|
-
// "A header value for "cf-region" contains non-ASCII characters: "..."
|
|
731
|
-
//
|
|
732
|
-
// and the warning is logged once per non-ASCII header — for a Brazilian
|
|
733
|
-
// storefront with cities/states full of accents that means ~2 warns per
|
|
734
|
-
// request × every request that hits the worker.
|
|
735
|
-
const headers = new Headers();
|
|
736
|
-
for (const [key, value] of request.headers.entries()) {
|
|
737
|
-
const lk = key.toLowerCase();
|
|
738
|
-
if (lk === "cf-region" || lk === "cf-ipcity") continue;
|
|
739
|
-
headers.set(key, value);
|
|
740
|
-
}
|
|
741
|
-
headers.set("cookie", combined);
|
|
742
|
-
|
|
743
|
-
// Mirror the ASCII-safe geo fields from request.cf into headers so matchers
|
|
744
|
-
// that read `request.headers.get("cf-region-code")` (parity with the
|
|
745
|
-
// upstream deco-cx/apps location matcher) still work even if the inbound
|
|
746
|
-
// request didn't carry them. Non-ASCII fields (region name, city) stay in
|
|
747
|
-
// the cookies above — putting them in headers would re-trigger the
|
|
748
|
-
// non-ASCII warning we strip on the loop above.
|
|
749
|
-
if (cf.country && !headers.has("cf-ipcountry")) headers.set("cf-ipcountry", cf.country);
|
|
750
|
-
if (cf.regionCode && !headers.has("cf-region-code")) headers.set("cf-region-code", cf.regionCode);
|
|
751
|
-
if (cf.latitude && !headers.has("cf-iplatitude")) headers.set("cf-iplatitude", cf.latitude);
|
|
752
|
-
if (cf.longitude && !headers.has("cf-iplongitude")) headers.set("cf-iplongitude", cf.longitude);
|
|
753
|
-
|
|
754
|
-
return new Request(request, { headers });
|
|
755
|
-
}
|
|
756
|
-
|
|
757
|
-
const ONE_YEAR = 31536000;
|
|
758
|
-
|
|
759
|
-
/**
|
|
760
|
-
* Sensible security headers for any production storefront.
|
|
761
|
-
*
|
|
762
|
-
* Framing protection is handled by a default `Content-Security-Policy:
|
|
763
|
-
* frame-ancestors` directive (see DEFAULT_FRAME_ANCESTORS_CSP), NOT
|
|
764
|
-
* `X-Frame-Options`. CSP level 3 `frame-ancestors` supersedes X-Frame-Options
|
|
765
|
-
* in every modern browser, and — unlike the all-or-nothing SAMEORIGIN value —
|
|
766
|
-
* it can allow the deco admin/studio to embed the storefront for live preview
|
|
767
|
-
* while still blocking arbitrary third-party framing (clickjacking).
|
|
768
|
-
*
|
|
769
|
-
* Full CSP (script-src etc.) is intentionally not included here — it's
|
|
770
|
-
* site-specific (third-party script domains) and passed via the `csp` option.
|
|
771
|
-
*/
|
|
772
|
-
export const DEFAULT_SECURITY_HEADERS: Record<string, string> = {
|
|
773
|
-
"X-Content-Type-Options": "nosniff",
|
|
774
|
-
"Referrer-Policy": "strict-origin-when-cross-origin",
|
|
775
|
-
"Permissions-Policy": "camera=(), microphone=(), geolocation=()",
|
|
776
|
-
"X-XSS-Protection": "1; mode=block",
|
|
777
|
-
"Strict-Transport-Security": "max-age=63072000; includeSubDomains; preload",
|
|
778
|
-
"Cross-Origin-Opener-Policy": "same-origin-allow-popups",
|
|
779
|
-
};
|
|
780
|
-
|
|
781
|
-
/**
|
|
782
|
-
* Origins allowed to embed the storefront in an iframe. These are the deco
|
|
783
|
-
* studio surfaces that render the live-preview iframe, plus `'self'` so the
|
|
784
|
-
* storefront can frame itself.
|
|
785
|
-
*
|
|
786
|
-
* A site can widen this by passing its own
|
|
787
|
-
* `securityHeaders["Content-Security-Policy"]`, or drop framing protection
|
|
788
|
-
* entirely with `securityHeaders: false`.
|
|
789
|
-
*/
|
|
790
|
-
export const DECO_ADMIN_FRAME_ANCESTORS: string[] = [
|
|
791
|
-
"'self'",
|
|
792
|
-
"https://studio.decocms.com",
|
|
793
|
-
"https://*.deco.studio",
|
|
794
|
-
];
|
|
795
|
-
|
|
796
|
-
/**
|
|
797
|
-
* Default enforcement CSP shipped on every SSR HTML response. Only the
|
|
798
|
-
* `frame-ancestors` directive is enforced by default; the full site CSP
|
|
799
|
-
* (passed via the `csp` option) is emitted report-only.
|
|
800
|
-
*/
|
|
801
|
-
export const DEFAULT_FRAME_ANCESTORS_CSP = `frame-ancestors ${DECO_ADMIN_FRAME_ANCESTORS.join(" ")}`;
|
|
802
|
-
|
|
803
|
-
/**
|
|
804
|
-
* Rewrite a `script-src` directive for nonce enforcement: drop `'unsafe-inline'`
|
|
805
|
-
* (a nonce makes it dead weight — and CSP ignores it once a nonce is present)
|
|
806
|
-
* and add `'nonce-<nonce>'` plus `'inline-speculation-rules'` (so the layout's
|
|
807
|
-
* `<script type="speculationrules">` still runs). `'unsafe-eval'` is left as-is.
|
|
808
|
-
*/
|
|
809
|
-
function hardenScriptSrc(directive: string, nonce: string): string {
|
|
810
|
-
const tokens = directive.trim().split(/\s+/).slice(1);
|
|
811
|
-
const kept = tokens.filter((t) => t.toLowerCase() !== "'unsafe-inline'");
|
|
812
|
-
for (const extra of [`'nonce-${nonce}'`, "'inline-speculation-rules'"]) {
|
|
813
|
-
if (!kept.includes(extra)) kept.push(extra);
|
|
814
|
-
}
|
|
815
|
-
return `script-src ${kept.join(" ")}`;
|
|
816
|
-
}
|
|
817
|
-
|
|
818
|
-
/**
|
|
819
|
-
* Build the enforced `Content-Security-Policy` value from the site's `csp`
|
|
820
|
-
* directives + the enforced `frame-ancestors`. The `script-src` directive is
|
|
821
|
-
* hardened with the request nonce (added if the site declared none). Any
|
|
822
|
-
* `frame-ancestors` the site put in `csp` is dropped in favour of the canonical
|
|
823
|
-
* enforced one.
|
|
824
|
-
*/
|
|
825
|
-
export function buildEnforcedCsp(
|
|
826
|
-
directives: string[],
|
|
827
|
-
frameAncestorsCsp: string,
|
|
828
|
-
nonce: string,
|
|
829
|
-
): string {
|
|
830
|
-
const out: string[] = [];
|
|
831
|
-
let sawScriptSrc = false;
|
|
832
|
-
for (const directive of directives) {
|
|
833
|
-
const name = directive.trim().split(/\s+/)[0]?.toLowerCase();
|
|
834
|
-
if (name === "script-src") {
|
|
835
|
-
sawScriptSrc = true;
|
|
836
|
-
out.push(hardenScriptSrc(directive, nonce));
|
|
837
|
-
} else if (name === "frame-ancestors") {
|
|
838
|
-
// replaced by the canonical enforced frame-ancestors appended below
|
|
839
|
-
} else {
|
|
840
|
-
out.push(directive.trim());
|
|
841
|
-
}
|
|
842
|
-
}
|
|
843
|
-
if (!sawScriptSrc) {
|
|
844
|
-
out.push(`script-src 'self' 'nonce-${nonce}' 'inline-speculation-rules'`);
|
|
845
|
-
}
|
|
846
|
-
out.push(frameAncestorsCsp.trim());
|
|
847
|
-
return out.join("; ");
|
|
848
|
-
}
|
|
849
|
-
|
|
850
|
-
const DEFAULT_BYPASS_PATHS = ["/_build", "/deco/", "/live/", "/.decofile"];
|
|
851
|
-
|
|
852
|
-
/**
|
|
853
|
-
* Cookie names that are safe for caching — they carry anonymous/public
|
|
854
|
-
* segment data, not per-user auth tokens.
|
|
855
|
-
*
|
|
856
|
-
* VTEX Intelligent Search sets `vtex_is_session` and `vtex_is_anonymous`
|
|
857
|
-
* on every response. `vtex_segment` encodes the sales channel.
|
|
858
|
-
* `_deco_bucket` is the A/B test cohort cookie.
|
|
859
|
-
*/
|
|
860
|
-
export const DEFAULT_SAFE_COOKIES: string[] = [
|
|
861
|
-
"vtex_is_session",
|
|
862
|
-
"vtex_is_anonymous",
|
|
863
|
-
"vtex_segment",
|
|
864
|
-
"_deco_bucket",
|
|
865
|
-
];
|
|
866
|
-
|
|
867
|
-
const DEFAULT_STATIC_PATHS = ["/fonts/"];
|
|
868
|
-
|
|
869
|
-
/**
|
|
870
|
-
* Parse Set-Cookie header values and return cookie names.
|
|
871
|
-
*/
|
|
872
|
-
function parseCookieNames(response: Response): string[] {
|
|
873
|
-
const names: string[] = [];
|
|
874
|
-
// getSetCookie() returns individual Set-Cookie values (available in Workers runtime)
|
|
875
|
-
const setCookies = (response.headers as any).getSetCookie?.() as string[] | undefined;
|
|
876
|
-
if (setCookies) {
|
|
877
|
-
for (const sc of setCookies) {
|
|
878
|
-
const eqIdx = sc.indexOf("=");
|
|
879
|
-
if (eqIdx > 0) names.push(sc.slice(0, eqIdx).trim());
|
|
880
|
-
}
|
|
881
|
-
} else {
|
|
882
|
-
// Fallback: parse from combined header (less reliable but covers edge cases)
|
|
883
|
-
const combined = response.headers.get("set-cookie") ?? "";
|
|
884
|
-
for (const part of combined.split(",")) {
|
|
885
|
-
const eqIdx = part.indexOf("=");
|
|
886
|
-
if (eqIdx > 0) {
|
|
887
|
-
const name = part.slice(0, eqIdx).trim();
|
|
888
|
-
// Skip attributes like "Expires=..." that appear after semicolons
|
|
889
|
-
if (!name.includes(";") && name.length > 0) names.push(name);
|
|
890
|
-
}
|
|
891
|
-
}
|
|
892
|
-
}
|
|
893
|
-
return names;
|
|
894
|
-
}
|
|
895
|
-
|
|
896
|
-
/**
|
|
897
|
-
* Check if ALL cookies in a response are in the safe list.
|
|
898
|
-
* Returns true if the response has no cookies or only safe cookies.
|
|
899
|
-
*
|
|
900
|
-
* Fail-closed: a response that HAS a `set-cookie` we couldn't parse into names
|
|
901
|
-
* is treated as unsafe. The parser's fallback path (comma-splitting the
|
|
902
|
-
* combined header) is documented as unreliable, and the cost of the two
|
|
903
|
-
* outcomes is not symmetric — guessing "safe" here caches a personalized
|
|
904
|
-
* response into the shared edge entry.
|
|
905
|
-
*/
|
|
906
|
-
function hasOnlySafeCookies(response: Response, safeCookieSet: Set<string>): boolean {
|
|
907
|
-
if (!response.headers.has("set-cookie")) return true;
|
|
908
|
-
const names = parseCookieNames(response);
|
|
909
|
-
if (names.length === 0) return false;
|
|
910
|
-
return names.every((name) => safeCookieSet.has(name));
|
|
911
|
-
}
|
|
912
|
-
|
|
913
|
-
/**
|
|
914
|
-
* Clone a response, stripping Set-Cookie headers that match the safe list.
|
|
915
|
-
* Uses response.clone() to preserve the original body for the served response.
|
|
916
|
-
* The returned copy is intended for cache storage only.
|
|
917
|
-
*/
|
|
918
|
-
function stripSafeCookiesForCache(response: Response, safeCookieSet: Set<string>): Response {
|
|
919
|
-
const clone = response.clone();
|
|
920
|
-
const setCookies = (response.headers as any).getSetCookie?.() as string[] | undefined;
|
|
921
|
-
if (!setCookies || setCookies.length === 0) return clone;
|
|
922
|
-
|
|
923
|
-
// Remove all Set-Cookie headers, then re-add only unsafe ones
|
|
924
|
-
clone.headers.delete("set-cookie");
|
|
925
|
-
for (const sc of setCookies) {
|
|
926
|
-
const eqIdx = sc.indexOf("=");
|
|
927
|
-
const name = eqIdx > 0 ? sc.slice(0, eqIdx).trim() : "";
|
|
928
|
-
if (name && !safeCookieSet.has(name)) {
|
|
929
|
-
clone.headers.append("set-cookie", sc);
|
|
930
|
-
}
|
|
931
|
-
}
|
|
932
|
-
return clone;
|
|
933
|
-
}
|
|
934
|
-
|
|
935
|
-
/**
|
|
936
|
-
* Deduplicate Set-Cookie headers — keep only the LAST occurrence of
|
|
937
|
-
* each cookie name. Multiple layers (VTEX middleware, invoke handlers,
|
|
938
|
-
* etc.) may independently append the same cookie.
|
|
939
|
-
*/
|
|
940
|
-
function deduplicateSetCookies(response: Response): void {
|
|
941
|
-
const setCookies = (response.headers as any).getSetCookie?.() as string[] | undefined;
|
|
942
|
-
if (!setCookies || setCookies.length <= 1) return;
|
|
943
|
-
|
|
944
|
-
// Build map: cookie name → last Set-Cookie value
|
|
945
|
-
const seen = new Map<string, string>();
|
|
946
|
-
for (const sc of setCookies) {
|
|
947
|
-
const eqIdx = sc.indexOf("=");
|
|
948
|
-
const name = eqIdx > 0 ? sc.slice(0, eqIdx).trim() : sc;
|
|
949
|
-
seen.set(name, sc);
|
|
950
|
-
}
|
|
951
|
-
|
|
952
|
-
// If no duplicates, nothing to do
|
|
953
|
-
if (seen.size === setCookies.length) return;
|
|
954
|
-
|
|
955
|
-
response.headers.delete("set-cookie");
|
|
956
|
-
for (const sc of seen.values()) {
|
|
957
|
-
response.headers.append("set-cookie", sc);
|
|
958
|
-
}
|
|
959
|
-
}
|
|
960
|
-
|
|
961
|
-
const FINGERPRINTED_ASSET_RE = /(?:\/_build)?\/assets\/.*-[a-zA-Z0-9_-]{8,}\.\w+$/;
|
|
962
|
-
|
|
963
|
-
// ---------------------------------------------------------------------------
|
|
964
|
-
// Auto geo-key detection (module-level singleton)
|
|
965
|
-
// ---------------------------------------------------------------------------
|
|
966
|
-
// Registered once so that multiple createDecoWorkerEntry calls in the same
|
|
967
|
-
// isolate (e.g. integration tests) don't accumulate listeners. Uses "region"
|
|
968
|
-
// (country+state) as the auto granularity — covers VTEX regionalization and
|
|
969
|
-
// most geo matchers without the city-level fragmentation (~hundreds of buckets).
|
|
970
|
-
// Sites that need city precision should set geoCacheKey: "city" explicitly.
|
|
971
|
-
|
|
972
|
-
let _autoGeoKey: "off" | "region" = "off";
|
|
973
|
-
/**
|
|
974
|
-
* Whether `_autoGeoKey` is an answer or still the pre-hydration default. It
|
|
975
|
-
* starts `"off"` and only becomes `"region"` once a decofile carrying a
|
|
976
|
-
* location matcher loads, so anything that *reports* on `"off"` (rather than
|
|
977
|
-
* just keying on it) has to wait for a non-empty decofile first. Recomputed on
|
|
978
|
-
* every change rather than latched, so a reset back to an empty decofile
|
|
979
|
-
* un-settles it.
|
|
980
|
-
*/
|
|
981
|
-
let _autoGeoSettled = false;
|
|
982
|
-
let _autoGeoListenerInstalled = false;
|
|
983
|
-
|
|
984
|
-
function installAutoGeoListener(): void {
|
|
985
|
-
if (_autoGeoListenerInstalled) return;
|
|
986
|
-
_autoGeoListenerInstalled = true;
|
|
987
|
-
const update = (blocks: Record<string, unknown>) => {
|
|
988
|
-
_autoGeoKey = detectLocationMatcher(blocks) ? "region" : "off";
|
|
989
|
-
_autoGeoSettled = Object.keys(blocks).length > 0;
|
|
990
|
-
};
|
|
991
|
-
onChange(update);
|
|
992
|
-
update(loadBlocks());
|
|
993
|
-
}
|
|
994
|
-
|
|
995
|
-
let _draftPreviewInstalled = false;
|
|
996
|
-
|
|
997
|
-
/**
|
|
998
|
-
* Wire draft preview once: register the request-scoped draft getter with the
|
|
999
|
-
* runtime and keep the `previewHosts` allowlist in sync with the base decofile.
|
|
1000
|
-
* Registered unconditionally (idempotent), but the feature stays fully inert
|
|
1001
|
-
* until an allowlist names the request's host — see `./draft`.
|
|
1002
|
-
*/
|
|
1003
|
-
function installDraftPreviewListener(): void {
|
|
1004
|
-
if (_draftPreviewInstalled) return;
|
|
1005
|
-
_draftPreviewInstalled = true;
|
|
1006
|
-
registerDraftOverride();
|
|
1007
|
-
onChange((blocks) => installPreviewHostsFromBlocks(blocks));
|
|
1008
|
-
installPreviewHostsFromBlocks(loadBlocks());
|
|
1009
|
-
}
|
|
1010
|
-
|
|
1011
|
-
const IMMUTABLE_HEADERS: Record<string, string> = {
|
|
1012
|
-
"Cache-Control": `public, max-age=${ONE_YEAR}, immutable`,
|
|
1013
|
-
Vary: "Accept-Encoding",
|
|
1014
|
-
};
|
|
1015
|
-
|
|
1016
|
-
/** SHA-256 hex hash of a string — used for POST body cache keys. */
|
|
1017
|
-
async function hashText(text: string): Promise<string> {
|
|
1018
|
-
const data = new TextEncoder().encode(text);
|
|
1019
|
-
const buf = await crypto.subtle.digest("SHA-256", data);
|
|
1020
|
-
return Array.from(new Uint8Array(buf))
|
|
1021
|
-
.map((b) => b.toString(16).padStart(2, "0"))
|
|
1022
|
-
.join("");
|
|
1023
|
-
}
|
|
1024
|
-
|
|
1025
|
-
// ---------------------------------------------------------------------------
|
|
1026
|
-
// CMS redirect cache — keyed by revision so cross-bundle setBlocks() calls
|
|
1027
|
-
// (Vite server-function split) are detected via globalThis.__deco.revision.
|
|
1028
|
-
// ---------------------------------------------------------------------------
|
|
1029
|
-
|
|
1030
|
-
let _redirectMap: RedirectMap | null = null;
|
|
1031
|
-
let _redirectMapRevision: string | null = null;
|
|
1032
|
-
|
|
1033
|
-
// ---------------------------------------------------------------------------
|
|
1034
|
-
// Factory
|
|
1035
|
-
// ---------------------------------------------------------------------------
|
|
1036
|
-
|
|
1037
|
-
/**
|
|
1038
|
-
* CORS headers for the `?renderJson` response, from
|
|
1039
|
-
* {@link DecoWorkerEntryOptions.pageJsonCors}. `?renderJson` is public page data
|
|
1040
|
-
* (secrets + request-derived keys are stripped), so the default is `"*"` — any
|
|
1041
|
-
* origin, no credentials (the standard public-API CORS). `false` turns it off;
|
|
1042
|
-
* a list reflects an allow-listed request Origin *with* credentials.
|
|
1043
|
-
*/
|
|
1044
|
-
function pageJsonCorsHeaders(
|
|
1045
|
-
request: Request,
|
|
1046
|
-
cors: string[] | "*" | false | undefined,
|
|
1047
|
-
): Record<string, string> {
|
|
1048
|
-
if (cors === false) return {}; // explicitly disabled
|
|
1049
|
-
const effective = cors ?? "*"; // default: any origin (no credentials)
|
|
1050
|
-
const base = {
|
|
1051
|
-
"Access-Control-Allow-Methods": "GET, OPTIONS",
|
|
1052
|
-
"Access-Control-Allow-Headers": "Content-Type, If-None-Match, Authorization",
|
|
1053
|
-
"Access-Control-Expose-Headers": "ETag",
|
|
1054
|
-
};
|
|
1055
|
-
if (effective === "*") {
|
|
1056
|
-
return { ...base, "Access-Control-Allow-Origin": "*" };
|
|
1057
|
-
}
|
|
1058
|
-
const origin = request.headers.get("origin");
|
|
1059
|
-
if (origin && effective.includes(origin)) {
|
|
1060
|
-
return {
|
|
1061
|
-
...base,
|
|
1062
|
-
"Access-Control-Allow-Origin": origin,
|
|
1063
|
-
"Access-Control-Allow-Credentials": "true",
|
|
1064
|
-
Vary: "Origin",
|
|
1065
|
-
};
|
|
1066
|
-
}
|
|
1067
|
-
return {}; // origin not allow-listed → no CORS headers
|
|
1068
|
-
}
|
|
1069
|
-
|
|
1070
|
-
/**
|
|
1071
|
-
* Creates a Cloudflare Worker fetch handler that wraps a TanStack Start
|
|
1072
|
-
* server entry with intelligent edge caching.
|
|
1073
|
-
*/
|
|
1074
|
-
export function createDecoWorkerEntry(
|
|
1075
|
-
serverEntry: ServerEntry,
|
|
1076
|
-
options: DecoWorkerEntryOptions = {},
|
|
1077
|
-
): {
|
|
1078
|
-
fetch(
|
|
1079
|
-
request: Request,
|
|
1080
|
-
env: Record<string, unknown>,
|
|
1081
|
-
ctx: WorkerExecutionContext,
|
|
1082
|
-
): Promise<Response>;
|
|
1083
|
-
} {
|
|
1084
|
-
const {
|
|
1085
|
-
admin,
|
|
1086
|
-
detectProfile: customDetect,
|
|
1087
|
-
deviceSpecificKeys = true,
|
|
1088
|
-
buildSegment: rawBuildSegment,
|
|
1089
|
-
purgeTokenEnv = "PURGE_TOKEN",
|
|
1090
|
-
bypassPaths,
|
|
1091
|
-
extraBypassPaths = [],
|
|
1092
|
-
fingerprintedAssetPattern = FINGERPRINTED_ASSET_RE,
|
|
1093
|
-
stripTrackingParams: shouldStripTracking = true,
|
|
1094
|
-
previewShell: customPreviewShell,
|
|
1095
|
-
cacheVersionEnv = "BUILD_HASH",
|
|
1096
|
-
securityHeaders: securityHeadersOpt,
|
|
1097
|
-
csp: cspOpt,
|
|
1098
|
-
cspMode = "report-only",
|
|
1099
|
-
autoInjectGeoCookies: geoOpt = true,
|
|
1100
|
-
geoCacheKey: geoCacheKeyOpt = "auto",
|
|
1101
|
-
safeCookies: safeCookiesOpt = DEFAULT_SAFE_COOKIES,
|
|
1102
|
-
staticPaths: staticPathsOpt = DEFAULT_STATIC_PATHS,
|
|
1103
|
-
cdnCacheControl: cdnCacheControlOpt = "serverfn-segment",
|
|
1104
|
-
observability: observabilityOpt,
|
|
1105
|
-
outboundUserAgent: outboundUserAgentOpt,
|
|
1106
|
-
speculationRules: speculationRulesOpt,
|
|
1107
|
-
} = options;
|
|
1108
|
-
|
|
1109
|
-
// Speculation Rules — store the site-wide config in the shared singleton so
|
|
1110
|
-
// DecoRootLayout (SSR) emits the tag in <head>. Inert unless the site opts in.
|
|
1111
|
-
setSpeculationRules(speculationRulesOpt);
|
|
1112
|
-
|
|
1113
|
-
// Patch global fetch once so every outbound request — apps calling
|
|
1114
|
-
// `fetch` directly, RequestContext.fetch, instrumentedFetch — carries a
|
|
1115
|
-
// User-Agent. Workers sends none by default, which WAFs on partner
|
|
1116
|
-
// origins read as bot traffic. Set-if-absent: callers that set their
|
|
1117
|
-
// own UA are untouched.
|
|
1118
|
-
if (outboundUserAgentOpt !== false) {
|
|
1119
|
-
installDefaultUserAgent(outboundUserAgentOpt);
|
|
1120
|
-
}
|
|
1121
|
-
|
|
1122
|
-
// When geoCacheKey is "auto", install the module-level listener that watches
|
|
1123
|
-
// the decofile for website/matchers/location.ts. The listener is registered
|
|
1124
|
-
// only once regardless of how many times this factory is called, so there is
|
|
1125
|
-
// no listener accumulation in tests or dynamic worker-composition scenarios.
|
|
1126
|
-
if (geoCacheKeyOpt === "auto") {
|
|
1127
|
-
installAutoGeoListener();
|
|
1128
|
-
}
|
|
1129
|
-
|
|
1130
|
-
// Draft preview (pull-based): getter DI + previewHosts sync. Inert unless
|
|
1131
|
-
// the site opts in via `previewHosts` / DECO_ALLOWED_PREVIEW_HOSTS.
|
|
1132
|
-
installDraftPreviewListener();
|
|
1133
|
-
|
|
1134
|
-
/** Resolve the effective geo granularity for the current request. */
|
|
1135
|
-
function effectiveGeoKey(): "off" | "country" | "region" | "city" {
|
|
1136
|
-
return geoCacheKeyOpt === "auto" ? _autoGeoKey : geoCacheKeyOpt;
|
|
1137
|
-
}
|
|
1138
|
-
|
|
1139
|
-
// Backfill `regionId` from Cloudflare geo when the consumer's buildSegment
|
|
1140
|
-
// doesn't set one. Without this, sites using website/matchers/location.ts
|
|
1141
|
-
// get a single cached response per device that leaks across regions: the
|
|
1142
|
-
// first visitor's resolved variant gets served to everyone. With this,
|
|
1143
|
-
// existing sites get region-segmented cache "for free" on bump — no
|
|
1144
|
-
// worker-entry.ts edit required.
|
|
1145
|
-
function readRegionFromRequest(request: Request): string | undefined {
|
|
1146
|
-
// Trust the Cloudflare-injected `request.cf` first — it can't be spoofed
|
|
1147
|
-
// by clients. Fall back to the `cf-region-code` header for environments
|
|
1148
|
-
// that surface geo only via headers (e.g. tests, non-CF proxies).
|
|
1149
|
-
const cf = (request as unknown as { cf?: { regionCode?: string } }).cf;
|
|
1150
|
-
if (cf?.regionCode) return cf.regionCode;
|
|
1151
|
-
const fromHeader = request.headers.get("cf-region-code");
|
|
1152
|
-
return fromHeader || undefined;
|
|
1153
|
-
}
|
|
1154
|
-
|
|
1155
|
-
// Sites generated by older migration templates set `regionId` from the
|
|
1156
|
-
// Cloudflare state on every request, which splits every page's cache ~27x
|
|
1157
|
-
// (one copy per BR state) even when no content varies by location. The
|
|
1158
|
-
// framework already does this backfill below, and only when a location
|
|
1159
|
-
// matcher exists — so flag the redundant, unconditional version once.
|
|
1160
|
-
let warnedGeoSegment = false;
|
|
1161
|
-
/**
|
|
1162
|
-
* Whether `effectiveGeoKey() === "off"` is a real answer or just the
|
|
1163
|
-
* pre-hydration default. Under `geoCacheKey: "auto"` a request that lands
|
|
1164
|
-
* before the decofile loads would otherwise latch the warning below and tell
|
|
1165
|
-
* the team to delete a geo fallback its location matcher actually needs. An
|
|
1166
|
-
* explicit `geoCacheKey` has no such race.
|
|
1167
|
-
*/
|
|
1168
|
-
function geoKeySettled(): boolean {
|
|
1169
|
-
return geoCacheKeyOpt !== "auto" || _autoGeoSettled;
|
|
1170
|
-
}
|
|
1171
|
-
const buildSegment = rawBuildSegment
|
|
1172
|
-
? (request: Request): SegmentKey => {
|
|
1173
|
-
const seg = rawBuildSegment(request);
|
|
1174
|
-
if (
|
|
1175
|
-
!warnedGeoSegment &&
|
|
1176
|
-
seg.regionId &&
|
|
1177
|
-
effectiveGeoKey() === "off" &&
|
|
1178
|
-
geoKeySettled() &&
|
|
1179
|
-
seg.regionId === readRegionFromRequest(request)
|
|
1180
|
-
) {
|
|
1181
|
-
warnedGeoSegment = true;
|
|
1182
|
-
console.warn(
|
|
1183
|
-
`[deco] buildSegment sets regionId to the Cloudflare region ("${seg.regionId}") ` +
|
|
1184
|
-
"but no website/matchers/location.ts block exists, so every page's edge cache " +
|
|
1185
|
-
"is split per region for nothing. Return only the VTEX regionId from buildSegment " +
|
|
1186
|
-
'and let geoCacheKey: "auto" backfill the region when a location matcher is added.',
|
|
1187
|
-
);
|
|
1188
|
-
}
|
|
1189
|
-
if (seg.regionId) return seg;
|
|
1190
|
-
if (effectiveGeoKey() === "off") return seg;
|
|
1191
|
-
const region = readRegionFromRequest(request);
|
|
1192
|
-
return region ? { ...seg, regionId: region } : seg;
|
|
1193
|
-
}
|
|
1194
|
-
: undefined;
|
|
1195
|
-
|
|
1196
|
-
const safeCookieSet = new Set(safeCookiesOpt);
|
|
1197
|
-
|
|
1198
|
-
// One warning per worker instance, not per request — same pattern as
|
|
1199
|
-
// `warnedLongMaxAge` in @decocms/blocks/sdk/cachedLoader.
|
|
1200
|
-
let warnedMatchProfile = false;
|
|
1201
|
-
|
|
1202
|
-
// Build the final security headers map (merged defaults + custom + CSP)
|
|
1203
|
-
const secHeaders: Record<string, string> | null = (() => {
|
|
1204
|
-
if (securityHeadersOpt === false) return null;
|
|
1205
|
-
const base = { ...DEFAULT_SECURITY_HEADERS };
|
|
1206
|
-
// Ship an enforcement `frame-ancestors` CSP by default so the deco
|
|
1207
|
-
// admin/studio can embed the storefront for live preview without every
|
|
1208
|
-
// site copy-pasting the directive into its worker entry. A site can
|
|
1209
|
-
// override the whole header via securityHeaders["Content-Security-Policy"]
|
|
1210
|
-
// (the merge loop below wins) or disable all security headers with `false`.
|
|
1211
|
-
base["Content-Security-Policy"] = DEFAULT_FRAME_ANCESTORS_CSP;
|
|
1212
|
-
if (securityHeadersOpt) {
|
|
1213
|
-
for (const [k, v] of Object.entries(securityHeadersOpt)) base[k] = v;
|
|
1214
|
-
}
|
|
1215
|
-
if (cspOpt && cspOpt.length > 0) {
|
|
1216
|
-
base["Content-Security-Policy-Report-Only"] = cspOpt.join("; ");
|
|
1217
|
-
}
|
|
1218
|
-
return base;
|
|
1219
|
-
})();
|
|
1220
|
-
|
|
1221
|
-
// The enforced frame-ancestors value that ends up on `Content-Security-Policy`
|
|
1222
|
-
// (site override wins, else the deco default). Reused when we build the
|
|
1223
|
-
// enforced nonce CSP so framing protection is preserved.
|
|
1224
|
-
const frameAncestorsCsp = secHeaders?.["Content-Security-Policy"] ?? DEFAULT_FRAME_ANCESTORS_CSP;
|
|
1225
|
-
|
|
1226
|
-
function applySecurityHeaders(resp: Response, nonce?: string): Response {
|
|
1227
|
-
if (!secHeaders) return resp;
|
|
1228
|
-
const ct = resp.headers.get("content-type") ?? "";
|
|
1229
|
-
if (!ct.includes("text/html")) return resp;
|
|
1230
|
-
const out = new Response(resp.body, resp);
|
|
1231
|
-
for (const [k, v] of Object.entries(secHeaders)) {
|
|
1232
|
-
if (!out.headers.has(k)) out.headers.set(k, v);
|
|
1233
|
-
}
|
|
1234
|
-
// Enforced nonce CSP: enforce mode + a real nonce + a non-cacheable
|
|
1235
|
-
// response only. On a cacheable response a per-request nonce baked into the
|
|
1236
|
-
// (cached) body would desync from the header on the next HIT and block every
|
|
1237
|
-
// script, so those stay report-only. `CDN-Cache-Control` is decided at the
|
|
1238
|
-
// single response exit just before this call, so `no-store` is reliable here.
|
|
1239
|
-
if (
|
|
1240
|
-
cspMode === "enforce" &&
|
|
1241
|
-
nonce &&
|
|
1242
|
-
cspOpt &&
|
|
1243
|
-
cspOpt.length > 0 &&
|
|
1244
|
-
(out.headers.get("CDN-Cache-Control") ?? "").includes("no-store")
|
|
1245
|
-
) {
|
|
1246
|
-
out.headers.delete("Content-Security-Policy-Report-Only");
|
|
1247
|
-
out.headers.set(
|
|
1248
|
-
"Content-Security-Policy",
|
|
1249
|
-
buildEnforcedCsp(cspOpt, frameAncestorsCsp, nonce),
|
|
1250
|
-
);
|
|
1251
|
-
}
|
|
1252
|
-
return out;
|
|
1253
|
-
}
|
|
1254
|
-
|
|
1255
|
-
// DEFAULT_BYPASS_PATHS is always included, even when a site passes its own
|
|
1256
|
-
// `bypassPaths`. It used to be replaced, so a site adding one path silently
|
|
1257
|
-
// lost `/deco/`, `/live/` and `/.decofile` — framework routes that must never
|
|
1258
|
-
// be cached. Cache configuration from a site can tighten, never loosen.
|
|
1259
|
-
const allBypassPaths = [
|
|
1260
|
-
...new Set([...DEFAULT_BYPASS_PATHS, ...(bypassPaths ?? []), ...extraBypassPaths]),
|
|
1261
|
-
];
|
|
1262
|
-
|
|
1263
|
-
// The logged-in bypass below reads `segment.loggedIn`, which only ever exists
|
|
1264
|
-
// when the site supplies `buildSegment`. Without it, authenticated and
|
|
1265
|
-
// anonymous visitors share one edge entry.
|
|
1266
|
-
if (!rawBuildSegment) {
|
|
1267
|
-
console.warn(
|
|
1268
|
-
"[deco] createDecoWorkerEntry: no `buildSegment` configured — logged-in " +
|
|
1269
|
-
"visitors share the anonymous edge cache entry. Required before enabling " +
|
|
1270
|
-
"CDN caching.",
|
|
1271
|
-
);
|
|
1272
|
-
}
|
|
1273
|
-
|
|
1274
|
-
// -- Helpers ----------------------------------------------------------------
|
|
1275
|
-
|
|
1276
|
-
function isBypassPath(pathname: string): boolean {
|
|
1277
|
-
return allBypassPaths.some((bp) => pathname.startsWith(bp));
|
|
1278
|
-
}
|
|
1279
|
-
|
|
1280
|
-
function isStaticAsset(pathname: string): boolean {
|
|
1281
|
-
if (fingerprintedAssetPattern.test(pathname)) return true;
|
|
1282
|
-
// Non-fingerprinted static paths (e.g., /fonts/)
|
|
1283
|
-
return staticPathsOpt.some((sp) => pathname.startsWith(sp));
|
|
1284
|
-
}
|
|
1285
|
-
|
|
1286
|
-
function isCacheable(request: Request, url: URL): boolean {
|
|
1287
|
-
if (request.method !== "GET") return false;
|
|
1288
|
-
if (isBypassPath(url.pathname)) return false;
|
|
1289
|
-
// Draft preview: never cache a request in draft mode. Keys on the real
|
|
1290
|
-
// `?__draft=` param OR the navigation cookie (SPA nav after entry), gated
|
|
1291
|
-
// on an allowed preview host — see requestCarriesDraft.
|
|
1292
|
-
if (requestCarriesDraft(request, url)) return false;
|
|
1293
|
-
// A next-major draft (`?__draft=` or the `deco-draft` cookie): same rule.
|
|
1294
|
-
if (draftPointer(request) !== null) return false;
|
|
1295
|
-
if (url.searchParams.has("__deco_preview")) return false;
|
|
1296
|
-
if (url.searchParams.has("pathTemplate")) return false;
|
|
1297
|
-
// Forced matcher results must never be served from (or stored in) the
|
|
1298
|
-
// shared edge cache.
|
|
1299
|
-
if (url.searchParams.has(DECO_MATCHERS_OVERRIDE_PARAM)) return false;
|
|
1300
|
-
if (request.headers.has(DECO_MATCHERS_OVERRIDE_PARAM)) return false;
|
|
1301
|
-
return true;
|
|
1302
|
-
}
|
|
1303
|
-
|
|
1304
|
-
function getProfile(url: URL): CacheProfileName {
|
|
1305
|
-
// For TanStack GET server-fn requests, resolve the page path embedded in
|
|
1306
|
-
// the payload so the data request inherits the PAGE's profile (product /
|
|
1307
|
-
// search / static) instead of the generic "listing" derived from the
|
|
1308
|
-
// `/_serverFn/...` pathname. This is what makes SPA-navigation data
|
|
1309
|
-
// requests cache as long as their HTML documents (e.g. PDP 5min) and hit
|
|
1310
|
-
// the edge like full reloads do. Falls back to the request URL when no
|
|
1311
|
-
// embedded path is found.
|
|
1312
|
-
const pagePath = serverFnPagePath(url);
|
|
1313
|
-
const target = pagePath ? new URL(pagePath, url.origin) : url;
|
|
1314
|
-
if (customDetect) {
|
|
1315
|
-
const custom = customDetect(target);
|
|
1316
|
-
if (custom !== null) return custom;
|
|
1317
|
-
}
|
|
1318
|
-
return detectCacheProfile(target);
|
|
1319
|
-
}
|
|
1320
|
-
|
|
1321
|
-
const KNOWN_SEGMENT_FIELDS = new Set(["device", "loggedIn", "salesChannel", "regionId", "flags"]);
|
|
1322
|
-
|
|
1323
|
-
function hashSegment(seg: SegmentKey): string {
|
|
1324
|
-
const parts: string[] = [seg.device];
|
|
1325
|
-
if (seg.loggedIn) parts.push("auth");
|
|
1326
|
-
if (seg.salesChannel) parts.push(`sc=${seg.salesChannel}`);
|
|
1327
|
-
if (seg.regionId) parts.push(`r=${seg.regionId}`);
|
|
1328
|
-
if (seg.flags?.length) parts.push(`f=${seg.flags.sort().join(",")}`);
|
|
1329
|
-
// Custom dimensions (anything beyond the known fields above) are
|
|
1330
|
-
// serialized generically so they aren't silently dropped from the
|
|
1331
|
-
// cache key — see #284.
|
|
1332
|
-
const customKeys = Object.keys(seg)
|
|
1333
|
-
.filter((k) => !KNOWN_SEGMENT_FIELDS.has(k) && seg[k] !== undefined)
|
|
1334
|
-
.sort();
|
|
1335
|
-
for (const k of customKeys) {
|
|
1336
|
-
const v = seg[k];
|
|
1337
|
-
if (v === "" || v === false || (Array.isArray(v) && v.length === 0)) {
|
|
1338
|
-
continue;
|
|
1339
|
-
}
|
|
1340
|
-
const serialized = Array.isArray(v) ? [...v].sort().join(",") : v === true ? "" : String(v);
|
|
1341
|
-
parts.push(serialized ? `${k}=${serialized}` : k);
|
|
1342
|
-
}
|
|
1343
|
-
return parts.join("|");
|
|
1344
|
-
}
|
|
1345
|
-
|
|
1346
|
-
/**
|
|
1347
|
-
* Resolve the per-deploy cache-key version with this priority:
|
|
1348
|
-
* 1. `env[cacheVersionEnv]` — explicit override (e.g. `wrangler
|
|
1349
|
-
* deploy --var BUILD_HASH:foo`). Wins so callers can always
|
|
1350
|
-
* force a specific value.
|
|
1351
|
-
* 2. `__DECO_BUILD_HASH__` — build-time constant injected by
|
|
1352
|
-
* `decoVitePlugin()` from WORKERS_CI_COMMIT_SHA / git rev-parse.
|
|
1353
|
-
* This is the production path on Cloudflare Workers Builds.
|
|
1354
|
-
* 3. Empty string — versioning disabled (legacy pre-plugin sites).
|
|
1355
|
-
*/
|
|
1356
|
-
function getBuildHash(env: Record<string, unknown>): string {
|
|
1357
|
-
if (cacheVersionEnv === false) return "";
|
|
1358
|
-
const fromEnv = (env[cacheVersionEnv] as string) || "";
|
|
1359
|
-
if (fromEnv) return fromEnv;
|
|
1360
|
-
return typeof __DECO_BUILD_HASH__ !== "undefined" ? __DECO_BUILD_HASH__ : "";
|
|
1361
|
-
}
|
|
1362
|
-
|
|
1363
|
-
function readRequestCookie(request: Request, name: string): string | undefined {
|
|
1364
|
-
for (const pair of (request.headers.get("cookie") ?? "").split(";")) {
|
|
1365
|
-
const idx = pair.indexOf("=");
|
|
1366
|
-
if (idx <= 0) continue;
|
|
1367
|
-
if (pair.slice(0, idx).trim() !== name) continue;
|
|
1368
|
-
const raw = pair.slice(idx + 1).trim();
|
|
1369
|
-
// Decode once so this matches TanStack's getCookies() used during SSR
|
|
1370
|
-
// (see cms/resolve.ts) — otherwise the worker's cache key and the render
|
|
1371
|
-
// could disagree on the cohort. The deco_segment value is raw base64 (no
|
|
1372
|
-
// percent-escapes), so decoding is a no-op for it and safe in general.
|
|
1373
|
-
try {
|
|
1374
|
-
return decodeURIComponent(raw);
|
|
1375
|
-
} catch {
|
|
1376
|
-
return raw;
|
|
1377
|
-
}
|
|
1378
|
-
}
|
|
1379
|
-
return undefined;
|
|
1380
|
-
}
|
|
1381
|
-
|
|
1382
|
-
function isServerFnPathname(pathname: string): boolean {
|
|
1383
|
-
return pathname.startsWith("/_serverFn/") || pathname.startsWith("/_server/");
|
|
1384
|
-
}
|
|
1385
|
-
|
|
1386
|
-
/**
|
|
1387
|
-
* Whether this `/_serverFn` request may be cached by Cloudflare's CDN.
|
|
1388
|
-
*
|
|
1389
|
-
* True only when the URL carries a `__cseg` marker (put there by
|
|
1390
|
-
* `decoServerFnFetch` on the client) AND recomputing the segment from this
|
|
1391
|
-
* request produces the same token. When it matches, the CDN's key — the raw
|
|
1392
|
-
* URL — is equivalent to the Worker's synthetic key, so serving from the CDN
|
|
1393
|
-
* cannot cross segments.
|
|
1394
|
-
*
|
|
1395
|
-
* Fail-closed on every axis: no marker (bot, curl, old client), diverging
|
|
1396
|
-
* marker, forged marker, stale build, logged-in / region / sales channel, a
|
|
1397
|
-
* custom segment dimension, a bot UA, or an A/B cohort cookie all keep
|
|
1398
|
-
* today's `no-store`. The worst case is not caching — never a wrong response.
|
|
1399
|
-
*
|
|
1400
|
-
* `isBot` and the A/B cookie are checked HERE rather than inside
|
|
1401
|
-
* `segmentToken` because they are request-only: the client cannot observe
|
|
1402
|
-
* them, and they are exactly the two dimensions the original site-level
|
|
1403
|
-
* version missed. They must use the same `isBot` / `segmentCacheToken` that
|
|
1404
|
-
* `buildCacheKey` uses — keying and releasing off different predicates is how
|
|
1405
|
-
* the two silently diverge.
|
|
1406
|
-
*/
|
|
1407
|
-
function cdnCacheableServerFn(request: Request, url: URL, env: Record<string, unknown>): boolean {
|
|
1408
|
-
if (!isServerFnPathname(url.pathname)) return false;
|
|
1409
|
-
|
|
1410
|
-
const marker = url.searchParams.get(CSEG_PARAM);
|
|
1411
|
-
if (!marker) return false;
|
|
1412
|
-
|
|
1413
|
-
// Without buildSegment the logged-in bypass is inert (see the boot warning),
|
|
1414
|
-
// so there is nothing reliable to verify the marker against.
|
|
1415
|
-
if (!buildSegment) return false;
|
|
1416
|
-
|
|
1417
|
-
// `__bot=1` in buildCacheKey: bots render every section eagerly (~10x
|
|
1418
|
-
// payload). Letting the CDN share one entry would serve that to humans, or
|
|
1419
|
-
// the deferred one to crawlers.
|
|
1420
|
-
if (isBot(request.headers.get("user-agent") ?? undefined)) return false;
|
|
1421
|
-
|
|
1422
|
-
// `__abf` in buildCacheKey: an A/B visitor must not get another cohort's
|
|
1423
|
-
// cached variant.
|
|
1424
|
-
if (segmentCacheToken(parseSegmentCookie(readRequestCookie(request, SEGMENT_COOKIE)))) {
|
|
1425
|
-
return false;
|
|
1426
|
-
}
|
|
1427
|
-
|
|
1428
|
-
// `__cf_geo` in buildCacheKey is a dimension the segment descriptor does not
|
|
1429
|
-
// carry: it comes from `buildGeoCacheParam` (country/region/city) rather
|
|
1430
|
-
// than from `buildSegment`. Fold it in so two visitors keyed differently by
|
|
1431
|
-
// the Worker can never share a URL.
|
|
1432
|
-
const expected = segmentToken(
|
|
1433
|
-
requestSegmentDescriptor(request),
|
|
1434
|
-
buildSegment(request).loggedIn === true,
|
|
1435
|
-
getBuildHash(env),
|
|
1436
|
-
);
|
|
1437
|
-
return expected !== null && marker === expected;
|
|
1438
|
-
}
|
|
1439
|
-
|
|
1440
|
-
/**
|
|
1441
|
-
* The full set of dimensions the Worker keys this request on, as one string.
|
|
1442
|
-
*
|
|
1443
|
-
* MUST stay in step with `buildCacheKey` — it is the same question ("what
|
|
1444
|
-
* makes this response different from another visitor's?") asked in a form
|
|
1445
|
-
* that fits in a URL. A dimension present there and missing here is a
|
|
1446
|
-
* cross-visitor leak, which is why both read the same helpers rather than
|
|
1447
|
-
* re-deriving anything.
|
|
1448
|
-
*/
|
|
1449
|
-
function requestSegmentDescriptor(request: Request): string {
|
|
1450
|
-
if (!buildSegment) return "";
|
|
1451
|
-
const parts = [hashSegment(buildSegment(request))];
|
|
1452
|
-
|
|
1453
|
-
const geo = buildGeoCacheParam(
|
|
1454
|
-
(request as unknown as { cf?: Record<string, string> }).cf,
|
|
1455
|
-
effectiveGeoKey(),
|
|
1456
|
-
);
|
|
1457
|
-
if (geo) parts.push(`geo=${geo}`);
|
|
1458
|
-
|
|
1459
|
-
return parts.join("|");
|
|
1460
|
-
}
|
|
1461
|
-
|
|
1462
|
-
function requestCarriesTracking(url: URL): boolean {
|
|
1463
|
-
if (hasTrackingParams(url.toString())) return true;
|
|
1464
|
-
if (url.pathname.startsWith("/_serverFn/") || url.pathname.startsWith("/_server/")) {
|
|
1465
|
-
const payload = url.searchParams.get("payload");
|
|
1466
|
-
return !!payload && payloadHasTrackingParams(payload);
|
|
1467
|
-
}
|
|
1468
|
-
return false;
|
|
1469
|
-
}
|
|
1470
|
-
|
|
1471
|
-
function buildCacheKey(
|
|
1472
|
-
request: Request,
|
|
1473
|
-
env: Record<string, unknown>,
|
|
1474
|
-
): { key: Request; segment?: SegmentKey } {
|
|
1475
|
-
const url = new URL(request.url);
|
|
1476
|
-
|
|
1477
|
-
if (shouldStripTracking) {
|
|
1478
|
-
const cleanPath = cleanPathForCacheKey(url.toString());
|
|
1479
|
-
const cleanUrl = new URL(cleanPath, url.origin);
|
|
1480
|
-
url.search = cleanUrl.search;
|
|
1481
|
-
}
|
|
1482
|
-
|
|
1483
|
-
// For GET server-fn requests (SPA navigation data), the page being loaded
|
|
1484
|
-
// is encoded in the `payload` arg. Canonicalize it and strip variant params
|
|
1485
|
-
// (skuId/idsku) that the loader ignores — otherwise `/p?skuId=X` and `/p`
|
|
1486
|
-
// get distinct keys and every variant-carrying PDP→PDP nav MISSes, even
|
|
1487
|
-
// though the resolved response is identical. Keeps PLP filter params intact.
|
|
1488
|
-
if (url.pathname.startsWith("/_serverFn/") || url.pathname.startsWith("/_server/")) {
|
|
1489
|
-
const payload = url.searchParams.get("payload");
|
|
1490
|
-
if (payload) {
|
|
1491
|
-
url.searchParams.set("payload", canonicalizeServerFnPayloadForCacheKey(payload));
|
|
1492
|
-
}
|
|
1493
|
-
}
|
|
1494
|
-
|
|
1495
|
-
const version = getBuildHash(env);
|
|
1496
|
-
if (version) {
|
|
1497
|
-
url.searchParams.set("__v", version);
|
|
1498
|
-
}
|
|
1499
|
-
|
|
1500
|
-
// Include CF geo data in cache key so location matcher results don't leak
|
|
1501
|
-
// across different geos. Granularity is controlled by `geoCacheKey`:
|
|
1502
|
-
// "city" (default) → country|region|city, "region" → country|region,
|
|
1503
|
-
// "country" → country only, "off" → omitted entirely.
|
|
1504
|
-
const geoParam = buildGeoCacheParam(
|
|
1505
|
-
(request as unknown as { cf?: Record<string, string> }).cf,
|
|
1506
|
-
effectiveGeoKey(),
|
|
1507
|
-
);
|
|
1508
|
-
if (geoParam) url.searchParams.set("__cf_geo", geoParam);
|
|
1509
|
-
|
|
1510
|
-
// Bots render every section eagerly (shouldDeferSection short-circuits in
|
|
1511
|
-
// resolve.ts), producing a ~10x larger HTML payload (all eager-section
|
|
1512
|
-
// props serialized into the SSR hydration blob). Key bots into a SEPARATE
|
|
1513
|
-
// bucket so a crawler / Lighthouse / PageSpeed request can never poison the
|
|
1514
|
-
// shared human cache entry (and vice-versa). This MUST use the same `isBot`
|
|
1515
|
-
// predicate that gates shouldDeferSection — keying off a different bot
|
|
1516
|
-
// regex (e.g. requestContext's BOT_RE, which misses Lighthouse/Semrush)
|
|
1517
|
-
// would let the key and render decisions diverge and re-introduce poisoning.
|
|
1518
|
-
if (isBot(request.headers.get("user-agent") ?? undefined)) {
|
|
1519
|
-
url.searchParams.set("__bot", "1");
|
|
1520
|
-
}
|
|
1521
|
-
|
|
1522
|
-
// Programmatic, non-navigation fetches (the PLP "Ver mais"/load-more AJAX,
|
|
1523
|
-
// embeds, server-to-server) read the static SSR HTML and can't run the
|
|
1524
|
-
// client-side deferred-section resolution, so the origin renders every
|
|
1525
|
-
// section eagerly for them (isProgrammaticFetch in cms/resolve.ts) — the
|
|
1526
|
-
// same ~10x larger payload as bots. Key them into a SEPARATE `__fetch=1`
|
|
1527
|
-
// bucket so a fetch-triggered eager response never poisons the navigation
|
|
1528
|
-
// (deferred) entry, and vice-versa. MUST use the same `Sec-Fetch-Dest:
|
|
1529
|
-
// empty` signal as isProgrammaticFetch so the key and render decisions can't
|
|
1530
|
-
// diverge. `/_serverFn` (SPA-nav data) is excluded: it sends the same
|
|
1531
|
-
// `Sec-Fetch-Dest: empty` but is NOT a programmatic fetch — it renders
|
|
1532
|
-
// through DecoPageRenderer and so keeps the same deferred split as the
|
|
1533
|
-
// document (isProgrammaticFetch bails on isClientNavigation for the same
|
|
1534
|
-
// reason). It needs no bucket of its own here: its cache key is the
|
|
1535
|
-
// `/_serverFn/...` pathname + canonicalized payload, which can never
|
|
1536
|
-
// collide with a document entry.
|
|
1537
|
-
const secFetchDest = request.headers.get("sec-fetch-dest");
|
|
1538
|
-
const isServerFnPath =
|
|
1539
|
-
url.pathname.startsWith("/_serverFn/") || url.pathname.startsWith("/_server/");
|
|
1540
|
-
if (!isServerFnPath && secFetchDest === "empty") {
|
|
1541
|
-
url.searchParams.set("__fetch", "1");
|
|
1542
|
-
}
|
|
1543
|
-
|
|
1544
|
-
// A/B cohort split: fold the sticky `deco_segment` cookie into the cache
|
|
1545
|
-
// key so each variant keeps its own cached HTML. The cookie carries the
|
|
1546
|
-
// traffic fingerprint (see sdk/flags.ts), so a `traffic` change lands
|
|
1547
|
-
// cohorts in fresh buckets. Empty for non-A/B visitors (no cookie) → they
|
|
1548
|
-
// keep sharing one entry. A freshly-assigned visitor sets the cookie on the
|
|
1549
|
-
// response, which is not a "safe" cookie, so that one response bypasses the
|
|
1550
|
-
// cache and never poisons the shared entry.
|
|
1551
|
-
const flagToken = segmentCacheToken(
|
|
1552
|
-
parseSegmentCookie(readRequestCookie(request, SEGMENT_COOKIE)),
|
|
1553
|
-
);
|
|
1554
|
-
if (flagToken) {
|
|
1555
|
-
url.searchParams.set("__abf", flagToken);
|
|
1556
|
-
}
|
|
1557
|
-
|
|
1558
|
-
if (buildSegment) {
|
|
1559
|
-
const segment = buildSegment(request);
|
|
1560
|
-
url.searchParams.set("__seg", hashSegment(segment));
|
|
1561
|
-
return { key: new Request(url.toString(), { method: "GET" }), segment };
|
|
1562
|
-
}
|
|
1563
|
-
|
|
1564
|
-
if (deviceSpecificKeys) {
|
|
1565
|
-
const device = isMobileUA(request.headers.get("user-agent") ?? "") ? "mobile" : "desktop";
|
|
1566
|
-
url.searchParams.set("__cf_device", device);
|
|
1567
|
-
}
|
|
1568
|
-
|
|
1569
|
-
return { key: new Request(url.toString(), { method: "GET" }) };
|
|
1570
|
-
}
|
|
1571
|
-
|
|
1572
|
-
// -- Purge handler ----------------------------------------------------------
|
|
1573
|
-
|
|
1574
|
-
interface PurgeRequestBody {
|
|
1575
|
-
paths?: string[];
|
|
1576
|
-
countries?: string[];
|
|
1577
|
-
/** Sales channels to include in segment combos. Defaults to ["1"]. */
|
|
1578
|
-
salesChannels?: string[];
|
|
1579
|
-
/** Region IDs to include in segment combos. Each ID generates additional entries. */
|
|
1580
|
-
regionIds?: string[];
|
|
1581
|
-
}
|
|
1582
|
-
|
|
1583
|
-
function buildPurgeSegments(body: PurgeRequestBody): SegmentKey[] {
|
|
1584
|
-
const devices: Array<"mobile" | "desktop"> = ["mobile", "desktop"];
|
|
1585
|
-
const channels = body.salesChannels ?? ["1"];
|
|
1586
|
-
const regions: Array<string | undefined> = [undefined, ...(body.regionIds ?? [])];
|
|
1587
|
-
|
|
1588
|
-
const segments: SegmentKey[] = [];
|
|
1589
|
-
for (const device of devices) {
|
|
1590
|
-
for (const salesChannel of channels) {
|
|
1591
|
-
for (const regionId of regions) {
|
|
1592
|
-
segments.push({ device, salesChannel, regionId });
|
|
1593
|
-
}
|
|
1594
|
-
}
|
|
1595
|
-
segments.push({ device });
|
|
1596
|
-
}
|
|
1597
|
-
return segments;
|
|
1598
|
-
}
|
|
1599
|
-
|
|
1600
|
-
// Constant-time string compare — avoids a byte-wise timing side-channel on the
|
|
1601
|
-
// purge token. Length is not secret here, so a fast length-mismatch reject is fine.
|
|
1602
|
-
function timingSafeEqualStr(a: string, b: string): boolean {
|
|
1603
|
-
if (a.length !== b.length) return false;
|
|
1604
|
-
let diff = 0;
|
|
1605
|
-
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
1606
|
-
return diff === 0;
|
|
1607
|
-
}
|
|
1608
|
-
|
|
1609
|
-
// Shared auth for the cache purge endpoints. Returns a Response when the request
|
|
1610
|
-
// is unauthorized or purge is disabled, or null when authorized. Single source
|
|
1611
|
-
// of truth so /_cache/purge and /_cache/purge-loaders can't drift.
|
|
1612
|
-
function authorizePurge(request: Request, env: Record<string, unknown>): Response | null {
|
|
1613
|
-
if (purgeTokenEnv === false) {
|
|
1614
|
-
return new Response("Purge disabled", { status: 404 });
|
|
1615
|
-
}
|
|
1616
|
-
const token = (env[purgeTokenEnv] as string) || "";
|
|
1617
|
-
const auth = request.headers.get("Authorization") ?? "";
|
|
1618
|
-
if (!token || !timingSafeEqualStr(auth, `Bearer ${token}`)) {
|
|
1619
|
-
return new Response("Unauthorized", { status: 401 });
|
|
1620
|
-
}
|
|
1621
|
-
return null;
|
|
1622
|
-
}
|
|
1623
|
-
|
|
1624
|
-
async function handlePurge(request: Request, env: Record<string, unknown>): Promise<Response> {
|
|
1625
|
-
const denied = authorizePurge(request, env);
|
|
1626
|
-
if (denied) return denied;
|
|
1627
|
-
|
|
1628
|
-
let body: PurgeRequestBody;
|
|
1629
|
-
try {
|
|
1630
|
-
body = await request.json();
|
|
1631
|
-
} catch {
|
|
1632
|
-
return new Response("Invalid JSON body", { status: 400 });
|
|
1633
|
-
}
|
|
1634
|
-
|
|
1635
|
-
const paths = body.paths;
|
|
1636
|
-
if (!Array.isArray(paths) || paths.length === 0) {
|
|
1637
|
-
return new Response('Body must include "paths": ["/", "/page"]', { status: 400 });
|
|
1638
|
-
}
|
|
1639
|
-
|
|
1640
|
-
const geoVariants = body.countries ?? [];
|
|
1641
|
-
|
|
1642
|
-
const cache = responseCache(request, env);
|
|
1643
|
-
|
|
1644
|
-
if (!cache) {
|
|
1645
|
-
return Response.json({ purged: [], total: 0, note: "Cache storage unavailable" });
|
|
1646
|
-
}
|
|
1647
|
-
|
|
1648
|
-
const baseUrl = new URL(request.url).origin;
|
|
1649
|
-
const purged: string[] = [];
|
|
1650
|
-
|
|
1651
|
-
const geoKeys: (string | null)[] = [null, ...geoVariants];
|
|
1652
|
-
|
|
1653
|
-
// Bots (`__bot=1`) and programmatic fetches (`__fetch=1`) are each keyed
|
|
1654
|
-
// into a separate bucket (see buildCacheKey), so purge every combination.
|
|
1655
|
-
// The param-set order below MUST mirror buildCacheKey exactly (__v,
|
|
1656
|
-
// __cf_geo, __bot, __fetch, then __seg/__cf_device) so the purge key
|
|
1657
|
-
// byte-matches the stored key.
|
|
1658
|
-
const botVariants = [false, true] as const;
|
|
1659
|
-
const fetchVariants = [false, true] as const;
|
|
1660
|
-
|
|
1661
|
-
for (const p of paths) {
|
|
1662
|
-
if (buildSegment) {
|
|
1663
|
-
const segments = buildPurgeSegments(body);
|
|
1664
|
-
for (const seg of segments) {
|
|
1665
|
-
for (const cc of geoKeys) {
|
|
1666
|
-
for (const bot of botVariants) {
|
|
1667
|
-
for (const fetchReq of fetchVariants) {
|
|
1668
|
-
const url = new URL(p, baseUrl);
|
|
1669
|
-
const purgeVersion = getBuildHash(env);
|
|
1670
|
-
if (purgeVersion) url.searchParams.set("__v", purgeVersion);
|
|
1671
|
-
if (cc) url.searchParams.set("__cf_geo", cc);
|
|
1672
|
-
if (bot) url.searchParams.set("__bot", "1");
|
|
1673
|
-
if (fetchReq) url.searchParams.set("__fetch", "1");
|
|
1674
|
-
url.searchParams.set("__seg", hashSegment(seg));
|
|
1675
|
-
const key = new Request(url.toString(), { method: "GET" });
|
|
1676
|
-
try {
|
|
1677
|
-
if (await cache.delete(key)) {
|
|
1678
|
-
const tags = [
|
|
1679
|
-
hashSegment(seg),
|
|
1680
|
-
cc,
|
|
1681
|
-
bot ? "bot" : null,
|
|
1682
|
-
fetchReq ? "fetch" : null,
|
|
1683
|
-
]
|
|
1684
|
-
.filter(Boolean)
|
|
1685
|
-
.join(", ");
|
|
1686
|
-
purged.push(`${p} (${tags})`);
|
|
1687
|
-
}
|
|
1688
|
-
} catch {
|
|
1689
|
-
/* ignore */
|
|
1690
|
-
}
|
|
1691
|
-
}
|
|
1692
|
-
}
|
|
1693
|
-
}
|
|
1694
|
-
}
|
|
1695
|
-
} else {
|
|
1696
|
-
const devices = deviceSpecificKeys ? (["mobile", "desktop"] as const) : ([null] as const);
|
|
1697
|
-
|
|
1698
|
-
for (const device of devices) {
|
|
1699
|
-
for (const cc of geoKeys) {
|
|
1700
|
-
for (const bot of botVariants) {
|
|
1701
|
-
for (const fetchReq of fetchVariants) {
|
|
1702
|
-
const url = new URL(p, baseUrl);
|
|
1703
|
-
const purgeVersion = getBuildHash(env);
|
|
1704
|
-
if (purgeVersion) url.searchParams.set("__v", purgeVersion);
|
|
1705
|
-
if (cc) url.searchParams.set("__cf_geo", cc);
|
|
1706
|
-
if (bot) url.searchParams.set("__bot", "1");
|
|
1707
|
-
if (fetchReq) url.searchParams.set("__fetch", "1");
|
|
1708
|
-
if (device) url.searchParams.set("__cf_device", device);
|
|
1709
|
-
const key = new Request(url.toString(), { method: "GET" });
|
|
1710
|
-
try {
|
|
1711
|
-
if (await cache.delete(key)) {
|
|
1712
|
-
const parts = [device, cc, bot ? "bot" : null, fetchReq ? "fetch" : null]
|
|
1713
|
-
.filter(Boolean)
|
|
1714
|
-
.join(", ");
|
|
1715
|
-
purged.push(parts ? `${p} (${parts})` : p);
|
|
1716
|
-
}
|
|
1717
|
-
} catch {
|
|
1718
|
-
/* ignore */
|
|
1719
|
-
}
|
|
1720
|
-
}
|
|
1721
|
-
}
|
|
1722
|
-
}
|
|
1723
|
-
}
|
|
1724
|
-
}
|
|
1725
|
-
}
|
|
1726
|
-
|
|
1727
|
-
return Response.json({ purged, total: purged.length });
|
|
1728
|
-
}
|
|
1729
|
-
|
|
1730
|
-
// Purge the in-memory loader/commerce cache for THIS isolate. Same auth as
|
|
1731
|
-
// handlePurge (Bearer `purgeTokenEnv`). Per-isolate by nature — the isolate
|
|
1732
|
-
// that serves this request clears its cache; other live isolates keep theirs
|
|
1733
|
-
// until they're recycled or hit too. For a guaranteed global flush, redeploy
|
|
1734
|
-
// (loader cache keys are build-hash versioned).
|
|
1735
|
-
async function handlePurgeLoaders(
|
|
1736
|
-
request: Request,
|
|
1737
|
-
env: Record<string, unknown>,
|
|
1738
|
-
): Promise<Response> {
|
|
1739
|
-
const denied = authorizePurge(request, env);
|
|
1740
|
-
if (denied) return denied;
|
|
1741
|
-
clearLoaderCache();
|
|
1742
|
-
return Response.json({
|
|
1743
|
-
cleared: true,
|
|
1744
|
-
scope: "isolate",
|
|
1745
|
-
...(options.cacheStorage
|
|
1746
|
-
? { sharedStorage: "Entries expire by TTL; this endpoint clears memory only." }
|
|
1747
|
-
: {}),
|
|
1748
|
-
});
|
|
1749
|
-
}
|
|
1750
|
-
|
|
1751
|
-
function responseCache(request: Request, env: Record<string, unknown>) {
|
|
1752
|
-
if (isDevMode()) return null;
|
|
1753
|
-
const context = getCacheStorageContext();
|
|
1754
|
-
if (context?.disabled && new URL(request.url).pathname !== "/_cache/purge") return null;
|
|
1755
|
-
let storage = context?.storage;
|
|
1756
|
-
// Purge is authenticated before this helper runs, and needs storage even though
|
|
1757
|
-
// ordinary Authorization-bearing requests bypass every shared cache.
|
|
1758
|
-
if (options.cacheStorage && new URL(request.url).pathname === "/_cache/purge") {
|
|
1759
|
-
try {
|
|
1760
|
-
storage = options.cacheStorage(env, request);
|
|
1761
|
-
} catch {
|
|
1762
|
-
return null;
|
|
1763
|
-
}
|
|
1764
|
-
}
|
|
1765
|
-
if (!options.cacheStorage) {
|
|
1766
|
-
const native =
|
|
1767
|
-
typeof caches !== "undefined"
|
|
1768
|
-
? (caches as unknown as { default?: Cache }).default
|
|
1769
|
-
: undefined;
|
|
1770
|
-
storage = native ? createWebCacheStorage(native, new URL(request.url).origin) : null;
|
|
1771
|
-
}
|
|
1772
|
-
return storage
|
|
1773
|
-
? createResponseCache(
|
|
1774
|
-
storage,
|
|
1775
|
-
JSON.stringify([new URL(request.url).origin, getBuildHash(env), getRevision()]),
|
|
1776
|
-
)
|
|
1777
|
-
: null;
|
|
1778
|
-
}
|
|
1779
|
-
|
|
1780
|
-
// -- Admin route handler ---------------------------------------------------
|
|
1781
|
-
|
|
1782
|
-
const ADMIN_NO_CACHE: Record<string, string> = {
|
|
1783
|
-
"Cache-Control": "no-store, no-cache, must-revalidate",
|
|
1784
|
-
"CDN-Cache-Control": "no-store",
|
|
1785
|
-
"Surrogate-Control": "no-store",
|
|
1786
|
-
};
|
|
1787
|
-
|
|
1788
|
-
function addCors(response: Response, request: Request): Response {
|
|
1789
|
-
if (!admin) return response;
|
|
1790
|
-
const cors = admin.corsHeaders(request);
|
|
1791
|
-
const resp = new Response(response.body, {
|
|
1792
|
-
status: response.status,
|
|
1793
|
-
statusText: response.statusText,
|
|
1794
|
-
headers: new Headers(response.headers),
|
|
1795
|
-
});
|
|
1796
|
-
for (const [k, v] of Object.entries({ ...cors, ...ADMIN_NO_CACHE })) {
|
|
1797
|
-
resp.headers.set(k, v);
|
|
1798
|
-
}
|
|
1799
|
-
return resp;
|
|
1800
|
-
}
|
|
1801
|
-
|
|
1802
|
-
async function tryAdminRoute(request: Request): Promise<Response | null> {
|
|
1803
|
-
if (!admin) return null;
|
|
1804
|
-
|
|
1805
|
-
const url = new URL(request.url);
|
|
1806
|
-
const { pathname } = url;
|
|
1807
|
-
const method = request.method;
|
|
1808
|
-
|
|
1809
|
-
if (pathname === "/live/_meta") {
|
|
1810
|
-
if (method === "OPTIONS") {
|
|
1811
|
-
return new Response(null, {
|
|
1812
|
-
status: 204,
|
|
1813
|
-
headers: { ...admin.corsHeaders(request), ...ADMIN_NO_CACHE },
|
|
1814
|
-
});
|
|
1815
|
-
}
|
|
1816
|
-
const resp = await withTracing("deco.admin.meta", async () => admin.handleMeta(request));
|
|
1817
|
-
return addCors(resp, request);
|
|
1818
|
-
}
|
|
1819
|
-
|
|
1820
|
-
if (pathname === "/.decofile") {
|
|
1821
|
-
if (method === "OPTIONS") {
|
|
1822
|
-
return new Response(null, {
|
|
1823
|
-
status: 204,
|
|
1824
|
-
headers: { ...admin.corsHeaders(request), ...ADMIN_NO_CACHE },
|
|
1825
|
-
});
|
|
1826
|
-
}
|
|
1827
|
-
if (method === "POST") {
|
|
1828
|
-
const resp = await withTracing("deco.admin.decofile.reload", () =>
|
|
1829
|
-
Promise.resolve(admin.handleDecofileReload(request)),
|
|
1830
|
-
);
|
|
1831
|
-
return addCors(resp, request);
|
|
1832
|
-
}
|
|
1833
|
-
const resp = await withTracing("deco.admin.decofile.read", async () =>
|
|
1834
|
-
admin.handleDecofileRead(),
|
|
1835
|
-
);
|
|
1836
|
-
return addCors(resp, request);
|
|
1837
|
-
}
|
|
1838
|
-
|
|
1839
|
-
if (pathname === "/deco/_liveness") {
|
|
1840
|
-
return new Response("OK", {
|
|
1841
|
-
status: 200,
|
|
1842
|
-
headers: { "Content-Type": "text/plain", ...ADMIN_NO_CACHE },
|
|
1843
|
-
});
|
|
1844
|
-
}
|
|
1845
|
-
|
|
1846
|
-
if ((pathname === "/live/previews" || pathname === "/live/previews/") && method === "GET") {
|
|
1847
|
-
const shell = customPreviewShell ?? buildPreviewShell();
|
|
1848
|
-
return new Response(shell, {
|
|
1849
|
-
status: 200,
|
|
1850
|
-
headers: {
|
|
1851
|
-
"Content-Type": "text/html; charset=utf-8",
|
|
1852
|
-
...admin.corsHeaders(request),
|
|
1853
|
-
...ADMIN_NO_CACHE,
|
|
1854
|
-
},
|
|
1855
|
-
});
|
|
1856
|
-
}
|
|
1857
|
-
|
|
1858
|
-
if (pathname.startsWith("/live/previews/") && pathname !== "/live/previews/") {
|
|
1859
|
-
if (method === "OPTIONS") {
|
|
1860
|
-
return new Response(null, {
|
|
1861
|
-
status: 204,
|
|
1862
|
-
headers: { ...admin.corsHeaders(request), ...ADMIN_NO_CACHE },
|
|
1863
|
-
});
|
|
1864
|
-
}
|
|
1865
|
-
const pathComponent = pathname.slice("/live/previews/".length);
|
|
1866
|
-
const resp = await withTracing(
|
|
1867
|
-
"deco.admin.render",
|
|
1868
|
-
() => Promise.resolve(admin.handleRender(request)),
|
|
1869
|
-
{ "cms.component": pathComponent || "(page)" },
|
|
1870
|
-
);
|
|
1871
|
-
return addCors(resp, request);
|
|
1872
|
-
}
|
|
1873
|
-
|
|
1874
|
-
return null;
|
|
1875
|
-
}
|
|
1876
|
-
|
|
1877
|
-
// -- Main fetch handler -----------------------------------------------------
|
|
1878
|
-
|
|
1879
|
-
const handler = {
|
|
1880
|
-
async fetch(
|
|
1881
|
-
request: Request,
|
|
1882
|
-
env: Record<string, unknown>,
|
|
1883
|
-
ctx: WorkerExecutionContext,
|
|
1884
|
-
): Promise<Response> {
|
|
1885
|
-
const startedAt = performance.now();
|
|
1886
|
-
const reqUrl = new URL(request.url);
|
|
1887
|
-
const method = request.method;
|
|
1888
|
-
|
|
1889
|
-
// Deco-hosted preview hosts (`<site>.deco.site`,
|
|
1890
|
-
// `<site>.deco-cx.workers.dev`) inferred from the DECO_SITE_NAME
|
|
1891
|
-
// binding. Installed before any draft
|
|
1892
|
-
// gate runs (requestCarriesDraft participates in the cacheability
|
|
1893
|
-
// decision below). The binding is deploy-constant, so this is an
|
|
1894
|
-
// idempotent write.
|
|
1895
|
-
installDecoSiteHostFromEnv(env);
|
|
1896
|
-
|
|
1897
|
-
// Inject CF geo data as cookies for location matchers (before anything reads cookies)
|
|
1898
|
-
if (geoOpt) {
|
|
1899
|
-
request = injectGeoCookies(request);
|
|
1900
|
-
}
|
|
1901
|
-
|
|
1902
|
-
// Captured inside the withTracing scope so the outer post-response
|
|
1903
|
-
// path (response headers, metric labels, log attrs) can stamp the
|
|
1904
|
-
// trace ID without re-entering AsyncLocalStorage. The closure
|
|
1905
|
-
// captures whatever the framework span saw; if the bridge tracer
|
|
1906
|
-
// is a no-op, both stay empty strings and the header writes below
|
|
1907
|
-
// become no-ops.
|
|
1908
|
-
const identity = { requestId: "", traceId: "" };
|
|
1909
|
-
|
|
1910
|
-
// Draft-preview decision — resolved inside RequestContext.run (below) so
|
|
1911
|
-
// the resolved decofile binds to the request bag before the render, then
|
|
1912
|
-
// lifted here so the cookie + no-store/noindex headers can be stamped on
|
|
1913
|
-
// the final response. Inert on non-preview builds/hosts.
|
|
1914
|
-
let draftDecision: DraftDecision = { previewing: false, setCookie: null, clearCookie: false };
|
|
1915
|
-
|
|
1916
|
-
// Per-request CSP nonce (enforce mode only). Generated inside the
|
|
1917
|
-
// RequestContext.run below — before the render — so SSR components and the
|
|
1918
|
-
// router can read it from the bag, then lifted here so the enforced CSP
|
|
1919
|
-
// header built after the render carries the same value.
|
|
1920
|
-
let cspNonce: string | undefined;
|
|
1921
|
-
|
|
1922
|
-
// Wrap the entire request in a RequestContext so that all code
|
|
1923
|
-
// in the call stack (loaders, invoke handlers, vtexFetchWithCookies)
|
|
1924
|
-
// can access the request and write response headers.
|
|
1925
|
-
const response = await RequestContext.run(request, async () => {
|
|
1926
|
-
// Stash env so request-scoped adapters (Workers Analytics Engine,
|
|
1927
|
-
// future binding-driven destinations) can resolve their bindings
|
|
1928
|
-
// via getRuntimeEnv() in sdk/otelAdapters.ts.
|
|
1929
|
-
setRuntimeEnv(env);
|
|
1930
|
-
|
|
1931
|
-
// Fast-deploy: hydrate the in-memory decofile from KV on the first
|
|
1932
|
-
// request per isolate (awaited, ~10-30ms once), then opportunistically
|
|
1933
|
-
// poll for content changes (non-blocking, via ctx.waitUntil). No-op
|
|
1934
|
-
// unless the DECO_KV binding + DECO_FAST_DEPLOY are present —
|
|
1935
|
-
// non-migrated sites are unaffected.
|
|
1936
|
-
//
|
|
1937
|
-
// MUST come before reconfigureAppsOnce() and bindRequestDraft() below.
|
|
1938
|
-
// Both read the decofile, and both are one-shot/latching:
|
|
1939
|
-
// - reconfigureAppsOnce() configures apps from the blocks it sees and
|
|
1940
|
-
// latches `reinitPromise` forever. Running it first means a
|
|
1941
|
-
// fastDeploy build (whose bundled decofile is `{}`) configures ZERO
|
|
1942
|
-
// apps, and the only recovery is setBlocks()'s onChange listener,
|
|
1943
|
-
// whose promise setBlocks drops unawaited — so the request would
|
|
1944
|
-
// proceed with no app loaders registered.
|
|
1945
|
-
// - bindRequestDraft() composes draft overrides into loadBlocks().
|
|
1946
|
-
await ensureBlocksHydrated(env, ctx);
|
|
1947
|
-
maybePollRevision(env, ctx);
|
|
1948
|
-
|
|
1949
|
-
// First-request re-configuration of apps. autoconfigApps() runs at
|
|
1950
|
-
// module init (setup.ts), before `env` — and thus DECO_CRYPTO_KEY —
|
|
1951
|
-
// is available, so encrypted app credentials (VTEX appKey/appToken,
|
|
1952
|
-
// etc.) decrypt to null at startup. Now that env is in the ALS,
|
|
1953
|
-
// getEnvVar() can reach the key; re-run configure once so apps pick up
|
|
1954
|
-
// real credentials. No-op on every request after the first.
|
|
1955
|
-
await reconfigureAppsOnce();
|
|
1956
|
-
|
|
1957
|
-
// RequestContext.run already resolved request.id from the
|
|
1958
|
-
// inbound headers (precedence: x-request-id → cf-ray → UUID).
|
|
1959
|
-
// Lift it into the closure so the response-write path below has
|
|
1960
|
-
// access without going back through ALS.
|
|
1961
|
-
identity.requestId = RequestContext.requestId ?? "";
|
|
1962
|
-
|
|
1963
|
-
// W3C tracecontext propagation — parse the inbound `traceparent`
|
|
1964
|
-
// header so the OTLP trace exporter creates root spans under
|
|
1965
|
-
// the caller's trace ID. No-op when the header is absent or
|
|
1966
|
-
// malformed; the exporter falls back to a fresh trace ID.
|
|
1967
|
-
const incomingTraceparent = request.headers.get("traceparent");
|
|
1968
|
-
const remoteTrace = parseTraceparent(incomingTraceparent);
|
|
1969
|
-
if (remoteTrace) _setRequestTraceContext(remoteTrace);
|
|
1970
|
-
|
|
1971
|
-
// Debug sampling: ?__d=<any> forces this request to be fully sampled
|
|
1972
|
-
// regardless of headSamplingRate. Lets operators trace a specific
|
|
1973
|
-
// production request without changing global sampling rates.
|
|
1974
|
-
if (new URL(request.url).searchParams.has("__d")) _setDebugSampled();
|
|
1975
|
-
|
|
1976
|
-
// Resolve + bind any draft preview BEFORE the render, so every
|
|
1977
|
-
// loadBlocks() in the call stack sees the merged draft decofile via
|
|
1978
|
-
// the request bag. Cheap no-op unless the site opts in.
|
|
1979
|
-
draftDecision = await bindRequestDraft(request);
|
|
1980
|
-
|
|
1981
|
-
// Wrap inner handler in a single root span carrying our normalized
|
|
1982
|
-
// path/method attributes. The framework span flows BOTH ways:
|
|
1983
|
-
// - via the OTLP direct-POST tracer (when DECO_OTEL_TRACES_ENDPOINT
|
|
1984
|
-
// is set) → ClickHouse `otel_traces`,
|
|
1985
|
-
// - via the @opentelemetry/api bridge → CF Workers Observability
|
|
1986
|
-
// when `observability.traces.enabled = true` in wrangler.jsonc.
|
|
1987
|
-
// See `configureTracerStack` in `otel.ts` for the composition.
|
|
1988
|
-
return withTracing(
|
|
1989
|
-
"deco.http.request",
|
|
1990
|
-
async () => {
|
|
1991
|
-
// Stamp identity on the root span so every child span +
|
|
1992
|
-
// every log emitted under the same active span carries
|
|
1993
|
-
// them. Done inside the span scope so getActiveSpan()
|
|
1994
|
-
// returns the right span. Cheap no-op for any of these
|
|
1995
|
-
// when no tracer is configured.
|
|
1996
|
-
if (identity.requestId) {
|
|
1997
|
-
setSpanAttribute("request.id", identity.requestId);
|
|
1998
|
-
}
|
|
1999
|
-
const spanCtx = getActiveSpan()?.spanContext?.();
|
|
2000
|
-
if (spanCtx?.traceId) {
|
|
2001
|
-
identity.traceId = spanCtx.traceId;
|
|
2002
|
-
}
|
|
2003
|
-
|
|
2004
|
-
// Run app middleware (injects app state into RequestContext.bag,
|
|
2005
|
-
// runs registered middleware like VTEX cookie forwarding).
|
|
2006
|
-
// Publish the segment token so the SSR can hand it to the browser
|
|
2007
|
-
// (see sdk/cdnSegment). Only the server can compute this: region
|
|
2008
|
-
// comes from `request.cf`, which the client never sees. Per-request
|
|
2009
|
-
// via the RequestContext bag — a module-level global here would be
|
|
2010
|
-
// the layout-cache race all over again.
|
|
2011
|
-
if (buildSegment && cdnCacheControlOpt === "serverfn-segment") {
|
|
2012
|
-
const token = segmentToken(
|
|
2013
|
-
requestSegmentDescriptor(request),
|
|
2014
|
-
buildSegment(request).loggedIn === true,
|
|
2015
|
-
getBuildHash(env),
|
|
2016
|
-
);
|
|
2017
|
-
if (token) RequestContext.setBag(CSEG_BAG_KEY, token);
|
|
2018
|
-
}
|
|
2019
|
-
|
|
2020
|
-
// CSP nonce (enforce mode only): produce it before the render and
|
|
2021
|
-
// publish it in the bag so `createDecoRouter` (router.options.ssr.nonce)
|
|
2022
|
-
// and the deco layout components pick it up while rendering. Lifted to
|
|
2023
|
-
// `cspNonce` so applySecurityHeaders below stamps the matching header.
|
|
2024
|
-
if (cspMode === "enforce") {
|
|
2025
|
-
cspNonce = generateNonce();
|
|
2026
|
-
RequestContext.setBag(NONCE_BAG_KEY, cspNonce);
|
|
2027
|
-
}
|
|
2028
|
-
|
|
2029
|
-
const appMw = getAppMiddleware();
|
|
2030
|
-
const innerResponse = appMw
|
|
2031
|
-
? await appMw(request, () => handleRequest(request, env, ctx))
|
|
2032
|
-
: await handleRequest(request, env, ctx);
|
|
2033
|
-
|
|
2034
|
-
// Access log at debug — no-op in prod (default warn minLevel),
|
|
2035
|
-
// visible in dev with DECO_OTEL_LOGS_MIN_LEVEL=debug.
|
|
2036
|
-
// Must run inside the span so getSpan() returns the active root
|
|
2037
|
-
// span and trace_id is stamped on the log record.
|
|
2038
|
-
try {
|
|
2039
|
-
logRequest(request, innerResponse.status, performance.now() - startedAt, {
|
|
2040
|
-
...(identity.requestId ? { "request.id": identity.requestId } : {}),
|
|
2041
|
-
...(identity.traceId ? { "trace.id": identity.traceId } : {}),
|
|
2042
|
-
});
|
|
2043
|
-
} catch {
|
|
2044
|
-
/* swallow — observability must never fail the request */
|
|
2045
|
-
}
|
|
2046
|
-
|
|
2047
|
-
return innerResponse;
|
|
2048
|
-
},
|
|
2049
|
-
{
|
|
2050
|
-
"http.method": method,
|
|
2051
|
-
"url.path": reqUrl.pathname,
|
|
2052
|
-
},
|
|
2053
|
-
);
|
|
2054
|
-
});
|
|
2055
|
-
|
|
2056
|
-
// Deduplicate Set-Cookie headers — multiple layers (VTEX middleware,
|
|
2057
|
-
// invoke handlers, etc.) may independently append the same cookie.
|
|
2058
|
-
deduplicateSetCookies(response);
|
|
2059
|
-
|
|
2060
|
-
// `CDN-Cache-Control` is decided here, at the single response exit, so no
|
|
2061
|
-
// branch can forget it. Two cases:
|
|
2062
|
-
//
|
|
2063
|
-
// - `X-Cache: BYPASS` — the worker deliberately declined to cache, so
|
|
2064
|
-
// the CDN must not either. A dozen call sites set this; some deleted
|
|
2065
|
-
// the header, some didn't, and several still emitted the profile's
|
|
2066
|
-
// public `Cache-Control` (`public, s-maxage=900`) on the way out.
|
|
2067
|
-
// - header absent — a branch that returned before `dressResponse` and
|
|
2068
|
-
// expressed no opinion. `?asJson`, `?renderJson`, proxied responses and
|
|
2069
|
-
// the redirect paths all land here. Defaulting these to `no-store` is
|
|
2070
|
-
// what makes the invariant hold: an early return can only ever be
|
|
2071
|
-
// MORE restrictive than the cache layer, never accidentally public.
|
|
2072
|
-
//
|
|
2073
|
-
// A value already set by `dressResponse` (the cacheable path) is left
|
|
2074
|
-
// alone — that is the one branch that has actually reasoned about whether
|
|
2075
|
-
// the CDN key matches the worker key.
|
|
2076
|
-
const bypassed = response.headers.get("X-Cache") === "BYPASS";
|
|
2077
|
-
if (bypassed || !response.headers.has("CDN-Cache-Control")) {
|
|
2078
|
-
response.headers.set("CDN-Cache-Control", "no-store");
|
|
2079
|
-
}
|
|
2080
|
-
|
|
2081
|
-
let finalResponse = applySecurityHeaders(response, cspNonce);
|
|
2082
|
-
|
|
2083
|
-
// Echo request.id + trace.id back to the client / tail worker.
|
|
2084
|
-
// The CF tail worker reads these headers off the response to
|
|
2085
|
-
// stamp `request.id` / `trace.id` on tail rows — they're the
|
|
2086
|
-
// join key against direct-POST logs/metrics (which carry the
|
|
2087
|
-
// same values via the logger + span attributes).
|
|
2088
|
-
//
|
|
2089
|
-
// Headers are written defensively: if a downstream component
|
|
2090
|
-
// already set them (e.g. a proxy upstream), the existing value
|
|
2091
|
-
// wins. That's intentional — a load-balancer-supplied request.id
|
|
2092
|
-
// is more useful for cross-system correlation than ours.
|
|
2093
|
-
if (identity.requestId || identity.traceId) {
|
|
2094
|
-
// applySecurityHeaders may return either the original Response
|
|
2095
|
-
// (HTML path, fresh Headers) or the same Response (non-HTML
|
|
2096
|
-
// path). Either way Response.headers is mutable on Workers, so
|
|
2097
|
-
// we can set on it directly.
|
|
2098
|
-
if (identity.requestId && !finalResponse.headers.has("x-request-id")) {
|
|
2099
|
-
try {
|
|
2100
|
-
finalResponse.headers.set("x-request-id", identity.requestId);
|
|
2101
|
-
} catch {
|
|
2102
|
-
// Some intermediaries seal response headers (e.g. cached
|
|
2103
|
-
// responses replayed from the Cache API). Fall back to
|
|
2104
|
-
// building a new Response.
|
|
2105
|
-
const headers = new Headers(finalResponse.headers);
|
|
2106
|
-
if (identity.requestId) headers.set("x-request-id", identity.requestId);
|
|
2107
|
-
if (identity.traceId) headers.set("x-trace-id", identity.traceId);
|
|
2108
|
-
finalResponse = new Response(finalResponse.body, {
|
|
2109
|
-
status: finalResponse.status,
|
|
2110
|
-
statusText: finalResponse.statusText,
|
|
2111
|
-
headers,
|
|
2112
|
-
});
|
|
2113
|
-
}
|
|
2114
|
-
}
|
|
2115
|
-
if (identity.traceId && !finalResponse.headers.has("x-trace-id")) {
|
|
2116
|
-
try {
|
|
2117
|
-
finalResponse.headers.set("x-trace-id", identity.traceId);
|
|
2118
|
-
} catch {
|
|
2119
|
-
/* see above — sealed header case already handled */
|
|
2120
|
-
}
|
|
2121
|
-
}
|
|
2122
|
-
}
|
|
2123
|
-
|
|
2124
|
-
// Old-runtime parity: deco-cx/deco stamped `x-powered-by: deco@<ver>`
|
|
2125
|
-
// on every response (utils/http.ts defaultHeaders); partner-side logs
|
|
2126
|
-
// and ops tooling use it to identify deco traffic. Set-if-absent so
|
|
2127
|
-
// an upstream origin's own value wins.
|
|
2128
|
-
if (!finalResponse.headers.has("x-powered-by")) {
|
|
2129
|
-
try {
|
|
2130
|
-
finalResponse.headers.set("x-powered-by", DECO_POWERED_BY);
|
|
2131
|
-
} catch {
|
|
2132
|
-
/* sealed headers (cached replay) — identification is best-effort */
|
|
2133
|
-
}
|
|
2134
|
-
}
|
|
2135
|
-
|
|
2136
|
-
// Draft preview: persist/clear the navigation cookie and stamp the
|
|
2137
|
-
// no-store/noindex headers so a drafted response is never cached under
|
|
2138
|
-
// its shared (cookie-only) URL. No-op when not previewing.
|
|
2139
|
-
applyDraftCookieAndHeaders(finalResponse, draftDecision);
|
|
2140
|
-
|
|
2141
|
-
// Metrics + structured request log. Done after security headers so
|
|
2142
|
-
// the recorded status reflects what the client actually receives.
|
|
2143
|
-
// Both calls are no-ops when no meter / logger is configured.
|
|
2144
|
-
const durationMs = performance.now() - startedAt;
|
|
2145
|
-
try {
|
|
2146
|
-
// Phase 2 / D-11 canonical labels — lift the cache decision +
|
|
2147
|
-
// profile + region off the response we just built so dashboards
|
|
2148
|
-
// can answer "cache hit rate per route" from
|
|
2149
|
-
// `http.server.request.duration` alone, no join to a cache counter
|
|
2150
|
-
// required.
|
|
2151
|
-
const xCacheRaw = finalResponse.headers.get("X-Cache");
|
|
2152
|
-
const cacheDecision = isCacheDecision(xCacheRaw) ? xCacheRaw : undefined;
|
|
2153
|
-
const colo = (request as unknown as { cf?: { colo?: string } }).cf?.colo;
|
|
2154
|
-
// NOTE: `request.id` and `trace.id` are intentionally NOT stamped
|
|
2155
|
-
// on the metric. They are per-request identifiers and would
|
|
2156
|
-
// collapse aggregation (every request → its own histogram data
|
|
2157
|
-
// point). They are stamped on the span; use traces for
|
|
2158
|
-
// request-level correlation.
|
|
2159
|
-
recordRequestMetric(method, reqUrl.pathname, finalResponse.status, durationMs, {
|
|
2160
|
-
...(cacheDecision ? { cache_decision: cacheDecision } : {}),
|
|
2161
|
-
...(cacheDecision ? { cache_layer: "edge" as const } : {}),
|
|
2162
|
-
...(typeof colo === "string" && colo.length > 0 ? { region: colo } : {}),
|
|
2163
|
-
});
|
|
2164
|
-
} catch {
|
|
2165
|
-
/* swallow — observability must never fail the request */
|
|
2166
|
-
}
|
|
2167
|
-
return finalResponse;
|
|
2168
|
-
},
|
|
2169
|
-
};
|
|
2170
|
-
|
|
2171
|
-
// Auto-instrument with `instrumentWorker` unless explicitly opted out.
|
|
2172
|
-
// When `observabilityOpt === false` the site is taking control of its own
|
|
2173
|
-
// OTel wiring; otherwise the framework wraps the handler so that, when
|
|
2174
|
-
// `DECO_OTEL_*_ENDPOINT` env vars are configured, telemetry flows
|
|
2175
|
-
// without any change to the site's worker-entry. When the env vars are
|
|
2176
|
-
// absent the wrap is a no-op (no exporters created, no flush calls).
|
|
2177
|
-
// `@decocms/blocks` background work (release checks, telemetry batches)
|
|
2178
|
-
// queued during a request runs after its response, inside ctx.waitUntil.
|
|
2179
|
-
installBackgroundHook();
|
|
2180
|
-
// Next major: upstream GETs made with createInstrumentedFetch are cached
|
|
2181
|
-
// with the Cache API (see ../v8/binding.ts).
|
|
2182
|
-
installUpstreamCache();
|
|
2183
|
-
const respond = handler.fetch;
|
|
2184
|
-
handler.fetch = async (request, env, ctx) => {
|
|
2185
|
-
try {
|
|
2186
|
-
return await respond(request, env, ctx);
|
|
2187
|
-
} finally {
|
|
2188
|
-
runBackgroundTasks(ctx);
|
|
2189
|
-
}
|
|
2190
|
-
};
|
|
2191
|
-
|
|
2192
|
-
return observabilityOpt === false
|
|
2193
|
-
? handler
|
|
2194
|
-
: instrumentWorker(handler, (observabilityOpt as OtelOptions | undefined) ?? {});
|
|
2195
|
-
|
|
2196
|
-
async function handleRequest(
|
|
2197
|
-
request: Request,
|
|
2198
|
-
env: Record<string, unknown>,
|
|
2199
|
-
ctx: WorkerExecutionContext,
|
|
2200
|
-
): Promise<Response> {
|
|
2201
|
-
const url = new URL(request.url);
|
|
2202
|
-
|
|
2203
|
-
// NOTE: fast-deploy hydration does NOT run here. It must happen before
|
|
2204
|
-
// `reconfigureAppsOnce()` and `bindRequestDraft()`, both of which run in
|
|
2205
|
-
// the outer fetch above — see the `ensureBlocksHydrated` call there.
|
|
2206
|
-
|
|
2207
|
-
{
|
|
2208
|
-
const segment = buildSegment?.(request);
|
|
2209
|
-
const privateRequest =
|
|
2210
|
-
requestCarriesDraft(request, url) ||
|
|
2211
|
-
segment?.loggedIn === true ||
|
|
2212
|
-
request.headers.has("authorization") ||
|
|
2213
|
-
url.searchParams.has("__deco_preview") ||
|
|
2214
|
-
url.searchParams.has(DECO_MATCHERS_OVERRIDE_PARAM) ||
|
|
2215
|
-
request.headers.has(DECO_MATCHERS_OVERRIDE_PARAM) ||
|
|
2216
|
-
url.pathname.startsWith("/live/previews") ||
|
|
2217
|
-
url.pathname.startsWith("/deco/render");
|
|
2218
|
-
let storage: CacheStorage | null = null;
|
|
2219
|
-
try {
|
|
2220
|
-
storage =
|
|
2221
|
-
privateRequest || isDevMode() ? null : (options.cacheStorage?.(env, request) ?? null);
|
|
2222
|
-
} catch {
|
|
2223
|
-
/* Missing storage is a cache miss, never a storefront failure. */
|
|
2224
|
-
}
|
|
2225
|
-
bindCacheStorage({
|
|
2226
|
-
storage,
|
|
2227
|
-
disabled: privateRequest || isDevMode(),
|
|
2228
|
-
scope: JSON.stringify([
|
|
2229
|
-
new URL(request.url).origin,
|
|
2230
|
-
getBuildHash(env),
|
|
2231
|
-
getRevision(),
|
|
2232
|
-
segment
|
|
2233
|
-
? hashSegment(segment)
|
|
2234
|
-
: isMobileUA(request.headers.get("user-agent") ?? "")
|
|
2235
|
-
? "mobile"
|
|
2236
|
-
: "desktop",
|
|
2237
|
-
buildGeoCacheParam(
|
|
2238
|
-
(request as unknown as { cf?: Record<string, string> }).cf,
|
|
2239
|
-
effectiveGeoKey(),
|
|
2240
|
-
),
|
|
2241
|
-
privateRequest ? crypto.randomUUID() : null,
|
|
2242
|
-
]),
|
|
2243
|
-
waitUntil: (work) => ctx.waitUntil(work),
|
|
2244
|
-
});
|
|
2245
|
-
}
|
|
2246
|
-
|
|
2247
|
-
// Admin routes (/_meta, /.decofile, /live/previews) — always handled first
|
|
2248
|
-
const adminResponse = await tryAdminRoute(request);
|
|
2249
|
-
if (adminResponse) return adminResponse;
|
|
2250
|
-
|
|
2251
|
-
// Purge endpoint
|
|
2252
|
-
if (url.pathname === "/_cache/purge" && request.method === "POST") {
|
|
2253
|
-
return handlePurge(request, env);
|
|
2254
|
-
}
|
|
2255
|
-
|
|
2256
|
-
// Loader/commerce cache purge (in-memory, this isolate only). Escape hatch
|
|
2257
|
-
// to invalidate loader results immediately after an out-of-band upstream
|
|
2258
|
-
// change (e.g. a Magento catalog sync) without waiting out the TTL. A
|
|
2259
|
-
// redeploy is the global lever — loader cache keys are build-hash versioned.
|
|
2260
|
-
if (url.pathname === "/_cache/purge-loaders" && request.method === "POST") {
|
|
2261
|
-
return handlePurgeLoaders(request, env);
|
|
2262
|
-
}
|
|
2263
|
-
|
|
2264
|
-
// CMS redirects (website/loaders/redirect.ts blocks) — checked before
|
|
2265
|
-
// ?asJson and commerce proxy so every request path respects redirects.
|
|
2266
|
-
// Revision-keyed so cross-bundle setBlocks() calls are detected even when
|
|
2267
|
-
// onChange listeners don't fire across Vite split-bundle module instances.
|
|
2268
|
-
const currentRevision = getRevision();
|
|
2269
|
-
if (_redirectMapRevision !== currentRevision) {
|
|
2270
|
-
_redirectMap = loadRedirects(loadBlocks());
|
|
2271
|
-
_redirectMapRevision = currentRevision;
|
|
2272
|
-
}
|
|
2273
|
-
// Exact before glob, across BOTH sources. On a fast-deploy site the exact
|
|
2274
|
-
// rules live under their own `redirect:<id>:<path>` KV keys and are absent
|
|
2275
|
-
// from the decofile, so the in-memory exact hit is the non-fast-deploy
|
|
2276
|
-
// case. Going straight to `matchRedirect` and only then to KV would let a
|
|
2277
|
-
// glob win over an exact rule, inverting the precedence.
|
|
2278
|
-
const cmsRedirect =
|
|
2279
|
-
matchExactRedirect(url.pathname, _redirectMap!) ??
|
|
2280
|
-
(await lookupExactRedirect(env as Record<string, unknown>, normalizePath(url.pathname))) ??
|
|
2281
|
-
matchPatternRedirect(url.pathname, _redirectMap!);
|
|
2282
|
-
if (cmsRedirect) {
|
|
2283
|
-
return new Response(null, {
|
|
2284
|
-
status: cmsRedirect.status,
|
|
2285
|
-
headers: { Location: encodeURI(cmsRedirect.to) },
|
|
2286
|
-
});
|
|
2287
|
-
}
|
|
2288
|
-
|
|
2289
|
-
// ?renderJson — structured JSON of the page for the mobile app. Lean shape
|
|
2290
|
-
// ({ name, path, sections:[{ component, props }] }), each section projected
|
|
2291
|
-
// through its `renderJson` export. Wins over ?asJson when both are present.
|
|
2292
|
-
// CORS preflight for ?renderJson (only emits headers when pageJsonCors is set).
|
|
2293
|
-
if (
|
|
2294
|
-
options.renderJson !== false &&
|
|
2295
|
-
request.method === "OPTIONS" &&
|
|
2296
|
-
url.searchParams.has("renderJson")
|
|
2297
|
-
) {
|
|
2298
|
-
return new Response(null, {
|
|
2299
|
-
status: 204,
|
|
2300
|
-
headers: pageJsonCorsHeaders(request, options.pageJsonCors),
|
|
2301
|
-
});
|
|
2302
|
-
}
|
|
2303
|
-
|
|
2304
|
-
if (
|
|
2305
|
-
options.renderJson !== false &&
|
|
2306
|
-
url.searchParams.has("renderJson") &&
|
|
2307
|
-
request.method === "GET"
|
|
2308
|
-
) {
|
|
2309
|
-
const basePath = url.pathname;
|
|
2310
|
-
const cookies: Record<string, string> = {};
|
|
2311
|
-
for (const pair of (request.headers.get("cookie") ?? "").split(";")) {
|
|
2312
|
-
const [k, ...v] = pair.split("=");
|
|
2313
|
-
if (k?.trim()) cookies[k.trim()] = v.join("=").trim();
|
|
2314
|
-
}
|
|
2315
|
-
const matcherCtx: MatcherContext = {
|
|
2316
|
-
userAgent: request.headers.get("user-agent") ?? "",
|
|
2317
|
-
url: url.toString(),
|
|
2318
|
-
path: basePath,
|
|
2319
|
-
cookies,
|
|
2320
|
-
request,
|
|
2321
|
-
};
|
|
2322
|
-
|
|
2323
|
-
// CORS for ?renderJson — off unless the site allow-lists origins via
|
|
2324
|
-
// options.pageJsonCors (native apps need none; browsers get same-origin).
|
|
2325
|
-
const corsHeaders = pageJsonCorsHeaders(request, options.pageJsonCors);
|
|
2326
|
-
|
|
2327
|
-
const page = await resolveDecoPage(basePath, matcherCtx);
|
|
2328
|
-
if (!page) {
|
|
2329
|
-
// Stable error envelope — the app gets a predictable "not found".
|
|
2330
|
-
return Response.json(
|
|
2331
|
-
{ status: 404, notFound: true },
|
|
2332
|
-
{ status: 404, headers: corsHeaders },
|
|
2333
|
-
);
|
|
2334
|
-
}
|
|
2335
|
-
|
|
2336
|
-
// Drop web-only / app-owned sections BEFORE running their loaders so a
|
|
2337
|
-
// dropped section never triggers its (expensive) VTEX call. Dual-sourced:
|
|
2338
|
-
// - the section's own `export const renderJson = false`
|
|
2339
|
-
// - the website app's renderJson.sectionsToIgnore (resolveType suffix)
|
|
2340
|
-
const rjBlocks = loadBlocks();
|
|
2341
|
-
const rjSite = rjBlocks["Site"] as Record<string, unknown> | undefined;
|
|
2342
|
-
const rawIgnore = (rjSite?.renderJson as { sectionsToIgnore?: unknown })?.sectionsToIgnore;
|
|
2343
|
-
const ignoreSuffixes = (Array.isArray(rawIgnore) ? rawIgnore : [])
|
|
2344
|
-
.filter((s): s is string => typeof s === "string")
|
|
2345
|
-
.map((s) => s.trim())
|
|
2346
|
-
.filter((s) => s.length > 0);
|
|
2347
|
-
const isDropped = (component: string) =>
|
|
2348
|
-
getSectionOptions(component)?.renderJson === false ||
|
|
2349
|
-
ignoreSuffixes.some((suffix) => component.endsWith(suffix));
|
|
2350
|
-
const getSectionModule = (component: string) => ({
|
|
2351
|
-
renderJson: getSectionOptions(component)?.renderJson,
|
|
2352
|
-
});
|
|
2353
|
-
|
|
2354
|
-
const jsonHeaders = {
|
|
2355
|
-
...corsHeaders,
|
|
2356
|
-
"Content-Type": "application/json; charset=utf-8",
|
|
2357
|
-
"Cache-Control": "public, max-age=0, must-revalidate",
|
|
2358
|
-
};
|
|
2359
|
-
const withEtag = (body: string): Response => {
|
|
2360
|
-
// Contract-stable ETag over the serialized body: identical → 304.
|
|
2361
|
-
const etag = `"rj-${djb2Hex(body)}"`;
|
|
2362
|
-
if (request.headers.get("if-none-match") === etag) {
|
|
2363
|
-
return new Response(null, { status: 304, headers: { ...corsHeaders, ETag: etag } });
|
|
2364
|
-
}
|
|
2365
|
-
return new Response(body, { headers: { ...jsonHeaders, ETag: etag } });
|
|
2366
|
-
};
|
|
2367
|
-
|
|
2368
|
-
// Lazy single-section fetch: `?renderJson&__section=<index>` resolves ONE
|
|
2369
|
-
// deferred section (the placeholder the whole-page envelope emitted) and
|
|
2370
|
-
// returns its serialized `{ component, props }`.
|
|
2371
|
-
const sectionParam = url.searchParams.get("__section");
|
|
2372
|
-
if (sectionParam !== null) {
|
|
2373
|
-
const sectionIndex = Number(sectionParam);
|
|
2374
|
-
const ds = page.deferredSections.find((d) => d.index === sectionIndex);
|
|
2375
|
-
if (!ds || isDropped(ds.component)) {
|
|
2376
|
-
return Response.json(
|
|
2377
|
-
{ status: 404, notFound: true },
|
|
2378
|
-
{ status: 404, headers: corsHeaders },
|
|
2379
|
-
);
|
|
2380
|
-
}
|
|
2381
|
-
const resolved = await resolveDeferredSectionFull(ds, basePath, request, matcherCtx);
|
|
2382
|
-
if (!resolved) {
|
|
2383
|
-
return Response.json(
|
|
2384
|
-
{ status: 404, notFound: true },
|
|
2385
|
-
{ status: 404, headers: corsHeaders },
|
|
2386
|
-
);
|
|
2387
|
-
}
|
|
2388
|
-
const [serialized] = serializeRenderJson(
|
|
2389
|
-
[{ component: resolved.component, props: resolved.props }],
|
|
2390
|
-
{ getSectionModule, sectionsToIgnore: ignoreSuffixes },
|
|
2391
|
-
);
|
|
2392
|
-
if (!serialized) {
|
|
2393
|
-
return Response.json(
|
|
2394
|
-
{ status: 404, notFound: true },
|
|
2395
|
-
{ status: 404, headers: corsHeaders },
|
|
2396
|
-
);
|
|
2397
|
-
}
|
|
2398
|
-
return withEtag(stringifyWithoutSecrets(serialized));
|
|
2399
|
-
}
|
|
2400
|
-
|
|
2401
|
-
// Whole page: eager sections are resolved + projected inline; deferred
|
|
2402
|
-
// sections become `{ component, lazyUrl }` placeholders the app fetches on
|
|
2403
|
-
// demand (interleaved by their position in the page).
|
|
2404
|
-
const keptSections = page.resolvedSections.filter((s) => !isDropped(s.component));
|
|
2405
|
-
const enrichedSections = await runSectionLoaders(keptSections, request);
|
|
2406
|
-
const lazyUrlFor = (ref: { index: number }): string => {
|
|
2407
|
-
const u = new URL(url.toString());
|
|
2408
|
-
u.searchParams.set("__section", String(ref.index));
|
|
2409
|
-
return u.pathname + u.search;
|
|
2410
|
-
};
|
|
2411
|
-
|
|
2412
|
-
const sections = serializeRenderJson(
|
|
2413
|
-
enrichedSections.map((s) => ({ component: s.component, props: s.props, index: s.index })),
|
|
2414
|
-
{
|
|
2415
|
-
getSectionModule,
|
|
2416
|
-
// Belt-and-suspenders: keptSections already dropped these, but the
|
|
2417
|
-
// serializer re-checks so a section that slipped through is still cut.
|
|
2418
|
-
sectionsToIgnore: ignoreSuffixes,
|
|
2419
|
-
deferred: page.deferredSections.map((d) => ({ component: d.component, index: d.index })),
|
|
2420
|
-
lazyUrlFor,
|
|
2421
|
-
},
|
|
2422
|
-
);
|
|
2423
|
-
|
|
2424
|
-
return withEtag(stringifyWithoutSecrets({ name: page.name, path: page.path, sections }));
|
|
2425
|
-
}
|
|
2426
|
-
|
|
2427
|
-
// ?asJson — return resolved page data as JSON (legacy deco compat)
|
|
2428
|
-
if (options.asJson !== false && url.searchParams.has("asJson") && request.method === "GET") {
|
|
2429
|
-
const basePath = url.pathname;
|
|
2430
|
-
const cookies: Record<string, string> = {};
|
|
2431
|
-
for (const pair of (request.headers.get("cookie") ?? "").split(";")) {
|
|
2432
|
-
const [k, ...v] = pair.split("=");
|
|
2433
|
-
if (k?.trim()) cookies[k.trim()] = v.join("=").trim();
|
|
2434
|
-
}
|
|
2435
|
-
const matcherCtx: MatcherContext = {
|
|
2436
|
-
userAgent: request.headers.get("user-agent") ?? "",
|
|
2437
|
-
url: url.toString(),
|
|
2438
|
-
path: basePath,
|
|
2439
|
-
cookies,
|
|
2440
|
-
request,
|
|
2441
|
-
};
|
|
2442
|
-
const page = await resolveDecoPage(basePath, matcherCtx);
|
|
2443
|
-
if (!page) {
|
|
2444
|
-
return Response.json(null, {
|
|
2445
|
-
status: 404,
|
|
2446
|
-
headers: { "Access-Control-Allow-Origin": "*" },
|
|
2447
|
-
});
|
|
2448
|
-
}
|
|
2449
|
-
const enrichedSections = await runSectionLoaders(page.resolvedSections, request);
|
|
2450
|
-
|
|
2451
|
-
// Run SEO section loader if registered
|
|
2452
|
-
let seoResult = page.seoSection;
|
|
2453
|
-
if (seoResult) {
|
|
2454
|
-
try {
|
|
2455
|
-
seoResult = await runSingleSectionLoader(seoResult, request);
|
|
2456
|
-
} catch {
|
|
2457
|
-
// use unloaded seoSection
|
|
2458
|
-
}
|
|
2459
|
-
}
|
|
2460
|
-
|
|
2461
|
-
// Merge site-wide SEO defaults into seo props
|
|
2462
|
-
const blocks = loadBlocks();
|
|
2463
|
-
const site = (blocks["Site"] ?? blocks["site"]) as Record<string, unknown> | undefined;
|
|
2464
|
-
const fullSiteSeo = (site?.seo as Record<string, unknown>) ?? {};
|
|
2465
|
-
|
|
2466
|
-
// When SeoV2 loader ran, use its output as base (preserves key order)
|
|
2467
|
-
// and only fill in missing fields from the site-wide SEO config.
|
|
2468
|
-
const loaderProps = seoResult?.props ?? {};
|
|
2469
|
-
const seoProps: Record<string, unknown> = { ...loaderProps };
|
|
2470
|
-
for (const [k, v] of Object.entries(fullSiteSeo)) {
|
|
2471
|
-
if (!(k in seoProps)) seoProps[k] = v;
|
|
2472
|
-
}
|
|
2473
|
-
// Strip internal template fields
|
|
2474
|
-
delete seoProps.titleTemplate;
|
|
2475
|
-
delete seoProps.descriptionTemplate;
|
|
2476
|
-
|
|
2477
|
-
// Build resolveChain statically to match legacy deco-cx/deco format.
|
|
2478
|
-
type FieldResolver = { type: string; value: string | number };
|
|
2479
|
-
const rawKey = page.blockKey ?? `pages-${page.name}`;
|
|
2480
|
-
const encodedKey = rawKey.replace(
|
|
2481
|
-
/^(pages-)(.+)$/,
|
|
2482
|
-
(_m, prefix, rest) => prefix + encodeURIComponent(rest),
|
|
2483
|
-
);
|
|
2484
|
-
const pageChain: FieldResolver[] = [
|
|
2485
|
-
{ type: "resolver", value: "website/handlers/fresh.ts" },
|
|
2486
|
-
{ type: "prop", value: "page" },
|
|
2487
|
-
{ type: "resolver", value: "resolved" },
|
|
2488
|
-
{ type: "resolvable", value: encodedKey },
|
|
2489
|
-
{ type: "resolver", value: "website/pages/Page.tsx" },
|
|
2490
|
-
];
|
|
2491
|
-
|
|
2492
|
-
const seoChain: FieldResolver[] = [
|
|
2493
|
-
...pageChain,
|
|
2494
|
-
{ type: "prop", value: "seo" },
|
|
2495
|
-
{ type: "resolver", value: seoResult?.component ?? "website/sections/Seo/SeoV2.tsx" },
|
|
2496
|
-
];
|
|
2497
|
-
|
|
2498
|
-
const result = {
|
|
2499
|
-
props: {
|
|
2500
|
-
name: page.name,
|
|
2501
|
-
path: page.path,
|
|
2502
|
-
seo: {
|
|
2503
|
-
props: seoProps,
|
|
2504
|
-
metadata: {
|
|
2505
|
-
resolveChain: seoChain,
|
|
2506
|
-
component: seoResult?.component ?? "website/sections/Seo/SeoV2.tsx",
|
|
2507
|
-
},
|
|
2508
|
-
},
|
|
2509
|
-
sections: enrichedSections.map((s, i) => ({
|
|
2510
|
-
props: s.props,
|
|
2511
|
-
metadata: {
|
|
2512
|
-
resolveChain: [
|
|
2513
|
-
...pageChain,
|
|
2514
|
-
{ type: "prop", value: "sections" },
|
|
2515
|
-
{ type: "prop", value: String(i) },
|
|
2516
|
-
{ type: "resolver", value: s.component },
|
|
2517
|
-
],
|
|
2518
|
-
component: s.component,
|
|
2519
|
-
},
|
|
2520
|
-
})),
|
|
2521
|
-
devMode: false,
|
|
2522
|
-
unindexedDomain: false,
|
|
2523
|
-
},
|
|
2524
|
-
metadata: {
|
|
2525
|
-
resolveChain: pageChain,
|
|
2526
|
-
component: "website/pages/Page.tsx",
|
|
2527
|
-
},
|
|
2528
|
-
};
|
|
2529
|
-
return Response.json(result, {
|
|
2530
|
-
headers: {
|
|
2531
|
-
"Access-Control-Allow-Origin": "*",
|
|
2532
|
-
"Access-Control-Allow-Headers": "Content-Type, Authorization",
|
|
2533
|
-
"Access-Control-Allow-Methods": "GET, OPTIONS",
|
|
2534
|
-
},
|
|
2535
|
-
});
|
|
2536
|
-
}
|
|
2537
|
-
|
|
2538
|
-
// Commerce proxy (checkout, account, API, etc.)
|
|
2539
|
-
if (options.proxyHandler) {
|
|
2540
|
-
const proxyResponse = await options.proxyHandler(request, url);
|
|
2541
|
-
if (proxyResponse) return proxyResponse;
|
|
2542
|
-
}
|
|
2543
|
-
|
|
2544
|
-
// Static fingerprinted assets — serve from origin with immutable headers
|
|
2545
|
-
if (isStaticAsset(url.pathname)) {
|
|
2546
|
-
const origin = await serverEntry.fetch(request, env, ctx);
|
|
2547
|
-
if (origin.status === 200) {
|
|
2548
|
-
const ct = origin.headers.get("content-type") ?? "";
|
|
2549
|
-
if (ct.includes("text/html")) {
|
|
2550
|
-
return new Response("Not Found", { status: 404 });
|
|
2551
|
-
}
|
|
2552
|
-
const resp = new Response(origin.body, origin);
|
|
2553
|
-
for (const [k, v] of Object.entries(IMMUTABLE_HEADERS)) {
|
|
2554
|
-
resp.headers.set(k, v);
|
|
2555
|
-
}
|
|
2556
|
-
return resp;
|
|
2557
|
-
}
|
|
2558
|
-
return origin;
|
|
2559
|
-
}
|
|
2560
|
-
|
|
2561
|
-
// -----------------------------------------------------------------
|
|
2562
|
-
// POST _serverFn — edge-cacheable using body-hash as cache key.
|
|
2563
|
-
// These carry public CMS section data (shelves, deferred sections)
|
|
2564
|
-
// that benefits from edge caching despite being POST requests.
|
|
2565
|
-
// -----------------------------------------------------------------
|
|
2566
|
-
if (
|
|
2567
|
-
request.method === "POST" &&
|
|
2568
|
-
(url.pathname.startsWith("/_serverFn/") || url.pathname.startsWith("/_server/"))
|
|
2569
|
-
) {
|
|
2570
|
-
const serverFnCache = responseCache(request, env);
|
|
2571
|
-
|
|
2572
|
-
// Draft preview: a drafted SPA navigation fetches its section data via
|
|
2573
|
-
// this POST, carrying the draft cookie. The draft is already bound to the
|
|
2574
|
-
// request bag (bindRequestDraft, above), so origin renders it — but the
|
|
2575
|
-
// body-hash cache key does not vary on the cookie, so it must bypass the
|
|
2576
|
-
// shared cache entirely or it would leak drafts / serve stale published.
|
|
2577
|
-
if (requestCarriesDraft(request, url)) {
|
|
2578
|
-
const origin = await serverEntry.fetch(request, env, ctx);
|
|
2579
|
-
const resp = new Response(origin.body, origin);
|
|
2580
|
-
resp.headers.set("Cache-Control", "no-store, private");
|
|
2581
|
-
resp.headers.set("X-Cache", "BYPASS");
|
|
2582
|
-
resp.headers.set("X-Cache-Reason", "draft-preview");
|
|
2583
|
-
return resp;
|
|
2584
|
-
}
|
|
2585
|
-
|
|
2586
|
-
// Build segment once — used for logged-in check and cache key
|
|
2587
|
-
const sfnSegment = buildSegment ? buildSegment(request) : undefined;
|
|
2588
|
-
|
|
2589
|
-
// Logged-in users always bypass — personalized content must not leak
|
|
2590
|
-
if (sfnSegment?.loggedIn) {
|
|
2591
|
-
const origin = await serverEntry.fetch(request, env, ctx);
|
|
2592
|
-
const resp = new Response(origin.body, origin);
|
|
2593
|
-
resp.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
|
|
2594
|
-
resp.headers.set("X-Cache", "BYPASS");
|
|
2595
|
-
resp.headers.set("X-Cache-Reason", "logged-in");
|
|
2596
|
-
return resp;
|
|
2597
|
-
}
|
|
2598
|
-
|
|
2599
|
-
// Matcher overrides via header don't vary the body-hash cache key —
|
|
2600
|
-
// bypass so forced variants are neither stored nor served from cache.
|
|
2601
|
-
// (QS overrides travel inside the payload's pageUrl, so they already
|
|
2602
|
-
// produce a distinct body hash.)
|
|
2603
|
-
if (request.headers.has(DECO_MATCHERS_OVERRIDE_PARAM)) {
|
|
2604
|
-
const origin = await serverEntry.fetch(request, env, ctx);
|
|
2605
|
-
const resp = new Response(origin.body, origin);
|
|
2606
|
-
resp.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
|
|
2607
|
-
resp.headers.set("X-Cache", "BYPASS");
|
|
2608
|
-
resp.headers.set("X-Cache-Reason", "matchers-override");
|
|
2609
|
-
return resp;
|
|
2610
|
-
}
|
|
2611
|
-
|
|
2612
|
-
// Clone request before consuming body — the clone goes to origin
|
|
2613
|
-
// untouched so TanStack Start internals (cookie passthrough, etc.)
|
|
2614
|
-
// work correctly. We only read the body for the cache key hash.
|
|
2615
|
-
const originClone = request.clone();
|
|
2616
|
-
const body = await request.text();
|
|
2617
|
-
// Key on the body with tracking params stripped (a deferred section's
|
|
2618
|
-
// `pageUrl` carries the landing URL, so `?gclid=…` otherwise mints one
|
|
2619
|
-
// entry per ad click), but never *store* a response rendered from a
|
|
2620
|
-
// tracked body: it embeds that URL, and every later visitor would get it.
|
|
2621
|
-
const sfnCarriesTracking = shouldStripTracking && payloadHasTrackingParams(body);
|
|
2622
|
-
const bodyHash = await hashText(
|
|
2623
|
-
shouldStripTracking ? canonicalizeServerFnPayloadForCacheKey(body, []) : body,
|
|
2624
|
-
);
|
|
2625
|
-
|
|
2626
|
-
// Build a synthetic GET cache key from the URL + body hash + segment
|
|
2627
|
-
// Includes device, salesChannel, regionId, flags — so users in
|
|
2628
|
-
// different regions or channels get separate cache entries.
|
|
2629
|
-
const cacheKeyUrl = new URL(request.url);
|
|
2630
|
-
cacheKeyUrl.searchParams.set("__body", bodyHash);
|
|
2631
|
-
const sfnVersion = getBuildHash(env);
|
|
2632
|
-
if (sfnVersion) cacheKeyUrl.searchParams.set("__v", sfnVersion);
|
|
2633
|
-
if (sfnSegment) {
|
|
2634
|
-
cacheKeyUrl.searchParams.set("__seg", hashSegment(sfnSegment));
|
|
2635
|
-
} else if (deviceSpecificKeys) {
|
|
2636
|
-
const device = isMobileUA(request.headers.get("user-agent") ?? "") ? "mobile" : "desktop";
|
|
2637
|
-
cacheKeyUrl.searchParams.set("__cf_device", device);
|
|
2638
|
-
}
|
|
2639
|
-
// Include CF geo data so location-based content doesn't leak across geos.
|
|
2640
|
-
// Uses the same effectiveGeoKey() as the GET path so geoCacheKey config
|
|
2641
|
-
// is respected consistently for both HTML and server-fn responses.
|
|
2642
|
-
const sfnGeoParam = buildGeoCacheParam(
|
|
2643
|
-
(request as unknown as { cf?: Record<string, string> }).cf,
|
|
2644
|
-
effectiveGeoKey(),
|
|
2645
|
-
);
|
|
2646
|
-
if (sfnGeoParam) cacheKeyUrl.searchParams.set("__cf_geo", sfnGeoParam);
|
|
2647
|
-
const sfnCacheKey = new Request(cacheKeyUrl.toString(), { method: "GET" });
|
|
2648
|
-
|
|
2649
|
-
// Use "listing" profile for server function responses
|
|
2650
|
-
const sfnProfile: CacheProfileName = "listing";
|
|
2651
|
-
const sfnEdge = edgeCacheConfig(sfnProfile);
|
|
2652
|
-
|
|
2653
|
-
// Check edge cache
|
|
2654
|
-
let sfnCached: Response | undefined;
|
|
2655
|
-
if (serverFnCache) {
|
|
2656
|
-
try {
|
|
2657
|
-
sfnCached = await withTracing(
|
|
2658
|
-
"deco.cache.lookup",
|
|
2659
|
-
async () => (await serverFnCache.match(sfnCacheKey)) ?? undefined,
|
|
2660
|
-
{ "cache.profile": sfnProfile, "cache.kind": "serverFn" },
|
|
2661
|
-
);
|
|
2662
|
-
} catch {
|
|
2663
|
-
/* Cache API unavailable */
|
|
2664
|
-
}
|
|
2665
|
-
}
|
|
2666
|
-
|
|
2667
|
-
if (sfnCached && sfnEdge.fresh > 0) {
|
|
2668
|
-
const storedAt = Number(sfnCached.headers.get("X-Deco-Stored-At") || "0");
|
|
2669
|
-
const ageSec = storedAt > 0 ? (Date.now() - storedAt) / 1000 : Infinity;
|
|
2670
|
-
|
|
2671
|
-
if (ageSec < sfnEdge.fresh) {
|
|
2672
|
-
recordCacheMetric(true, sfnProfile, "HIT", "edge");
|
|
2673
|
-
const out = new Response(sfnCached.body, sfnCached);
|
|
2674
|
-
const hdrs = cacheHeaders(sfnProfile);
|
|
2675
|
-
for (const [k, v] of Object.entries(hdrs)) out.headers.set(k, v);
|
|
2676
|
-
out.headers.set("X-Cache", "HIT");
|
|
2677
|
-
out.headers.set("X-Cache-Profile", sfnProfile);
|
|
2678
|
-
return out;
|
|
2679
|
-
}
|
|
2680
|
-
|
|
2681
|
-
if (ageSec < sfnEdge.fresh + sfnEdge.swr) {
|
|
2682
|
-
recordCacheMetric(true, sfnProfile, "STALE-HIT", "edge");
|
|
2683
|
-
// Stale-while-revalidate: serve stale, refresh in background
|
|
2684
|
-
ctx.waitUntil(
|
|
2685
|
-
(async () => {
|
|
2686
|
-
try {
|
|
2687
|
-
// Revalidate from the canonical body, for the same reason the
|
|
2688
|
-
// HTML path revalidates from the clean URL: the entry is keyed
|
|
2689
|
-
// on it, and a render from the tracked body embeds that landing
|
|
2690
|
-
// URL. Rendering the tracked body would only be discarded,
|
|
2691
|
-
// leaving the entry stale for the rest of the SWR window.
|
|
2692
|
-
const bgBody = sfnCarriesTracking
|
|
2693
|
-
? canonicalizeServerFnPayloadForCacheKey(body, [])
|
|
2694
|
-
: body;
|
|
2695
|
-
const bgReq = new Request(request, { body: bgBody, method: "POST" });
|
|
2696
|
-
const bgOrigin = await serverEntry.fetch(bgReq, env, ctx);
|
|
2697
|
-
if (
|
|
2698
|
-
bgOrigin.status === 200 &&
|
|
2699
|
-
bgOrigin.headers.get("X-Deco-Cacheable") === "true" &&
|
|
2700
|
-
!bgOrigin.headers.has("set-cookie") &&
|
|
2701
|
-
serverFnCache
|
|
2702
|
-
) {
|
|
2703
|
-
const ttl = sfnEdge.fresh + Math.max(sfnEdge.swr, sfnEdge.sie);
|
|
2704
|
-
const toStore = bgOrigin.clone();
|
|
2705
|
-
toStore.headers.set("Cache-Control", `public, max-age=${ttl}`);
|
|
2706
|
-
toStore.headers.set("X-Deco-Stored-At", String(Date.now()));
|
|
2707
|
-
toStore.headers.delete("CDN-Cache-Control");
|
|
2708
|
-
toStore.headers.delete("X-Deco-Cacheable");
|
|
2709
|
-
await serverFnCache.put(sfnCacheKey, toStore);
|
|
2710
|
-
}
|
|
2711
|
-
} catch {
|
|
2712
|
-
/* background revalidation failed */
|
|
2713
|
-
}
|
|
2714
|
-
})(),
|
|
2715
|
-
);
|
|
2716
|
-
const out = new Response(sfnCached.body, sfnCached);
|
|
2717
|
-
const hdrs = cacheHeaders(sfnProfile);
|
|
2718
|
-
for (const [k, v] of Object.entries(hdrs)) out.headers.set(k, v);
|
|
2719
|
-
out.headers.set("X-Cache", "STALE-HIT");
|
|
2720
|
-
out.headers.set("X-Cache-Profile", sfnProfile);
|
|
2721
|
-
out.headers.set("X-Cache-Age", String(Math.round(ageSec)));
|
|
2722
|
-
return out;
|
|
2723
|
-
}
|
|
2724
|
-
}
|
|
2725
|
-
|
|
2726
|
-
// Cache MISS — fetch origin with the body we already read
|
|
2727
|
-
recordCacheMetric(false, sfnProfile, "MISS", "edge");
|
|
2728
|
-
const origin = await serverEntry.fetch(originClone, env, ctx);
|
|
2729
|
-
|
|
2730
|
-
// Only cache responses explicitly marked as cacheable by the handler
|
|
2731
|
-
// (loadDeferredSection sets X-Deco-Cacheable: true). Checkout actions,
|
|
2732
|
-
// invoke mutations, and other server functions are passed through.
|
|
2733
|
-
const isCacheableResponse =
|
|
2734
|
-
origin.headers.get("X-Deco-Cacheable") === "true" &&
|
|
2735
|
-
!origin.headers.has("set-cookie") &&
|
|
2736
|
-
origin.status === 200;
|
|
2737
|
-
|
|
2738
|
-
if (!isCacheableResponse) {
|
|
2739
|
-
const resp = new Response(origin.body, origin);
|
|
2740
|
-
resp.headers.delete("X-Deco-Cacheable");
|
|
2741
|
-
resp.headers.set("X-Cache", "BYPASS");
|
|
2742
|
-
resp.headers.set(
|
|
2743
|
-
"X-Cache-Reason",
|
|
2744
|
-
origin.headers.has("set-cookie") ? "set-cookie" : "not-cacheable",
|
|
2745
|
-
);
|
|
2746
|
-
return resp;
|
|
2747
|
-
}
|
|
2748
|
-
|
|
2749
|
-
// Store in edge cache (see sfnCarriesTracking above)
|
|
2750
|
-
if (serverFnCache && !sfnCarriesTracking) {
|
|
2751
|
-
try {
|
|
2752
|
-
const ttl = sfnEdge.fresh + Math.max(sfnEdge.swr, sfnEdge.sie);
|
|
2753
|
-
const toStore = origin.clone();
|
|
2754
|
-
toStore.headers.set("Cache-Control", `public, max-age=${ttl}`);
|
|
2755
|
-
toStore.headers.set("X-Deco-Stored-At", String(Date.now()));
|
|
2756
|
-
toStore.headers.delete("CDN-Cache-Control");
|
|
2757
|
-
toStore.headers.delete("X-Deco-Cacheable");
|
|
2758
|
-
ctx.waitUntil(
|
|
2759
|
-
withTracing("deco.cache.store", () => serverFnCache.put(sfnCacheKey, toStore), {
|
|
2760
|
-
"cache.profile": sfnProfile,
|
|
2761
|
-
"cache.kind": "serverFn",
|
|
2762
|
-
}),
|
|
2763
|
-
);
|
|
2764
|
-
} catch {
|
|
2765
|
-
/* Cache API unavailable */
|
|
2766
|
-
}
|
|
2767
|
-
}
|
|
2768
|
-
|
|
2769
|
-
const resp = new Response(origin.body, origin);
|
|
2770
|
-
resp.headers.delete("X-Deco-Cacheable");
|
|
2771
|
-
const hdrs = cacheHeaders(sfnProfile);
|
|
2772
|
-
for (const [k, v] of Object.entries(hdrs)) resp.headers.set(k, v);
|
|
2773
|
-
resp.headers.set("X-Cache", "MISS");
|
|
2774
|
-
resp.headers.set("X-Cache-Profile", sfnProfile);
|
|
2775
|
-
// Same label the HTML path emits, so the documented probe works on a
|
|
2776
|
-
// deferred section too.
|
|
2777
|
-
if (sfnCarriesTracking) resp.headers.set("X-Cache-Store", "skipped-tracking");
|
|
2778
|
-
return resp;
|
|
2779
|
-
}
|
|
2780
|
-
|
|
2781
|
-
// Non-cacheable requests — pass through but protect against accidental caching
|
|
2782
|
-
if (!isCacheable(request, url)) {
|
|
2783
|
-
const origin = await serverEntry.fetch(request, env, ctx);
|
|
2784
|
-
const profile = getProfile(url);
|
|
2785
|
-
|
|
2786
|
-
if (profile === "private" || profile === "none" || profile === "cart") {
|
|
2787
|
-
const resp = new Response(origin.body, origin);
|
|
2788
|
-
resp.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
|
|
2789
|
-
resp.headers.delete("CDN-Cache-Control");
|
|
2790
|
-
resp.headers.set("X-Cache", "BYPASS");
|
|
2791
|
-
resp.headers.set("X-Cache-Reason", `non-cacheable:${profile}`);
|
|
2792
|
-
return resp;
|
|
2793
|
-
}
|
|
2794
|
-
|
|
2795
|
-
const resp = new Response(origin.body, origin);
|
|
2796
|
-
|
|
2797
|
-
// Responses with private Set-Cookie headers carry per-user tokens —
|
|
2798
|
-
// never expose them with public cache headers.
|
|
2799
|
-
// Safe/public cookies (e.g., vtex_is_session) are allowed through.
|
|
2800
|
-
if (origin.headers.has("set-cookie") && !hasOnlySafeCookies(origin, safeCookieSet)) {
|
|
2801
|
-
resp.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
|
|
2802
|
-
resp.headers.delete("CDN-Cache-Control");
|
|
2803
|
-
resp.headers.set("X-Cache", "BYPASS");
|
|
2804
|
-
resp.headers.set("X-Cache-Reason", "private-set-cookie");
|
|
2805
|
-
return resp;
|
|
2806
|
-
}
|
|
2807
|
-
|
|
2808
|
-
// Set cache headers from the detected profile so the response
|
|
2809
|
-
// is explicit about cacheability (avoids ambiguous empty header).
|
|
2810
|
-
const hdrsNc = cacheHeaders(profile);
|
|
2811
|
-
for (const [k, v] of Object.entries(hdrsNc)) resp.headers.set(k, v);
|
|
2812
|
-
|
|
2813
|
-
const reason = request.method !== "GET" ? `method:${request.method}` : "bypass-path";
|
|
2814
|
-
resp.headers.set("X-Cache", "BYPASS");
|
|
2815
|
-
resp.headers.set("X-Cache-Profile", profile);
|
|
2816
|
-
resp.headers.set("X-Cache-Reason", reason);
|
|
2817
|
-
return resp;
|
|
2818
|
-
}
|
|
2819
|
-
|
|
2820
|
-
// Cacheable request — build segment-aware cache key
|
|
2821
|
-
const { key: cacheKey, segment } = buildCacheKey(request, env);
|
|
2822
|
-
|
|
2823
|
-
// The key drops tracking params, but the renderer sees the raw URL and
|
|
2824
|
-
// embeds it (page URL, router match id, analytics payloads, pagination
|
|
2825
|
-
// base URLs). Storing that response under the clean key served one ad
|
|
2826
|
-
// visitor's `gclid` to everyone. Tracked requests still READ the clean
|
|
2827
|
-
// entry; only clean requests WRITE it.
|
|
2828
|
-
const skipStoreTracking = shouldStripTracking && requestCarriesTracking(url);
|
|
2829
|
-
|
|
2830
|
-
// Logged-in users always bypass the cache (personalized content)
|
|
2831
|
-
if (segment?.loggedIn) {
|
|
2832
|
-
const origin = await serverEntry.fetch(request, env, ctx);
|
|
2833
|
-
const resp = new Response(origin.body, origin);
|
|
2834
|
-
resp.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
|
|
2835
|
-
resp.headers.set("X-Cache", "BYPASS");
|
|
2836
|
-
resp.headers.set("X-Cache-Reason", "logged-in");
|
|
2837
|
-
return resp;
|
|
2838
|
-
}
|
|
2839
|
-
|
|
2840
|
-
// Check Cache API — disabled in local dev to avoid stale responses
|
|
2841
|
-
const cache = responseCache(request, env);
|
|
2842
|
-
|
|
2843
|
-
const profile = getProfile(url);
|
|
2844
|
-
const edgeConfig = edgeCacheConfig(profile);
|
|
2845
|
-
|
|
2846
|
-
// Helper: dress a response with proper client-facing headers
|
|
2847
|
-
function dressResponse(
|
|
2848
|
-
resp: Response,
|
|
2849
|
-
xCache: string,
|
|
2850
|
-
extra?: Record<string, string>,
|
|
2851
|
-
): Response {
|
|
2852
|
-
const out = new Response(resp.body, resp);
|
|
2853
|
-
const hdrs = cacheHeaders(profile);
|
|
2854
|
-
for (const [k, v] of Object.entries(hdrs)) out.headers.set(k, v);
|
|
2855
|
-
|
|
2856
|
-
// CDN-Cache-Control: controls Cloudflare's automatic CDN layer
|
|
2857
|
-
// (separate from Cache API which the worker manages directly).
|
|
2858
|
-
const cdnPublic = `public, max-age=${edgeConfig.fresh}`;
|
|
2859
|
-
const cdnCacheable = edgeConfig.isPublic && edgeConfig.fresh > 0;
|
|
2860
|
-
|
|
2861
|
-
if (cdnCacheControlOpt === "serverfn-segment") {
|
|
2862
|
-
// Only `/_serverFn` requests whose URL carries a verified segment
|
|
2863
|
-
// marker. Everything else — including every HTML document, which has no
|
|
2864
|
-
// client hook to attach a marker on the initial navigation — keeps
|
|
2865
|
-
// `no-store`.
|
|
2866
|
-
out.headers.set(
|
|
2867
|
-
"CDN-Cache-Control",
|
|
2868
|
-
cdnCacheable && cdnCacheableServerFn(request, url, env) ? cdnPublic : "no-store",
|
|
2869
|
-
);
|
|
2870
|
-
} else if (cdnCacheControlOpt === "match-profile") {
|
|
2871
|
-
// `match-profile` is only sound when the Worker's cache key is the raw
|
|
2872
|
-
// URL. It almost never is: `deviceSpecificKeys` defaults to true, so
|
|
2873
|
-
// every site keys on `__cf_device` even without a `buildSegment`, and a
|
|
2874
|
-
// location matcher adds `__cf_geo`. Honoring the option under those
|
|
2875
|
-
// conditions would serve desktop HTML to mobile, or one region's to
|
|
2876
|
-
// another — silently. Refuse, and say why once.
|
|
2877
|
-
const keyed =
|
|
2878
|
-
buildSegment !== undefined || deviceSpecificKeys || effectiveGeoKey() !== "off";
|
|
2879
|
-
if (keyed) {
|
|
2880
|
-
if (!warnedMatchProfile) {
|
|
2881
|
-
warnedMatchProfile = true;
|
|
2882
|
-
console.warn(
|
|
2883
|
-
'[deco] cdnCacheControl: "match-profile" ignored — the edge cache key is ' +
|
|
2884
|
-
"segmented (buildSegment / deviceSpecificKeys / geoCacheKey), which the CDN " +
|
|
2885
|
-
"cannot reproduce from the URL alone. Keeping CDN-Cache-Control: no-store.",
|
|
2886
|
-
);
|
|
2887
|
-
}
|
|
2888
|
-
out.headers.set("CDN-Cache-Control", "no-store");
|
|
2889
|
-
} else {
|
|
2890
|
-
out.headers.set("CDN-Cache-Control", cdnCacheable ? cdnPublic : "no-store");
|
|
2891
|
-
}
|
|
2892
|
-
} else if (typeof cdnCacheControlOpt === "function") {
|
|
2893
|
-
const val = cdnCacheControlOpt(profile);
|
|
2894
|
-
out.headers.set("CDN-Cache-Control", val ?? "no-store");
|
|
2895
|
-
} else {
|
|
2896
|
-
out.headers.set("CDN-Cache-Control", "no-store");
|
|
2897
|
-
}
|
|
2898
|
-
|
|
2899
|
-
out.headers.set("X-Cache", xCache);
|
|
2900
|
-
out.headers.set("X-Cache-Profile", profile);
|
|
2901
|
-
if (segment) out.headers.set("X-Cache-Segment", hashSegment(segment));
|
|
2902
|
-
const headerVersion = getBuildHash(env);
|
|
2903
|
-
if (headerVersion) out.headers.set("X-Cache-Version", headerVersion);
|
|
2904
|
-
if (extra) for (const [k, v] of Object.entries(extra)) out.headers.set(k, v);
|
|
2905
|
-
appendResourceHints(out);
|
|
2906
|
-
return out;
|
|
2907
|
-
}
|
|
2908
|
-
|
|
2909
|
-
// Helper: store a response in Cache API with the full retention window.
|
|
2910
|
-
// Callers own the tracking decision: a response is storable iff it was
|
|
2911
|
-
// rendered from the clean URL this `cacheKey` represents.
|
|
2912
|
-
function storeInCache(resp: Response) {
|
|
2913
|
-
if (!cache) return;
|
|
2914
|
-
try {
|
|
2915
|
-
const storageTtl = edgeConfig.fresh + Math.max(edgeConfig.swr, edgeConfig.sie);
|
|
2916
|
-
const toStore = resp.clone();
|
|
2917
|
-
toStore.headers.set("Cache-Control", `public, max-age=${storageTtl}`);
|
|
2918
|
-
toStore.headers.set("X-Deco-Stored-At", String(Date.now()));
|
|
2919
|
-
toStore.headers.delete("CDN-Cache-Control");
|
|
2920
|
-
ctx.waitUntil(
|
|
2921
|
-
withTracing("deco.cache.store", () => cache.put(cacheKey, toStore), {
|
|
2922
|
-
"cache.profile": profile,
|
|
2923
|
-
"cache.kind": "html",
|
|
2924
|
-
}),
|
|
2925
|
-
);
|
|
2926
|
-
} catch {
|
|
2927
|
-
// Cache API unavailable
|
|
2928
|
-
}
|
|
2929
|
-
}
|
|
2930
|
-
|
|
2931
|
-
// A tracked request must revalidate from the CLEAN URL. The renderer
|
|
2932
|
-
// embeds the URL it was given, and the entry being refreshed is keyed
|
|
2933
|
-
// clean — so rendering the tracked URL here is either poisoning (what this
|
|
2934
|
-
// used to do) or dead weight (`storeInCache` drops it), which would leave
|
|
2935
|
-
// the entry stale for the whole SWR window while every ad visitor pays a
|
|
2936
|
-
// full SSR that refreshes nothing. Rendering clean costs the same fetch
|
|
2937
|
-
// and actually warms the entry, so paid traffic keeps the cache alive.
|
|
2938
|
-
function revalidationRequest(): Request {
|
|
2939
|
-
if (!skipStoreTracking) return request;
|
|
2940
|
-
const clean = new URL(cleanPathForCacheKey(url.toString()), url.origin);
|
|
2941
|
-
// A GET server fn can carry the tracking inside `payload` (the page it
|
|
2942
|
-
// loads), not in its own query — strip it there too, or this renders and
|
|
2943
|
-
// stores the tracked page under the clean key.
|
|
2944
|
-
const payload = clean.searchParams.get("payload");
|
|
2945
|
-
if (
|
|
2946
|
-
payload &&
|
|
2947
|
-
(clean.pathname.startsWith("/_serverFn/") || clean.pathname.startsWith("/_server/"))
|
|
2948
|
-
) {
|
|
2949
|
-
clean.searchParams.set("payload", canonicalizeServerFnPayloadForCacheKey(payload, []));
|
|
2950
|
-
}
|
|
2951
|
-
// Build the init field by field instead of passing `request` as init:
|
|
2952
|
-
// whether the `new Request(url, request)` form carries `cf` over is
|
|
2953
|
-
// runtime-dependent, and a location matcher reading a dropped `cf` would
|
|
2954
|
-
// store a wrong-region render under a region-keyed entry. No body — this
|
|
2955
|
-
// path is GET-only (every other method bypasses the cache above) — and
|
|
2956
|
-
// no `signal`, so a client disconnecting mid-revalidation doesn't abort
|
|
2957
|
-
// the refresh that the next visitor is going to read.
|
|
2958
|
-
const cf = (request as unknown as { cf?: unknown }).cf;
|
|
2959
|
-
return new Request(clean.toString(), {
|
|
2960
|
-
method: request.method,
|
|
2961
|
-
headers: request.headers,
|
|
2962
|
-
redirect: request.redirect,
|
|
2963
|
-
...(cf ? { cf } : {}),
|
|
2964
|
-
} as RequestInit);
|
|
2965
|
-
}
|
|
2966
|
-
|
|
2967
|
-
// Helper: background revalidation (fetch origin, store result)
|
|
2968
|
-
function revalidateInBackground() {
|
|
2969
|
-
ctx.waitUntil(
|
|
2970
|
-
Promise.resolve(serverEntry.fetch(revalidationRequest(), env, ctx))
|
|
2971
|
-
.then((origin) => {
|
|
2972
|
-
// Never overwrite a good entry with a degraded 200 (a critical
|
|
2973
|
-
// section failed) — that would poison the cache. Leave the stale
|
|
2974
|
-
// entry in place until a healthy revalidation succeeds.
|
|
2975
|
-
if (origin.status === 200 && origin.headers.get("X-Deco-Degraded") !== "true") {
|
|
2976
|
-
// Only cache if response has no cookies or only safe cookies.
|
|
2977
|
-
// Strip safe cookies from the cached copy.
|
|
2978
|
-
if (hasOnlySafeCookies(origin, safeCookieSet)) {
|
|
2979
|
-
const cleanOrigin = origin.headers.has("set-cookie")
|
|
2980
|
-
? stripSafeCookiesForCache(origin, safeCookieSet)
|
|
2981
|
-
: origin;
|
|
2982
|
-
storeInCache(cleanOrigin);
|
|
2983
|
-
}
|
|
2984
|
-
}
|
|
2985
|
-
})
|
|
2986
|
-
.catch(() => {
|
|
2987
|
-
// Background revalidation failed — stale entry stays until SIE expires
|
|
2988
|
-
}),
|
|
2989
|
-
);
|
|
2990
|
-
}
|
|
2991
|
-
|
|
2992
|
-
// --- Edge cache check with SWR + SIE ---
|
|
2993
|
-
let cached: Response | undefined;
|
|
2994
|
-
if (cache) {
|
|
2995
|
-
try {
|
|
2996
|
-
cached = await withTracing(
|
|
2997
|
-
"deco.cache.lookup",
|
|
2998
|
-
async () => (await cache.match(cacheKey)) ?? undefined,
|
|
2999
|
-
{ "cache.profile": profile, "cache.kind": "html" },
|
|
3000
|
-
);
|
|
3001
|
-
} catch {
|
|
3002
|
-
// Cache API unavailable
|
|
3003
|
-
}
|
|
3004
|
-
}
|
|
3005
|
-
|
|
3006
|
-
if (cached && edgeConfig.isPublic && edgeConfig.fresh > 0) {
|
|
3007
|
-
const storedAtStr = cached.headers.get("X-Deco-Stored-At");
|
|
3008
|
-
const storedAt = storedAtStr ? Number(storedAtStr) : 0;
|
|
3009
|
-
const ageMs = storedAt > 0 ? Date.now() - storedAt : Infinity;
|
|
3010
|
-
const ageSec = ageMs / 1000;
|
|
3011
|
-
|
|
3012
|
-
if (ageSec < edgeConfig.fresh) {
|
|
3013
|
-
// FRESH HIT — serve immediately
|
|
3014
|
-
recordCacheMetric(true, profile, "HIT", "edge");
|
|
3015
|
-
return dressResponse(cached, "HIT");
|
|
3016
|
-
}
|
|
3017
|
-
|
|
3018
|
-
if (ageSec < edgeConfig.fresh + edgeConfig.swr) {
|
|
3019
|
-
// STALE-HIT within SWR window — serve stale, revalidate in background
|
|
3020
|
-
recordCacheMetric(true, profile, "STALE-HIT", "edge");
|
|
3021
|
-
revalidateInBackground();
|
|
3022
|
-
return dressResponse(cached, "STALE-HIT", { "X-Cache-Age": String(Math.round(ageSec)) });
|
|
3023
|
-
}
|
|
3024
|
-
|
|
3025
|
-
// Past SWR window but still in cache (within SIE window) — keep reference
|
|
3026
|
-
// for potential error fallback below
|
|
3027
|
-
}
|
|
3028
|
-
|
|
3029
|
-
// Cache MISS or past SWR window — fetch from origin
|
|
3030
|
-
recordCacheMetric(false, profile, "MISS", "edge");
|
|
3031
|
-
let origin: Response;
|
|
3032
|
-
try {
|
|
3033
|
-
origin = await serverEntry.fetch(request, env, ctx);
|
|
3034
|
-
} catch (err) {
|
|
3035
|
-
// Origin fetch threw — SIE fallback if we have a stale entry
|
|
3036
|
-
if (cached && edgeConfig.sie > 0) {
|
|
3037
|
-
const storedAtStr = cached.headers.get("X-Deco-Stored-At");
|
|
3038
|
-
const storedAt = storedAtStr ? Number(storedAtStr) : 0;
|
|
3039
|
-
const ageSec = storedAt > 0 ? (Date.now() - storedAt) / 1000 : Infinity;
|
|
3040
|
-
if (ageSec < edgeConfig.fresh + edgeConfig.sie) {
|
|
3041
|
-
console.warn(
|
|
3042
|
-
`[edge-cache] Origin threw, serving stale (age=${Math.round(ageSec)}s, sie=${edgeConfig.sie}s)`,
|
|
3043
|
-
);
|
|
3044
|
-
recordCacheMetric(true, profile, "STALE-ERROR", "edge");
|
|
3045
|
-
return dressResponse(cached, "STALE-ERROR", {
|
|
3046
|
-
"X-Cache-Age": String(Math.round(ageSec)),
|
|
3047
|
-
});
|
|
3048
|
-
}
|
|
3049
|
-
}
|
|
3050
|
-
throw err;
|
|
3051
|
-
}
|
|
3052
|
-
|
|
3053
|
-
if (origin.status !== 200) {
|
|
3054
|
-
// Non-200 origin — SIE fallback on 5xx/429
|
|
3055
|
-
if (origin.status >= 500 || origin.status === 429) {
|
|
3056
|
-
if (cached && edgeConfig.sie > 0) {
|
|
3057
|
-
const storedAtStr = cached.headers.get("X-Deco-Stored-At");
|
|
3058
|
-
const storedAt = storedAtStr ? Number(storedAtStr) : 0;
|
|
3059
|
-
const ageSec = storedAt > 0 ? (Date.now() - storedAt) / 1000 : Infinity;
|
|
3060
|
-
if (ageSec < edgeConfig.fresh + edgeConfig.sie) {
|
|
3061
|
-
console.warn(
|
|
3062
|
-
`[edge-cache] Origin ${origin.status}, serving stale (age=${Math.round(ageSec)}s)`,
|
|
3063
|
-
);
|
|
3064
|
-
recordCacheMetric(true, profile, "STALE-ERROR", "edge");
|
|
3065
|
-
return dressResponse(cached, "STALE-ERROR", {
|
|
3066
|
-
"X-Cache-Age": String(Math.round(ageSec)),
|
|
3067
|
-
"X-Cache-Origin-Status": String(origin.status),
|
|
3068
|
-
});
|
|
3069
|
-
}
|
|
3070
|
-
}
|
|
3071
|
-
}
|
|
3072
|
-
const resp = new Response(origin.body, origin);
|
|
3073
|
-
resp.headers.set("X-Cache", "BYPASS");
|
|
3074
|
-
resp.headers.set("X-Cache-Reason", `status:${origin.status}`);
|
|
3075
|
-
appendResourceHints(resp);
|
|
3076
|
-
return resp;
|
|
3077
|
-
}
|
|
3078
|
-
|
|
3079
|
-
// Responses with private Set-Cookie headers must never be cached —
|
|
3080
|
-
// they carry per-user session/auth tokens that would leak to other users.
|
|
3081
|
-
// Safe/public cookies (IS session, segment, etc.) are stripped from the
|
|
3082
|
-
// cached copy but kept on the response served to the current user.
|
|
3083
|
-
if (origin.headers.has("set-cookie") && !hasOnlySafeCookies(origin, safeCookieSet)) {
|
|
3084
|
-
const resp = new Response(origin.body, origin);
|
|
3085
|
-
resp.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
|
|
3086
|
-
resp.headers.delete("CDN-Cache-Control");
|
|
3087
|
-
resp.headers.set("X-Cache", "BYPASS");
|
|
3088
|
-
resp.headers.set("X-Cache-Reason", "private-set-cookie");
|
|
3089
|
-
appendResourceHints(resp);
|
|
3090
|
-
return resp;
|
|
3091
|
-
}
|
|
3092
|
-
|
|
3093
|
-
// Degraded origin — a critical section loader failed, so this 200 carries
|
|
3094
|
-
// raw/empty data (e.g. an empty product shelf during a VTEX outage). Treat
|
|
3095
|
-
// it like a 5xx for caching: prefer a warm stale entry (STALE-ERROR) and
|
|
3096
|
-
// NEVER store it. Without this, the broken page would be cached as healthy
|
|
3097
|
-
// for the full retention window and stale-if-error would never fire —
|
|
3098
|
-
// turning a seconds-long blip into hours of empty pages.
|
|
3099
|
-
if (origin.headers.get("X-Deco-Degraded") === "true") {
|
|
3100
|
-
if (cached && edgeConfig.sie > 0) {
|
|
3101
|
-
const storedAtStr = cached.headers.get("X-Deco-Stored-At");
|
|
3102
|
-
const storedAt = storedAtStr ? Number(storedAtStr) : 0;
|
|
3103
|
-
const ageSec = storedAt > 0 ? (Date.now() - storedAt) / 1000 : Infinity;
|
|
3104
|
-
if (ageSec < edgeConfig.fresh + edgeConfig.sie) {
|
|
3105
|
-
console.warn(
|
|
3106
|
-
`[edge-cache] Origin degraded, serving stale (age=${Math.round(ageSec)}s, sie=${edgeConfig.sie}s)`,
|
|
3107
|
-
);
|
|
3108
|
-
recordCacheMetric(true, profile, "STALE-ERROR", "edge");
|
|
3109
|
-
return dressResponse(cached, "STALE-ERROR", {
|
|
3110
|
-
"X-Cache-Age": String(Math.round(ageSec)),
|
|
3111
|
-
"X-Cache-Reason": "degraded",
|
|
3112
|
-
});
|
|
3113
|
-
}
|
|
3114
|
-
}
|
|
3115
|
-
// Cold cache — serve the degraded page but never persist it.
|
|
3116
|
-
const resp = new Response(origin.body, origin);
|
|
3117
|
-
resp.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
|
|
3118
|
-
resp.headers.delete("CDN-Cache-Control");
|
|
3119
|
-
resp.headers.set("X-Cache", "BYPASS");
|
|
3120
|
-
resp.headers.set("X-Cache-Reason", "degraded");
|
|
3121
|
-
appendResourceHints(resp);
|
|
3122
|
-
return resp;
|
|
3123
|
-
}
|
|
3124
|
-
|
|
3125
|
-
const profileConfig = getCacheProfile(profile);
|
|
3126
|
-
|
|
3127
|
-
if (!profileConfig.isPublic || profileConfig.edge.fresh === 0) {
|
|
3128
|
-
const resp = new Response(origin.body, origin);
|
|
3129
|
-
resp.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
|
|
3130
|
-
resp.headers.set("X-Cache", "BYPASS");
|
|
3131
|
-
resp.headers.set("X-Cache-Reason", `profile:${profile}`);
|
|
3132
|
-
appendResourceHints(resp);
|
|
3133
|
-
return resp;
|
|
3134
|
-
}
|
|
3135
|
-
|
|
3136
|
-
// Clone for cache BEFORE dressResponse consumes the body stream.
|
|
3137
|
-
// dressResponse() calls new Response(resp.body, resp) which locks
|
|
3138
|
-
// the ReadableStream. Calling clone() on a locked body corrupts
|
|
3139
|
-
// the stream in Workers runtime, causing Error 1101.
|
|
3140
|
-
// Strip safe cookies from the cached copy so they don't leak
|
|
3141
|
-
// to other users, but the current user still gets them.
|
|
3142
|
-
const cacheOrigin = origin.headers.has("set-cookie")
|
|
3143
|
-
? stripSafeCookiesForCache(origin, safeCookieSet)
|
|
3144
|
-
: origin;
|
|
3145
|
-
// This render saw the tracked URL and embedded it — never store it under
|
|
3146
|
-
// the clean key. The next clean visitor fills the entry.
|
|
3147
|
-
if (!skipStoreTracking) storeInCache(cacheOrigin);
|
|
3148
|
-
return dressResponse(
|
|
3149
|
-
origin,
|
|
3150
|
-
"MISS",
|
|
3151
|
-
skipStoreTracking ? { "X-Cache-Store": "skipped-tracking" } : undefined,
|
|
3152
|
-
);
|
|
3153
|
-
}
|
|
3154
|
-
}
|