@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,167 +0,0 @@
1
- /**
2
- * Section mixins — focused on `withSectionLoader` since the device/mobile
3
- * mixins are exercised by sectionLoaders integration tests already.
4
- */
5
- import { describe, expect, it, vi } from "vitest";
6
- import {
7
- compose,
8
- withDevice,
9
- withMobile,
10
- withSearchParam,
11
- withSectionLoader,
12
- } from "./sectionMixins";
13
-
14
- // `__requestDependent` is the runtime tag the framework reads in
15
- // `registerSectionLoaders` to decide whether to emit the layout-cache
16
- // contamination warning (#206). Any future mixin that depends on the
17
- // request must opt in by setting this flag — and `compose` must propagate
18
- // it whenever any input has it.
19
- const isRequestDependent = (fn: unknown): boolean =>
20
- typeof fn === "function" && (fn as { __requestDependent?: boolean }).__requestDependent === true;
21
-
22
- const makeReq = (url = "https://store.example/foo?q=hello") =>
23
- new Request(url, { headers: { "user-agent": "vitest" } });
24
-
25
- describe("withSectionLoader", () => {
26
- it("invokes the section's exported loader and returns its result", async () => {
27
- const loader = vi.fn(async (props: Record<string, unknown>) => ({
28
- ...props,
29
- url: "https://store.example/foo?q=hello",
30
- enriched: true,
31
- }));
32
-
33
- const mixin = withSectionLoader(async () => ({ loader }));
34
- const result = await mixin({ original: "value" }, makeReq());
35
-
36
- expect(loader).toHaveBeenCalledTimes(1);
37
- expect(result).toEqual({
38
- original: "value",
39
- url: "https://store.example/foo?q=hello",
40
- enriched: true,
41
- });
42
- });
43
-
44
- it("returns props unchanged when module has no loader export", async () => {
45
- const mixin = withSectionLoader(async () => ({ default: () => null }));
46
- const props = { foo: "bar" };
47
- const result = await mixin(props, makeReq());
48
- expect(result).toBe(props);
49
- });
50
-
51
- it("returns props unchanged when module is undefined / loader is not a function", async () => {
52
- const mixin = withSectionLoader(async () => undefined);
53
- const props = { foo: "bar" };
54
- expect(await mixin(props, makeReq())).toBe(props);
55
-
56
- const mixinWithBadLoader = withSectionLoader(async () => ({
57
- loader: "not-a-function",
58
- }));
59
- expect(await mixinWithBadLoader(props, makeReq())).toBe(props);
60
- });
61
-
62
- it("swallows loader errors and returns the original props", async () => {
63
- const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
64
- const mixin = withSectionLoader(async () => ({
65
- loader: async () => {
66
- throw new Error("boom");
67
- },
68
- }));
69
- const props = { foo: "bar" };
70
- const result = await mixin(props, makeReq());
71
- expect(result).toBe(props);
72
- expect(errorSpy).toHaveBeenCalledWith(
73
- "[withSectionLoader] section loader threw:",
74
- expect.any(Error),
75
- );
76
- errorSpy.mockRestore();
77
- });
78
-
79
- it("falls back to original props when loader returns undefined", async () => {
80
- const mixin = withSectionLoader(async () => ({
81
- loader: async () => undefined,
82
- }));
83
- const props = { foo: "bar" };
84
- expect(await mixin(props, makeReq())).toBe(props);
85
- });
86
-
87
- it("composes alongside mixins: mixins run first, then the section loader sees the enriched props", async () => {
88
- const seen: Array<Record<string, unknown>> = [];
89
- const sectionLoader = vi.fn(async (props: Record<string, unknown>) => {
90
- seen.push({ ...props });
91
- return { ...props, sectionLoaderRan: true };
92
- });
93
-
94
- const composed = compose(
95
- withSearchParam(),
96
- withSectionLoader(async () => ({ loader: sectionLoader })),
97
- );
98
-
99
- const result = await composed({ original: 1 }, makeReq());
100
-
101
- expect(seen).toHaveLength(1);
102
- // The section loader sees the enriched props (currentSearchParam injected by withSearchParam)
103
- expect(seen[0]).toMatchObject({
104
- original: 1,
105
- currentSearchParam: "hello",
106
- });
107
- expect(result).toMatchObject({
108
- original: 1,
109
- currentSearchParam: "hello",
110
- sectionLoaderRan: true,
111
- });
112
- });
113
-
114
- it("loads the module lazily — modImport is only called on first invocation", async () => {
115
- const modImport = vi.fn(async () => ({
116
- loader: async (p: Record<string, unknown>) => ({ ...p, ran: true }),
117
- }));
118
- const mixin = withSectionLoader(modImport);
119
- expect(modImport).not.toHaveBeenCalled();
120
-
121
- await mixin({ a: 1 }, makeReq());
122
- expect(modImport).toHaveBeenCalledTimes(1);
123
-
124
- // A second invocation calls the import again — caching is the
125
- // dynamic import's responsibility (which the runtime memoises).
126
- await mixin({ a: 2 }, makeReq());
127
- expect(modImport).toHaveBeenCalledTimes(2);
128
- });
129
- });
130
-
131
- describe("request-dependent tagging (#206)", () => {
132
- it("tags withDevice", () => {
133
- expect(isRequestDependent(withDevice())).toBe(true);
134
- });
135
-
136
- it("tags withMobile", () => {
137
- expect(isRequestDependent(withMobile())).toBe(true);
138
- });
139
-
140
- it("tags withSearchParam", () => {
141
- expect(isRequestDependent(withSearchParam())).toBe(true);
142
- });
143
-
144
- it("does NOT tag withSectionLoader (its loader may or may not touch req)", () => {
145
- expect(isRequestDependent(withSectionLoader(async () => ({})))).toBe(false);
146
- });
147
-
148
- it("compose propagates the flag when any input is request-dependent", () => {
149
- expect(isRequestDependent(compose(withDevice(), async (p) => p))).toBe(true);
150
- expect(isRequestDependent(compose(async (p) => p, withSearchParam()))).toBe(true);
151
- });
152
-
153
- it("compose does NOT set the flag when no input is request-dependent", () => {
154
- expect(
155
- isRequestDependent(
156
- compose(
157
- async (p) => p,
158
- async (p) => p,
159
- ),
160
- ),
161
- ).toBe(false);
162
- });
163
-
164
- it("empty compose() is not request-dependent", () => {
165
- expect(isRequestDependent(compose())).toBe(false);
166
- });
167
- });
@@ -1,153 +0,0 @@
1
- /**
2
- * Section Loader Mixins
3
- *
4
- * Reusable section loader factories for common patterns like device detection,
5
- * mobile flag injection, and search param extraction. Eliminates repetitive
6
- * `(props, req) => ({ ...props, device: detectDevice(...) })` boilerplate.
7
- *
8
- * @example
9
- * ```ts
10
- * import { withDevice, withMobile, compose } from "@decocms/start/cms";
11
- *
12
- * registerSectionLoaders({
13
- * "site/sections/Product/ProductShelf.tsx": withDevice(),
14
- * "site/sections/Images/Carousel.tsx": withMobile(),
15
- * "site/sections/Header/Header.tsx": compose(withDevice(), withSearchParam()),
16
- * });
17
- * ```
18
- */
19
- import { detectDevice } from "../sdk/detectDevice";
20
- import type { SectionLoaderFn } from "./sectionLoaders";
21
-
22
- /**
23
- * Mixins that derive props from the incoming request (UA, search params,
24
- * cookies, geo, segment) carry this flag so the framework can warn when a
25
- * site accidentally combines them with a layout-cached section — the layout
26
- * cache is keyed only by component path, so the first visitor's variant
27
- * would be served to all viewers for the cache TTL. See #206.
28
- */
29
- type TaggedSectionLoaderFn = SectionLoaderFn & { __requestDependent?: boolean };
30
-
31
- function tagRequestDependent(fn: SectionLoaderFn): SectionLoaderFn {
32
- (fn as TaggedSectionLoaderFn).__requestDependent = true;
33
- return fn;
34
- }
35
-
36
- /**
37
- * Injects `device: "mobile" | "desktop" | "tablet"` from the request User-Agent.
38
- */
39
- export function withDevice(): SectionLoaderFn {
40
- return tagRequestDependent((props, req) => ({
41
- ...props,
42
- device: detectDevice(req.headers.get("user-agent") ?? ""),
43
- }));
44
- }
45
-
46
- /**
47
- * Injects `isMobile: boolean` (true for mobile and tablet) from the request User-Agent.
48
- */
49
- export function withMobile(): SectionLoaderFn {
50
- return tagRequestDependent((props, req) => {
51
- const d = detectDevice(req.headers.get("user-agent") ?? "");
52
- return { ...props, isMobile: d === "mobile" || d === "tablet" };
53
- });
54
- }
55
-
56
- const REGEX_QUERY_VALUE = /[?&]q=([^&]*)/;
57
-
58
- /**
59
- * Injects `currentSearchParam: string | undefined` extracted from the `?q=` URL parameter.
60
- */
61
- export function withSearchParam(): SectionLoaderFn {
62
- return tagRequestDependent((props, req) => {
63
- const match = req.url.match(REGEX_QUERY_VALUE);
64
- return {
65
- ...props,
66
- currentSearchParam: match ? decodeURIComponent(match[1]) : undefined,
67
- };
68
- });
69
- }
70
-
71
- /**
72
- * Composes multiple section loader mixins into a single loader.
73
- * Each mixin's result is merged left-to-right (later mixins override earlier ones).
74
- *
75
- * Propagates the `__requestDependent` flag from any input mixin so the
76
- * layout-cache contamination warning (#206) fires even when a request-
77
- * dependent mixin is hidden inside a compose() chain.
78
- *
79
- * @example
80
- * ```ts
81
- * compose(withDevice(), withSearchParam())
82
- * // Equivalent to: (props, req) => ({ ...props, device: ..., currentSearchParam: ... })
83
- * ```
84
- */
85
- export function compose(...mixins: SectionLoaderFn[]): SectionLoaderFn {
86
- const composed: SectionLoaderFn = async (props, req, ctx) => {
87
- let result = { ...props };
88
- for (const mixin of mixins) {
89
- const partial = await mixin(result, req, ctx);
90
- result = { ...result, ...partial };
91
- }
92
- return result;
93
- };
94
- if (mixins.some((m) => (m as TaggedSectionLoaderFn).__requestDependent)) {
95
- (composed as TaggedSectionLoaderFn).__requestDependent = true;
96
- }
97
- return composed;
98
- }
99
-
100
- /**
101
- * Wraps a section module's exported `loader` so it can be composed alongside
102
- * mixins like {@link withDevice}, {@link withMobile}, {@link withSearchParam}.
103
- *
104
- * The `modImport` argument is a lazy factory (typically `() => import("~/sections/...")`)
105
- * — the module is loaded on first call. If the module does not export a
106
- * `loader`, the original `props` are returned unchanged (no-op).
107
- *
108
- * Why this exists: the migrator and many sites lifted from Fresh declare a
109
- * `loader` export on the section file (often re-exported from the inner
110
- * component). That loader sets things like `url: req.url`, runs platform
111
- * invocations, or calls the section's domain logic. If the section is wired
112
- * in `registerSectionLoaders` with mixin-only (e.g. `withSearchParam()`),
113
- * the section's own loader is silently *replaced* — its work never runs and
114
- * its returned props are dropped.
115
- *
116
- * Compose this helper FIRST in the chain so mixin-injected props
117
- * (`device`, `currentSearchParam`, …) are available to the section's loader,
118
- * then the section's loader has the final word over what is returned.
119
- *
120
- * @example
121
- * ```ts
122
- * import {
123
- * compose,
124
- * withMobile,
125
- * withSearchParam,
126
- * withSectionLoader,
127
- * } from "@decocms/start/cms";
128
- *
129
- * registerSectionLoaders({
130
- * "site/sections/Product/SearchContainerV2.tsx": compose(
131
- * withMobile(),
132
- * withSearchParam(),
133
- * withSectionLoader(() => import("~/sections/Product/SearchContainerV2")),
134
- * ),
135
- * });
136
- * ```
137
- */
138
- export function withSectionLoader(modImport: () => Promise<unknown>): SectionLoaderFn {
139
- return async (props, req, ctx) => {
140
- const mod = (await modImport()) as { loader?: unknown } | undefined;
141
- const loader = mod?.loader;
142
- if (typeof loader !== "function") return props;
143
- try {
144
- // Forward the compat `ctx` (issue #305) so migrated Fresh loaders that
145
- // read `ctx.device`/`ctx.invoke`/`ctx.<app>` get the real 3rd argument.
146
- const result = await (loader as SectionLoaderFn)(props, req, ctx);
147
- return result ?? props;
148
- } catch (error) {
149
- console.error("[withSectionLoader] section loader threw:", error);
150
- return props;
151
- }
152
- };
153
- }
@@ -1,117 +0,0 @@
1
- import { afterEach, describe, expect, it, vi } from "vitest";
2
-
3
- vi.mock("./sectionLoaders", () => ({
4
- isLayoutSection: () => false,
5
- runSingleSectionLoader: vi.fn(async (section: any) => section),
6
- }));
7
-
8
- vi.mock("../sdk/normalizeUrls", () => ({
9
- normalizeUrlsInObject: vi.fn(<T>(x: T) => x),
10
- }));
11
-
12
- // A page whose A/B "TestHero" matcher block resolves to a 50/50 random matcher.
13
- vi.mock("./loader", () => ({
14
- findPageByPath: vi.fn(),
15
- loadBlocks: vi.fn(() => ({
16
- TestHero: { __resolveType: "website/matchers/random.ts", traffic: 0.5 },
17
- })),
18
- }));
19
-
20
- vi.mock("./registry", () => ({
21
- getSection: vi.fn(),
22
- }));
23
-
24
- import { DECO_MATCHERS_OVERRIDE_PARAM } from "../matchers/override";
25
- import { type StoredFlag, serializeSegmentCookie } from "../sdk/flags";
26
- import type { MatcherContext } from "./resolve";
27
- import { resolveValue } from "./resolve";
28
-
29
- const FLAG = {
30
- __resolveType: "website/flags/multivariate.ts",
31
- variants: [
32
- { rule: { __resolveType: "TestHero" }, value: "VARIANT_1" },
33
- { rule: { __resolveType: "website/matchers/always.ts" }, value: "VARIANT_2" },
34
- ],
35
- };
36
-
37
- function ctx(decision?: { value: boolean; pct: number }): MatcherContext & { flags: StoredFlag[] } {
38
- const cookie = decision
39
- ? serializeSegmentCookie([{ name: "TestHero", value: decision.value, pct: decision.pct }])
40
- : undefined;
41
- return {
42
- cookies: cookie ? { deco_segment: cookie } : {},
43
- flags: [],
44
- };
45
- }
46
-
47
- afterEach(() => vi.restoreAllMocks());
48
-
49
- describe("sticky A/B multivariate resolution", () => {
50
- it("honors a matching cookie without rolling (test cohort)", async () => {
51
- const rand = vi.spyOn(Math, "random");
52
- const c = ctx({ value: true, pct: 50 });
53
-
54
- const result = await resolveValue(FLAG, undefined, c);
55
-
56
- expect(result).toBe("VARIANT_1");
57
- expect(rand).not.toHaveBeenCalled();
58
- expect(c.flags).toEqual([{ name: "TestHero", value: true, pct: 50 }]);
59
- });
60
-
61
- it("honors a matching cookie without rolling (control cohort)", async () => {
62
- const rand = vi.spyOn(Math, "random");
63
- const c = ctx({ value: false, pct: 50 });
64
-
65
- const result = await resolveValue(FLAG, undefined, c);
66
-
67
- expect(result).toBe("VARIANT_2");
68
- expect(rand).not.toHaveBeenCalled();
69
- expect(c.flags).toEqual([{ name: "TestHero", value: false, pct: 50 }]);
70
- });
71
-
72
- it("rolls and records when there is no cookie", async () => {
73
- vi.spyOn(Math, "random").mockReturnValue(0.9); // >= 0.5 -> control
74
- const c = ctx();
75
-
76
- const result = await resolveValue(FLAG, undefined, c);
77
-
78
- expect(result).toBe("VARIANT_2");
79
- expect(c.flags).toEqual([{ name: "TestHero", value: false, pct: 50 }]);
80
- });
81
-
82
- it("re-rolls when the cookie's traffic fingerprint is stale", async () => {
83
- vi.spyOn(Math, "random").mockReturnValue(0.1); // < 0.5 -> test
84
- // Cookie says the user was in control at 70% traffic; current traffic is 50%.
85
- const c = ctx({ value: false, pct: 70 });
86
-
87
- const result = await resolveValue(FLAG, undefined, c);
88
-
89
- expect(result).toBe("VARIANT_1");
90
- expect(c.flags).toEqual([{ name: "TestHero", value: true, pct: 50 }]);
91
- });
92
-
93
- it("does not record flags when recording is not opted into", async () => {
94
- vi.spyOn(Math, "random").mockReturnValue(0.1);
95
- // No `flags` array on the context -> nothing to record, but still resolves.
96
- const result = await resolveValue(FLAG, undefined, { cookies: {} });
97
- expect(result).toBe("VARIANT_1");
98
- });
99
-
100
- it("honors the admin matchers-override instead of the cookie/roll", async () => {
101
- const rand = vi.spyOn(Math, "random");
102
- // Admin forces TestHero=0 for preview, but the cookie says test cohort.
103
- const c: MatcherContext & { flags: StoredFlag[] } = {
104
- cookies: {
105
- deco_segment: serializeSegmentCookie([{ name: "TestHero", value: true, pct: 50 }]),
106
- },
107
- headers: { [DECO_MATCHERS_OVERRIDE_PARAM]: "TestHero=0" },
108
- flags: [],
109
- };
110
-
111
- const result = await resolveValue(FLAG, undefined, c);
112
-
113
- expect(result).toBe("VARIANT_2"); // override wins over the cookie
114
- expect(rand).not.toHaveBeenCalled();
115
- expect(c.flags).toEqual([]); // previews don't persist a cohort
116
- });
117
- });
@@ -1,56 +0,0 @@
1
- import type { FlagObj, Matcher } from "./types";
2
- import Flag from "./flag";
3
-
4
- /**
5
- * @title Site Route
6
- * @titleBy pathTemplate
7
- */
8
- export interface Route {
9
- pathTemplate: string;
10
- /**
11
- * @description if true so the path will be checked against the coming from request instead of using urlpattern.
12
- */
13
- isHref?: boolean;
14
- handler: {
15
- value: unknown;
16
- };
17
- /**
18
- * @title Priority
19
- * @description higher priority means that this route will be used in favor of other routes with less or none priority
20
- */
21
- highPriority?: boolean;
22
- }
23
-
24
- /**
25
- * @title Routes
26
- * @description Used to configure your site routes
27
- */
28
- export type Routes = Route[];
29
-
30
- /**
31
- * @titleBy name
32
- */
33
- export interface Audience {
34
- matcher: Matcher;
35
- /**
36
- * @title The audience name (will be used on cookies).
37
- * @description Add a meaningful short word for the audience name.
38
- * @minLength 3
39
- * @pattern ^[A-Za-z0-9_-]+$
40
- */
41
- name: string;
42
- routes?: Routes;
43
- }
44
-
45
- /**
46
- * @title Audience
47
- * @description Select routes based on the matched audience.
48
- */
49
- export default function Audience({ matcher, routes, name }: Audience): FlagObj<Route[]> {
50
- return Flag<Route[]>({
51
- matcher,
52
- true: routes ?? [],
53
- false: [],
54
- name,
55
- });
56
- }
@@ -1,29 +0,0 @@
1
- import type { FlagObj, Matcher } from "./types";
2
- import Audience, { type Route, type Routes } from "./audience";
3
-
4
- /**
5
- * Ported from apps-start's `website/matchers/always.ts`. That file existed
6
- * as its own block file only because deco-cx's old manifest system
7
- * discovered matchers by scanning files; this codebase's matcher/flag
8
- * mechanisms aren't file-scanned, so it's inlined here as its sole
9
- * consumer. (Its `cacheable = true` export was manifest-generation
10
- * metadata for that old system with no runtime consumer — dropped, same
11
- * as the rest of the `date`/matcher ports in `../matchers/builtins.ts`.)
12
- */
13
- const MatchAlways: Matcher = () => true;
14
-
15
- export interface EveryoneConfig {
16
- routes?: Routes;
17
- }
18
-
19
- /**
20
- * @title Audience Everyone
21
- * @description Always match regardless of the current user
22
- */
23
- export default function Everyone({ routes }: EveryoneConfig): FlagObj<Route[]> {
24
- return Audience({
25
- matcher: MatchAlways,
26
- routes: routes ?? [],
27
- name: "Everyone",
28
- });
29
- }
package/src/flags/flag.ts DELETED
@@ -1,15 +0,0 @@
1
- import type { FlagObj } from "./types";
2
-
3
- export type Props<T> = FlagObj<T>;
4
-
5
- /**
6
- * @title Flag
7
- */
8
- export default function Flag<T>({ matcher, name, true: T, false: F }: Props<T>): FlagObj<T> {
9
- return {
10
- matcher,
11
- true: T,
12
- false: F,
13
- name,
14
- };
15
- }
@@ -1,148 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import Audience from "./audience";
3
- import Everyone from "./everyone";
4
- import Flag from "./flag";
5
- import type { Matcher } from "./types";
6
- import multivariate from "./utils/multivariate";
7
- import ImageVariants from "./multivariate/image";
8
- import MessageVariants from "./multivariate/message";
9
- import PageVariants from "./multivariate/page";
10
- import SectionVariants from "./multivariate/section";
11
-
12
- // ---------------------------------------------------------------------------
13
- // flag.ts
14
- // ---------------------------------------------------------------------------
15
-
16
- describe("Flag", () => {
17
- it("returns a FlagObj with the same values", () => {
18
- const matcher: Matcher = () => true;
19
- const result = Flag({
20
- matcher,
21
- true: "variant-a",
22
- false: "variant-b",
23
- name: "test-flag",
24
- });
25
-
26
- expect(result.matcher).toBe(matcher);
27
- expect(result.true).toBe("variant-a");
28
- expect(result.false).toBe("variant-b");
29
- expect(result.name).toBe("test-flag");
30
- });
31
-
32
- it("preserves complex true/false values", () => {
33
- const routes = [{ pathTemplate: "/*", handler: { value: {} } }];
34
- const result = Flag<typeof routes>({
35
- matcher: () => false,
36
- true: routes,
37
- false: [],
38
- name: "routes-flag",
39
- });
40
-
41
- expect(result.true).toBe(routes);
42
- expect(result.false).toEqual([]);
43
- });
44
- });
45
-
46
- // ---------------------------------------------------------------------------
47
- // audience.ts
48
- // ---------------------------------------------------------------------------
49
-
50
- describe("Audience", () => {
51
- it("returns FlagObj with routes as true branch and empty as false", () => {
52
- const matcher: Matcher = () => true;
53
- const routes = [{ pathTemplate: "/products/*", handler: { value: {} } }];
54
-
55
- const result = Audience({ matcher, name: "vip-users", routes });
56
-
57
- expect(result.name).toBe("vip-users");
58
- expect(result.true).toEqual(routes);
59
- expect(result.false).toEqual([]);
60
- });
61
-
62
- it("defaults routes to empty array when not provided", () => {
63
- const result = Audience({ matcher: () => false, name: "empty" });
64
-
65
- expect(result.true).toEqual([]);
66
- expect(result.false).toEqual([]);
67
- });
68
- });
69
-
70
- // ---------------------------------------------------------------------------
71
- // everyone.ts
72
- // ---------------------------------------------------------------------------
73
-
74
- describe("Everyone", () => {
75
- it("creates a flag named Everyone that always matches", () => {
76
- const routes = [{ pathTemplate: "/*", handler: { value: {} } }];
77
- const result = Everyone({ routes });
78
-
79
- expect(result.name).toBe("Everyone");
80
- expect(result.true).toEqual(routes);
81
- expect(result.false).toEqual([]);
82
- // The matcher should be MatchAlways which returns true
83
- expect(result.matcher({} as any)).toBe(true);
84
- });
85
-
86
- it("works with no routes", () => {
87
- const result = Everyone({});
88
-
89
- expect(result.name).toBe("Everyone");
90
- expect(result.true).toEqual([]);
91
- });
92
- });
93
-
94
- // ---------------------------------------------------------------------------
95
- // multivariate
96
- // ---------------------------------------------------------------------------
97
-
98
- describe("multivariate", () => {
99
- it("returns the variants as-is", () => {
100
- const variants = [
101
- { value: "A", weight: 0.5 },
102
- { value: "B", weight: 0.5 },
103
- ];
104
-
105
- const result = multivariate({ variants });
106
-
107
- expect(result.variants).toBe(variants);
108
- expect(result.variants).toHaveLength(2);
109
- });
110
-
111
- it("supports variants with matchers", () => {
112
- const matcher: Matcher = () => true;
113
- const variants = [{ value: "control", matcher }, { value: "default" }];
114
-
115
- const result = multivariate({ variants });
116
-
117
- expect(result.variants[0].matcher).toBe(matcher);
118
- expect(result.variants[1].matcher).toBeUndefined();
119
- });
120
- });
121
-
122
- // ---------------------------------------------------------------------------
123
- // multivariate/* (Image/Message/Page/Section variants) + the multivariate.ts
124
- // re-export (`./multivariate.ts` re-exports `./multivariate/page.ts`'s
125
- // default, so `PageVariants` doubles as the coverage for that re-export).
126
- // ---------------------------------------------------------------------------
127
-
128
- describe("multivariate/*", () => {
129
- it("Image delegates to multivariate", () => {
130
- const variants = [{ value: "a.png" }, { value: "b.png" }];
131
- expect(ImageVariants({ variants })).toEqual({ variants });
132
- });
133
-
134
- it("Message delegates to multivariate", () => {
135
- const variants = [{ value: "hello" }, { value: "world" }];
136
- expect(MessageVariants({ variants })).toEqual({ variants });
137
- });
138
-
139
- it("Page delegates to multivariate", () => {
140
- const variants = [{ value: [] }, { value: [] }];
141
- expect(PageVariants({ variants })).toEqual({ variants });
142
- });
143
-
144
- it("Section delegates to multivariate", () => {
145
- const variants = [{ value: {} }, { value: {} }];
146
- expect(SectionVariants({ variants })).toEqual({ variants });
147
- });
148
- });