@decocms/blocks 8.1.0-next.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 (114) hide show
  1. package/package.json +6 -92
  2. package/src/index.ts +2 -12
  3. package/src/protocol/storage/memory.ts +1 -1
  4. package/src/v8/background.ts +3 -3
  5. package/src/v8/builtins/legacy.ts +1 -1
  6. package/src/v8/cli/index.ts +1 -1
  7. package/src/v8/fetch.ts +8 -27
  8. package/src/v8/remoteLoader.ts +1 -1
  9. package/src/v8/telemetry.ts +1 -1
  10. package/src/cms/applySectionConventions.ts +0 -148
  11. package/src/cms/blockSource.ts +0 -228
  12. package/src/cms/client.ts +0 -85
  13. package/src/cms/deferredTrigger.ts +0 -58
  14. package/src/cms/draftSource.ts +0 -476
  15. package/src/cms/index.ts +0 -180
  16. package/src/cms/loadDecofileDirectory.ts +0 -89
  17. package/src/cms/loader.ts +0 -563
  18. package/src/cms/registry.ts +0 -264
  19. package/src/cms/renderJson.ts +0 -179
  20. package/src/cms/resolve.ts +0 -2583
  21. package/src/cms/schema.ts +0 -1219
  22. package/src/cms/sectionLoaderContext.ts +0 -113
  23. package/src/cms/sectionLoaders.ts +0 -686
  24. package/src/cms/sectionMixins.ts +0 -153
  25. package/src/flags/audience.ts +0 -56
  26. package/src/flags/everyone.ts +0 -29
  27. package/src/flags/flag.ts +0 -15
  28. package/src/flags/multivariate/image.ts +0 -11
  29. package/src/flags/multivariate/message.ts +0 -11
  30. package/src/flags/multivariate/page.ts +0 -16
  31. package/src/flags/multivariate/section.ts +0 -16
  32. package/src/flags/multivariate.ts +0 -1
  33. package/src/flags/types.ts +0 -59
  34. package/src/flags/utils/multivariate.ts +0 -20
  35. package/src/hooks/Image.tsx +0 -314
  36. package/src/hooks/JsonLd.tsx +0 -353
  37. package/src/hooks/LazySection.tsx +0 -121
  38. package/src/hooks/LiveControls.tsx +0 -144
  39. package/src/hooks/Picture.tsx +0 -127
  40. package/src/hooks/RenderSection.tsx +0 -91
  41. package/src/hooks/SectionErrorFallback.tsx +0 -97
  42. package/src/hooks/Stats.tsx +0 -134
  43. package/src/hooks/index.ts +0 -35
  44. package/src/hooks/useLoadMore.ts +0 -100
  45. package/src/matchers/builtins.ts +0 -459
  46. package/src/matchers/countryNames.ts +0 -104
  47. package/src/matchers/override.ts +0 -136
  48. package/src/matchers/posthog.ts +0 -154
  49. package/src/middleware/decoState.ts +0 -55
  50. package/src/middleware/healthMetrics.ts +0 -133
  51. package/src/middleware/hydrationContext.ts +0 -79
  52. package/src/middleware/index.ts +0 -88
  53. package/src/middleware/liveness.ts +0 -21
  54. package/src/middleware/observability.ts +0 -800
  55. package/src/middleware/validateSection.ts +0 -100
  56. package/src/preview/DraftPreviewBadge.tsx +0 -306
  57. package/src/preview/decoMark.ts +0 -11
  58. package/src/preview/index.ts +0 -8
  59. package/src/sdk/abTesting.ts +0 -556
  60. package/src/sdk/analytics.ts +0 -147
  61. package/src/sdk/cacheHeaders.ts +0 -633
  62. package/src/sdk/cacheStorage.ts +0 -287
  63. package/src/sdk/cachedLoader.ts +0 -556
  64. package/src/sdk/clx.ts +0 -5
  65. package/src/sdk/cn.ts +0 -28
  66. package/src/sdk/composite.ts +0 -114
  67. package/src/sdk/cookie.ts +0 -129
  68. package/src/sdk/crypto.ts +0 -199
  69. package/src/sdk/csp.ts +0 -59
  70. package/src/sdk/deepOmit.ts +0 -52
  71. package/src/sdk/detectDevice.ts +0 -45
  72. package/src/sdk/djb2.ts +0 -20
  73. package/src/sdk/encoding.ts +0 -44
  74. package/src/sdk/env.ts +0 -54
  75. package/src/sdk/experiments.ts +0 -314
  76. package/src/sdk/fetchCache.ts +0 -269
  77. package/src/sdk/fetchTimeout.ts +0 -58
  78. package/src/sdk/flags.ts +0 -138
  79. package/src/sdk/http.ts +0 -124
  80. package/src/sdk/index.ts +0 -97
  81. package/src/sdk/inflightTimeout.ts +0 -53
  82. package/src/sdk/instrumentedFetch.ts +0 -362
  83. package/src/sdk/invoke.ts +0 -298
  84. package/src/sdk/logger.ts +0 -304
  85. package/src/sdk/mergeCacheControl.ts +0 -150
  86. package/src/sdk/nonce.ts +0 -46
  87. package/src/sdk/normalizeUrls.ts +0 -91
  88. package/src/sdk/observability.ts +0 -116
  89. package/src/sdk/otel.ts +0 -1118
  90. package/src/sdk/otelAdapters/clickhouseCollector.ts +0 -65
  91. package/src/sdk/otelAdapters.ts +0 -144
  92. package/src/sdk/otelHttpLog.ts +0 -419
  93. package/src/sdk/otelHttpMeter.ts +0 -532
  94. package/src/sdk/otelHttpTracer.ts +0 -543
  95. package/src/sdk/redirects.ts +0 -336
  96. package/src/sdk/requestContext.ts +0 -281
  97. package/src/sdk/requestContextStorage.browser.ts +0 -43
  98. package/src/sdk/requestContextStorage.ts +0 -35
  99. package/src/sdk/responseCache.ts +0 -82
  100. package/src/sdk/retry.ts +0 -45
  101. package/src/sdk/serverTimings.ts +0 -68
  102. package/src/sdk/signal.ts +0 -42
  103. package/src/sdk/sitemap.ts +0 -160
  104. package/src/sdk/urlRedaction.ts +0 -82
  105. package/src/sdk/urlUtils.ts +0 -183
  106. package/src/sdk/useDevice.ts +0 -89
  107. package/src/sdk/useDeviceContext.tsx +0 -108
  108. package/src/sdk/useId.ts +0 -7
  109. package/src/sdk/useScript.ts +0 -210
  110. package/src/sdk/useSuggestions.ts +0 -188
  111. package/src/sdk/wrapCaughtErrors.ts +0 -107
  112. package/src/setup.ts +0 -120
  113. package/src/types/index.ts +0 -53
  114. package/src/types/widgets.ts +0 -14
@@ -1,532 +0,0 @@
1
- /**
2
- * OTLP/HTTP JSON metrics exporter — direct POST from a Cloudflare Worker
3
- * to `deco-otel-ingest` `/v1/metrics`.
4
- *
5
- * Why direct POST and not Cloudflare Destinations? CF Destinations supports
6
- * OTLP for `logs` and `traces` only; there is no `observability.metrics`
7
- * block. Metrics travel from the site Worker to the ingestor over a normal
8
- * outbound `fetch`. Sub-requests are free on the paid plan, and the
9
- * ingestor's per-POST charge is captured in the cost model in
10
- * `docs/observability.md`.
11
- *
12
- * **Aggregation model.** Buffers are per-isolate, accumulated forever (until
13
- * the isolate dies), and exported with `AggregationTemporality = CUMULATIVE`
14
- * (matching the `clickhouseexporter` schema used by the ingestor's
15
- * `otel_metrics_{sum,gauge,histogram}` tables).
16
- *
17
- * **Flush triggers.**
18
- * 1. `flush()` — caller-driven, used by `workerEntry` inside
19
- * `ctx.waitUntil(...)` at request end. Throttled by `minFlushIntervalMs`
20
- * per-isolate so a 1000-req/s isolate doesn't fire 1000 POSTs/s.
21
- * 2. Buffer-size cap — when total pending datapoints exceeds
22
- * `maxBufferDatapoints`, the next `flush()` ignores the cooldown.
23
- * 3. Worker isolate shutdown — there is no "before-shutdown" hook on
24
- * Workers; instead, every request's `ctx.waitUntil(flush())` keeps the
25
- * buffer drained to roughly within one cooldown window of real time.
26
- *
27
- * **Data loss profile.** Documented in `docs/observability.md` under
28
- * "Worker isolate lifecycle". Worst case is the cooldown window of
29
- * datapoints lost on isolate teardown — for `minFlushIntervalMs: 5000`,
30
- * that's ≤ 5s of metrics from one isolate. At fleet scale this is well
31
- * under the 0.01% loss budget we agreed on.
32
- */
33
-
34
- import type { MeterAdapter } from "./observability";
35
-
36
- // ---------------------------------------------------------------------------
37
- // Types
38
- // ---------------------------------------------------------------------------
39
-
40
- type Labels = Record<string, string | number | boolean>;
41
-
42
- export interface OtlpHttpMeterOptions {
43
- /** Full OTLP/HTTP JSON metrics endpoint, e.g. `https://.../v1/metrics`. */
44
- endpoint: string;
45
- /** Resource attributes stamped on every OTLP payload (service.name etc.). */
46
- resourceAttributes: Record<string, string>;
47
- /** Scope name advertised in `scopeMetrics[].scope.name`. */
48
- scopeName?: string;
49
- /** Scope version. */
50
- scopeVersion?: string;
51
- /**
52
- * Explicit histogram bounds. Default targets HTTP/sub-fetch latency in ms.
53
- * Datapoints below the first bound land in bucket 0; above the last bound
54
- * in the overflow bucket (length = bounds.length + 1).
55
- */
56
- histogramBounds?: number[];
57
- /** Hard cap on pending datapoints across all metric kinds. Default: 2000. */
58
- maxBufferDatapoints?: number;
59
- /** Cooldown between successful flushes (ms). Default: 5000. */
60
- minFlushIntervalMs?: number;
61
- /** Per-flush HTTP timeout (ms). Default: 5000. */
62
- flushTimeoutMs?: number;
63
- /**
64
- * Extra HTTP headers merged into every OTLP POST (e.g. `Authorization: Bearer …`).
65
- * `Content-Type: application/json` is always set and cannot be overridden here.
66
- */
67
- headers?: Record<string, string>;
68
- /**
69
- * Test seam — override fetch for the flush path so unit tests can
70
- * inspect the OTLP payload without going to the network.
71
- */
72
- fetchImpl?: typeof fetch;
73
- /**
74
- * Test seam — override Date.now() for deterministic timestamps in
75
- * snapshot tests.
76
- */
77
- nowMs?: () => number;
78
- /** Optional sink for transport errors so callers can surface them. */
79
- onError?: (kind: "flush" | "overflow" | "kind-mismatch", err: unknown) => void;
80
- /**
81
- * Per-metric metadata emitted in the OTLP payload's `description` and
82
- * `unit` fields. Looked up by metric name at flush time. Names absent
83
- * from the map flush with empty description/unit (still valid OTLP).
84
- * The framework owns the lookup; callers MUST NOT pass metadata at
85
- * record time. See `MetricNames` / `METRIC_METADATA` in
86
- * `middleware/observability.ts`.
87
- *
88
- * `boundaries`, when present, is ALSO used to bucket that metric, overriding
89
- * the adapter-wide `histogramBounds`. Without this a byte-sized histogram and
90
- * a seconds-valued one would share the single ms-tuned default and both read
91
- * back as a single saturated bucket.
92
- */
93
- metricMetadata?: Record<string, MetricMetadata>;
94
- }
95
-
96
- export interface MetricMetadata {
97
- description?: string;
98
- unit?: string;
99
- /** Explicit bucket bounds for THIS metric, in the metric's own unit. */
100
- boundaries?: readonly number[];
101
- }
102
-
103
- export interface OtlpHttpMeter extends MeterAdapter {
104
- /** Always defined on this adapter — declared required to drop the `?.` at call sites. */
105
- gaugeSet(name: string, value: number, labels?: Labels): void;
106
- /** Always defined on this adapter — declared required to drop the `?.` at call sites. */
107
- histogramRecord(name: string, value: number, labels?: Labels): void;
108
- /** Flush, subject to the per-isolate cooldown unless `force` is true. */
109
- flush(force?: boolean): Promise<void>;
110
- /** Pending datapoint count across all metric kinds. For tests + audit. */
111
- pendingDatapointCount(): number;
112
- }
113
-
114
- // ---------------------------------------------------------------------------
115
- // Internal buffer shapes
116
- // ---------------------------------------------------------------------------
117
-
118
- type MetricKind = "counter" | "gauge" | "histogram";
119
-
120
- interface CounterPoint {
121
- value: number;
122
- attrs: Labels;
123
- startTimeUnixNano: string;
124
- }
125
- interface GaugePoint {
126
- value: number;
127
- attrs: Labels;
128
- timeUnixNano: string;
129
- }
130
- interface HistogramPoint {
131
- count: number;
132
- sum: number;
133
- min: number;
134
- max: number;
135
- bucketCounts: number[];
136
- attrs: Labels;
137
- startTimeUnixNano: string;
138
- }
139
-
140
- interface MetricEntry {
141
- kind: MetricKind;
142
- counter?: Map<string, CounterPoint>;
143
- gauge?: Map<string, GaugePoint>;
144
- histogram?: Map<string, HistogramPoint>;
145
- /**
146
- * Bounds this metric is bucketed with — resolved once from the metric's own
147
- * `boundaries` metadata, falling back to the adapter-wide default. Held on
148
- * the entry so `serializeOtlp` emits the bounds the counts were actually
149
- * filed against; emitting a different array silently mislabels every bucket.
150
- */
151
- bounds?: readonly number[];
152
- }
153
-
154
- // ---------------------------------------------------------------------------
155
- // Factory
156
- // ---------------------------------------------------------------------------
157
-
158
- const DEFAULT_HISTOGRAM_BOUNDS = [
159
- // ms — tuned for HTTP/sub-fetch latency. Coarser bounds than VTEX-specific
160
- // commerce histograms; sites that need finer buckets can register their
161
- // own histogram bounds in a follow-up.
162
- 5, 10, 25, 50, 75, 100, 250, 500, 1000,
163
- ];
164
-
165
- export function createOtlpHttpMeterAdapter(options: OtlpHttpMeterOptions): OtlpHttpMeter {
166
- const endpoint = options.endpoint;
167
- const resourceAttributes = options.resourceAttributes;
168
- const scopeName = options.scopeName ?? "@decocms/start";
169
- const scopeVersion = options.scopeVersion ?? "";
170
- const histogramBounds = options.histogramBounds ?? DEFAULT_HISTOGRAM_BOUNDS;
171
- const maxBuffer = options.maxBufferDatapoints ?? 2000;
172
- const minFlushIntervalMs = options.minFlushIntervalMs ?? 5000;
173
- const flushTimeoutMs = options.flushTimeoutMs ?? 5000;
174
- const extraHeaders = options.headers ?? {};
175
- const fetchImpl = options.fetchImpl ?? fetch;
176
- const now = options.nowMs ?? (() => Date.now());
177
- const onError = options.onError;
178
- const metricMetadata = options.metricMetadata ?? {};
179
-
180
- // Buffer state — per-isolate, never reset (CUMULATIVE temporality).
181
- const metrics = new Map<string, MetricEntry>();
182
- // Isolate boot wall-clock — counters/histograms anchor their startTime here.
183
- const isolateStartMs = now();
184
- // Per-isolate flush throttle.
185
- let lastFlushAt = 0;
186
- let inflight: Promise<void> | null = null;
187
-
188
- function attrKey(attrs?: Labels): string {
189
- if (!attrs) return "";
190
- const keys = Object.keys(attrs).sort();
191
- const parts: string[] = [];
192
- for (const k of keys) {
193
- const v = attrs[k];
194
- if (v === undefined || v === null) continue;
195
- parts.push(`${k}=${String(v)}`);
196
- }
197
- return parts.join("\u0001");
198
- }
199
-
200
- /**
201
- * Look up an existing entry without creating one. The two helpers below
202
- * (`checkAdmissibility`, `materializeEntry`) split what was a single
203
- * `getOrCreate` so the overflow check can run BEFORE we materialize a
204
- * new entry — otherwise a dropped datapoint leaves a permanent empty
205
- * `MetricEntry` in the `metrics` map that gets serialized as an empty
206
- * OTLP envelope each flush, inflating payloads and leaking memory.
207
- */
208
- function checkAdmissibility(
209
- name: string,
210
- kind: MetricKind,
211
- ): { entry: MetricEntry | null; isNewName: boolean } {
212
- const existing = metrics.get(name);
213
- if (!existing) return { entry: null, isNewName: true };
214
- if (existing.kind !== kind) {
215
- onError?.(
216
- "kind-mismatch",
217
- new Error(`metric "${name}" already registered as ${existing.kind}`),
218
- );
219
- return { entry: null, isNewName: false };
220
- }
221
- return { entry: existing, isNewName: false };
222
- }
223
-
224
- function materializeEntry(name: string, kind: MetricKind): MetricEntry {
225
- const entry: MetricEntry = { kind };
226
- if (kind === "counter") entry.counter = new Map();
227
- else if (kind === "gauge") entry.gauge = new Map();
228
- else entry.histogram = new Map();
229
- metrics.set(name, entry);
230
- return entry;
231
- }
232
-
233
- function pendingDatapointCount(): number {
234
- let n = 0;
235
- for (const entry of metrics.values()) {
236
- if (entry.counter) n += entry.counter.size;
237
- if (entry.gauge) n += entry.gauge.size;
238
- if (entry.histogram) n += entry.histogram.size;
239
- }
240
- return n;
241
- }
242
-
243
- function counterInc(name: string, value = 1, labels?: Labels) {
244
- const { entry: existing, isNewName } = checkAdmissibility(name, "counter");
245
- if (existing === null && !isNewName) return; // kind mismatch
246
- const key = attrKey(labels);
247
- const isNewDatapoint = !existing?.counter?.has(key);
248
- if (isNewDatapoint && pendingDatapointCount() >= maxBuffer) {
249
- onError?.("overflow", new Error(`metric buffer at cap (${maxBuffer}) — dropping "${name}"`));
250
- return;
251
- }
252
- const entry = existing ?? materializeEntry(name, "counter");
253
- if (!entry.counter) return;
254
- let point = entry.counter.get(key);
255
- if (!point) {
256
- point = {
257
- value: 0,
258
- attrs: labels ? { ...labels } : {},
259
- startTimeUnixNano: msToNs(isolateStartMs),
260
- };
261
- entry.counter.set(key, point);
262
- }
263
- point.value += value;
264
- }
265
-
266
- function gaugeSet(name: string, value: number, labels?: Labels) {
267
- const { entry: existing, isNewName } = checkAdmissibility(name, "gauge");
268
- if (existing === null && !isNewName) return; // kind mismatch
269
- const key = attrKey(labels);
270
- const isNewDatapoint = !existing?.gauge?.has(key);
271
- if (isNewDatapoint && pendingDatapointCount() >= maxBuffer) {
272
- onError?.("overflow", new Error(`metric buffer at cap (${maxBuffer}) — dropping "${name}"`));
273
- return;
274
- }
275
- const entry = existing ?? materializeEntry(name, "gauge");
276
- if (!entry.gauge) return;
277
- entry.gauge.set(key, {
278
- value,
279
- attrs: labels ? { ...labels } : {},
280
- timeUnixNano: msToNs(now()),
281
- });
282
- }
283
-
284
- function histogramRecord(name: string, value: number, labels?: Labels) {
285
- const { entry: existing, isNewName } = checkAdmissibility(name, "histogram");
286
- if (existing === null && !isNewName) return; // kind mismatch
287
- const key = attrKey(labels);
288
- const isNewDatapoint = !existing?.histogram?.has(key);
289
- if (isNewDatapoint && pendingDatapointCount() >= maxBuffer) {
290
- onError?.("overflow", new Error(`metric buffer at cap (${maxBuffer}) — dropping "${name}"`));
291
- return;
292
- }
293
- const entry = existing ?? materializeEntry(name, "histogram");
294
- if (!entry.histogram) return;
295
- const bounds = entry.bounds ?? metricMetadata[name]?.boundaries ?? histogramBounds;
296
- entry.bounds = bounds;
297
- let point = entry.histogram.get(key);
298
- if (!point) {
299
- point = {
300
- count: 0,
301
- sum: 0,
302
- min: Number.POSITIVE_INFINITY,
303
- max: Number.NEGATIVE_INFINITY,
304
- bucketCounts: new Array(bounds.length + 1).fill(0),
305
- attrs: labels ? { ...labels } : {},
306
- startTimeUnixNano: msToNs(isolateStartMs),
307
- };
308
- entry.histogram.set(key, point);
309
- }
310
- point.count += 1;
311
- point.sum += value;
312
- if (value < point.min) point.min = value;
313
- if (value > point.max) point.max = value;
314
- // Locate bucket. bounds is small (<=20); linear scan is fine.
315
- let bucketIdx = bounds.length;
316
- for (let i = 0; i < bounds.length; i++) {
317
- if (value <= bounds[i]) {
318
- bucketIdx = i;
319
- break;
320
- }
321
- }
322
- point.bucketCounts[bucketIdx] += 1;
323
- }
324
-
325
- async function doFlush(): Promise<void> {
326
- if (metrics.size === 0) return;
327
-
328
- const flushAtNs = msToNs(now());
329
- const payload = serializeOtlp(metrics, {
330
- resourceAttributes,
331
- scopeName,
332
- scopeVersion,
333
- histogramBounds,
334
- flushAtNs,
335
- metricMetadata,
336
- });
337
-
338
- const controller = new AbortController();
339
- const timer = setTimeout(() => controller.abort(), flushTimeoutMs);
340
- try {
341
- const res = await fetchImpl(endpoint, {
342
- method: "POST",
343
- headers: { ...extraHeaders, "Content-Type": "application/json" },
344
- body: JSON.stringify(payload),
345
- signal: controller.signal,
346
- });
347
- if (!res.ok) {
348
- // Drain the body so the underlying connection can be reused, then
349
- // surface as a flush error. Don't throw — flush failures must never
350
- // surface on the request hot path.
351
- try {
352
- await res.text();
353
- } catch {
354
- /* swallow */
355
- }
356
- onError?.("flush", new Error(`POST ${endpoint} → ${res.status}`));
357
- }
358
- } catch (err) {
359
- onError?.("flush", err);
360
- } finally {
361
- clearTimeout(timer);
362
- }
363
- }
364
-
365
- async function flush(force = false): Promise<void> {
366
- // If a flush is in flight, reuse it — concurrent requests should not
367
- // pile up POSTs. The in-flight POST already snapshotted the buffer at
368
- // its enqueue time; new datapoints land in the buffer and will go out
369
- // on the next flush.
370
- if (inflight) return inflight;
371
-
372
- const elapsed = now() - lastFlushAt;
373
- const overCap = pendingDatapointCount() >= maxBuffer;
374
- if (!force && !overCap && elapsed < minFlushIntervalMs) {
375
- // Cooldown not elapsed and buffer is not at the cap — skip. `force`
376
- // bypasses this for callers with no next-request opportunity to
377
- // retry the flush (e.g. a Cloudflare Workflow's `run()` exit — see
378
- // `instrumentWorkflowRun` in `otel.ts`).
379
- return;
380
- }
381
-
382
- inflight = doFlush().finally(() => {
383
- lastFlushAt = now();
384
- inflight = null;
385
- });
386
- return inflight;
387
- }
388
-
389
- return {
390
- counterInc,
391
- gaugeSet,
392
- histogramRecord,
393
- flush,
394
- pendingDatapointCount,
395
- };
396
- }
397
-
398
- // ---------------------------------------------------------------------------
399
- // OTLP/HTTP JSON serialization
400
- // ---------------------------------------------------------------------------
401
-
402
- function msToNs(ms: number): string {
403
- // OTLP wants nanoseconds-since-epoch as a string (uint64). Workers don't
404
- // give us better than ms precision in `Date.now()`; we pad with zeros.
405
- return `${Math.floor(ms)}000000`;
406
- }
407
-
408
- function attrsToOtlp(attrs: Labels): Array<{
409
- key: string;
410
- value:
411
- | { stringValue: string }
412
- | { intValue: string }
413
- | { doubleValue: number }
414
- | { boolValue: boolean };
415
- }> {
416
- const out: ReturnType<typeof attrsToOtlp> = [];
417
- for (const k of Object.keys(attrs).sort()) {
418
- const v = attrs[k];
419
- if (v === undefined || v === null) continue;
420
- if (typeof v === "string") out.push({ key: k, value: { stringValue: v } });
421
- else if (typeof v === "boolean") out.push({ key: k, value: { boolValue: v } });
422
- else if (Number.isInteger(v)) out.push({ key: k, value: { intValue: String(v) } });
423
- else out.push({ key: k, value: { doubleValue: v } });
424
- }
425
- return out;
426
- }
427
-
428
- interface SerializeOpts {
429
- resourceAttributes: Record<string, string>;
430
- scopeName: string;
431
- scopeVersion: string;
432
- histogramBounds: number[];
433
- flushAtNs: string;
434
- metricMetadata: Record<string, MetricMetadata>;
435
- }
436
-
437
- function serializeOtlp(
438
- metrics: Map<string, MetricEntry>,
439
- opts: SerializeOpts,
440
- ): { resourceMetrics: unknown[] } {
441
- const otlpMetrics: unknown[] = [];
442
-
443
- for (const [name, entry] of metrics) {
444
- const meta = opts.metricMetadata[name];
445
- const description = meta?.description ?? "";
446
- const unit = meta?.unit ?? "";
447
- if (entry.kind === "counter" && entry.counter) {
448
- const dataPoints: unknown[] = [];
449
- for (const point of entry.counter.values()) {
450
- dataPoints.push({
451
- attributes: attrsToOtlp(point.attrs),
452
- startTimeUnixNano: point.startTimeUnixNano,
453
- timeUnixNano: opts.flushAtNs,
454
- asDouble: point.value,
455
- });
456
- }
457
- otlpMetrics.push({
458
- name,
459
- description,
460
- unit,
461
- sum: {
462
- aggregationTemporality: 2, // CUMULATIVE
463
- isMonotonic: true,
464
- dataPoints,
465
- },
466
- });
467
- } else if (entry.kind === "gauge" && entry.gauge) {
468
- const dataPoints: unknown[] = [];
469
- for (const point of entry.gauge.values()) {
470
- dataPoints.push({
471
- attributes: attrsToOtlp(point.attrs),
472
- timeUnixNano: point.timeUnixNano,
473
- asDouble: point.value,
474
- });
475
- }
476
- otlpMetrics.push({
477
- name,
478
- description,
479
- unit,
480
- gauge: { dataPoints },
481
- });
482
- } else if (entry.kind === "histogram" && entry.histogram) {
483
- const dataPoints: unknown[] = [];
484
- for (const point of entry.histogram.values()) {
485
- dataPoints.push({
486
- attributes: attrsToOtlp(point.attrs),
487
- startTimeUnixNano: point.startTimeUnixNano,
488
- timeUnixNano: opts.flushAtNs,
489
- count: String(point.count),
490
- sum: point.sum,
491
- min: point.min === Number.POSITIVE_INFINITY ? 0 : point.min,
492
- max: point.max === Number.NEGATIVE_INFINITY ? 0 : point.max,
493
- bucketCounts: point.bucketCounts.map((c) => String(c)),
494
- // Must be the array the counts were bucketed against, not the
495
- // adapter-wide default — see MetricEntry.bounds.
496
- explicitBounds: entry.bounds ?? opts.histogramBounds,
497
- });
498
- }
499
- otlpMetrics.push({
500
- name,
501
- description,
502
- unit,
503
- histogram: {
504
- aggregationTemporality: 2, // CUMULATIVE
505
- dataPoints,
506
- },
507
- });
508
- }
509
- }
510
-
511
- const resourceAttrs: Array<{
512
- key: string;
513
- value: { stringValue: string };
514
- }> = [];
515
- for (const k of Object.keys(opts.resourceAttributes).sort()) {
516
- resourceAttrs.push({ key: k, value: { stringValue: opts.resourceAttributes[k] } });
517
- }
518
-
519
- return {
520
- resourceMetrics: [
521
- {
522
- resource: { attributes: resourceAttrs },
523
- scopeMetrics: [
524
- {
525
- scope: { name: opts.scopeName, version: opts.scopeVersion },
526
- metrics: otlpMetrics,
527
- },
528
- ],
529
- },
530
- ],
531
- };
532
- }