@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.
Files changed (114) hide show
  1. package/package.json +6 -92
  2. package/src/index.ts +2 -12
  3. package/src/protocol/storage/memory.ts +1 -1
  4. package/src/v8/background.ts +3 -3
  5. package/src/v8/builtins/legacy.ts +1 -1
  6. package/src/v8/cli/index.ts +1 -1
  7. package/src/v8/fetch.ts +8 -27
  8. package/src/v8/remoteLoader.ts +1 -1
  9. package/src/v8/telemetry.ts +1 -1
  10. package/src/cms/applySectionConventions.ts +0 -148
  11. package/src/cms/blockSource.ts +0 -228
  12. package/src/cms/client.ts +0 -85
  13. package/src/cms/deferredTrigger.ts +0 -58
  14. package/src/cms/draftSource.ts +0 -476
  15. package/src/cms/index.ts +0 -180
  16. package/src/cms/loadDecofileDirectory.ts +0 -89
  17. package/src/cms/loader.ts +0 -563
  18. package/src/cms/registry.ts +0 -264
  19. package/src/cms/renderJson.ts +0 -179
  20. package/src/cms/resolve.ts +0 -2583
  21. package/src/cms/schema.ts +0 -1219
  22. package/src/cms/sectionLoaderContext.ts +0 -113
  23. package/src/cms/sectionLoaders.ts +0 -686
  24. package/src/cms/sectionMixins.ts +0 -153
  25. package/src/flags/audience.ts +0 -56
  26. package/src/flags/everyone.ts +0 -29
  27. package/src/flags/flag.ts +0 -15
  28. package/src/flags/multivariate/image.ts +0 -11
  29. package/src/flags/multivariate/message.ts +0 -11
  30. package/src/flags/multivariate/page.ts +0 -16
  31. package/src/flags/multivariate/section.ts +0 -16
  32. package/src/flags/multivariate.ts +0 -1
  33. package/src/flags/types.ts +0 -59
  34. package/src/flags/utils/multivariate.ts +0 -20
  35. package/src/hooks/Image.tsx +0 -314
  36. package/src/hooks/JsonLd.tsx +0 -353
  37. package/src/hooks/LazySection.tsx +0 -121
  38. package/src/hooks/LiveControls.tsx +0 -144
  39. package/src/hooks/Picture.tsx +0 -127
  40. package/src/hooks/RenderSection.tsx +0 -91
  41. package/src/hooks/SectionErrorFallback.tsx +0 -97
  42. package/src/hooks/Stats.tsx +0 -134
  43. package/src/hooks/index.ts +0 -35
  44. package/src/hooks/useLoadMore.ts +0 -100
  45. package/src/matchers/builtins.ts +0 -459
  46. package/src/matchers/countryNames.ts +0 -104
  47. package/src/matchers/override.ts +0 -136
  48. package/src/matchers/posthog.ts +0 -154
  49. package/src/middleware/decoState.ts +0 -55
  50. package/src/middleware/healthMetrics.ts +0 -133
  51. package/src/middleware/hydrationContext.ts +0 -79
  52. package/src/middleware/index.ts +0 -88
  53. package/src/middleware/liveness.ts +0 -21
  54. package/src/middleware/observability.ts +0 -800
  55. package/src/middleware/validateSection.ts +0 -100
  56. package/src/preview/DraftPreviewBadge.tsx +0 -306
  57. package/src/preview/decoMark.ts +0 -11
  58. package/src/preview/index.ts +0 -8
  59. package/src/sdk/abTesting.ts +0 -556
  60. package/src/sdk/analytics.ts +0 -147
  61. package/src/sdk/cacheHeaders.ts +0 -633
  62. package/src/sdk/cacheStorage.ts +0 -287
  63. package/src/sdk/cachedLoader.ts +0 -556
  64. package/src/sdk/clx.ts +0 -5
  65. package/src/sdk/cn.ts +0 -28
  66. package/src/sdk/composite.ts +0 -114
  67. package/src/sdk/cookie.ts +0 -129
  68. package/src/sdk/crypto.ts +0 -199
  69. package/src/sdk/csp.ts +0 -59
  70. package/src/sdk/deepOmit.ts +0 -52
  71. package/src/sdk/detectDevice.ts +0 -45
  72. package/src/sdk/djb2.ts +0 -20
  73. package/src/sdk/encoding.ts +0 -44
  74. package/src/sdk/env.ts +0 -54
  75. package/src/sdk/experiments.ts +0 -314
  76. package/src/sdk/fetchCache.ts +0 -269
  77. package/src/sdk/fetchTimeout.ts +0 -58
  78. package/src/sdk/flags.ts +0 -138
  79. package/src/sdk/http.ts +0 -124
  80. package/src/sdk/index.ts +0 -97
  81. package/src/sdk/inflightTimeout.ts +0 -53
  82. package/src/sdk/instrumentedFetch.ts +0 -362
  83. package/src/sdk/invoke.ts +0 -298
  84. package/src/sdk/logger.ts +0 -304
  85. package/src/sdk/mergeCacheControl.ts +0 -150
  86. package/src/sdk/nonce.ts +0 -46
  87. package/src/sdk/normalizeUrls.ts +0 -91
  88. package/src/sdk/observability.ts +0 -116
  89. package/src/sdk/otel.ts +0 -1118
  90. package/src/sdk/otelAdapters/clickhouseCollector.ts +0 -65
  91. package/src/sdk/otelAdapters.ts +0 -144
  92. package/src/sdk/otelHttpLog.ts +0 -419
  93. package/src/sdk/otelHttpMeter.ts +0 -532
  94. package/src/sdk/otelHttpTracer.ts +0 -543
  95. package/src/sdk/redirects.ts +0 -336
  96. package/src/sdk/requestContext.ts +0 -281
  97. package/src/sdk/requestContextStorage.browser.ts +0 -43
  98. package/src/sdk/requestContextStorage.ts +0 -35
  99. package/src/sdk/responseCache.ts +0 -82
  100. package/src/sdk/retry.ts +0 -45
  101. package/src/sdk/serverTimings.ts +0 -68
  102. package/src/sdk/signal.ts +0 -42
  103. package/src/sdk/sitemap.ts +0 -160
  104. package/src/sdk/urlRedaction.ts +0 -82
  105. package/src/sdk/urlUtils.ts +0 -183
  106. package/src/sdk/useDevice.ts +0 -89
  107. package/src/sdk/useDeviceContext.tsx +0 -108
  108. package/src/sdk/useId.ts +0 -7
  109. package/src/sdk/useScript.ts +0 -210
  110. package/src/sdk/useSuggestions.ts +0 -188
  111. package/src/sdk/wrapCaughtErrors.ts +0 -107
  112. package/src/setup.ts +0 -120
  113. package/src/types/index.ts +0 -53
  114. package/src/types/widgets.ts +0 -14
package/src/sdk/flags.ts DELETED
@@ -1,138 +0,0 @@
1
- /**
2
- * Sticky A/B flag persistence via the `deco_segment` cookie — shared by the
3
- * resolver (SSR variant selection), the worker entry (cache-key cohort
4
- * splitting), and consumed by analytics (@decocms/apps OneDollarStats reads
5
- * the same cookie to enrich pageviews/events).
6
- *
7
- * ## Why
8
- *
9
- * `website/matchers/random.ts` is a stateless `Math.random() < traffic`, so a
10
- * visitor's variant used to be re-rolled on every request AND frozen per
11
- * edge-cache entry (the HTML is cached and the cache key never carried the
12
- * variant). The variant a first visitor happened to roll then got served to
13
- * everyone in that device/geo bucket, and analytics never saw the flag.
14
- *
15
- * ## Cookie format
16
- *
17
- * `deco_segment` is the classic deco segment cookie:
18
- * `btoa(encodeURIComponent(JSON.stringify({ active, inactiveDrawn, pct })))`.
19
- * - `active` — flag names the visitor was assigned to (`true` branch).
20
- * - `inactiveDrawn` — flag names drawn but not matched (`false` branch).
21
- * - `pct` — `{ name: round(traffic*100) }`, a blocks extension (analytics
22
- * ignores unknown fields) used as the re-roll fingerprint: when the operator
23
- * changes `traffic` and redeploys, the fingerprint no longer matches and the
24
- * visitor is re-rolled once, then re-sticks — same self-healing scheme as
25
- * {@link ./abTesting.ts}.
26
- * - `exp` — `{ experimentKey: variantId }`, the N-way assignments written by
27
- * {@link ./experiments.ts}. `active`/`inactiveDrawn` are boolean buckets and
28
- * physically cannot hold a variant id, so string-valued decisions ride in
29
- * their own map. It is deliberately the same shape Deco Analytics consumes,
30
- * so pointing the collector at it later is a read, not a translation.
31
- * Their re-roll fingerprints share the `pct` map, keyed by experiment key.
32
- *
33
- * The cookie MUST be written un-encoded (raw base64) — OneDollarStats reads it
34
- * with `atob()` directly. Base64's `+ / =` are all valid cookie-value octets
35
- * (RFC 6265), so pass `encode: (v) => v` to the cookie setter.
36
- */
37
-
38
- /** Cookie carrying the visitor's sticky flag decisions (classic deco segment). */
39
- export const SEGMENT_COOKIE = "deco_segment";
40
-
41
- /** A recorded flag decision: which named flag, the branch taken, and the
42
- * `traffic` fingerprint (0–100) it was decided under. */
43
- export interface StoredFlag {
44
- /** Matcher block name, e.g. "TestHero", or an experiment key, e.g.
45
- * "plp-ranking". Stable identity for the cohort. */
46
- name: string;
47
- /**
48
- * The branch the visitor was assigned to. A boolean for CMS multivariate
49
- * matchers (the historical case); a variant id for N-way experiments.
50
- */
51
- value: boolean | string;
52
- /**
53
- * The fingerprint this decision was made under — `round(traffic * 100)` for
54
- * a CMS matcher, a weight-vector hash for an experiment. A decision whose
55
- * stored fingerprint no longer matches the current one is re-rolled once.
56
- */
57
- pct: number;
58
- }
59
-
60
- /** Wire shape of the `deco_segment` cookie payload. */
61
- interface DecoSegment {
62
- active?: string[];
63
- inactiveDrawn?: string[];
64
- /** blocks extension: per-flag traffic fingerprint. Ignored by analytics. */
65
- pct?: Record<string, number>;
66
- /** blocks extension: N-way experiment assignments, `{ key: variantId }`. */
67
- exp?: Record<string, string>;
68
- }
69
-
70
- /** Convert a 0–1 traffic ratio to the 0–100 integer fingerprint. */
71
- export function trafficToPct(traffic: number): number {
72
- if (!Number.isFinite(traffic) || traffic <= 0) return 0;
73
- if (traffic >= 1) return 100;
74
- return Math.round(traffic * 100);
75
- }
76
-
77
- /**
78
- * Parse the `deco_segment` cookie value into decisions. The value is raw
79
- * base64 (no URL-decoding needed). Foreign cookies without the `pct` extension
80
- * parse with `pct: -1`, which the resolver treats as "always matches" so a
81
- * classic-deco segment stays sticky instead of re-rolling. Malformed cookies
82
- * yield `[]`.
83
- */
84
- export function parseSegmentCookie(raw: string | undefined | null): StoredFlag[] {
85
- if (!raw) return [];
86
- try {
87
- const seg = JSON.parse(decodeURIComponent(atob(raw))) as DecoSegment;
88
- const pct = seg.pct ?? {};
89
- const out: StoredFlag[] = [];
90
- for (const name of seg.active ?? []) out.push({ name, value: true, pct: pct[name] ?? -1 });
91
- for (const name of seg.inactiveDrawn ?? []) {
92
- out.push({ name, value: false, pct: pct[name] ?? -1 });
93
- }
94
- for (const [name, variantId] of Object.entries(seg.exp ?? {})) {
95
- out.push({ name, value: variantId, pct: pct[name] ?? -1 });
96
- }
97
- return out;
98
- } catch {
99
- return [];
100
- }
101
- }
102
-
103
- /** Serialize decisions into a raw-base64 `deco_segment` cookie value. */
104
- export function serializeSegmentCookie(flags: StoredFlag[]): string {
105
- const active: string[] = [];
106
- const inactiveDrawn: string[] = [];
107
- const pct: Record<string, number> = {};
108
- const exp: Record<string, string> = {};
109
- for (const f of [...flags].sort((a, b) => a.name.localeCompare(b.name))) {
110
- if (typeof f.value === "string") {
111
- exp[f.name] = f.value;
112
- } else {
113
- (f.value ? active : inactiveDrawn).push(f.name);
114
- }
115
- pct[f.name] = f.pct;
116
- }
117
- const seg: DecoSegment = { active, inactiveDrawn, pct };
118
- // Omit `exp` entirely when unused so the cookie stays byte-identical to what
119
- // sites emit today — an added empty map would re-issue every visitor's cookie
120
- // on deploy and, via segmentCacheToken, cold-start every edge cache entry.
121
- if (Object.keys(exp).length) seg.exp = exp;
122
- return btoa(encodeURIComponent(JSON.stringify(seg)));
123
- }
124
-
125
- /**
126
- * Stable token for the cache key — includes the `pct` fingerprint so a
127
- * `traffic` (or experiment weight) change lands cohorts in fresh buckets.
128
- * Empty string when there are no flags, so non-A/B pages keep sharing one
129
- * entry. Experiment assignments fold in on the same footing as boolean flags:
130
- * without that, two visitors on different variants would share cached HTML.
131
- */
132
- export function segmentCacheToken(flags: StoredFlag[]): string {
133
- if (!flags.length) return "";
134
- return [...flags]
135
- .sort((a, b) => a.name.localeCompare(b.name))
136
- .map((f) => `${f.name}:${typeof f.value === "string" ? f.value : f.value ? "1" : "0"}:${f.pct}`)
137
- .join(",");
138
- }
package/src/sdk/http.ts DELETED
@@ -1,124 +0,0 @@
1
- /**
2
- * HTTP constants and small typed helpers — replaces the parts of Deno's
3
- * `@std/http` (other than cookies, which live in `./cookie.ts`) that deco
4
- * storefronts touch.
5
- *
6
- * Currently exposes:
7
- * - `STATUS_CODE` — full IANA status-code map (parity with @std/http).
8
- * - `UserAgent` — minimal class with the same shape; does not parse
9
- * the UA string (sites only used `.toString()` and
10
- * basic browser/os accessors in dev). Replace with a
11
- * real parser like `ua-parser-js` if you actually
12
- * depend on the parsed fields.
13
- */
14
-
15
- export const STATUS_CODE = {
16
- Continue: 100,
17
- SwitchingProtocols: 101,
18
- Processing: 102,
19
- EarlyHints: 103,
20
- OK: 200,
21
- Created: 201,
22
- Accepted: 202,
23
- NonAuthoritativeInfo: 203,
24
- NoContent: 204,
25
- ResetContent: 205,
26
- PartialContent: 206,
27
- MultiStatus: 207,
28
- AlreadyReported: 208,
29
- IMUsed: 226,
30
- MultipleChoices: 300,
31
- MovedPermanently: 301,
32
- Found: 302,
33
- SeeOther: 303,
34
- NotModified: 304,
35
- UseProxy: 305,
36
- TemporaryRedirect: 307,
37
- PermanentRedirect: 308,
38
- BadRequest: 400,
39
- Unauthorized: 401,
40
- PaymentRequired: 402,
41
- Forbidden: 403,
42
- NotFound: 404,
43
- MethodNotAllowed: 405,
44
- NotAcceptable: 406,
45
- ProxyAuthRequired: 407,
46
- RequestTimeout: 408,
47
- Conflict: 409,
48
- Gone: 410,
49
- LengthRequired: 411,
50
- PreconditionFailed: 412,
51
- ContentTooLarge: 413,
52
- URITooLong: 414,
53
- UnsupportedMediaType: 415,
54
- RangeNotSatisfiable: 416,
55
- ExpectationFailed: 417,
56
- Teapot: 418,
57
- MisdirectedRequest: 421,
58
- UnprocessableEntity: 422,
59
- Locked: 423,
60
- FailedDependency: 424,
61
- TooEarly: 425,
62
- UpgradeRequired: 426,
63
- PreconditionRequired: 428,
64
- TooManyRequests: 429,
65
- RequestHeaderFieldsTooLarge: 431,
66
- UnavailableForLegalReasons: 451,
67
- InternalServerError: 500,
68
- NotImplemented: 501,
69
- BadGateway: 502,
70
- ServiceUnavailable: 503,
71
- GatewayTimeout: 504,
72
- HTTPVersionNotSupported: 505,
73
- VariantAlsoNegotiates: 506,
74
- InsufficientStorage: 507,
75
- LoopDetected: 508,
76
- NotExtended: 510,
77
- NetworkAuthenticationRequired: 511,
78
- } as const;
79
-
80
- export type StatusCode = typeof STATUS_CODE[keyof typeof STATUS_CODE];
81
-
82
- /**
83
- * Minimal stand-in for Deno's `@std/http`'s `UserAgent`. Captures the raw
84
- * UA string and exposes the same field shape; does NOT parse. Replace with
85
- * a real parser when you start depending on parsed fields.
86
- */
87
- export class UserAgent {
88
- ua: string;
89
- browser: { name?: string; version?: string };
90
- os: { name?: string; version?: string };
91
- device: { vendor?: string; model?: string; type?: string };
92
- cpu: { architecture?: string };
93
- engine: { name?: string; version?: string };
94
-
95
- constructor(ua: string | null) {
96
- this.ua = ua ?? "";
97
- this.browser = {};
98
- this.os = {};
99
- this.device = {};
100
- this.cpu = {};
101
- this.engine = {};
102
- }
103
-
104
- toString(): string {
105
- return this.ua;
106
- }
107
- }
108
-
109
- /**
110
- * Lightweight HTTP error class. Drop-in for the `HttpError` shape that
111
- * `deco-cx/apps` exposes — sites use it as `error instanceof HttpError &&
112
- * error.status === 304` and similar.
113
- */
114
- export class HttpError extends Error {
115
- status: number;
116
- body?: unknown;
117
-
118
- constructor(status: number, message?: string, body?: unknown) {
119
- super(message ?? `HTTP ${status}`);
120
- this.name = "HttpError";
121
- this.status = status;
122
- this.body = body;
123
- }
124
- }
package/src/sdk/index.ts DELETED
@@ -1,97 +0,0 @@
1
- export { ANALYTICS_SCRIPT, type DataEventParams, gtmScript, useSendEvent } from "./analytics";
2
- export {
3
- type CacheProfileConfig,
4
- type CacheProfileName,
5
- type CacheProfileOverrides,
6
- type CacheTimingWindow,
7
- cacheHeaders,
8
- detectCacheProfile,
9
- type EdgeCacheConfig,
10
- edgeCacheConfig,
11
- getCacheProfile,
12
- type LoaderCacheOptions,
13
- loaderCacheOptions,
14
- registerCachePattern,
15
- routeCacheDefaults,
16
- setCacheProfile,
17
- } from "./cacheHeaders";
18
- export { clx } from "./clx";
19
- export { decodeCookie, deleteCookie, getCookie, getServerSideCookie, setCookie } from "./cookie";
20
- export { buildCSPHeaderValue, type CSPOptions, setCSPHeaders } from "./csp";
21
- export { deepOmit } from "./deepOmit";
22
- export { djb2, djb2Hex } from "./djb2";
23
- export { isDevMode } from "./env";
24
- export {
25
- DEFAULT_FETCH_TIMEOUT_MS,
26
- type FetchFn,
27
- withFetchTimeout,
28
- withTimeoutSignal,
29
- } from "./fetchTimeout";
30
- export {
31
- createInstrumentedFetch,
32
- type FetchInstrumentationOptions,
33
- type FetchMetrics,
34
- instrumentFetch,
35
- } from "./instrumentedFetch";
36
- export {
37
- batchInvoke,
38
- createAppInvoke,
39
- createInvokeProxy,
40
- type InvokeProxy,
41
- invoke,
42
- invokeQueryOptions,
43
- type NestedFromFlat,
44
- } from "./invoke";
45
- export { createCacheControlCollector, mergeCacheControl } from "./mergeCacheControl";
46
- export {
47
- getProductionOrigins,
48
- normalizeUrlsInObject,
49
- registerProductionOrigins,
50
- } from "./normalizeUrls";
51
- export {
52
- addRedirects,
53
- loadRedirects,
54
- matchRedirect,
55
- parseRedirectsCsv,
56
- type Redirect,
57
- type RedirectMap,
58
- registerRedirectResolveType,
59
- } from "./redirects";
60
- export { createServerTimings, type ServerTimings } from "./serverTimings";
61
- export { type ReactiveSignal, signal } from "./signal";
62
- export { redactUrl, type RedactUrlOptions } from "./urlRedaction";
63
- export {
64
- canonicalUrl,
65
- cleanPathForCacheKey,
66
- hasTrackingParams,
67
- registerTrackingParam,
68
- registerTrackingParams,
69
- stripTrackingParams,
70
- } from "./urlUtils";
71
- export {
72
- checkDesktop,
73
- checkMobile,
74
- checkTablet,
75
- type Device,
76
- DeviceContext,
77
- DeviceProvider,
78
- detectDevice,
79
- isMobileUA,
80
- MOBILE_RE,
81
- TABLET_RE,
82
- useDevice,
83
- } from "./useDevice";
84
- export { useId } from "./useId";
85
- export {
86
- inlineScript,
87
- usePartialSection,
88
- useScript,
89
- useScriptAsDataURI,
90
- useSection,
91
- } from "./useScript";
92
- export {
93
- isWrappedError,
94
- unwrapError,
95
- type WrappedError,
96
- wrapCaughtErrors,
97
- } from "./wrapCaughtErrors";
@@ -1,53 +0,0 @@
1
- /**
2
- * Inflight-Promise timeout guard for module-level dedup caches.
3
- *
4
- * Background: across `@decocms/start` (and `@decocms/apps`) we keep
5
- * `Map<string, Promise<...>>` caches at module scope to dedup concurrent
6
- * resolutions of the same loader / section / layout block. Entries are
7
- * evicted via `.finally()` on the stored Promise.
8
- *
9
- * The problem: if the wrapped work never settles — e.g. an upstream `fetch()`
10
- * hangs because a CDN holds the TCP connection open — the `.finally()` never
11
- * runs and the Map entry leaks forever. With
12
- * `no_handle_cross_request_promise_resolution: true` on the consumer Worker,
13
- * the zombie Promise survives across requests. Every subsequent caller for
14
- * the same key `await`s it, pinning request context into memory until
15
- * `exceededMemory` terminates the isolate.
16
- *
17
- * Production observation on a TanStack Start storefront (24h window): 514
18
- * hard `exceededMemory` crashes, with CPU time ~0 and wall time in the tens
19
- * of minutes — workers sleeping on the dead Promise, not computing.
20
- *
21
- * Fix: race the stored Promise against a timeout so its terminal state is
22
- * guaranteed, which means `.finally()` always runs and the Map slot is
23
- * freed. The underlying hung work is abandoned (the CF runtime will GC it
24
- * once the request ends).
25
- */
26
-
27
- /** Default per-entry timeout for inflight dedup caches. */
28
- export const DEFAULT_INFLIGHT_TIMEOUT_MS = 10_000;
29
-
30
- /**
31
- * Race `work` against a timeout. If `work` doesn't settle within `ms`, the
32
- * returned Promise rejects with a descriptive error so callers' `.finally()`
33
- * cleanup always runs.
34
- */
35
- export function withInflightTimeout<T>(
36
- work: Promise<T>,
37
- label: string,
38
- ms: number = DEFAULT_INFLIGHT_TIMEOUT_MS,
39
- ): Promise<T> {
40
- let timer: ReturnType<typeof setTimeout> | undefined;
41
- const timeout = new Promise<never>((_, reject) => {
42
- timer = setTimeout(() => {
43
- reject(
44
- new Error(
45
- `[blocks] inflight cache entry "${label}" timed out after ${ms}ms`,
46
- ),
47
- );
48
- }, ms);
49
- });
50
- return Promise.race([work, timeout]).finally(() => {
51
- if (timer !== undefined) clearTimeout(timer);
52
- });
53
- }