@decocms/blocks 8.0.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 (220) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +32 -82
  3. package/src/index.ts +35 -8
  4. package/src/protocol/assets.ts +124 -0
  5. package/src/protocol/canonical.ts +7 -0
  6. package/src/protocol/ciphertext.ts +6 -0
  7. package/src/protocol/client.ts +170 -0
  8. package/src/protocol/conformance/cases/assets.ts +81 -0
  9. package/src/protocol/conformance/cases/guards.ts +314 -0
  10. package/src/protocol/conformance/cases/reads.ts +168 -0
  11. package/src/protocol/conformance/cases/types.ts +9 -0
  12. package/src/protocol/conformance/cases/wire.ts +138 -0
  13. package/src/protocol/conformance/cases/writes.ts +345 -0
  14. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  15. package/src/protocol/conformance/context.ts +222 -0
  16. package/src/protocol/conformance/index.ts +140 -0
  17. package/src/protocol/errors.ts +142 -0
  18. package/src/protocol/index.ts +39 -0
  19. package/src/protocol/keys.ts +279 -0
  20. package/src/protocol/params.ts +67 -0
  21. package/src/protocol/secrets.ts +231 -0
  22. package/src/protocol/server/assets.ts +119 -0
  23. package/src/protocol/server/auth.ts +49 -0
  24. package/src/protocol/server/bodyCache.ts +84 -0
  25. package/src/protocol/server/content.ts +175 -0
  26. package/src/protocol/server/core.ts +112 -0
  27. package/src/protocol/server/handler.ts +102 -0
  28. package/src/protocol/server/http.ts +139 -0
  29. package/src/protocol/server/index.ts +11 -0
  30. package/src/protocol/server/methods/apply.ts +341 -0
  31. package/src/protocol/server/methods/read.ts +156 -0
  32. package/src/protocol/server/rpc.ts +136 -0
  33. package/src/protocol/storage/fs/hash.ts +21 -0
  34. package/src/protocol/storage/fs/index.ts +338 -0
  35. package/src/protocol/storage/fs/lock.ts +68 -0
  36. package/src/protocol/storage/fs/transaction.ts +183 -0
  37. package/src/protocol/storage/fs/unsupported.ts +15 -0
  38. package/src/protocol/storage/memory.ts +238 -0
  39. package/src/protocol/storage.ts +182 -0
  40. package/src/protocol/types.ts +172 -0
  41. package/src/v8/analytics.ts +50 -0
  42. package/src/v8/background.ts +107 -0
  43. package/src/v8/builtins/data.ts +23 -0
  44. package/src/v8/builtins/index.ts +26 -0
  45. package/src/v8/builtins/lazy.ts +23 -0
  46. package/src/v8/builtins/legacy.ts +65 -0
  47. package/src/v8/builtins/matchers.ts +31 -0
  48. package/src/v8/builtins/multivariate.ts +25 -0
  49. package/src/v8/builtins/secret.ts +82 -0
  50. package/src/v8/canonical.ts +117 -0
  51. package/src/v8/ciphertext.ts +158 -0
  52. package/src/v8/cli/builtins.ts +20 -0
  53. package/src/v8/cli/check/index.ts +774 -0
  54. package/src/v8/cli/check/messages.ts +168 -0
  55. package/src/v8/cli/content.ts +287 -0
  56. package/src/v8/cli/index.ts +17 -0
  57. package/src/v8/cli/log.ts +18 -0
  58. package/src/v8/cli/main.ts +12 -0
  59. package/src/v8/cli/root.ts +66 -0
  60. package/src/v8/cli/run.ts +236 -0
  61. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  62. package/src/v8/cli/schema/generate.ts +507 -0
  63. package/src/v8/cli/schema/index.ts +63 -0
  64. package/src/v8/cli/schema/tsProgram.ts +497 -0
  65. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  66. package/src/v8/cli/serve/server.ts +303 -0
  67. package/src/v8/cli/watch.ts +86 -0
  68. package/src/v8/client.ts +147 -0
  69. package/src/v8/cms.ts +237 -0
  70. package/src/v8/content.ts +195 -0
  71. package/src/v8/draft.ts +136 -0
  72. package/src/v8/errors.ts +59 -0
  73. package/src/v8/fetch.ts +133 -0
  74. package/src/v8/identity.ts +65 -0
  75. package/src/v8/index.ts +39 -0
  76. package/src/v8/json.ts +74 -0
  77. package/src/v8/matchRoute.ts +204 -0
  78. package/src/v8/remoteLoader.ts +282 -0
  79. package/src/v8/resolver.ts +278 -0
  80. package/src/v8/secrets.ts +17 -0
  81. package/src/v8/telemetry.ts +533 -0
  82. package/src/v8/types.ts +240 -0
  83. package/src/cms/applySectionConventions.ts +0 -124
  84. package/src/cms/blockSource.test.ts +0 -76
  85. package/src/cms/blockSource.ts +0 -191
  86. package/src/cms/client.browserBundle.test.ts +0 -44
  87. package/src/cms/client.ts +0 -80
  88. package/src/cms/draftSource.test.ts +0 -343
  89. package/src/cms/draftSource.ts +0 -362
  90. package/src/cms/index.ts +0 -151
  91. package/src/cms/layoutCacheRace.test.ts +0 -181
  92. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  93. package/src/cms/loadDecofileDirectory.ts +0 -89
  94. package/src/cms/loader.test.ts +0 -200
  95. package/src/cms/loader.ts +0 -304
  96. package/src/cms/registry.test.ts +0 -110
  97. package/src/cms/registry.ts +0 -242
  98. package/src/cms/resolve.test.ts +0 -980
  99. package/src/cms/resolve.ts +0 -2282
  100. package/src/cms/schema.test.ts +0 -356
  101. package/src/cms/schema.ts +0 -1215
  102. package/src/cms/sectionLoaderContext.test.ts +0 -111
  103. package/src/cms/sectionLoaderContext.ts +0 -113
  104. package/src/cms/sectionLoaders.test.ts +0 -533
  105. package/src/cms/sectionLoaders.ts +0 -636
  106. package/src/cms/sectionMixins.test.ts +0 -167
  107. package/src/cms/sectionMixins.ts +0 -153
  108. package/src/cms/stickyFlags.test.ts +0 -117
  109. package/src/flags/audience.ts +0 -56
  110. package/src/flags/everyone.ts +0 -29
  111. package/src/flags/flag.ts +0 -15
  112. package/src/flags/flags.test.ts +0 -148
  113. package/src/flags/multivariate/image.ts +0 -11
  114. package/src/flags/multivariate/message.ts +0 -11
  115. package/src/flags/multivariate/page.ts +0 -16
  116. package/src/flags/multivariate/section.ts +0 -16
  117. package/src/flags/multivariate.ts +0 -1
  118. package/src/flags/types.ts +0 -59
  119. package/src/flags/utils/multivariate.ts +0 -20
  120. package/src/hooks/Image.test.ts +0 -100
  121. package/src/hooks/Image.tsx +0 -250
  122. package/src/hooks/JsonLd.tsx +0 -353
  123. package/src/hooks/LazySection.tsx +0 -121
  124. package/src/hooks/LiveControls.tsx +0 -122
  125. package/src/hooks/Picture.tsx +0 -127
  126. package/src/hooks/RenderSection.test.tsx +0 -81
  127. package/src/hooks/RenderSection.tsx +0 -91
  128. package/src/hooks/SectionErrorFallback.tsx +0 -97
  129. package/src/hooks/index.ts +0 -30
  130. package/src/matchers/builtins.test.ts +0 -318
  131. package/src/matchers/builtins.ts +0 -459
  132. package/src/matchers/countryNames.ts +0 -104
  133. package/src/matchers/override.test.ts +0 -205
  134. package/src/matchers/override.ts +0 -136
  135. package/src/matchers/posthog.ts +0 -154
  136. package/src/middleware/decoState.ts +0 -55
  137. package/src/middleware/healthMetrics.ts +0 -133
  138. package/src/middleware/hydrationContext.test.ts +0 -61
  139. package/src/middleware/hydrationContext.ts +0 -79
  140. package/src/middleware/index.ts +0 -88
  141. package/src/middleware/liveness.ts +0 -21
  142. package/src/middleware/observability.test.ts +0 -242
  143. package/src/middleware/observability.ts +0 -643
  144. package/src/middleware/validateSection.test.ts +0 -147
  145. package/src/middleware/validateSection.ts +0 -100
  146. package/src/sdk/abTesting.test.ts +0 -326
  147. package/src/sdk/abTesting.ts +0 -499
  148. package/src/sdk/analytics.ts +0 -77
  149. package/src/sdk/cacheHeaders.test.ts +0 -115
  150. package/src/sdk/cacheHeaders.ts +0 -433
  151. package/src/sdk/cachedLoader.test.ts +0 -122
  152. package/src/sdk/cachedLoader.ts +0 -503
  153. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  154. package/src/sdk/clx.ts +0 -5
  155. package/src/sdk/cn.test.ts +0 -34
  156. package/src/sdk/cn.ts +0 -28
  157. package/src/sdk/composite.test.ts +0 -121
  158. package/src/sdk/composite.ts +0 -114
  159. package/src/sdk/cookie.test.ts +0 -108
  160. package/src/sdk/cookie.ts +0 -129
  161. package/src/sdk/crypto.ts +0 -185
  162. package/src/sdk/csp.ts +0 -59
  163. package/src/sdk/detectDevice.ts +0 -45
  164. package/src/sdk/djb2.ts +0 -20
  165. package/src/sdk/encoding.test.ts +0 -71
  166. package/src/sdk/encoding.ts +0 -47
  167. package/src/sdk/env.test.ts +0 -33
  168. package/src/sdk/env.ts +0 -54
  169. package/src/sdk/flags.test.ts +0 -91
  170. package/src/sdk/flags.ts +0 -108
  171. package/src/sdk/http.test.ts +0 -71
  172. package/src/sdk/http.ts +0 -124
  173. package/src/sdk/index.ts +0 -90
  174. package/src/sdk/inflightTimeout.test.ts +0 -35
  175. package/src/sdk/inflightTimeout.ts +0 -53
  176. package/src/sdk/instrumentedFetch.test.ts +0 -559
  177. package/src/sdk/instrumentedFetch.ts +0 -339
  178. package/src/sdk/invoke.test.ts +0 -115
  179. package/src/sdk/invoke.ts +0 -298
  180. package/src/sdk/logger.test.ts +0 -432
  181. package/src/sdk/logger.ts +0 -304
  182. package/src/sdk/mergeCacheControl.ts +0 -150
  183. package/src/sdk/normalizeUrls.ts +0 -91
  184. package/src/sdk/observability.ts +0 -109
  185. package/src/sdk/otel.test.ts +0 -526
  186. package/src/sdk/otel.ts +0 -1012
  187. package/src/sdk/otelAdapters/clickhouseCollector.ts +0 -65
  188. package/src/sdk/otelAdapters.test.ts +0 -89
  189. package/src/sdk/otelAdapters.ts +0 -144
  190. package/src/sdk/otelHttpLog.test.ts +0 -457
  191. package/src/sdk/otelHttpLog.ts +0 -419
  192. package/src/sdk/otelHttpMeter.test.ts +0 -292
  193. package/src/sdk/otelHttpMeter.ts +0 -506
  194. package/src/sdk/otelHttpTracer.test.ts +0 -474
  195. package/src/sdk/otelHttpTracer.ts +0 -543
  196. package/src/sdk/redirects.ts +0 -228
  197. package/src/sdk/requestContext.ts +0 -281
  198. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  199. package/src/sdk/requestContextStorage.browser.ts +0 -43
  200. package/src/sdk/requestContextStorage.ts +0 -35
  201. package/src/sdk/retry.ts +0 -45
  202. package/src/sdk/serverTimings.ts +0 -68
  203. package/src/sdk/signal.ts +0 -42
  204. package/src/sdk/sitemap.ts +0 -160
  205. package/src/sdk/urlRedaction.test.ts +0 -73
  206. package/src/sdk/urlRedaction.ts +0 -82
  207. package/src/sdk/urlUtils.ts +0 -134
  208. package/src/sdk/useDevice.test.ts +0 -130
  209. package/src/sdk/useDevice.ts +0 -89
  210. package/src/sdk/useDeviceContext.tsx +0 -108
  211. package/src/sdk/useId.ts +0 -7
  212. package/src/sdk/useScript.test.ts +0 -128
  213. package/src/sdk/useScript.ts +0 -210
  214. package/src/sdk/useSuggestions.test.ts +0 -230
  215. package/src/sdk/useSuggestions.ts +0 -188
  216. package/src/sdk/wrapCaughtErrors.ts +0 -107
  217. package/src/setup.ts +0 -120
  218. package/src/types/index.ts +0 -53
  219. package/src/types/widgets.ts +0 -14
  220. package/tsconfig.json +0 -7
@@ -1,91 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import {
3
- parseSegmentCookie,
4
- type StoredFlag,
5
- segmentCacheToken,
6
- serializeSegmentCookie,
7
- trafficToPct,
8
- } from "./flags";
9
-
10
- describe("trafficToPct", () => {
11
- it("maps a ratio to a 0-100 integer", () => {
12
- expect(trafficToPct(0.5)).toBe(50);
13
- expect(trafficToPct(0.234)).toBe(23);
14
- });
15
-
16
- it("clamps out-of-range and non-finite values", () => {
17
- expect(trafficToPct(0)).toBe(0);
18
- expect(trafficToPct(-1)).toBe(0);
19
- expect(trafficToPct(1)).toBe(100);
20
- expect(trafficToPct(2)).toBe(100);
21
- expect(trafficToPct(NaN)).toBe(0);
22
- });
23
- });
24
-
25
- describe("deco_segment round-trip", () => {
26
- it("round-trips a single active flag", () => {
27
- const flags: StoredFlag[] = [{ name: "TestHero", value: true, pct: 50 }];
28
- expect(parseSegmentCookie(serializeSegmentCookie(flags))).toEqual(flags);
29
- });
30
-
31
- it("round-trips active + inactive flags (sorted by name)", () => {
32
- const flags: StoredFlag[] = [
33
- { name: "Zeta", value: false, pct: 20 },
34
- { name: "Alpha", value: true, pct: 70 },
35
- ];
36
- expect(parseSegmentCookie(serializeSegmentCookie(flags))).toEqual([
37
- { name: "Alpha", value: true, pct: 70 },
38
- { name: "Zeta", value: false, pct: 20 },
39
- ]);
40
- });
41
-
42
- it("produces the classic deco_segment shape that OneDollarStats reads", () => {
43
- const raw = serializeSegmentCookie([
44
- { name: "TestHero", value: true, pct: 50 },
45
- { name: "Promo", value: false, pct: 30 },
46
- ]);
47
- // Mirrors @decocms/apps OneDollarStats readFlagsFromCookie decode.
48
- const seg = JSON.parse(decodeURIComponent(atob(raw)));
49
- expect(seg.active).toContain("TestHero");
50
- expect(seg.inactiveDrawn).toContain("Promo");
51
- expect(seg.pct).toEqual({ TestHero: 50, Promo: 30 });
52
- });
53
-
54
- it("is raw base64 (no percent-escapes) so atob() works directly", () => {
55
- const raw = serializeSegmentCookie([{ name: "TestHero", value: true, pct: 50 }]);
56
- expect(raw).not.toMatch(/%/);
57
- expect(() => atob(raw)).not.toThrow();
58
- });
59
- });
60
-
61
- describe("parseSegmentCookie robustness", () => {
62
- it("returns [] for empty / nullish / malformed input", () => {
63
- expect(parseSegmentCookie(undefined)).toEqual([]);
64
- expect(parseSegmentCookie(null)).toEqual([]);
65
- expect(parseSegmentCookie("")).toEqual([]);
66
- expect(parseSegmentCookie("not-base64-!!!")).toEqual([]);
67
- });
68
-
69
- it("marks classic segments without a pct fingerprint as pct: -1", () => {
70
- const raw = btoa(encodeURIComponent(JSON.stringify({ active: ["Legacy"], inactiveDrawn: [] })));
71
- expect(parseSegmentCookie(raw)).toEqual([{ name: "Legacy", value: true, pct: -1 }]);
72
- });
73
- });
74
-
75
- describe("segmentCacheToken", () => {
76
- it("is empty for no flags so non-A/B pages share a cache entry", () => {
77
- expect(segmentCacheToken([])).toBe("");
78
- });
79
-
80
- it("includes the pct fingerprint so a traffic change re-buckets", () => {
81
- const at50 = segmentCacheToken([{ name: "TestHero", value: true, pct: 50 }]);
82
- const at70 = segmentCacheToken([{ name: "TestHero", value: true, pct: 70 }]);
83
- expect(at50).not.toBe(at70);
84
- });
85
-
86
- it("differs by decision so cohorts split", () => {
87
- const on = segmentCacheToken([{ name: "TestHero", value: true, pct: 50 }]);
88
- const off = segmentCacheToken([{ name: "TestHero", value: false, pct: 50 }]);
89
- expect(on).not.toBe(off);
90
- });
91
- });
package/src/sdk/flags.ts DELETED
@@ -1,108 +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
- *
27
- * The cookie MUST be written un-encoded (raw base64) — OneDollarStats reads it
28
- * with `atob()` directly. Base64's `+ / =` are all valid cookie-value octets
29
- * (RFC 6265), so pass `encode: (v) => v` to the cookie setter.
30
- */
31
-
32
- /** Cookie carrying the visitor's sticky flag decisions (classic deco segment). */
33
- export const SEGMENT_COOKIE = "deco_segment";
34
-
35
- /** A recorded flag decision: which named flag, the branch taken, and the
36
- * `traffic` fingerprint (0–100) it was decided under. */
37
- export interface StoredFlag {
38
- /** Matcher block name, e.g. "TestHero". Stable identity for the cohort. */
39
- name: string;
40
- /** The branch the visitor was assigned to. */
41
- value: boolean;
42
- /** `round(traffic * 100)` at assignment time — the re-roll fingerprint. */
43
- pct: number;
44
- }
45
-
46
- /** Wire shape of the `deco_segment` cookie payload. */
47
- interface DecoSegment {
48
- active?: string[];
49
- inactiveDrawn?: string[];
50
- /** blocks extension: per-flag traffic fingerprint. Ignored by analytics. */
51
- pct?: Record<string, number>;
52
- }
53
-
54
- /** Convert a 0–1 traffic ratio to the 0–100 integer fingerprint. */
55
- export function trafficToPct(traffic: number): number {
56
- if (!Number.isFinite(traffic) || traffic <= 0) return 0;
57
- if (traffic >= 1) return 100;
58
- return Math.round(traffic * 100);
59
- }
60
-
61
- /**
62
- * Parse the `deco_segment` cookie value into decisions. The value is raw
63
- * base64 (no URL-decoding needed). Foreign cookies without the `pct` extension
64
- * parse with `pct: -1`, which the resolver treats as "always matches" so a
65
- * classic-deco segment stays sticky instead of re-rolling. Malformed cookies
66
- * yield `[]`.
67
- */
68
- export function parseSegmentCookie(raw: string | undefined | null): StoredFlag[] {
69
- if (!raw) return [];
70
- try {
71
- const seg = JSON.parse(decodeURIComponent(atob(raw))) as DecoSegment;
72
- const pct = seg.pct ?? {};
73
- const out: StoredFlag[] = [];
74
- for (const name of seg.active ?? []) out.push({ name, value: true, pct: pct[name] ?? -1 });
75
- for (const name of seg.inactiveDrawn ?? []) {
76
- out.push({ name, value: false, pct: pct[name] ?? -1 });
77
- }
78
- return out;
79
- } catch {
80
- return [];
81
- }
82
- }
83
-
84
- /** Serialize decisions into a raw-base64 `deco_segment` cookie value. */
85
- export function serializeSegmentCookie(flags: StoredFlag[]): string {
86
- const active: string[] = [];
87
- const inactiveDrawn: string[] = [];
88
- const pct: Record<string, number> = {};
89
- for (const f of [...flags].sort((a, b) => a.name.localeCompare(b.name))) {
90
- (f.value ? active : inactiveDrawn).push(f.name);
91
- pct[f.name] = f.pct;
92
- }
93
- const seg: DecoSegment = { active, inactiveDrawn, pct };
94
- return btoa(encodeURIComponent(JSON.stringify(seg)));
95
- }
96
-
97
- /**
98
- * Stable token for the cache key — includes the `pct` fingerprint so a
99
- * `traffic` change lands cohorts in fresh buckets. Empty string when there are
100
- * no flags, so non-A/B pages keep sharing one entry.
101
- */
102
- export function segmentCacheToken(flags: StoredFlag[]): string {
103
- if (!flags.length) return "";
104
- return [...flags]
105
- .sort((a, b) => a.name.localeCompare(b.name))
106
- .map((f) => `${f.name}:${f.value ? "1" : "0"}:${f.pct}`)
107
- .join(",");
108
- }
@@ -1,71 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { HttpError, STATUS_CODE, UserAgent } from "./http";
3
-
4
- describe("STATUS_CODE", () => {
5
- it("exposes common codes with the IANA-canonical names", () => {
6
- expect(STATUS_CODE.OK).toBe(200);
7
- expect(STATUS_CODE.MovedPermanently).toBe(301);
8
- expect(STATUS_CODE.NotFound).toBe(404);
9
- expect(STATUS_CODE.TooManyRequests).toBe(429);
10
- expect(STATUS_CODE.InternalServerError).toBe(500);
11
- });
12
-
13
- it("is readonly at the type level", () => {
14
- // @ts-expect-error — assigning into the const map should not type-check.
15
- STATUS_CODE.OK = 999;
16
- // Even though the assignment is allowed at runtime (frozen-by-convention),
17
- // we just want the type to flag it. The value is whatever JS allows.
18
- expect(typeof STATUS_CODE.OK).toBe("number");
19
- });
20
- });
21
-
22
- describe("UserAgent", () => {
23
- it("accepts a string and exposes it via toString", () => {
24
- const ua = new UserAgent("Mozilla/5.0 (test)");
25
- expect(ua.toString()).toBe("Mozilla/5.0 (test)");
26
- });
27
-
28
- it("treats null as an empty UA string", () => {
29
- const ua = new UserAgent(null);
30
- expect(ua.toString()).toBe("");
31
- });
32
-
33
- it("exposes empty browser/os/cpu/device/engine accessors", () => {
34
- const ua = new UserAgent("anything");
35
- expect(ua.browser).toEqual({});
36
- expect(ua.os).toEqual({});
37
- expect(ua.cpu).toEqual({});
38
- expect(ua.device).toEqual({});
39
- expect(ua.engine).toEqual({});
40
- });
41
- });
42
-
43
- describe("HttpError", () => {
44
- it("captures status and message", () => {
45
- const err = new HttpError(404, "Missing");
46
- expect(err).toBeInstanceOf(Error);
47
- expect(err.name).toBe("HttpError");
48
- expect(err.status).toBe(404);
49
- expect(err.message).toBe("Missing");
50
- });
51
-
52
- it("defaults the message from the status when not provided", () => {
53
- const err = new HttpError(503);
54
- expect(err.message).toBe("HTTP 503");
55
- });
56
-
57
- it("preserves an optional body payload for downstream handling", () => {
58
- const body = { code: "rate_limited" };
59
- const err = new HttpError(429, "Too Many Requests", body);
60
- expect(err.body).toEqual(body);
61
- });
62
-
63
- it("supports `instanceof` discrimination", () => {
64
- const err = new HttpError(304);
65
- function isNotModified(e: unknown): e is HttpError {
66
- return e instanceof HttpError && e.status === 304;
67
- }
68
- expect(isNotModified(err)).toBe(true);
69
- expect(isNotModified(new Error("nope"))).toBe(false);
70
- });
71
- });
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,90 +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 { djb2, djb2Hex } from "./djb2";
22
- export { isDevMode } from "./env";
23
- export {
24
- createInstrumentedFetch,
25
- type FetchInstrumentationOptions,
26
- type FetchMetrics,
27
- instrumentFetch,
28
- } from "./instrumentedFetch";
29
- export {
30
- batchInvoke,
31
- createAppInvoke,
32
- createInvokeProxy,
33
- type InvokeProxy,
34
- invoke,
35
- invokeQueryOptions,
36
- type NestedFromFlat,
37
- } from "./invoke";
38
- export { createCacheControlCollector, mergeCacheControl } from "./mergeCacheControl";
39
- export {
40
- getProductionOrigins,
41
- normalizeUrlsInObject,
42
- registerProductionOrigins,
43
- } from "./normalizeUrls";
44
- export {
45
- addRedirects,
46
- loadRedirects,
47
- matchRedirect,
48
- parseRedirectsCsv,
49
- type Redirect,
50
- type RedirectMap,
51
- registerRedirectResolveType,
52
- } from "./redirects";
53
- export { createServerTimings, type ServerTimings } from "./serverTimings";
54
- export { type ReactiveSignal, signal } from "./signal";
55
- export { redactUrl, type RedactUrlOptions } from "./urlRedaction";
56
- export {
57
- canonicalUrl,
58
- cleanPathForCacheKey,
59
- hasTrackingParams,
60
- registerTrackingParam,
61
- registerTrackingParams,
62
- stripTrackingParams,
63
- } from "./urlUtils";
64
- export {
65
- checkDesktop,
66
- checkMobile,
67
- checkTablet,
68
- type Device,
69
- DeviceContext,
70
- DeviceProvider,
71
- detectDevice,
72
- isMobileUA,
73
- MOBILE_RE,
74
- TABLET_RE,
75
- useDevice,
76
- } from "./useDevice";
77
- export { useId } from "./useId";
78
- export {
79
- inlineScript,
80
- usePartialSection,
81
- useScript,
82
- useScriptAsDataURI,
83
- useSection,
84
- } from "./useScript";
85
- export {
86
- isWrappedError,
87
- unwrapError,
88
- type WrappedError,
89
- wrapCaughtErrors,
90
- } from "./wrapCaughtErrors";
@@ -1,35 +0,0 @@
1
- import { describe, expect, it, vi } from "vitest";
2
- import { DEFAULT_INFLIGHT_TIMEOUT_MS, withInflightTimeout } from "./inflightTimeout";
3
-
4
- describe("withInflightTimeout", () => {
5
- it("returns the underlying value when work settles in time", async () => {
6
- const result = await withInflightTimeout(Promise.resolve(42), "ok-case");
7
- expect(result).toBe(42);
8
- });
9
-
10
- it("propagates rejection when underlying work rejects in time", async () => {
11
- await expect(
12
- withInflightTimeout(Promise.reject(new Error("boom")), "reject-case"),
13
- ).rejects.toThrow("boom");
14
- });
15
-
16
- it("rejects with a timeout error when underlying work never settles", async () => {
17
- vi.useFakeTimers();
18
- try {
19
- const hung = new Promise<number>(() => {});
20
- const raced = withInflightTimeout(hung, "hung-case", 1_000);
21
- // Swallow the eventual rejection so the runner doesn't see it as unhandled
22
- raced.catch(() => {});
23
-
24
- await vi.advanceTimersByTimeAsync(1_500);
25
- await expect(raced).rejects.toThrow(/timed out/);
26
- } finally {
27
- vi.useRealTimers();
28
- }
29
- });
30
-
31
- it("exports a sane default timeout", () => {
32
- expect(DEFAULT_INFLIGHT_TIMEOUT_MS).toBeGreaterThanOrEqual(1_000);
33
- expect(DEFAULT_INFLIGHT_TIMEOUT_MS).toBeLessThanOrEqual(60_000);
34
- });
35
- });
@@ -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
- }