@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,474 +0,0 @@
1
- /**
2
- * Phase 3 (D-12) coverage for the direct-POST OTLP trace exporter.
3
- * Mirrors the test style of `otelHttpMeter.test.ts` — fake fetch,
4
- * deterministic clock, deterministic IDs via injected accessors.
5
- */
6
- import { describe, expect, it, vi } from "vitest";
7
- import type { Span } from "../middleware/observability";
8
- import {
9
- createOtlpHttpTracerAdapter,
10
- newSpanId,
11
- newTraceId,
12
- parseTraceparent,
13
- shouldSampleTrace,
14
- type TraceContext,
15
- } from "./otelHttpTracer";
16
-
17
- // ---------------------------------------------------------------------------
18
- // Helpers — capture fetch & emulate active-span propagation
19
- // ---------------------------------------------------------------------------
20
-
21
- function captureFetch(): {
22
- fetchImpl: typeof fetch;
23
- calls: Array<{ url: string; payload: Record<string, unknown> }>;
24
- } {
25
- const calls: Array<{ url: string; payload: Record<string, unknown> }> = [];
26
- const fetchImpl: typeof fetch = async (input, init) => {
27
- const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
28
- const body = init?.body as string | undefined;
29
- calls.push({ url, payload: body ? JSON.parse(body) : {} });
30
- return new Response("", { status: 200 });
31
- };
32
- return { fetchImpl, calls };
33
- }
34
-
35
- /**
36
- * Build a minimal active-span scope helper. Tests can push a parent
37
- * span before calling `startSpan`, simulating what `withTracing` does
38
- * via ALS.
39
- */
40
- function activeSpanStack(): {
41
- push(span: Span): void;
42
- pop(): void;
43
- get(): Span | null;
44
- } {
45
- const stack: Span[] = [];
46
- return {
47
- push(span) {
48
- stack.push(span);
49
- },
50
- pop() {
51
- stack.pop();
52
- },
53
- get() {
54
- return stack[stack.length - 1] ?? null;
55
- },
56
- };
57
- }
58
-
59
- // ---------------------------------------------------------------------------
60
- // parseTraceparent
61
- // ---------------------------------------------------------------------------
62
-
63
- describe("parseTraceparent (D-12)", () => {
64
- it("parses a well-formed sampled header", () => {
65
- const ctx = parseTraceparent("00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01");
66
- expect(ctx).toEqual({
67
- traceId: "0af7651916cd43dd8448eb211c80319c",
68
- parentSpanId: "b7ad6b7169203331",
69
- sampled: true,
70
- remoteParent: true,
71
- });
72
- });
73
-
74
- it("parses a well-formed unsampled header", () => {
75
- const ctx = parseTraceparent("00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-00");
76
- expect(ctx?.sampled).toBe(false);
77
- });
78
-
79
- it("returns null on null / undefined / empty string", () => {
80
- expect(parseTraceparent(null)).toBeNull();
81
- expect(parseTraceparent(undefined)).toBeNull();
82
- expect(parseTraceparent("")).toBeNull();
83
- });
84
-
85
- it("rejects unknown versions", () => {
86
- expect(parseTraceparent("01-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01")).toBeNull();
87
- });
88
-
89
- it("rejects the well-known all-zero IDs (per W3C §3.2.2)", () => {
90
- expect(
91
- parseTraceparent("00-00000000000000000000000000000000-b7ad6b7169203331-01"),
92
- ).toBeNull();
93
- expect(
94
- parseTraceparent("00-0af7651916cd43dd8448eb211c80319c-0000000000000000-01"),
95
- ).toBeNull();
96
- });
97
-
98
- it("rejects malformed lengths and non-hex characters", () => {
99
- expect(parseTraceparent("00-tooshort-b7ad6b7169203331-01")).toBeNull();
100
- expect(parseTraceparent("00-zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz-b7ad6b7169203331-01")).toBeNull();
101
- });
102
- });
103
-
104
- // ---------------------------------------------------------------------------
105
- // shouldSampleTrace — consistency + boundary cases
106
- // ---------------------------------------------------------------------------
107
-
108
- describe("shouldSampleTrace (D-12)", () => {
109
- it("returns true for rate >= 1 (always sample)", () => {
110
- expect(shouldSampleTrace("0".repeat(31) + "1", 1)).toBe(true);
111
- expect(shouldSampleTrace("0".repeat(31) + "1", 5)).toBe(true);
112
- expect(shouldSampleTrace("0".repeat(31) + "1", Infinity)).toBe(true);
113
- });
114
-
115
- it("returns false for rate <= 0 (never sample)", () => {
116
- expect(shouldSampleTrace("0".repeat(31) + "1", 0)).toBe(false);
117
- expect(shouldSampleTrace("0".repeat(31) + "1", -1)).toBe(false);
118
- });
119
-
120
- it("decisions are stable per trace ID (called twice → same answer)", () => {
121
- const traceId = newTraceId();
122
- const first = shouldSampleTrace(traceId, 0.1);
123
- const second = shouldSampleTrace(traceId, 0.1);
124
- expect(first).toBe(second);
125
- });
126
-
127
- it("approximates the configured rate over a large sample", () => {
128
- // 5000 random trace IDs sampled at 10% should land within ±3% of
129
- // the target — bounded statistical noise, deterministic seed not
130
- // required because `Math.random` flakes here would already
131
- // indicate a broken hash.
132
- const trials = 5000;
133
- let kept = 0;
134
- for (let i = 0; i < trials; i++) {
135
- if (shouldSampleTrace(newTraceId(), 0.1)) kept++;
136
- }
137
- const observed = kept / trials;
138
- expect(observed).toBeGreaterThan(0.07);
139
- expect(observed).toBeLessThan(0.13);
140
- });
141
- });
142
-
143
- // ---------------------------------------------------------------------------
144
- // ID generation — shape only (entropy depends on crypto.getRandomValues)
145
- // ---------------------------------------------------------------------------
146
-
147
- describe("newTraceId / newSpanId (D-12)", () => {
148
- it("returns 32-hex-char trace IDs and 16-hex-char span IDs", () => {
149
- expect(newTraceId()).toMatch(/^[0-9a-f]{32}$/);
150
- expect(newSpanId()).toMatch(/^[0-9a-f]{16}$/);
151
- });
152
- it("does not repeat over 100 calls", () => {
153
- const set = new Set<string>();
154
- for (let i = 0; i < 100; i++) set.add(newTraceId());
155
- expect(set.size).toBe(100);
156
- });
157
- });
158
-
159
- // ---------------------------------------------------------------------------
160
- // Adapter — startSpan / end / flush
161
- // ---------------------------------------------------------------------------
162
-
163
- describe("createOtlpHttpTracerAdapter (D-12)", () => {
164
- it("buffers a root span and POSTs OTLP payload on flush", async () => {
165
- const { fetchImpl, calls } = captureFetch();
166
- const stack = activeSpanStack();
167
- let clock = 100;
168
-
169
- const tracer = createOtlpHttpTracerAdapter({
170
- endpoint: "https://collector.example/v1/traces",
171
- resourceAttributes: { "service.name": "test-site" },
172
- headSamplingRate: 1,
173
- minFlushIntervalMs: 0,
174
- fetchImpl,
175
- nowMs: () => clock,
176
- getActiveSpanForParent: () => stack.get(),
177
- });
178
-
179
- const span = tracer.startSpan("deco.http.request", { "http.method": "GET" });
180
- clock = 250;
181
- span.setAttribute?.("http.status_code", 200);
182
- span.end();
183
-
184
- expect(tracer.pendingSpanCount()).toBe(1);
185
- await tracer.flush();
186
- expect(tracer.pendingSpanCount()).toBe(0);
187
- expect(calls).toHaveLength(1);
188
-
189
- const resourceSpans = (calls[0].payload as { resourceSpans: unknown[] }).resourceSpans as Array<{
190
- resource: { attributes: Array<{ key: string; value: { stringValue: string } }> };
191
- scopeSpans: Array<{
192
- spans: Array<{
193
- name: string;
194
- traceId: string;
195
- spanId: string;
196
- parentSpanId: string;
197
- startTimeUnixNano: string;
198
- endTimeUnixNano: string;
199
- attributes: Array<{ key: string; value: unknown }>;
200
- status: { code: number };
201
- }>;
202
- }>;
203
- }>;
204
- const rs = resourceSpans[0];
205
- expect(rs.resource.attributes).toContainEqual({
206
- key: "service.name",
207
- value: { stringValue: "test-site" },
208
- });
209
- const spans = rs.scopeSpans[0].spans;
210
- expect(spans).toHaveLength(1);
211
- expect(spans[0].name).toBe("deco.http.request");
212
- expect(spans[0].traceId).toMatch(/^[0-9a-f]{32}$/);
213
- expect(spans[0].spanId).toMatch(/^[0-9a-f]{16}$/);
214
- expect(spans[0].parentSpanId).toBe("");
215
- // 200 status_code → status.code = OK (1)
216
- expect(spans[0].status.code).toBe(1);
217
- });
218
-
219
- it("inherits trace ID from the active parent span", async () => {
220
- const { fetchImpl, calls } = captureFetch();
221
- const stack = activeSpanStack();
222
- const tracer = createOtlpHttpTracerAdapter({
223
- endpoint: "https://collector.example/v1/traces",
224
- resourceAttributes: {},
225
- headSamplingRate: 1,
226
- minFlushIntervalMs: 0,
227
- fetchImpl,
228
- getActiveSpanForParent: () => stack.get(),
229
- });
230
-
231
- const parent = tracer.startSpan("deco.http.request");
232
- stack.push(parent);
233
- const child = tracer.startSpan("deco.cache.lookup");
234
- stack.pop();
235
-
236
- const parentCtx = parent.spanContext?.();
237
- const childCtx = child.spanContext?.();
238
- expect(childCtx?.traceId).toBe(parentCtx?.traceId);
239
- expect(childCtx?.spanId).not.toBe(parentCtx?.spanId);
240
-
241
- child.end();
242
- parent.end();
243
- await tracer.flush();
244
-
245
- const payload = calls[0].payload as { resourceSpans: Array<{ scopeSpans: Array<{ spans: Array<{
246
- name: string;
247
- parentSpanId: string;
248
- spanId: string;
249
- }> }> }> };
250
- const spans = payload.resourceSpans[0].scopeSpans[0].spans;
251
- const childRow = spans.find((s) => s.name === "deco.cache.lookup");
252
- const parentRow = spans.find((s) => s.name === "deco.http.request");
253
- expect(childRow?.parentSpanId).toBe(parentRow?.spanId);
254
- });
255
-
256
- it("honors an inbound W3C traceparent for root spans", async () => {
257
- const { fetchImpl } = captureFetch();
258
- const stack = activeSpanStack();
259
- const remote: TraceContext = {
260
- traceId: "0af7651916cd43dd8448eb211c80319c",
261
- parentSpanId: "b7ad6b7169203331",
262
- sampled: true,
263
- remoteParent: true,
264
- };
265
- const tracer = createOtlpHttpTracerAdapter({
266
- endpoint: "https://collector.example/v1/traces",
267
- resourceAttributes: {},
268
- headSamplingRate: 0, // would normally drop everything
269
- minFlushIntervalMs: 0,
270
- fetchImpl,
271
- getActiveSpanForParent: () => stack.get(),
272
- getRequestTraceContext: () => remote,
273
- });
274
-
275
- const root = tracer.startSpan("deco.http.request");
276
- const ctx = root.spanContext?.();
277
- expect(ctx?.traceId).toBe(remote.traceId);
278
- // parentSpanId from the remote should appear on the OTLP record
279
- root.end();
280
-
281
- // Even at samplingRate=0, the remote `sampled=true` overrides and
282
- // keeps this span.
283
- expect(tracer.pendingSpanCount()).toBe(1);
284
- });
285
-
286
- it("drops spans deterministically when samplingRate=0 and no remote sample bit", async () => {
287
- const stack = activeSpanStack();
288
- const tracer = createOtlpHttpTracerAdapter({
289
- endpoint: "https://collector.example/v1/traces",
290
- resourceAttributes: {},
291
- headSamplingRate: 0,
292
- minFlushIntervalMs: 0,
293
- fetchImpl: vi.fn() as unknown as typeof fetch,
294
- getActiveSpanForParent: () => stack.get(),
295
- });
296
- const span = tracer.startSpan("deco.http.request");
297
- span.end();
298
- expect(tracer.pendingSpanCount()).toBe(0);
299
- });
300
-
301
- it("captures setError as an OTLP exception event", async () => {
302
- const { fetchImpl, calls } = captureFetch();
303
- const stack = activeSpanStack();
304
- const tracer = createOtlpHttpTracerAdapter({
305
- endpoint: "https://collector.example/v1/traces",
306
- resourceAttributes: {},
307
- headSamplingRate: 1,
308
- minFlushIntervalMs: 0,
309
- fetchImpl,
310
- getActiveSpanForParent: () => stack.get(),
311
- });
312
- const span = tracer.startSpan("deco.cache.lookup");
313
- span.setError?.(new TypeError("boom"));
314
- span.end();
315
- await tracer.flush();
316
-
317
- const payload = calls[0].payload as { resourceSpans: Array<{ scopeSpans: Array<{ spans: Array<{
318
- status: { code: number; message?: string };
319
- events: Array<{ name: string; attributes: Array<{ key: string }> }>;
320
- attributes: Array<{ key: string; value: { stringValue: string } }>;
321
- }> }> }> };
322
- const span0 = payload.resourceSpans[0].scopeSpans[0].spans[0];
323
- expect(span0.status.code).toBe(2);
324
- expect(span0.status.message).toBe("boom");
325
- expect(span0.events[0].name).toBe("exception");
326
- expect(span0.attributes.find((a) => a.key === "exception.type")?.value.stringValue).toBe(
327
- "TypeError",
328
- );
329
- });
330
-
331
- it("setAttribute http.status_code >= 400 promotes span to ERROR", async () => {
332
- const { fetchImpl, calls } = captureFetch();
333
- const stack = activeSpanStack();
334
- const tracer = createOtlpHttpTracerAdapter({
335
- endpoint: "https://collector.example/v1/traces",
336
- resourceAttributes: {},
337
- headSamplingRate: 1,
338
- minFlushIntervalMs: 0,
339
- fetchImpl,
340
- getActiveSpanForParent: () => stack.get(),
341
- });
342
-
343
- for (const status of [400, 429, 500, 503]) {
344
- const span = tracer.startSpan("vtex.catalog.search");
345
- span.setAttribute?.("http.status_code", status);
346
- span.end();
347
- }
348
- await tracer.flush();
349
-
350
- const spans = (calls[0].payload as { resourceSpans: Array<{ scopeSpans: Array<{ spans: Array<{ status: { code: number; message: string } }> }> }> })
351
- .resourceSpans[0].scopeSpans[0].spans;
352
- for (const span of spans) {
353
- // ERROR = 2
354
- expect(span.status.code).toBe(2);
355
- expect(span.status.message).toMatch(/^HTTP (400|429|500|503)$/);
356
- }
357
- });
358
-
359
- it("setAttribute http.status_code < 400 does not overwrite an existing ERROR status", async () => {
360
- const { fetchImpl, calls } = captureFetch();
361
- const stack = activeSpanStack();
362
- const tracer = createOtlpHttpTracerAdapter({
363
- endpoint: "https://collector.example/v1/traces",
364
- resourceAttributes: {},
365
- headSamplingRate: 1,
366
- minFlushIntervalMs: 0,
367
- fetchImpl,
368
- getActiveSpanForParent: () => stack.get(),
369
- });
370
-
371
- const span = tracer.startSpan("deco.cache.lookup");
372
- span.setError?.(new Error("internal failure"));
373
- // A 200 attribute set afterwards should not clear the ERROR status
374
- span.setAttribute?.("http.status_code", 200);
375
- span.end();
376
- await tracer.flush();
377
-
378
- const span0 = (calls[0].payload as { resourceSpans: Array<{ scopeSpans: Array<{ spans: Array<{ status: { code: number } }> }> }> })
379
- .resourceSpans[0].scopeSpans[0].spans[0];
380
- expect(span0.status.code).toBe(2);
381
- });
382
-
383
- it("flush is a no-op when the buffer is empty", async () => {
384
- const fetchImpl = vi.fn() as unknown as typeof fetch;
385
- const stack = activeSpanStack();
386
- const tracer = createOtlpHttpTracerAdapter({
387
- endpoint: "https://collector.example/v1/traces",
388
- resourceAttributes: {},
389
- headSamplingRate: 1,
390
- minFlushIntervalMs: 0,
391
- fetchImpl,
392
- getActiveSpanForParent: () => stack.get(),
393
- });
394
- await tracer.flush();
395
- expect(fetchImpl).not.toHaveBeenCalled();
396
- });
397
-
398
- it("respects the cooldown — second flush within window is skipped", async () => {
399
- const { fetchImpl, calls } = captureFetch();
400
- const stack = activeSpanStack();
401
- // Use wall-clock-realistic values: `lastFlushAt` starts at 0, so the
402
- // first flush's `elapsed` needs to exceed `minFlushIntervalMs` to
403
- // get through. That's always true in production where `now() =
404
- // Date.now() ~= 1.7e12`; we model that by starting the fake clock
405
- // at the same scale.
406
- let clock = 1_000_000_000_000;
407
- const tracer = createOtlpHttpTracerAdapter({
408
- endpoint: "https://collector.example/v1/traces",
409
- resourceAttributes: {},
410
- headSamplingRate: 1,
411
- minFlushIntervalMs: 5000,
412
- fetchImpl,
413
- nowMs: () => clock,
414
- getActiveSpanForParent: () => stack.get(),
415
- });
416
- const a = tracer.startSpan("a");
417
- a.end();
418
- clock += 100;
419
- await tracer.flush();
420
- expect(calls).toHaveLength(1);
421
-
422
- const b = tracer.startSpan("b");
423
- b.end();
424
- clock += 100; // 200ms after first flush — still within 5s cooldown
425
- await tracer.flush();
426
- expect(calls).toHaveLength(1); // still one — cooldown blocked it
427
- expect(tracer.pendingSpanCount()).toBe(1);
428
-
429
- clock += 10_000; // past cooldown
430
- await tracer.flush();
431
- expect(calls).toHaveLength(2);
432
- });
433
-
434
- it("calls onError when the buffer overflows", async () => {
435
- const stack = activeSpanStack();
436
- const onError = vi.fn();
437
- const tracer = createOtlpHttpTracerAdapter({
438
- endpoint: "https://collector.example/v1/traces",
439
- resourceAttributes: {},
440
- headSamplingRate: 1,
441
- minFlushIntervalMs: 0,
442
- maxBufferSpans: 2,
443
- fetchImpl: (async () => new Response("", { status: 200 })) as typeof fetch,
444
- getActiveSpanForParent: () => stack.get(),
445
- onError,
446
- });
447
- for (let i = 0; i < 5; i++) {
448
- const s = tracer.startSpan(`s${i}`);
449
- s.end();
450
- }
451
- expect(onError).toHaveBeenCalled();
452
- expect(onError.mock.calls[0][0]).toBe("overflow");
453
- });
454
-
455
- it("calls onError on flush failure (non-2xx)", async () => {
456
- const stack = activeSpanStack();
457
- const onError = vi.fn();
458
- const fetchImpl: typeof fetch = async () => new Response("server explosion", { status: 503 });
459
- const tracer = createOtlpHttpTracerAdapter({
460
- endpoint: "https://collector.example/v1/traces",
461
- resourceAttributes: {},
462
- headSamplingRate: 1,
463
- minFlushIntervalMs: 0,
464
- fetchImpl,
465
- getActiveSpanForParent: () => stack.get(),
466
- onError,
467
- });
468
- const s = tracer.startSpan("x");
469
- s.end();
470
- await tracer.flush();
471
- expect(onError).toHaveBeenCalled();
472
- expect(onError.mock.calls[0][0]).toBe("flush");
473
- });
474
- });