@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,419 +0,0 @@
1
- /**
2
- * Direct OTLP/HTTP JSON error-log exporter.
3
- *
4
- * Errors are too important to leave to head sampling. When CF Destinations'
5
- * `logs.head_sampling_rate` drops below 1.0 (the cost model in
6
- * `docs/observability.md` lowers it to `0.01` once this channel lands),
7
- * a 1%-sampled log pipe would lose 99 of every 100 errors emitted by
8
- * `logger.error(...)`. Sites lose the one signal they care about most.
9
- *
10
- * This adapter solves it by carrying `level: "error"` log records over a
11
- * separate, framework-controlled pipe direct to `deco-otel-ingest`
12
- * `/v1/logs`, the same endpoint CF Destinations targets. The two pipes
13
- * write to the same `otel_logs` table — the ingestor doesn't know or
14
- * care which transport the record arrived on, and dashboards / SQL
15
- * queries are unchanged.
16
- *
17
- * Design:
18
- *
19
- * - Filters out `debug`/`info`/`warn` upstream of the buffer — only
20
- * errors travel through this transport. Calls below "error" are a
21
- * no-op on this adapter; the composite logger fans them out to the
22
- * default console-JSON adapter which CF Destinations then samples
23
- * according to `logs.head_sampling_rate`.
24
- * - Per-isolate token-bucket rate limiter prevents log storms (a
25
- * pathological error loop blasting 10K errors/sec into the ingestor
26
- * would be a self-inflicted denial-of-service against stats-lake).
27
- * Default: 100 errors per minute, burst capacity of 20.
28
- * - Buffer + flush + cooldown identical to `otelHttpMeter.ts`. The
29
- * same `ctx.waitUntil(flush())` in `instrumentWorker` drains both.
30
- * - Wire format: OTLP/HTTP JSON `ResourceLogs` payload matching the
31
- * shape CF Destinations produces, so the existing ingestor handler
32
- * accepts both transports unchanged.
33
- *
34
- * Why a separate adapter and not a sampling-bypass flag on
35
- * `defaultLoggerAdapter`: the default writes via `console.error` which
36
- * is what CF Destinations samples. Bypassing CF Destinations means
37
- * NOT writing via `console.*` — a different transport, different
38
- * code path, different failure modes. Better as a dedicated adapter
39
- * composed onto the active logger via `createCompositeLogger`.
40
- */
41
-
42
- import { getActiveSpan } from "./observability";
43
- import type { LoggerAdapter, LogLevel } from "./logger";
44
-
45
- // ---------------------------------------------------------------------------
46
- // Types
47
- // ---------------------------------------------------------------------------
48
-
49
- export interface OtlpHttpLogOptions {
50
- /** Full OTLP/HTTP JSON logs endpoint, e.g. `https://.../v1/logs`. */
51
- endpoint: string;
52
- /** Resource attributes stamped on every payload (service.name etc.). */
53
- resourceAttributes: Record<string, string>;
54
- /** Scope name advertised in `scopeLogs[].scope.name`. */
55
- scopeName?: string;
56
- /** Scope version. */
57
- scopeVersion?: string;
58
- /** Hard cap on pending log records. Default: 500. */
59
- maxBufferRecords?: number;
60
- /** Cooldown between successful flushes (ms). Default: 5000. */
61
- minFlushIntervalMs?: number;
62
- /** Per-flush HTTP timeout (ms). Default: 5000. */
63
- flushTimeoutMs?: number;
64
- /**
65
- * Token-bucket parameters. The bucket holds up to `burstCapacity`
66
- * tokens and refills at `refillPerMinute` per minute. Each log record
67
- * costs one token. When the bucket is empty, records are dropped (with
68
- * `onError("rate-limit", ...)`) until refill resumes.
69
- * Defaults: 500 burst, 1000/min — sized for console monkey-patch, which
70
- * routes ALL console.* (including third-party libs at boot) through this
71
- * adapter. The old 20/100 defaults were sized for error-only traffic.
72
- */
73
- rateLimitBurstCapacity?: number;
74
- rateLimitRefillPerMinute?: number;
75
- /**
76
- * Minimum log level that this adapter forwards to OTLP. Levels below
77
- * this threshold are silently dropped at ingress. Defaults to `"error"`
78
- * — production-safe (only errors travel direct-POST; info/warn flow
79
- * through CF Destinations sampling). Set to `"info"` or `"debug"` in
80
- * local dev to capture lower-severity logs in the same channel.
81
- * Resolved from `DECO_OTEL_LOGS_MIN_LEVEL` in `bootObservability`.
82
- */
83
- minLevel?: LogLevel;
84
- /**
85
- * Extra HTTP headers merged into every OTLP POST (e.g. `Authorization: Bearer …`).
86
- * `Content-Type: application/json` is always set and cannot be overridden here.
87
- */
88
- headers?: Record<string, string>;
89
- /** Test seam — override fetch. */
90
- fetchImpl?: typeof fetch;
91
- /** Test seam — override Date.now(). */
92
- nowMs?: () => number;
93
- /**
94
- * Test seam — override getActiveSpan. Production code uses the
95
- * framework's AsyncLocalStorage-backed getActiveSpan automatically.
96
- */
97
- getActiveSpanFn?: () => { spanContext?: () => { traceId?: string; spanId?: string; traceFlags?: number } } | undefined | null;
98
- /** Optional sink for transport / rate-limit / overflow errors. */
99
- onError?: (kind: "flush" | "overflow" | "rate-limit", err: unknown) => void;
100
- /**
101
- * Called when an `error`-level log fires with an active trace context.
102
- * Used by the caller to promote unsampled traces so their spans are
103
- * exported regardless of head-sampling decisions.
104
- */
105
- promoteTrace?: (traceId: string) => void;
106
- }
107
-
108
- export interface OtlpHttpLog {
109
- adapter: LoggerAdapter;
110
- /** Force a flush, subject to the per-isolate cooldown. */
111
- flush(): Promise<void>;
112
- /** Pending log record count. For tests + audit. */
113
- pendingRecordCount(): number;
114
- }
115
-
116
- // ---------------------------------------------------------------------------
117
- // Internal types
118
- // ---------------------------------------------------------------------------
119
-
120
- interface PendingRecord {
121
- timeUnixNano: string;
122
- observedTimeUnixNano: string;
123
- severityNumber: number;
124
- severityText: string;
125
- body: string;
126
- attributes: Record<string, unknown>;
127
- traceId: string;
128
- spanId: string;
129
- traceFlags: number;
130
- }
131
-
132
- // OTel SeverityNumber values, OTel spec. See
133
- // https://opentelemetry.io/docs/specs/otel/logs/data-model/#field-severitynumber
134
- const SEVERITY_NUMBER: Record<LogLevel, number> = {
135
- debug: 5,
136
- info: 9,
137
- warn: 13,
138
- error: 17,
139
- };
140
-
141
- // ---------------------------------------------------------------------------
142
- // Factory
143
- // ---------------------------------------------------------------------------
144
-
145
- export function createOtlpHttpLogAdapter(options: OtlpHttpLogOptions): OtlpHttpLog {
146
- const endpoint = options.endpoint;
147
- const resourceAttributes = options.resourceAttributes;
148
- const scopeName = options.scopeName ?? "@decocms/start";
149
- const scopeVersion = options.scopeVersion ?? "";
150
- const maxBuffer = options.maxBufferRecords ?? 500;
151
- const minFlushIntervalMs = options.minFlushIntervalMs ?? 5000;
152
- const flushTimeoutMs = options.flushTimeoutMs ?? 5000;
153
- const burstCapacity = options.rateLimitBurstCapacity ?? 500;
154
- const refillPerMinute = options.rateLimitRefillPerMinute ?? 1000;
155
- const minSeverity = SEVERITY_NUMBER[options.minLevel ?? "error"];
156
- const extraHeaders = options.headers ?? {};
157
- const fetchImpl = options.fetchImpl ?? fetch;
158
- const now = options.nowMs ?? (() => Date.now());
159
- const onError = options.onError;
160
- const promoteTrace = options.promoteTrace;
161
- const getSpan = options.getActiveSpanFn ?? getActiveSpan;
162
-
163
- const buffer: PendingRecord[] = [];
164
- // Token bucket — starts full.
165
- let tokens = burstCapacity;
166
- let tokensLastRefilledAt = now();
167
-
168
- let lastFlushAt = 0;
169
- let inflight: Promise<void> | null = null;
170
-
171
- function refillTokens(): void {
172
- const t = now();
173
- const elapsedMs = t - tokensLastRefilledAt;
174
- if (elapsedMs <= 0) return;
175
- // refillPerMinute tokens per 60_000ms.
176
- const refill = (elapsedMs / 60_000) * refillPerMinute;
177
- tokens = Math.min(burstCapacity, tokens + refill);
178
- tokensLastRefilledAt = t;
179
- }
180
-
181
- function tryConsumeToken(): boolean {
182
- refillTokens();
183
- if (tokens < 1) return false;
184
- tokens -= 1;
185
- return true;
186
- }
187
-
188
- const adapter: LoggerAdapter = {
189
- log(level, msg, attrs) {
190
- // Filter by severity threshold. Levels below minLevel are dropped.
191
- if (SEVERITY_NUMBER[level] < minSeverity) return;
192
-
193
- // No SDK-level sampling for info/debug. Volume is controlled by
194
- // minLevel (severity threshold) here, and by the probabilistic
195
- // sampler in the otel-ingest collector — keeping log and trace
196
- // sampling pipelines fully independent per OTel spec.
197
-
198
- if (!tryConsumeToken()) {
199
- onError?.(
200
- "rate-limit",
201
- new Error(`rate limit exceeded: ${refillPerMinute}/min, burst ${burstCapacity}`),
202
- );
203
- return;
204
- }
205
-
206
- if (buffer.length >= maxBuffer) {
207
- onError?.(
208
- "overflow",
209
- new Error(`error-log buffer at cap (${maxBuffer}) — dropping record`),
210
- );
211
- return;
212
- }
213
-
214
- const spanCtx = getSpan()?.spanContext?.();
215
- const t = msToNs(now());
216
- buffer.push({
217
- timeUnixNano: t,
218
- observedTimeUnixNano: t,
219
- severityNumber: SEVERITY_NUMBER[level],
220
- severityText: level,
221
- body: msg,
222
- attributes: attrs ? { ...attrs } : {},
223
- traceId: spanCtx?.traceId ?? "",
224
- spanId: spanCtx?.spanId ?? "",
225
- traceFlags: spanCtx?.traceFlags ?? 0,
226
- });
227
-
228
- if (level === "error" && spanCtx?.traceId) {
229
- promoteTrace?.(spanCtx.traceId);
230
- }
231
- },
232
- };
233
-
234
- async function doFlush(): Promise<void> {
235
- if (buffer.length === 0) return;
236
- // Snapshot + remove BEFORE the network call so concurrent records
237
- // landing during the POST don't get reset on success. On failure we
238
- // restore the snapshot to the FRONT of the buffer (preserving order
239
- // and prioritizing the originating-error context). The `maxBuffer`
240
- // cap on the `log()` path still bounds total memory if the endpoint
241
- // stays down — newest records are dropped via `onError("overflow")`.
242
- const snapshot = buffer.splice(0, buffer.length);
243
- const payload = serializeOtlp(snapshot, {
244
- resourceAttributes,
245
- scopeName,
246
- scopeVersion,
247
- });
248
-
249
- const restoreOnFailure = () => {
250
- // The snapshot was buffered BEFORE any records that landed during
251
- // the failed POST — its contents are older and more likely to be
252
- // the originating-error context operators care about. Restore
253
- // policy preserves the snapshot first, evicts the NEWEST records
254
- // when the cap is tight:
255
- //
256
- // 1. If snapshot + current buffer fit under the cap → unshift,
257
- // done.
258
- // 2. Otherwise, drop newest-tail records from the current buffer
259
- // (records that arrived during the failed POST). If that
260
- // suffices, unshift the full snapshot.
261
- // 3. Only if the snapshot ALONE exceeds the cap do we truncate
262
- // the snapshot — and even then, we keep its OLDEST end
263
- // (`snapshot.length = maxBuffer`) and drop the newest tail.
264
- //
265
- // This is the inverse of the original (buggy) restore which kept
266
- // newer records by truncating the older snapshot.
267
- const total = snapshot.length + buffer.length;
268
- if (total <= maxBuffer) {
269
- buffer.unshift(...snapshot);
270
- return;
271
- }
272
-
273
- let overflow = total - maxBuffer;
274
- let droppedFromBuffer = 0;
275
- if (buffer.length > 0 && overflow > 0) {
276
- droppedFromBuffer = Math.min(buffer.length, overflow);
277
- buffer.length -= droppedFromBuffer;
278
- overflow -= droppedFromBuffer;
279
- }
280
- let droppedFromSnapshot = 0;
281
- if (overflow > 0) {
282
- // Snapshot alone exceeds the cap. Keep the oldest `maxBuffer`
283
- // entries and drop the rest from the newest tail.
284
- droppedFromSnapshot = Math.min(snapshot.length, overflow);
285
- snapshot.length -= droppedFromSnapshot;
286
- }
287
- buffer.unshift(...snapshot);
288
-
289
- const parts = [`dropped ${droppedFromBuffer} newer records from buffer`];
290
- if (droppedFromSnapshot > 0) {
291
- parts.push(`${droppedFromSnapshot} newest-tail records from snapshot`);
292
- }
293
- onError?.(
294
- "overflow",
295
- new Error(
296
- `error-log buffer overflow on restore — ${parts.join(" and ")} (preserved ${snapshot.length} originating-error records)`,
297
- ),
298
- );
299
- };
300
-
301
- const controller = new AbortController();
302
- const timer = setTimeout(() => controller.abort(), flushTimeoutMs);
303
- try {
304
- const res = await fetchImpl(endpoint, {
305
- method: "POST",
306
- headers: { ...extraHeaders, "Content-Type": "application/json" },
307
- body: JSON.stringify(payload),
308
- signal: controller.signal,
309
- });
310
- if (!res.ok) {
311
- try {
312
- await res.text();
313
- } catch {
314
- /* swallow */
315
- }
316
- restoreOnFailure();
317
- onError?.("flush", new Error(`POST ${endpoint} → ${res.status}`));
318
- }
319
- } catch (err) {
320
- restoreOnFailure();
321
- onError?.("flush", err);
322
- } finally {
323
- clearTimeout(timer);
324
- }
325
- }
326
-
327
- async function flush(): Promise<void> {
328
- if (inflight) return inflight;
329
-
330
- const elapsed = now() - lastFlushAt;
331
- const overCap = buffer.length >= maxBuffer;
332
- if (!overCap && elapsed < minFlushIntervalMs) return;
333
-
334
- inflight = doFlush().finally(() => {
335
- lastFlushAt = now();
336
- inflight = null;
337
- });
338
- return inflight;
339
- }
340
-
341
- return {
342
- adapter,
343
- flush,
344
- pendingRecordCount: () => buffer.length,
345
- };
346
- }
347
-
348
- // ---------------------------------------------------------------------------
349
- // OTLP/HTTP JSON serialization
350
- // ---------------------------------------------------------------------------
351
-
352
- function msToNs(ms: number): string {
353
- return `${Math.floor(ms)}000000`;
354
- }
355
-
356
- function attrToOtlpValue(
357
- v: unknown,
358
- ):
359
- | { stringValue: string }
360
- | { intValue: string }
361
- | { doubleValue: number }
362
- | { boolValue: boolean } {
363
- if (typeof v === "string") return { stringValue: v };
364
- if (typeof v === "boolean") return { boolValue: v };
365
- if (typeof v === "number" && Number.isFinite(v)) {
366
- if (Number.isInteger(v)) return { intValue: String(v) };
367
- return { doubleValue: v };
368
- }
369
- // Fallback — JSON-stringify so structured attrs round-trip as strings.
370
- // `JSON.stringify` returns `undefined` for `undefined`, functions, and
371
- // symbols. OTLP requires `stringValue` to be a string, so coerce with
372
- // `String(v)` whenever serialization yields nothing parseable.
373
- try {
374
- const s = JSON.stringify(v);
375
- return { stringValue: typeof s === "string" ? s : String(v) };
376
- } catch {
377
- return { stringValue: String(v) };
378
- }
379
- }
380
-
381
- interface SerializeOpts {
382
- resourceAttributes: Record<string, string>;
383
- scopeName: string;
384
- scopeVersion: string;
385
- }
386
-
387
- function serializeOtlp(records: PendingRecord[], opts: SerializeOpts): { resourceLogs: unknown[] } {
388
- const otlpRecords = records.map((r) => ({
389
- timeUnixNano: r.timeUnixNano,
390
- observedTimeUnixNano: r.observedTimeUnixNano,
391
- severityNumber: r.severityNumber,
392
- severityText: r.severityText,
393
- body: { stringValue: r.body },
394
- attributes: Object.entries(r.attributes)
395
- .filter(([_, v]) => v !== undefined && v !== null)
396
- .map(([k, v]) => ({ key: k, value: attrToOtlpValue(v) })),
397
- ...(r.traceId ? { traceId: r.traceId } : {}),
398
- ...(r.spanId ? { spanId: r.spanId } : {}),
399
- ...(r.traceFlags ? { flags: r.traceFlags } : {}),
400
- }));
401
-
402
- const resourceAttrs = Object.entries(opts.resourceAttributes)
403
- .sort(([a], [b]) => a.localeCompare(b))
404
- .map(([k, v]) => ({ key: k, value: { stringValue: v } }));
405
-
406
- return {
407
- resourceLogs: [
408
- {
409
- resource: { attributes: resourceAttrs },
410
- scopeLogs: [
411
- {
412
- scope: { name: opts.scopeName, version: opts.scopeVersion },
413
- logRecords: otlpRecords,
414
- },
415
- ],
416
- },
417
- ],
418
- };
419
- }