@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,130 +0,0 @@
1
- import { createElement } from "react";
2
- import { renderToStaticMarkup } from "react-dom/server";
3
- import { describe, expect, it } from "vitest";
4
- import { DeviceProvider, detectDevice, isMobileUA, useDevice } from "./useDevice";
5
-
6
- describe("detectDevice", () => {
7
- it("detects iPhone as mobile", () => {
8
- expect(
9
- detectDevice(
10
- "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1",
11
- ),
12
- ).toBe("mobile");
13
- });
14
-
15
- it("detects Android phone as mobile", () => {
16
- expect(
17
- detectDevice(
18
- "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36",
19
- ),
20
- ).toBe("mobile");
21
- });
22
-
23
- it("detects iPad as tablet", () => {
24
- expect(
25
- detectDevice(
26
- "Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1",
27
- ),
28
- ).toBe("tablet");
29
- });
30
-
31
- it("detects Android tablet as tablet", () => {
32
- expect(
33
- detectDevice(
34
- "Mozilla/5.0 (Linux; Android 14; SM-X200) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
35
- ),
36
- ).toBe("tablet");
37
- });
38
-
39
- it("detects Chrome desktop as desktop", () => {
40
- expect(
41
- detectDevice(
42
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
43
- ),
44
- ).toBe("desktop");
45
- });
46
-
47
- it("returns desktop for empty UA", () => {
48
- expect(detectDevice("")).toBe("desktop");
49
- });
50
-
51
- it("detects Googlebot as desktop", () => {
52
- expect(
53
- detectDevice(
54
- "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
55
- ),
56
- ).toBe("desktop");
57
- });
58
-
59
- it("detects Googlebot mobile as mobile", () => {
60
- expect(
61
- detectDevice(
62
- "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36 (compatible; Googlebot/2.1)",
63
- ),
64
- ).toBe("mobile");
65
- });
66
- });
67
-
68
- describe("isMobileUA", () => {
69
- it("returns true for mobile UAs", () => {
70
- expect(isMobileUA("iPhone")).toBe(true);
71
- });
72
-
73
- it("returns true for tablet UAs", () => {
74
- expect(isMobileUA("iPad")).toBe(true);
75
- });
76
-
77
- it("returns false for desktop UAs", () => {
78
- expect(
79
- isMobileUA(
80
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
81
- ),
82
- ).toBe(false);
83
- });
84
- });
85
-
86
- describe("useDevice (isomorphic)", () => {
87
- it("uses navigator.userAgent on client, not viewport width", () => {
88
- // In jsdom, document exists → useDevice takes the client path.
89
- // It should use navigator.userAgent (same mechanism as server-side)
90
- // to ensure consistent values between SSR and hydration.
91
- // jsdom's navigator.userAgent is a desktop-like string.
92
- const device = useDevice();
93
- const expected = detectDevice(navigator.userAgent);
94
- expect(device).toBe(expected);
95
- });
96
-
97
- it("returns consistent result with detectDevice(navigator.userAgent)", () => {
98
- // This is the key SSR/hydration consistency check:
99
- // server calls detectDevice(req.headers["user-agent"])
100
- // client calls detectDevice(navigator.userAgent)
101
- // Both use the same detectDevice() function → same result for same UA.
102
- const clientResult = useDevice();
103
- const directResult = detectDevice(navigator.userAgent);
104
- expect(clientResult).toBe(directResult);
105
- });
106
- });
107
-
108
- describe("DeviceProvider seeds useDevice() with the serialized value (#278)", () => {
109
- function Probe() {
110
- // Inside a render, useDevice() reads DeviceContext — this is the path that
111
- // makes hydration stable when the value comes from the page loader.
112
- return createElement("span", null, useDevice());
113
- }
114
-
115
- it("useDevice() returns the provider value, overriding runtime detection", () => {
116
- // jsdom's navigator is desktop-like, so a "tablet" result can only come
117
- // from the provider value (the server-resolved device), not runtime.
118
- const html = renderToStaticMarkup(
119
- createElement(DeviceProvider, { value: "tablet", children: createElement(Probe) }),
120
- );
121
- expect(html).toBe("<span>tablet</span>");
122
- });
123
-
124
- it("falls back to runtime resolution when no value is provided", () => {
125
- const html = renderToStaticMarkup(
126
- createElement(DeviceProvider, { children: createElement(Probe) }),
127
- );
128
- expect(html).toBe(`<span>${detectDevice(navigator.userAgent)}</span>`);
129
- });
130
- });
@@ -1,128 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
- import {
3
- HTMX_LEGACY_URL,
4
- inlineScript,
5
- usePartialSection,
6
- useScript,
7
- useSection,
8
- } from "./useScript";
9
-
10
- describe("inlineScript", () => {
11
- it("returns dangerouslySetInnerHTML with the provided string", () => {
12
- const result = inlineScript('alert("hello")');
13
- expect(result).toEqual({
14
- dangerouslySetInnerHTML: { __html: 'alert("hello")' },
15
- });
16
- });
17
-
18
- it("handles empty string", () => {
19
- const result = inlineScript("");
20
- expect(result).toEqual({
21
- dangerouslySetInnerHTML: { __html: "" },
22
- });
23
- });
24
-
25
- it("handles multiline scripts", () => {
26
- const js = `
27
- const el = document.getElementById("btn");
28
- el.addEventListener("click", () => { console.log("clicked"); });
29
- `;
30
- const result = inlineScript(js);
31
- expect(result.dangerouslySetInnerHTML.__html).toBe(js);
32
- });
33
- });
34
-
35
- describe("useScript", () => {
36
- it("serializes a function into an IIFE string", () => {
37
- function greet(name: string) {
38
- console.log(name);
39
- }
40
- const result = useScript(greet, "world");
41
- expect(result).toContain("(");
42
- expect(result).toContain('"world"');
43
- expect(result).toContain("console.log");
44
- });
45
-
46
- it("serializes multiple arguments", () => {
47
- function add(a: number, b: number) {
48
- return a + b;
49
- }
50
- const result = useScript(add, 1, 2);
51
- expect(result).toContain("1,2");
52
- });
53
-
54
- it("handles functions with no arguments", () => {
55
- function noop() {}
56
- const result = useScript(noop);
57
- expect(result).toMatch(/^\(.*\)\(\)$/);
58
- });
59
- });
60
-
61
- // ---------------------------------------------------------------------------
62
- // Legacy HTMX stubs — useSection / usePartialSection
63
- // ---------------------------------------------------------------------------
64
-
65
- describe("useSection / usePartialSection (legacy HTMX stubs)", () => {
66
- let warnSpy: ReturnType<typeof vi.spyOn>;
67
- let prevNodeEnv: string | undefined;
68
-
69
- beforeEach(() => {
70
- // Reset the dedup set so each test sees a fresh warning fire.
71
- delete (globalThis as any).__DECO_LEGACY_HTMX_WARNED;
72
- prevNodeEnv = process.env.NODE_ENV;
73
- process.env.NODE_ENV = "development";
74
- warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
75
- });
76
-
77
- afterEach(() => {
78
- warnSpy.mockRestore();
79
- if (prevNodeEnv === undefined) delete process.env.NODE_ENV;
80
- else process.env.NODE_ENV = prevNodeEnv;
81
- });
82
-
83
- it("useSection returns a stable placeholder URL instead of throwing", () => {
84
- expect(useSection()).toBe(HTMX_LEGACY_URL);
85
- expect(useSection({ props: { x: 1 } })).toBe(HTMX_LEGACY_URL);
86
- });
87
-
88
- it("usePartialSection returns the same placeholder URL", () => {
89
- expect(usePartialSection()).toBe(HTMX_LEGACY_URL);
90
- });
91
-
92
- it("warns on first call (in development)", () => {
93
- useSection();
94
- expect(warnSpy).toHaveBeenCalledTimes(1);
95
- expect(warnSpy.mock.calls[0][0]).toMatch(/useSection/);
96
- expect(warnSpy.mock.calls[0][0]).toMatch(/were removed/);
97
- expect(warnSpy.mock.calls[0][0]).toMatch(/htmx-residue/);
98
- });
99
-
100
- it("dedups warnings: a second call to the same stub is silent", () => {
101
- useSection();
102
- useSection();
103
- useSection();
104
- expect(warnSpy).toHaveBeenCalledTimes(1);
105
- });
106
-
107
- it("tracks warnings per-stub: useSection and usePartialSection warn independently", () => {
108
- useSection();
109
- usePartialSection();
110
- expect(warnSpy).toHaveBeenCalledTimes(2);
111
- const messages = warnSpy.mock.calls.map((c) => c[0] as string);
112
- expect(messages.some((m) => m.includes("useSection"))).toBe(true);
113
- expect(messages.some((m) => m.includes("usePartialSection"))).toBe(true);
114
- });
115
-
116
- it("does NOT warn in production", () => {
117
- process.env.NODE_ENV = "production";
118
- useSection();
119
- usePartialSection();
120
- expect(warnSpy).not.toHaveBeenCalled();
121
- });
122
-
123
- it("returns the placeholder URL even in production (still safe to embed)", () => {
124
- process.env.NODE_ENV = "production";
125
- expect(useSection()).toBe(HTMX_LEGACY_URL);
126
- expect(usePartialSection()).toBe(HTMX_LEGACY_URL);
127
- });
128
- });
@@ -1,230 +0,0 @@
1
- /**
2
- * Tests for the `createUseSuggestions` factory.
3
- *
4
- * The hook itself depends on React (useCallback). This file exercises
5
- * the parts of the factory that don't need a React renderer:
6
- * - factory shape + isolation between calls
7
- * - the non-React `_internal.setQuery` flow which carries every bit
8
- * of behaviour the React hook delegates to (queue, cancel guard,
9
- * loading-flag invariants, error path)
10
- *
11
- * Hook-level integration is exercised by the site-level smoke (the
12
- * factory has shipped to two production sites with the same shape).
13
- */
14
-
15
- import { describe, expect, it, vi } from "vitest";
16
- import { createUseSuggestions } from "./useSuggestions";
17
-
18
- interface FakeSuggestion {
19
- products: string[];
20
- }
21
-
22
- const FAKE_LOADER = {
23
- __resolveType: "site/loaders/search/suggestions.ts",
24
- limit: 5,
25
- } as unknown as FakeSuggestion;
26
-
27
- function makeOkFetch(payload: unknown, delayMs = 0): typeof fetch {
28
- return ((_input: RequestInfo | URL, _init?: RequestInit) =>
29
- new Promise((resolve) => {
30
- setTimeout(
31
- () =>
32
- resolve(
33
- new Response(JSON.stringify(payload), {
34
- status: 200,
35
- headers: { "Content-Type": "application/json" },
36
- }),
37
- ),
38
- delayMs,
39
- );
40
- })) as typeof fetch;
41
- }
42
-
43
- describe("createUseSuggestions — factory shape", () => {
44
- it("returns useSuggestions + _internal", () => {
45
- const f = createUseSuggestions<FakeSuggestion>();
46
- expect(typeof f.useSuggestions).toBe("function");
47
- expect(typeof f._internal.setQuery).toBe("function");
48
- expect(typeof f._internal.drain).toBe("function");
49
- expect(f._internal.payload.value).toBeNull();
50
- expect(f._internal.loading.value).toBe(false);
51
- });
52
-
53
- it("two factory calls produce independent state + functions", () => {
54
- const a = createUseSuggestions<FakeSuggestion>();
55
- const b = createUseSuggestions<FakeSuggestion>();
56
- expect(a.useSuggestions).not.toBe(b.useSuggestions);
57
- expect(a._internal.payload).not.toBe(b._internal.payload);
58
- expect(a._internal.loading).not.toBe(b._internal.loading);
59
- });
60
- });
61
-
62
- describe("createUseSuggestions — fetch happy path", () => {
63
- it("posts to /deco/invoke/<__resolveType> with the query + extra props", async () => {
64
- const spy = vi.fn(makeOkFetch({ products: ["a", "b"] }));
65
- const f = createUseSuggestions<FakeSuggestion>({ fetchImpl: spy });
66
- f._internal.setQuery("samsung", FAKE_LOADER);
67
- await f._internal.drain();
68
-
69
- expect(spy).toHaveBeenCalledTimes(1);
70
- const [url, init] = spy.mock.calls[0];
71
- expect(url).toBe("/deco/invoke/site/loaders/search/suggestions.ts");
72
- expect(init?.method).toBe("POST");
73
- expect(JSON.parse(init?.body as string)).toEqual({
74
- query: "samsung",
75
- limit: 5,
76
- });
77
- });
78
-
79
- it("populates payload with the parsed response", async () => {
80
- const f = createUseSuggestions<FakeSuggestion>({
81
- fetchImpl: makeOkFetch({ products: ["a", "b"] }),
82
- });
83
- f._internal.setQuery("samsung", FAKE_LOADER);
84
- await f._internal.drain();
85
- expect(f._internal.payload.value).toEqual({ products: ["a", "b"] });
86
- });
87
-
88
- it("flips loading to true synchronously, back to false after fetch settles", async () => {
89
- const f = createUseSuggestions<FakeSuggestion>({
90
- fetchImpl: makeOkFetch({ products: [] }),
91
- });
92
- expect(f._internal.loading.value).toBe(false);
93
- f._internal.setQuery("hi", FAKE_LOADER);
94
- expect(f._internal.loading.value).toBe(true);
95
- await f._internal.drain();
96
- expect(f._internal.loading.value).toBe(false);
97
- });
98
- });
99
-
100
- describe("createUseSuggestions — cancel + queue semantics", () => {
101
- it("cancels older queries BEFORE they fetch — only the latest hits the network", async () => {
102
- // Mock echoes the body's `query` field so we can tell which
103
- // invocation actually reached the network.
104
- const calls: string[] = [];
105
- const fetchImpl: typeof fetch = ((_url, init) => {
106
- const body = JSON.parse(init?.body as string) as { query: string };
107
- calls.push(body.query);
108
- return Promise.resolve(
109
- new Response(JSON.stringify({ products: [body.query] }), {
110
- status: 200,
111
- }),
112
- );
113
- }) as typeof fetch;
114
-
115
- const f = createUseSuggestions<FakeSuggestion>({ fetchImpl });
116
- // Three queries kicked off back-to-back synchronously.
117
- f._internal.setQuery("a", FAKE_LOADER);
118
- f._internal.setQuery("b", FAKE_LOADER);
119
- f._internal.setQuery("c", FAKE_LOADER);
120
- await f._internal.drain();
121
-
122
- // Only the latest query reaches the network — the cancel
123
- // guard short-circuits the first two before they fetch.
124
- expect(calls).toEqual(["c"]);
125
- expect(f._internal.payload.value).toEqual({ products: ["c"] });
126
- });
127
-
128
- it("the latest-query guard prevents stale fetches from clearing loading prematurely", async () => {
129
- // If the cancel guard ever regresses, this is the test that
130
- // catches it: we kick off fetch #1, immediately call setQuery
131
- // again, await drain, and expect the FINAL state to reflect
132
- // the latest query — not an inconsistent "loading false but
133
- // payload stale" mid-state.
134
- const fetchImpl = makeOkFetch({ products: ["latest"] }, 5);
135
- const f = createUseSuggestions<FakeSuggestion>({ fetchImpl });
136
- f._internal.setQuery("a", FAKE_LOADER);
137
- f._internal.setQuery("b", FAKE_LOADER);
138
- f._internal.setQuery("c", FAKE_LOADER);
139
- await f._internal.drain();
140
- expect(f._internal.loading.value).toBe(false);
141
- expect(f._internal.payload.value).toEqual({ products: ["latest"] });
142
- });
143
-
144
- it("queues serially — fetches don't run concurrently", async () => {
145
- // Race detector: track whether the count of in-flight fetches
146
- // ever exceeds 1.
147
- let inflight = 0;
148
- let maxInflight = 0;
149
- const fetchImpl: typeof fetch = (() =>
150
- new Promise<Response>((resolve) => {
151
- inflight += 1;
152
- maxInflight = Math.max(maxInflight, inflight);
153
- setTimeout(() => {
154
- inflight -= 1;
155
- resolve(
156
- new Response(JSON.stringify({ products: [] }), { status: 200 }),
157
- );
158
- }, 5);
159
- })) as typeof fetch;
160
-
161
- const f = createUseSuggestions<FakeSuggestion>({ fetchImpl });
162
- f._internal.setQuery("a", FAKE_LOADER);
163
- f._internal.setQuery("b", FAKE_LOADER);
164
- f._internal.setQuery("c", FAKE_LOADER);
165
- await f._internal.drain();
166
- expect(maxInflight).toBe(1);
167
- });
168
- });
169
-
170
- describe("createUseSuggestions — error path", () => {
171
- it("forwards thrown errors to onError + console.error, does NOT update payload", async () => {
172
- const onError = vi.fn();
173
- const consoleError = vi
174
- .spyOn(console, "error")
175
- .mockImplementation(() => {});
176
-
177
- const fetchImpl = (() =>
178
- Promise.reject(new Error("network down"))) as typeof fetch;
179
- const f = createUseSuggestions<FakeSuggestion>({ fetchImpl, onError });
180
-
181
- f._internal.setQuery("samsung", FAKE_LOADER);
182
- await f._internal.drain();
183
-
184
- expect(onError).toHaveBeenCalledTimes(1);
185
- const [err, query] = onError.mock.calls[0];
186
- expect((err as Error).message).toBe("network down");
187
- expect(query).toBe("samsung");
188
- expect(consoleError).toHaveBeenCalled();
189
- expect(f._internal.payload.value).toBeNull();
190
- expect(f._internal.loading.value).toBe(false);
191
-
192
- consoleError.mockRestore();
193
- });
194
-
195
- it("non-2xx responses surface as errors", async () => {
196
- const onError = vi.fn();
197
- const consoleError = vi
198
- .spyOn(console, "error")
199
- .mockImplementation(() => {});
200
- const fetchImpl = (() =>
201
- Promise.resolve(
202
- new Response("internal error", { status: 500 }),
203
- )) as typeof fetch;
204
- const f = createUseSuggestions<FakeSuggestion>({ fetchImpl, onError });
205
-
206
- f._internal.setQuery("x", FAKE_LOADER);
207
- await f._internal.drain();
208
-
209
- expect(onError).toHaveBeenCalledTimes(1);
210
- expect((onError.mock.calls[0][0] as Error).message).toContain("500");
211
- expect(f._internal.payload.value).toBeNull();
212
- expect(f._internal.loading.value).toBe(false);
213
-
214
- consoleError.mockRestore();
215
- });
216
-
217
- it("does NOT throw if onError is omitted (still console.errors)", async () => {
218
- const consoleError = vi
219
- .spyOn(console, "error")
220
- .mockImplementation(() => {});
221
- const fetchImpl = (() =>
222
- Promise.reject(new Error("boom"))) as typeof fetch;
223
- const f = createUseSuggestions<FakeSuggestion>({ fetchImpl });
224
-
225
- f._internal.setQuery("x", FAKE_LOADER);
226
- await expect(f._internal.drain()).resolves.toBeUndefined();
227
- expect(consoleError).toHaveBeenCalled();
228
- consoleError.mockRestore();
229
- });
230
- });
package/tsconfig.json DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.base.json",
3
- "compilerOptions": {
4
- "outDir": "dist"
5
- },
6
- "include": ["src/**/*", "package.json"]
7
- }