@decocms/blocks 8.1.0-next.0 → 8.1.0-next.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/package.json +6 -92
- package/src/index.ts +2 -12
- package/src/protocol/storage/memory.ts +1 -1
- package/src/v8/background.ts +3 -3
- package/src/v8/builtins/legacy.ts +1 -1
- package/src/v8/cli/index.ts +1 -1
- package/src/v8/fetch.ts +8 -27
- package/src/v8/remoteLoader.ts +1 -1
- package/src/v8/telemetry.ts +1 -1
- package/src/cms/applySectionConventions.ts +0 -148
- package/src/cms/blockSource.ts +0 -228
- package/src/cms/client.ts +0 -85
- package/src/cms/deferredTrigger.ts +0 -58
- package/src/cms/draftSource.ts +0 -476
- package/src/cms/index.ts +0 -180
- package/src/cms/loadDecofileDirectory.ts +0 -89
- package/src/cms/loader.ts +0 -563
- package/src/cms/registry.ts +0 -264
- package/src/cms/renderJson.ts +0 -179
- package/src/cms/resolve.ts +0 -2583
- package/src/cms/schema.ts +0 -1219
- package/src/cms/sectionLoaderContext.ts +0 -113
- package/src/cms/sectionLoaders.ts +0 -686
- package/src/cms/sectionMixins.ts +0 -153
- package/src/flags/audience.ts +0 -56
- package/src/flags/everyone.ts +0 -29
- package/src/flags/flag.ts +0 -15
- package/src/flags/multivariate/image.ts +0 -11
- package/src/flags/multivariate/message.ts +0 -11
- package/src/flags/multivariate/page.ts +0 -16
- package/src/flags/multivariate/section.ts +0 -16
- package/src/flags/multivariate.ts +0 -1
- package/src/flags/types.ts +0 -59
- package/src/flags/utils/multivariate.ts +0 -20
- package/src/hooks/Image.tsx +0 -314
- package/src/hooks/JsonLd.tsx +0 -353
- package/src/hooks/LazySection.tsx +0 -121
- package/src/hooks/LiveControls.tsx +0 -144
- package/src/hooks/Picture.tsx +0 -127
- package/src/hooks/RenderSection.tsx +0 -91
- package/src/hooks/SectionErrorFallback.tsx +0 -97
- package/src/hooks/Stats.tsx +0 -134
- package/src/hooks/index.ts +0 -35
- package/src/hooks/useLoadMore.ts +0 -100
- package/src/matchers/builtins.ts +0 -459
- package/src/matchers/countryNames.ts +0 -104
- package/src/matchers/override.ts +0 -136
- package/src/matchers/posthog.ts +0 -154
- package/src/middleware/decoState.ts +0 -55
- package/src/middleware/healthMetrics.ts +0 -133
- package/src/middleware/hydrationContext.ts +0 -79
- package/src/middleware/index.ts +0 -88
- package/src/middleware/liveness.ts +0 -21
- package/src/middleware/observability.ts +0 -800
- package/src/middleware/validateSection.ts +0 -100
- package/src/preview/DraftPreviewBadge.tsx +0 -306
- package/src/preview/decoMark.ts +0 -11
- package/src/preview/index.ts +0 -8
- package/src/sdk/abTesting.ts +0 -556
- package/src/sdk/analytics.ts +0 -147
- package/src/sdk/cacheHeaders.ts +0 -633
- package/src/sdk/cacheStorage.ts +0 -287
- package/src/sdk/cachedLoader.ts +0 -556
- package/src/sdk/clx.ts +0 -5
- package/src/sdk/cn.ts +0 -28
- package/src/sdk/composite.ts +0 -114
- package/src/sdk/cookie.ts +0 -129
- package/src/sdk/crypto.ts +0 -199
- package/src/sdk/csp.ts +0 -59
- package/src/sdk/deepOmit.ts +0 -52
- package/src/sdk/detectDevice.ts +0 -45
- package/src/sdk/djb2.ts +0 -20
- package/src/sdk/encoding.ts +0 -44
- package/src/sdk/env.ts +0 -54
- package/src/sdk/experiments.ts +0 -314
- package/src/sdk/fetchCache.ts +0 -269
- package/src/sdk/fetchTimeout.ts +0 -58
- package/src/sdk/flags.ts +0 -138
- package/src/sdk/http.ts +0 -124
- package/src/sdk/index.ts +0 -97
- package/src/sdk/inflightTimeout.ts +0 -53
- package/src/sdk/instrumentedFetch.ts +0 -362
- package/src/sdk/invoke.ts +0 -298
- package/src/sdk/logger.ts +0 -304
- package/src/sdk/mergeCacheControl.ts +0 -150
- package/src/sdk/nonce.ts +0 -46
- package/src/sdk/normalizeUrls.ts +0 -91
- package/src/sdk/observability.ts +0 -116
- package/src/sdk/otel.ts +0 -1118
- package/src/sdk/otelAdapters/clickhouseCollector.ts +0 -65
- package/src/sdk/otelAdapters.ts +0 -144
- package/src/sdk/otelHttpLog.ts +0 -419
- package/src/sdk/otelHttpMeter.ts +0 -532
- package/src/sdk/otelHttpTracer.ts +0 -543
- package/src/sdk/redirects.ts +0 -336
- package/src/sdk/requestContext.ts +0 -281
- package/src/sdk/requestContextStorage.browser.ts +0 -43
- package/src/sdk/requestContextStorage.ts +0 -35
- package/src/sdk/responseCache.ts +0 -82
- package/src/sdk/retry.ts +0 -45
- package/src/sdk/serverTimings.ts +0 -68
- package/src/sdk/signal.ts +0 -42
- package/src/sdk/sitemap.ts +0 -160
- package/src/sdk/urlRedaction.ts +0 -82
- package/src/sdk/urlUtils.ts +0 -183
- package/src/sdk/useDevice.ts +0 -89
- package/src/sdk/useDeviceContext.tsx +0 -108
- package/src/sdk/useId.ts +0 -7
- package/src/sdk/useScript.ts +0 -210
- package/src/sdk/useSuggestions.ts +0 -188
- package/src/sdk/wrapCaughtErrors.ts +0 -107
- package/src/setup.ts +0 -120
- package/src/types/index.ts +0 -53
- package/src/types/widgets.ts +0 -14
package/src/sdk/cachedLoader.ts
DELETED
|
@@ -1,556 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Server-side loader caching with stale-while-revalidate + stale-if-error.
|
|
3
|
-
*
|
|
4
|
-
* Caches commerce loader results in memory and optional app-provided storage.
|
|
5
|
-
* Supports:
|
|
6
|
-
* - Single-flight dedup (identical concurrent requests share one fetch)
|
|
7
|
-
* - SWR: serve stale immediately, refresh in background
|
|
8
|
-
* - SIE: on origin error, fall back to stale entry within a configurable window
|
|
9
|
-
*
|
|
10
|
-
* Can be configured with explicit options or by passing a cache profile name
|
|
11
|
-
* (e.g. "product") which derives timing from the unified profile system.
|
|
12
|
-
*/
|
|
13
|
-
|
|
14
|
-
import {
|
|
15
|
-
recordCacheMetric,
|
|
16
|
-
recordCacheSizeMetric,
|
|
17
|
-
recordLoaderError,
|
|
18
|
-
recordLoaderMetric,
|
|
19
|
-
withTracing,
|
|
20
|
-
} from "../middleware/observability";
|
|
21
|
-
import { type CacheProfileName, loaderCacheOptions } from "./cacheHeaders";
|
|
22
|
-
import { cacheBackground, createCacheStore, getCacheStorageContext } from "./cacheStorage";
|
|
23
|
-
import { withInflightTimeout } from "./inflightTimeout";
|
|
24
|
-
import { RequestContext } from "./requestContext";
|
|
25
|
-
|
|
26
|
-
// Build-time constant injected by `decoVitePlugin()` (see @decocms/tanstack's
|
|
27
|
-
// vite plugin) — the same commit-SHA/deploy token the edge Cache API uses as
|
|
28
|
-
// its `__v` cache-key version. Declared here with a `typeof` guard so it's
|
|
29
|
-
// inert where the define is not applied (Node tests, non-plugin builds). Same
|
|
30
|
-
// pattern already used in `../cms/blockSource.ts`.
|
|
31
|
-
declare const __DECO_BUILD_HASH__: string | undefined;
|
|
32
|
-
|
|
33
|
-
// Include the build version even when called outside the TanStack worker. The
|
|
34
|
-
// request-scoped store additionally separates sites, content revisions and segments.
|
|
35
|
-
const BUILD =
|
|
36
|
-
typeof __DECO_BUILD_HASH__ !== "undefined" && __DECO_BUILD_HASH__ ? __DECO_BUILD_HASH__ : "";
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* `maxAge` above this (10 min) is almost always a mistake for a commerce loader:
|
|
40
|
-
* upstream (catalog/price/stock) changes then take that long to propagate and a
|
|
41
|
-
* redeploy is the only fast lever. Warned once per loader name.
|
|
42
|
-
*/
|
|
43
|
-
const LONG_MAXAGE_WARN = 600_000;
|
|
44
|
-
const warnedLongMaxAge = new Set<string>();
|
|
45
|
-
|
|
46
|
-
export type CachePolicy = "no-store" | "no-cache" | "stale-while-revalidate";
|
|
47
|
-
|
|
48
|
-
export interface CachedLoaderOptions {
|
|
49
|
-
policy: CachePolicy;
|
|
50
|
-
/** Max age in milliseconds before an entry is considered stale. Default: 60_000 (1 min). */
|
|
51
|
-
maxAge?: number;
|
|
52
|
-
/** How long to serve stale on origin error, in ms. Default: 0 (no error fallback). */
|
|
53
|
-
staleIfError?: number;
|
|
54
|
-
/** Maximum stale-while-revalidate window in ms. Default: 5 minutes. */
|
|
55
|
-
staleWhileRevalidate?: number;
|
|
56
|
-
/** Key function to generate a cache key from loader props. Default: JSON.stringify. */
|
|
57
|
-
keyFn?: (props: unknown) => string;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/**
|
|
61
|
-
* The `@decocms/apps` loader/action module shape: a `default` loader plus the
|
|
62
|
-
* optional `cache` / `cacheKey` exports Fresh loaders ship with.
|
|
63
|
-
*
|
|
64
|
-
* export const cache = "stale-while-revalidate";
|
|
65
|
-
* export const cacheKey = (props, req) => `${new URL(req.url).pathname}...`;
|
|
66
|
-
*
|
|
67
|
-
* `cache` is the OPT-IN: absent (or `"no-store"`) means the loader runs on every
|
|
68
|
-
* invocation, matching `@decocms/apps`' default. Any other value opts the loader
|
|
69
|
-
* into single-flight dedup (concurrent identical calls in one render collapse to
|
|
70
|
-
* one upstream call — the #339 N+1 fix). `cacheKey` computes the dedup identity
|
|
71
|
-
* from `(props, req)`; returning `null` means "do not dedup, run fresh".
|
|
72
|
-
*/
|
|
73
|
-
export interface LoaderModule<TProps = any, TResult = any> {
|
|
74
|
-
default: (props: TProps, req?: Request) => Promise<TResult>;
|
|
75
|
-
cache?: CachePolicy | { maxAge: number };
|
|
76
|
-
cacheKey?: (props: TProps, req?: Request) => string | null;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
interface CacheEntry<T = unknown> {
|
|
80
|
-
value: T;
|
|
81
|
-
createdAt: number;
|
|
82
|
-
refreshing: boolean;
|
|
83
|
-
/** Estimated payload size in bytes (UTF-16 length of JSON.stringify). */
|
|
84
|
-
estimatedBytes: number;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
const DEFAULT_MAX_AGE = 60_000;
|
|
88
|
-
|
|
89
|
-
/**
|
|
90
|
-
* Byte-cap for the in-memory loader cache. Default 32 MB — comfortably below
|
|
91
|
-
* the Cloudflare Workers 128 MB isolate limit even when other caches (router,
|
|
92
|
-
* VTEX fetch cache, V8 heap) are also resident.
|
|
93
|
-
*
|
|
94
|
-
* Override via env: `DECO_LOADER_CACHE_MAX_BYTES=67108864` (64 MB).
|
|
95
|
-
*
|
|
96
|
-
* Switched from entry-count to byte-based eviction because PLP payloads
|
|
97
|
-
* (~0.5–2 MB each) blew past 128 MB at well under the previous 500-entry cap.
|
|
98
|
-
*/
|
|
99
|
-
const DEFAULT_MAX_CACHE_BYTES = 32 * 1024 * 1024;
|
|
100
|
-
|
|
101
|
-
function resolveMaxBytes(): number {
|
|
102
|
-
const env = typeof globalThis.process !== "undefined" ? globalThis.process.env : undefined;
|
|
103
|
-
const raw = env?.DECO_LOADER_CACHE_MAX_BYTES;
|
|
104
|
-
if (!raw) return DEFAULT_MAX_CACHE_BYTES;
|
|
105
|
-
const parsed = Number.parseInt(raw, 10);
|
|
106
|
-
return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_MAX_CACHE_BYTES;
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
let maxCacheBytes = resolveMaxBytes();
|
|
110
|
-
|
|
111
|
-
/**
|
|
112
|
-
* Override the loader cache byte cap at runtime.
|
|
113
|
-
*
|
|
114
|
-
* The `DECO_LOADER_CACHE_MAX_BYTES` env override above only lands when the
|
|
115
|
-
* Worker's `compatibility_date` is new enough for `nodejs_compat` to populate
|
|
116
|
-
* `process.env`. Verified in workerd: with `2024-09-23` it is empty both at
|
|
117
|
-
* module scope and inside the handler; with `2025-06-01` it is populated. Sites
|
|
118
|
-
* pinned to an older date — a common thing to do, since the date also gates
|
|
119
|
-
* behaviour flags they may have tuned deliberately — had a documented knob that
|
|
120
|
-
* silently did nothing.
|
|
121
|
-
*
|
|
122
|
-
* Call this from the site's `setup.ts`, before any loader is wrapped.
|
|
123
|
-
*
|
|
124
|
-
* Sizing note: the cap is per ISOLATE, not per site, and a Worker isolate has
|
|
125
|
-
* 128 MB total, shared with the bundle, the V8 heap and the render working set.
|
|
126
|
-
* Setting it at or near 128 MB does not give headroom — it removes the ceiling.
|
|
127
|
-
*/
|
|
128
|
-
export function setLoaderCacheMaxBytes(bytes: number): void {
|
|
129
|
-
if (!Number.isFinite(bytes) || bytes <= 0) return;
|
|
130
|
-
maxCacheBytes = bytes;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
/** Current byte cap — exported for diagnostics and tests. */
|
|
134
|
-
export function getLoaderCacheMaxBytes(): number {
|
|
135
|
-
return maxCacheBytes;
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
const cache = createCacheStore<CacheEntry>(
|
|
139
|
-
"loaders",
|
|
140
|
-
Infinity,
|
|
141
|
-
Infinity,
|
|
142
|
-
(entry) => entry.estimatedBytes,
|
|
143
|
-
);
|
|
144
|
-
|
|
145
|
-
// Bumped by clearLoaderCache(). A loader invocation captures this at entry and
|
|
146
|
-
// only writes its result back if the generation is unchanged when it settles —
|
|
147
|
-
// so a purge (e.g. POST /_cache/purge-loaders) that lands while a loader is
|
|
148
|
-
// in flight can't be silently undone by that in-flight loader repopulating a
|
|
149
|
-
// just-cleared entry with pre-purge data.
|
|
150
|
-
let cacheGeneration = 0;
|
|
151
|
-
|
|
152
|
-
// Floor each entry at 512 bytes so we never accumulate unbounded zero-cost
|
|
153
|
-
// entries when a loader legitimately returns `undefined` or an empty object
|
|
154
|
-
// — `JSON.stringify(undefined) === undefined` and the eviction loop would
|
|
155
|
-
// otherwise never reclaim them. JSON-length also under-counts V8's actual
|
|
156
|
-
// retention (structured objects retain 2–5× the JSON byte size); the 32 MB
|
|
157
|
-
// cap is conservative enough that this approximation is fine for an OOM
|
|
158
|
-
// safety net, but real RSS at the cap can land around 64–160 MB on
|
|
159
|
-
// object-heavy payloads.
|
|
160
|
-
const MIN_ENTRY_BYTES = 512;
|
|
161
|
-
|
|
162
|
-
function estimateBytes(value: unknown): number {
|
|
163
|
-
try {
|
|
164
|
-
// UTF-16 string length is an order-of-magnitude estimate of the bytes the
|
|
165
|
-
// object retains in V8 (V8 keeps a structured representation, not JSON).
|
|
166
|
-
// The absolute value is less important than the relative pressure signal.
|
|
167
|
-
const len = JSON.stringify(value)?.length ?? 0;
|
|
168
|
-
return Math.max(len, MIN_ENTRY_BYTES);
|
|
169
|
-
} catch {
|
|
170
|
-
// Circular refs / non-serializable values: fall back to a fixed budget so
|
|
171
|
-
// the entry still counts against the cap.
|
|
172
|
-
return 1024;
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
/**
|
|
177
|
-
* The single write path into the cache — both the cold-miss and the SWR
|
|
178
|
-
* background-refresh callers route through here, which is why the size metric
|
|
179
|
-
* is emitted at this chokepoint rather than at each call site.
|
|
180
|
-
*/
|
|
181
|
-
function setCacheEntry<T>(key: string, entry: CacheEntry<T>, name: string, retention: number) {
|
|
182
|
-
recordCacheSizeMetric(entry.estimatedBytes, name);
|
|
183
|
-
cache.set(key, entry, entry.createdAt + retention);
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
function deleteCacheEntry(key: string) {
|
|
187
|
-
cache.delete(key);
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
function evictIfNeeded() {
|
|
191
|
-
let cacheBytes = cache.estimatedBytes;
|
|
192
|
-
if (cacheBytes <= maxCacheBytes) return;
|
|
193
|
-
const oldest = [...cache.entries()].sort((a, b) => a[1].createdAt - b[1].createdAt);
|
|
194
|
-
for (const [key, entry] of oldest) {
|
|
195
|
-
deleteCacheEntry(key);
|
|
196
|
-
cacheBytes -= entry.estimatedBytes;
|
|
197
|
-
if (cacheBytes <= maxCacheBytes) break;
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
const inflightRequests = new Map<string, Promise<unknown>>();
|
|
202
|
-
|
|
203
|
-
function resolveOptions(
|
|
204
|
-
optionsOrProfile: CachedLoaderOptions | CacheProfileName,
|
|
205
|
-
): CachedLoaderOptions {
|
|
206
|
-
if (typeof optionsOrProfile === "string") {
|
|
207
|
-
return loaderCacheOptions(optionsOrProfile);
|
|
208
|
-
}
|
|
209
|
-
return optionsOrProfile;
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
/**
|
|
213
|
-
* Wraps a loader function with server-side caching, single-flight dedup,
|
|
214
|
-
* and stale-if-error resilience.
|
|
215
|
-
*
|
|
216
|
-
* Accepts either explicit options or a cache profile name:
|
|
217
|
-
*
|
|
218
|
-
* @example
|
|
219
|
-
* ```ts
|
|
220
|
-
* // Profile-driven (recommended):
|
|
221
|
-
* const cachedPDP = createCachedLoader("vtex/productDetailsPage", pdpLoader, "product");
|
|
222
|
-
*
|
|
223
|
-
* // Explicit options (when loader needs different timing than its profile):
|
|
224
|
-
* const cachedSuggestions = createCachedLoader("vtex/suggestions", suggestionsLoader, {
|
|
225
|
-
* policy: "stale-while-revalidate",
|
|
226
|
-
* maxAge: 120_000,
|
|
227
|
-
* staleIfError: 300_000,
|
|
228
|
-
* });
|
|
229
|
-
* ```
|
|
230
|
-
*/
|
|
231
|
-
export function createCachedLoader<TProps, TResult>(
|
|
232
|
-
name: string,
|
|
233
|
-
loaderFn: (props: TProps) => Promise<TResult>,
|
|
234
|
-
optionsOrProfile: CachedLoaderOptions | CacheProfileName,
|
|
235
|
-
): (props: TProps) => Promise<TResult> {
|
|
236
|
-
const resolved = resolveOptions(optionsOrProfile);
|
|
237
|
-
const {
|
|
238
|
-
policy,
|
|
239
|
-
maxAge = DEFAULT_MAX_AGE,
|
|
240
|
-
staleIfError = 0,
|
|
241
|
-
staleWhileRevalidate = 300_000,
|
|
242
|
-
keyFn = JSON.stringify,
|
|
243
|
-
} = resolved;
|
|
244
|
-
|
|
245
|
-
const env = typeof globalThis.process !== "undefined" ? globalThis.process.env : undefined;
|
|
246
|
-
const isDev = env?.DECO_CACHE_DISABLE === "true" || env?.NODE_ENV === "development";
|
|
247
|
-
|
|
248
|
-
if (policy !== "no-store" && maxAge > LONG_MAXAGE_WARN && !warnedLongMaxAge.has(name)) {
|
|
249
|
-
warnedLongMaxAge.add(name);
|
|
250
|
-
console.warn(
|
|
251
|
-
`[cachedLoader] ${name}: maxAge=${Math.round(maxAge / 1000)}s is very long — ` +
|
|
252
|
-
`upstream changes take that long to propagate. Prefer a short window and use ` +
|
|
253
|
-
`short TTLs for shared storage; the purge-loaders endpoint clears memory only.`,
|
|
254
|
-
);
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
if (policy === "no-store") return loaderFn;
|
|
258
|
-
|
|
259
|
-
return async (props: TProps): Promise<TResult> => {
|
|
260
|
-
const cacheKey = cache.key(`${BUILD}::${name}::${keyFn(props)}`);
|
|
261
|
-
const retention =
|
|
262
|
-
maxAge +
|
|
263
|
-
Math.max(staleIfError, policy === "stale-while-revalidate" ? staleWhileRevalidate : 0);
|
|
264
|
-
// Snapshot the cache generation; a purge during this invocation bumps it,
|
|
265
|
-
// and the deferred writes below skip repopulating a just-cleared entry.
|
|
266
|
-
const gen = cacheGeneration;
|
|
267
|
-
|
|
268
|
-
const inflight = inflightRequests.get(cacheKey);
|
|
269
|
-
if (inflight) {
|
|
270
|
-
// Treat in-flight dedup as a cache hit — avoided the origin call.
|
|
271
|
-
recordCacheMetric(true, name, undefined, "cachedLoader");
|
|
272
|
-
const start = performance.now();
|
|
273
|
-
return inflight.then((r) => {
|
|
274
|
-
recordLoaderMetric(name, performance.now() - start, "HIT");
|
|
275
|
-
return r as TResult;
|
|
276
|
-
});
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
if (isDev) {
|
|
280
|
-
// Dev mode: no caching, but still useful to count attempts.
|
|
281
|
-
recordCacheMetric(false, name, undefined, "cachedLoader");
|
|
282
|
-
const devStart = performance.now();
|
|
283
|
-
const promise = withInflightTimeout(
|
|
284
|
-
withTracing("deco.cachedLoader", () => loaderFn(props), {
|
|
285
|
-
"deco.loader": name,
|
|
286
|
-
"deco.cache.policy": "no-cache-dev",
|
|
287
|
-
}),
|
|
288
|
-
`cachedLoader:dev ${cacheKey}`,
|
|
289
|
-
)
|
|
290
|
-
.then((r) => {
|
|
291
|
-
recordLoaderMetric(name, performance.now() - devStart, "BYPASS");
|
|
292
|
-
return r;
|
|
293
|
-
})
|
|
294
|
-
.catch((err) => {
|
|
295
|
-
recordLoaderMetric(name, performance.now() - devStart, "BYPASS");
|
|
296
|
-
recordLoaderError(name);
|
|
297
|
-
throw err;
|
|
298
|
-
})
|
|
299
|
-
.finally(() => inflightRequests.delete(cacheKey));
|
|
300
|
-
inflightRequests.set(cacheKey, promise);
|
|
301
|
-
return promise;
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
let entry = cache.get(cacheKey) as CacheEntry<TResult> | undefined;
|
|
305
|
-
if (!entry && getCacheStorageContext()?.storage) {
|
|
306
|
-
entry = (await cache.read(cacheKey)) as CacheEntry<TResult> | undefined;
|
|
307
|
-
evictIfNeeded();
|
|
308
|
-
}
|
|
309
|
-
// Another caller may have started the origin fetch while storage was being read.
|
|
310
|
-
const pending = inflightRequests.get(cacheKey);
|
|
311
|
-
if (pending) return pending as Promise<TResult>;
|
|
312
|
-
const now = Date.now();
|
|
313
|
-
const isStale = entry ? now - entry.createdAt > maxAge : true;
|
|
314
|
-
|
|
315
|
-
if (policy === "no-cache") {
|
|
316
|
-
if (entry && !isStale) {
|
|
317
|
-
recordCacheMetric(true, name, "HIT", "cachedLoader");
|
|
318
|
-
recordLoaderMetric(name, 0, "HIT");
|
|
319
|
-
return entry.value;
|
|
320
|
-
}
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
if (policy === "stale-while-revalidate") {
|
|
324
|
-
if (entry && !isStale) {
|
|
325
|
-
recordCacheMetric(true, name, "HIT", "cachedLoader");
|
|
326
|
-
recordLoaderMetric(name, 0, "HIT");
|
|
327
|
-
return entry.value;
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
if (
|
|
331
|
-
entry &&
|
|
332
|
-
isStale &&
|
|
333
|
-
now - entry.createdAt <= maxAge + staleWhileRevalidate &&
|
|
334
|
-
!entry.refreshing
|
|
335
|
-
) {
|
|
336
|
-
// Stale-while-revalidate hit: serve stale, refresh in background.
|
|
337
|
-
recordCacheMetric(true, name, "STALE-HIT", "cachedLoader");
|
|
338
|
-
recordLoaderMetric(name, 0, "STALE-HIT");
|
|
339
|
-
entry.refreshing = true;
|
|
340
|
-
cacheBackground(
|
|
341
|
-
Promise.resolve()
|
|
342
|
-
.then(() => loaderFn(props))
|
|
343
|
-
.then((result) => {
|
|
344
|
-
// Skip the write if a purge cleared the cache mid-refresh — otherwise
|
|
345
|
-
// we'd re-insert pre-purge data the purge was meant to drop.
|
|
346
|
-
if (gen !== cacheGeneration) return;
|
|
347
|
-
setCacheEntry(
|
|
348
|
-
cacheKey,
|
|
349
|
-
{
|
|
350
|
-
value: result,
|
|
351
|
-
createdAt: Date.now(),
|
|
352
|
-
refreshing: false,
|
|
353
|
-
estimatedBytes: estimateBytes(result),
|
|
354
|
-
},
|
|
355
|
-
name,
|
|
356
|
-
retention,
|
|
357
|
-
);
|
|
358
|
-
evictIfNeeded();
|
|
359
|
-
})
|
|
360
|
-
.catch(() => {
|
|
361
|
-
// Background refresh failed — entry stays stale.
|
|
362
|
-
// If past the SIE window, evict so we don't serve indefinitely stale data.
|
|
363
|
-
entry.refreshing = false;
|
|
364
|
-
if (staleIfError > 0 && now - entry.createdAt > maxAge + staleIfError) {
|
|
365
|
-
deleteCacheEntry(cacheKey);
|
|
366
|
-
}
|
|
367
|
-
}),
|
|
368
|
-
);
|
|
369
|
-
return entry.value;
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
if (entry && now - entry.createdAt <= maxAge + staleWhileRevalidate) {
|
|
373
|
-
// A background refresh is already running in this isolate.
|
|
374
|
-
recordCacheMetric(true, name, "STALE-HIT", "cachedLoader");
|
|
375
|
-
recordLoaderMetric(name, 0, "STALE-HIT");
|
|
376
|
-
return entry.value;
|
|
377
|
-
}
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
// Cache miss — emit metric, then run loader inside a span so individual
|
|
381
|
-
// slow loaders are visible in traces.
|
|
382
|
-
recordCacheMetric(false, name, "MISS", "cachedLoader");
|
|
383
|
-
const loaderStart = performance.now();
|
|
384
|
-
const promise = withInflightTimeout(
|
|
385
|
-
withTracing("deco.cachedLoader", () => loaderFn(props), {
|
|
386
|
-
"deco.loader": name,
|
|
387
|
-
"deco.cache.policy": policy,
|
|
388
|
-
}),
|
|
389
|
-
`cachedLoader ${cacheKey}`,
|
|
390
|
-
)
|
|
391
|
-
.then((result) => {
|
|
392
|
-
recordLoaderMetric(name, performance.now() - loaderStart, "MISS");
|
|
393
|
-
// Skip caching if a purge landed while this loader was in flight — still
|
|
394
|
-
// return the fresh value to the caller, just don't persist a raced entry.
|
|
395
|
-
if (gen === cacheGeneration) {
|
|
396
|
-
setCacheEntry(
|
|
397
|
-
cacheKey,
|
|
398
|
-
{
|
|
399
|
-
value: result,
|
|
400
|
-
createdAt: Date.now(),
|
|
401
|
-
refreshing: false,
|
|
402
|
-
estimatedBytes: estimateBytes(result),
|
|
403
|
-
},
|
|
404
|
-
name,
|
|
405
|
-
retention,
|
|
406
|
-
);
|
|
407
|
-
evictIfNeeded();
|
|
408
|
-
}
|
|
409
|
-
return result;
|
|
410
|
-
})
|
|
411
|
-
.catch((err) => {
|
|
412
|
-
// SIE fallback: if we have a stale entry within the error window, return it
|
|
413
|
-
if (staleIfError > 0 && entry) {
|
|
414
|
-
const age = Date.now() - entry.createdAt;
|
|
415
|
-
if (age < maxAge + staleIfError) {
|
|
416
|
-
console.warn(
|
|
417
|
-
`[cachedLoader] ${name}: origin error, serving stale entry (age=${Math.round(age / 1000)}s, sie=${Math.round(staleIfError / 1000)}s)`,
|
|
418
|
-
);
|
|
419
|
-
recordLoaderMetric(name, performance.now() - loaderStart, "STALE-ERROR");
|
|
420
|
-
return entry.value;
|
|
421
|
-
}
|
|
422
|
-
}
|
|
423
|
-
recordLoaderMetric(name, performance.now() - loaderStart, "MISS");
|
|
424
|
-
recordLoaderError(name);
|
|
425
|
-
throw err;
|
|
426
|
-
})
|
|
427
|
-
.finally(() => inflightRequests.delete(cacheKey));
|
|
428
|
-
|
|
429
|
-
inflightRequests.set(cacheKey, promise);
|
|
430
|
-
return promise;
|
|
431
|
-
};
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
// ---------------------------------------------------------------------------
|
|
435
|
-
// Module loader dedup (the `@decocms/apps` cache/cacheKey convention)
|
|
436
|
-
//
|
|
437
|
-
// Distinct from `createCachedLoader` above (VTEX's byte-capped SWR cache): the
|
|
438
|
-
// module path is DEDUP-ONLY. A loader that opts in via `export const cache`
|
|
439
|
-
// gets single-flight — concurrent identical invocations in one render (N
|
|
440
|
-
// sections referencing the same loader) share one upstream call — but nothing
|
|
441
|
-
// is retained past settlement, so there is zero cross-request staleness. This
|
|
442
|
-
// is the deliberately-conservative fix for the #339 N+1 (2–3× product GraphQL
|
|
443
|
-
// per PDP render) without the SWR machinery's stale-serving semantics.
|
|
444
|
-
// ---------------------------------------------------------------------------
|
|
445
|
-
|
|
446
|
-
const moduleInflight = new Map<string, Promise<unknown>>();
|
|
447
|
-
|
|
448
|
-
/**
|
|
449
|
-
* Wrap an `@decocms/apps`-shaped loader module so its `cache`/`cacheKey` exports
|
|
450
|
-
* drive single-flight dedup. Loaders without a `cache` export (or `"no-store"`)
|
|
451
|
-
* are returned unwrapped — they run on every call, matching apps' default.
|
|
452
|
-
*
|
|
453
|
-
* The dedup key is `${name}::${cacheKey(props, req)}`; `req` comes from the
|
|
454
|
-
* caller or, on the CMS-resolution path (which passes only props), from
|
|
455
|
-
* `RequestContext.current` — both execute inside the same AsyncLocalStorage
|
|
456
|
-
* scope. `cacheKey` returning `null`, or `req` being unavailable when `cacheKey`
|
|
457
|
-
* needs it, falls back to running fresh / keying on `JSON.stringify(props)`.
|
|
458
|
-
*/
|
|
459
|
-
export function createCachedLoaderFromModule<TProps, TResult>(
|
|
460
|
-
name: string,
|
|
461
|
-
mod: LoaderModule<TProps, TResult>,
|
|
462
|
-
): (props: TProps, req?: Request) => Promise<TResult> {
|
|
463
|
-
const policy: CachePolicy =
|
|
464
|
-
typeof mod.cache === "string"
|
|
465
|
-
? mod.cache
|
|
466
|
-
: mod.cache && typeof mod.cache === "object"
|
|
467
|
-
? "stale-while-revalidate"
|
|
468
|
-
: "no-store";
|
|
469
|
-
|
|
470
|
-
// Only `stale-while-revalidate` (or `{ maxAge }`) opts into dedup — matching
|
|
471
|
-
// `@decocms/apps`/deco, where `no-store` (the default) and `no-cache` both
|
|
472
|
-
// bypass single-flight and run on every call. Return unwrapped otherwise.
|
|
473
|
-
if (policy !== "stale-while-revalidate") return mod.default;
|
|
474
|
-
|
|
475
|
-
const cacheKeyFn = mod.cacheKey;
|
|
476
|
-
|
|
477
|
-
return (props: TProps, req?: Request): Promise<TResult> => {
|
|
478
|
-
const request = req ?? RequestContext.current?.request ?? undefined;
|
|
479
|
-
|
|
480
|
-
let keyPart: string | null;
|
|
481
|
-
if (cacheKeyFn) {
|
|
482
|
-
// A cacheKey that dereferences `req` (e.g. `new URL(req.url)`) would throw
|
|
483
|
-
// when the request is unavailable — fall back to props-hash dedup instead.
|
|
484
|
-
keyPart = request ? cacheKeyFn(props, request) : JSON.stringify(props);
|
|
485
|
-
} else {
|
|
486
|
-
keyPart = JSON.stringify(props);
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
// Explicit null → the loader declared this call uncacheable: run fresh.
|
|
490
|
-
if (keyPart === null) return mod.default(props, req);
|
|
491
|
-
|
|
492
|
-
const key = cache.key(`${BUILD}::${name}::${keyPart}`);
|
|
493
|
-
const existing = moduleInflight.get(key) as Promise<TResult> | undefined;
|
|
494
|
-
if (existing) return existing;
|
|
495
|
-
|
|
496
|
-
const promise = Promise.resolve(mod.default(props, req)).finally(() => {
|
|
497
|
-
moduleInflight.delete(key);
|
|
498
|
-
});
|
|
499
|
-
moduleInflight.set(key, promise);
|
|
500
|
-
return promise;
|
|
501
|
-
};
|
|
502
|
-
}
|
|
503
|
-
|
|
504
|
-
/**
|
|
505
|
-
* Registry entry factory for generated loader maps (`.deco/loaders.gen.ts`).
|
|
506
|
-
* Lazily imports the loader module on first call, then delegates to a memoized
|
|
507
|
-
* `createCachedLoaderFromModule` wrapper so `cache`/`cacheKey` exports take
|
|
508
|
-
* effect. Keeps generated code a one-liner while the dedup logic stays here,
|
|
509
|
-
* unit-tested, in the framework.
|
|
510
|
-
*/
|
|
511
|
-
export function createLoaderEntry<TProps = any, TResult = any>(
|
|
512
|
-
name: string,
|
|
513
|
-
importFn: () => Promise<LoaderModule<TProps, TResult>>,
|
|
514
|
-
): (props: TProps, req?: Request) => Promise<TResult> {
|
|
515
|
-
// Memoize the import+build PROMISE (not the resolved wrapper) so concurrent
|
|
516
|
-
// first-calls — exactly the N-sections-per-render case — share one import
|
|
517
|
-
// instead of racing into N. Reset on failure so a transient import error can
|
|
518
|
-
// retry rather than poisoning the entry forever.
|
|
519
|
-
let wrappedPromise: Promise<(props: TProps, req?: Request) => Promise<TResult>> | undefined;
|
|
520
|
-
return (props: TProps, req?: Request): Promise<TResult> => {
|
|
521
|
-
if (!wrappedPromise) {
|
|
522
|
-
wrappedPromise = importFn()
|
|
523
|
-
.then((mod) => createCachedLoaderFromModule(name, mod))
|
|
524
|
-
.catch((err) => {
|
|
525
|
-
wrappedPromise = undefined;
|
|
526
|
-
throw err;
|
|
527
|
-
});
|
|
528
|
-
}
|
|
529
|
-
return wrappedPromise.then((wrapped) => wrapped(props, req));
|
|
530
|
-
};
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
/**
|
|
534
|
-
* Clear all cached entries in THIS isolate. Used both by decofile hot-reload
|
|
535
|
-
* (`@decocms/blocks-admin`) and by the `POST /_cache/purge-loaders` route — an
|
|
536
|
-
* memory eviction hook. Shared storage entries expire by TTL and may hydrate
|
|
537
|
-
* memory again. Deployment/content scopes prevent reuse across versions. Bumps the cache
|
|
538
|
-
* generation so any loader in flight at purge time won't repopulate a cleared
|
|
539
|
-
* entry with pre-purge data.
|
|
540
|
-
*/
|
|
541
|
-
export function clearLoaderCache() {
|
|
542
|
-
cache.clear();
|
|
543
|
-
inflightRequests.clear();
|
|
544
|
-
moduleInflight.clear();
|
|
545
|
-
cacheGeneration++;
|
|
546
|
-
}
|
|
547
|
-
|
|
548
|
-
/** Get cache stats for diagnostics. */
|
|
549
|
-
export function getLoaderCacheStats() {
|
|
550
|
-
return {
|
|
551
|
-
entries: cache.size,
|
|
552
|
-
inflight: inflightRequests.size,
|
|
553
|
-
estimatedBytes: cache.estimatedBytes,
|
|
554
|
-
maxBytes: maxCacheBytes,
|
|
555
|
-
};
|
|
556
|
-
}
|
package/src/sdk/clx.ts
DELETED
package/src/sdk/cn.ts
DELETED
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* `cn(...inputs)` — the canonical Tailwind class-name combinator
|
|
3
|
-
* (clsx + tailwind-merge). Every storefront we audited shipped a
|
|
4
|
-
* site-local copy of this; we promote it to the framework so sites
|
|
5
|
-
* can drop the duplicate.
|
|
6
|
-
*
|
|
7
|
-
* Behaviour:
|
|
8
|
-
* - Accepts the full `clsx` input format (strings, objects, arrays,
|
|
9
|
-
* conditionals, falsy values).
|
|
10
|
-
* - De-duplicates conflicting Tailwind utilities via `tailwind-merge`
|
|
11
|
-
* (e.g. `cn("p-2", "p-4")` → `"p-4"`).
|
|
12
|
-
*
|
|
13
|
-
* The simpler `clx` (no tailwind-merge, just `filter+join`) is still
|
|
14
|
-
* exported from `@decocms/start/sdk/clx` for cases where you want to
|
|
15
|
-
* keep the literal class string. Re-exported here so a single import
|
|
16
|
-
* covers both.
|
|
17
|
-
*/
|
|
18
|
-
|
|
19
|
-
import { clsx, type ClassValue } from "clsx";
|
|
20
|
-
import { twMerge } from "tailwind-merge";
|
|
21
|
-
|
|
22
|
-
export { clx } from "./clx";
|
|
23
|
-
|
|
24
|
-
export function cn(...inputs: ClassValue[]): string {
|
|
25
|
-
return twMerge(clsx(inputs));
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
export type { ClassValue };
|