@decocms/blocks 8.0.0 → 8.1.0-next.0

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 (175) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +39 -3
  3. package/src/cms/applySectionConventions.ts +26 -2
  4. package/src/cms/blockSource.ts +37 -0
  5. package/src/cms/client.ts +5 -0
  6. package/src/cms/deferredTrigger.ts +58 -0
  7. package/src/cms/draftSource.ts +171 -57
  8. package/src/cms/index.ts +32 -3
  9. package/src/cms/loader.ts +318 -59
  10. package/src/cms/registry.ts +22 -0
  11. package/src/cms/renderJson.ts +179 -0
  12. package/src/cms/resolve.ts +396 -95
  13. package/src/cms/schema.ts +9 -5
  14. package/src/cms/sectionLoaders.ts +106 -56
  15. package/src/hooks/Image.tsx +70 -6
  16. package/src/hooks/LiveControls.tsx +30 -8
  17. package/src/hooks/Stats.tsx +134 -0
  18. package/src/hooks/index.ts +5 -0
  19. package/src/hooks/useLoadMore.ts +100 -0
  20. package/src/index.ts +37 -0
  21. package/src/middleware/observability.ts +173 -16
  22. package/src/preview/DraftPreviewBadge.tsx +306 -0
  23. package/src/preview/decoMark.ts +11 -0
  24. package/src/preview/index.ts +8 -0
  25. package/src/protocol/assets.ts +124 -0
  26. package/src/protocol/canonical.ts +7 -0
  27. package/src/protocol/ciphertext.ts +6 -0
  28. package/src/protocol/client.ts +170 -0
  29. package/src/protocol/conformance/cases/assets.ts +81 -0
  30. package/src/protocol/conformance/cases/guards.ts +314 -0
  31. package/src/protocol/conformance/cases/reads.ts +168 -0
  32. package/src/protocol/conformance/cases/types.ts +9 -0
  33. package/src/protocol/conformance/cases/wire.ts +138 -0
  34. package/src/protocol/conformance/cases/writes.ts +345 -0
  35. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  36. package/src/protocol/conformance/context.ts +222 -0
  37. package/src/protocol/conformance/index.ts +140 -0
  38. package/src/protocol/errors.ts +142 -0
  39. package/src/protocol/index.ts +39 -0
  40. package/src/protocol/keys.ts +279 -0
  41. package/src/protocol/params.ts +67 -0
  42. package/src/protocol/secrets.ts +231 -0
  43. package/src/protocol/server/assets.ts +119 -0
  44. package/src/protocol/server/auth.ts +49 -0
  45. package/src/protocol/server/bodyCache.ts +84 -0
  46. package/src/protocol/server/content.ts +175 -0
  47. package/src/protocol/server/core.ts +112 -0
  48. package/src/protocol/server/handler.ts +102 -0
  49. package/src/protocol/server/http.ts +139 -0
  50. package/src/protocol/server/index.ts +11 -0
  51. package/src/protocol/server/methods/apply.ts +341 -0
  52. package/src/protocol/server/methods/read.ts +156 -0
  53. package/src/protocol/server/rpc.ts +136 -0
  54. package/src/protocol/storage/fs/hash.ts +21 -0
  55. package/src/protocol/storage/fs/index.ts +338 -0
  56. package/src/protocol/storage/fs/lock.ts +68 -0
  57. package/src/protocol/storage/fs/transaction.ts +183 -0
  58. package/src/protocol/storage/fs/unsupported.ts +15 -0
  59. package/src/protocol/storage/memory.ts +238 -0
  60. package/src/protocol/storage.ts +182 -0
  61. package/src/protocol/types.ts +172 -0
  62. package/src/sdk/abTesting.ts +60 -3
  63. package/src/sdk/analytics.ts +72 -2
  64. package/src/sdk/cacheHeaders.ts +210 -10
  65. package/src/sdk/cacheStorage.ts +287 -0
  66. package/src/sdk/cachedLoader.ts +143 -90
  67. package/src/sdk/crypto.ts +16 -2
  68. package/src/sdk/deepOmit.ts +52 -0
  69. package/src/sdk/encoding.ts +2 -5
  70. package/src/sdk/experiments.ts +314 -0
  71. package/src/sdk/fetchCache.ts +269 -0
  72. package/src/sdk/fetchTimeout.ts +58 -0
  73. package/src/sdk/flags.ts +38 -8
  74. package/src/sdk/index.ts +7 -0
  75. package/src/sdk/instrumentedFetch.ts +25 -2
  76. package/src/sdk/nonce.ts +46 -0
  77. package/src/sdk/normalizeUrls.ts +2 -2
  78. package/src/sdk/observability.ts +8 -1
  79. package/src/sdk/otel.ts +131 -25
  80. package/src/sdk/otelHttpLog.ts +4 -4
  81. package/src/sdk/otelHttpMeter.ts +39 -13
  82. package/src/sdk/otelHttpTracer.ts +4 -4
  83. package/src/sdk/redirects.ts +113 -5
  84. package/src/sdk/responseCache.ts +82 -0
  85. package/src/sdk/urlUtils.ts +49 -0
  86. package/src/sdk/useSuggestions.ts +1 -1
  87. package/src/v8/analytics.ts +50 -0
  88. package/src/v8/background.ts +107 -0
  89. package/src/v8/builtins/data.ts +23 -0
  90. package/src/v8/builtins/index.ts +26 -0
  91. package/src/v8/builtins/lazy.ts +23 -0
  92. package/src/v8/builtins/legacy.ts +65 -0
  93. package/src/v8/builtins/matchers.ts +31 -0
  94. package/src/v8/builtins/multivariate.ts +25 -0
  95. package/src/v8/builtins/secret.ts +82 -0
  96. package/src/v8/canonical.ts +117 -0
  97. package/src/v8/ciphertext.ts +158 -0
  98. package/src/v8/cli/builtins.ts +20 -0
  99. package/src/v8/cli/check/index.ts +774 -0
  100. package/src/v8/cli/check/messages.ts +168 -0
  101. package/src/v8/cli/content.ts +287 -0
  102. package/src/v8/cli/index.ts +17 -0
  103. package/src/v8/cli/log.ts +18 -0
  104. package/src/v8/cli/main.ts +12 -0
  105. package/src/v8/cli/root.ts +66 -0
  106. package/src/v8/cli/run.ts +236 -0
  107. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  108. package/src/v8/cli/schema/generate.ts +507 -0
  109. package/src/v8/cli/schema/index.ts +63 -0
  110. package/src/v8/cli/schema/tsProgram.ts +497 -0
  111. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  112. package/src/v8/cli/serve/server.ts +303 -0
  113. package/src/v8/cli/watch.ts +86 -0
  114. package/src/v8/client.ts +147 -0
  115. package/src/v8/cms.ts +237 -0
  116. package/src/v8/content.ts +195 -0
  117. package/src/v8/draft.ts +136 -0
  118. package/src/v8/errors.ts +59 -0
  119. package/src/v8/fetch.ts +152 -0
  120. package/src/v8/identity.ts +65 -0
  121. package/src/v8/index.ts +39 -0
  122. package/src/v8/json.ts +74 -0
  123. package/src/v8/matchRoute.ts +204 -0
  124. package/src/v8/remoteLoader.ts +282 -0
  125. package/src/v8/resolver.ts +278 -0
  126. package/src/v8/secrets.ts +17 -0
  127. package/src/v8/telemetry.ts +533 -0
  128. package/src/v8/types.ts +240 -0
  129. package/src/cms/blockSource.test.ts +0 -76
  130. package/src/cms/client.browserBundle.test.ts +0 -44
  131. package/src/cms/draftSource.test.ts +0 -343
  132. package/src/cms/layoutCacheRace.test.ts +0 -181
  133. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  134. package/src/cms/loader.test.ts +0 -200
  135. package/src/cms/registry.test.ts +0 -110
  136. package/src/cms/resolve.test.ts +0 -980
  137. package/src/cms/schema.test.ts +0 -356
  138. package/src/cms/sectionLoaderContext.test.ts +0 -111
  139. package/src/cms/sectionLoaders.test.ts +0 -533
  140. package/src/cms/sectionMixins.test.ts +0 -167
  141. package/src/cms/stickyFlags.test.ts +0 -117
  142. package/src/flags/flags.test.ts +0 -148
  143. package/src/hooks/Image.test.ts +0 -100
  144. package/src/hooks/RenderSection.test.tsx +0 -81
  145. package/src/matchers/builtins.test.ts +0 -318
  146. package/src/matchers/override.test.ts +0 -205
  147. package/src/middleware/hydrationContext.test.ts +0 -61
  148. package/src/middleware/observability.test.ts +0 -242
  149. package/src/middleware/validateSection.test.ts +0 -147
  150. package/src/sdk/abTesting.test.ts +0 -326
  151. package/src/sdk/cacheHeaders.test.ts +0 -115
  152. package/src/sdk/cachedLoader.test.ts +0 -122
  153. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  154. package/src/sdk/cn.test.ts +0 -34
  155. package/src/sdk/composite.test.ts +0 -121
  156. package/src/sdk/cookie.test.ts +0 -108
  157. package/src/sdk/encoding.test.ts +0 -71
  158. package/src/sdk/env.test.ts +0 -33
  159. package/src/sdk/flags.test.ts +0 -91
  160. package/src/sdk/http.test.ts +0 -71
  161. package/src/sdk/inflightTimeout.test.ts +0 -35
  162. package/src/sdk/instrumentedFetch.test.ts +0 -559
  163. package/src/sdk/invoke.test.ts +0 -115
  164. package/src/sdk/logger.test.ts +0 -432
  165. package/src/sdk/otel.test.ts +0 -526
  166. package/src/sdk/otelAdapters.test.ts +0 -89
  167. package/src/sdk/otelHttpLog.test.ts +0 -457
  168. package/src/sdk/otelHttpMeter.test.ts +0 -292
  169. package/src/sdk/otelHttpTracer.test.ts +0 -474
  170. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  171. package/src/sdk/urlRedaction.test.ts +0 -73
  172. package/src/sdk/useDevice.test.ts +0 -130
  173. package/src/sdk/useScript.test.ts +0 -128
  174. package/src/sdk/useSuggestions.test.ts +0 -230
  175. 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,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,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
- });
@@ -1,100 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
- import { getOptimizedMediaUrl, getSrcSet } from "./Image";
3
-
4
- describe("getOptimizedMediaUrl", () => {
5
- let warnSpy: ReturnType<typeof vi.spyOn>;
6
- let prevNodeEnv: string | undefined;
7
-
8
- beforeEach(() => {
9
- prevNodeEnv = process.env.NODE_ENV;
10
- process.env.NODE_ENV = "development";
11
- warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
12
- });
13
-
14
- afterEach(() => {
15
- warnSpy.mockRestore();
16
- if (prevNodeEnv === undefined) delete process.env.NODE_ENV;
17
- else process.env.NODE_ENV = prevNodeEnv;
18
- });
19
-
20
- it("returns empty string and warns when src is undefined", () => {
21
- const result = getOptimizedMediaUrl({
22
- originalSrc: undefined as unknown as string,
23
- width: 100,
24
- fit: "cover",
25
- });
26
- expect(result).toBe("");
27
- expect(warnSpy).toHaveBeenCalledTimes(1);
28
- expect(warnSpy.mock.calls[0][0]).toMatch(/empty\/undefined src/);
29
- });
30
-
31
- it("returns empty string when src is empty", () => {
32
- const result = getOptimizedMediaUrl({
33
- originalSrc: "",
34
- width: 100,
35
- fit: "cover",
36
- });
37
- expect(result).toBe("");
38
- });
39
-
40
- it("returns empty string when src is null", () => {
41
- const result = getOptimizedMediaUrl({
42
- originalSrc: null as unknown as string,
43
- width: 100,
44
- fit: "cover",
45
- });
46
- expect(result).toBe("");
47
- });
48
-
49
- it("does NOT warn in production for missing src", () => {
50
- process.env.NODE_ENV = "production";
51
- const result = getOptimizedMediaUrl({
52
- originalSrc: undefined as unknown as string,
53
- width: 100,
54
- fit: "cover",
55
- });
56
- expect(result).toBe("");
57
- expect(warnSpy).not.toHaveBeenCalled();
58
- });
59
-
60
- it("returns data URI as-is", () => {
61
- const dataUri = "data:image/png;base64,iVBORw0KGgo=";
62
- expect(
63
- getOptimizedMediaUrl({
64
- originalSrc: dataUri,
65
- width: 100,
66
- fit: "cover",
67
- }),
68
- ).toBe(dataUri);
69
- });
70
-
71
- it("routes through Deco image CDN for arbitrary src", () => {
72
- const result = getOptimizedMediaUrl({
73
- originalSrc: "https://cdn.example.com/foo.jpg",
74
- width: 200,
75
- fit: "cover",
76
- });
77
- expect(result).toContain("/image?");
78
- expect(result).toContain("width=200");
79
- expect(result).toContain("fit=cover");
80
- expect(result).toContain("src=https://cdn.example.com/foo.jpg");
81
- });
82
- });
83
-
84
- describe("getSrcSet", () => {
85
- it("returns undefined when src is undefined", () => {
86
- expect(getSrcSet(undefined as unknown as string, 100)).toBeUndefined();
87
- });
88
-
89
- it("returns undefined when src is empty", () => {
90
- expect(getSrcSet("", 100)).toBeUndefined();
91
- });
92
-
93
- it("produces a srcset string for valid src", () => {
94
- const result = getSrcSet("https://cdn.example.com/foo.jpg", 100);
95
- expect(result).toBeDefined();
96
- // Each factor entry is "<url> <width>w".
97
- expect(result).toMatch(/\d+w/);
98
- expect(result).toContain("foo.jpg");
99
- });
100
- });
@@ -1,81 +0,0 @@
1
- import { renderToString } from "react-dom/server";
2
- import { describe, expect, it } from "vitest";
3
- import { registerSection, registerSectionsSync } from "../cms/registry";
4
- import RenderSection from "./RenderSection";
5
-
6
- // NOTE: each test uses its OWN section key. The registry module captures the
7
- // `globalThis.__deco.*` objects at module load, so re-assigning them in a
8
- // beforeEach (the registry.test.ts pattern) does not actually clear the
9
- // registry this module writes to — and RenderSection additionally keeps a
10
- // module-level lazy cache keyed by resolveType. Unique keys sidestep both.
11
-
12
- function Hero({ label }: { label?: string }) {
13
- // Single text node — avoids React's `<!-- -->` separator between
14
- // adjacent text/expression children, keeping assertions simple.
15
- return <h1>{`hero-${label ?? "none"}`}</h1>;
16
- }
17
-
18
- // A lazy loader that never settles: the lazy path suspends forever, so any
19
- // content that DOES render must have come from the sync registry.
20
- const neverResolves = () => new Promise<never>(() => {});
21
-
22
- describe("RenderSection sync-first", () => {
23
- it("renders a sync-registered section directly (no Suspense fallback)", () => {
24
- const KEY = "site/sections/SyncA.tsx";
25
- registerSectionsSync({ [KEY]: { default: Hero } });
26
-
27
- const html = renderToString(<RenderSection section={{ __resolveType: KEY, label: "a" }} />);
28
- expect(html).toContain("hero-a");
29
- });
30
-
31
- it("renders sync for the old { Component: string } shape too", () => {
32
- const KEY = "site/sections/SyncB.tsx";
33
- registerSectionsSync({ [KEY]: { default: Hero } });
34
-
35
- const html = renderToString(
36
- <RenderSection section={{ Component: KEY as any, props: { label: "b" } }} />,
37
- );
38
- expect(html).toContain("hero-b");
39
- });
40
-
41
- it("prefers the sync component over a pending lazy loader", () => {
42
- const KEY = "site/sections/SyncC.tsx";
43
- // Both registered: lazy loader never settles, sync is available.
44
- // Sync-first must render the content without suspending.
45
- registerSection(KEY, neverResolves as any);
46
- registerSectionsSync({ [KEY]: { default: Hero } });
47
-
48
- const html = renderToString(
49
- <RenderSection
50
- section={{ __resolveType: KEY, label: "c" }}
51
- fallback={<span>loading</span>}
52
- />,
53
- );
54
- expect(html).toContain("hero-c");
55
- expect(html).not.toContain("loading");
56
- });
57
-
58
- it("falls back to the lazy path when no sync component is registered", () => {
59
- const KEY = "site/sections/LazyOnlyD.tsx";
60
- registerSection(KEY, neverResolves as any);
61
-
62
- const html = renderToString(
63
- <RenderSection
64
- section={{ __resolveType: KEY, label: "d" }}
65
- fallback={<span>loading</span>}
66
- />,
67
- );
68
- expect(html).toContain("loading");
69
- expect(html).not.toContain("hero-d");
70
- });
71
-
72
- it("renders the fallback when the section is not registered at all", () => {
73
- const html = renderToString(
74
- <RenderSection
75
- section={{ __resolveType: "site/sections/MissingE.tsx" }}
76
- fallback={<span>missing</span>}
77
- />,
78
- );
79
- expect(html).toContain("missing");
80
- });
81
- });