@utk09/ui-observability 0.4.0 → 0.5.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 (77) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +74 -33
  3. package/dist/bus/bus.d.ts +9 -0
  4. package/dist/bus-D3OO0OcL.js +378 -0
  5. package/dist/bus-D3OO0OcL.js.map +1 -0
  6. package/dist/bus-OdRJVUzr.cjs +2 -0
  7. package/dist/bus-OdRJVUzr.cjs.map +1 -0
  8. package/dist/capture/types.d.ts +14 -0
  9. package/dist/capture/web-vitals.d.ts +9 -3
  10. package/dist/{constants-CrU3IUyy.js → constants-B6kdsCzF.js} +9 -8
  11. package/dist/constants-B6kdsCzF.js.map +1 -0
  12. package/dist/constants-DZH04585.cjs +2 -0
  13. package/dist/constants-DZH04585.cjs.map +1 -0
  14. package/dist/constants.d.ts +8 -1
  15. package/dist/core/journey.d.ts +5 -2
  16. package/dist/core/logger.d.ts +22 -3
  17. package/dist/core/pipeline.d.ts +10 -1
  18. package/dist/core/runtime.d.ts +102 -18
  19. package/dist/core/sender.d.ts +58 -0
  20. package/dist/errors-DPju_xSI.cjs +3 -0
  21. package/dist/errors-DPju_xSI.cjs.map +1 -0
  22. package/dist/errors-Dme9tz-6.js +76 -0
  23. package/dist/errors-Dme9tz-6.js.map +1 -0
  24. package/dist/index.cjs +1 -3
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.js +462 -2196
  27. package/dist/index.js.map +1 -1
  28. package/dist/indexeddb-storage-lGdoHGHy.cjs +2 -0
  29. package/dist/indexeddb-storage-lGdoHGHy.cjs.map +1 -0
  30. package/dist/{indexeddb-storage-CSaDuHGk.js → indexeddb-storage-nxs_rxGx.js} +30 -17
  31. package/dist/indexeddb-storage-nxs_rxGx.js.map +1 -0
  32. package/dist/interactions-C1romMpE.js +67 -0
  33. package/dist/interactions-C1romMpE.js.map +1 -0
  34. package/dist/interactions-DP0-rIPJ.cjs +2 -0
  35. package/dist/interactions-DP0-rIPJ.cjs.map +1 -0
  36. package/dist/models/config.d.ts +29 -11
  37. package/dist/network-DDVIJSHd.cjs +2 -0
  38. package/dist/network-DDVIJSHd.cjs.map +1 -0
  39. package/dist/network-au-Tqt1n.js +111 -0
  40. package/dist/network-au-Tqt1n.js.map +1 -0
  41. package/dist/platform-DMYo3AX3.js +48 -0
  42. package/dist/platform-DMYo3AX3.js.map +1 -0
  43. package/dist/platform-g99Kn755.cjs +2 -0
  44. package/dist/platform-g99Kn755.cjs.map +1 -0
  45. package/dist/sampling-ByI5H44E.js +248 -0
  46. package/dist/sampling-ByI5H44E.js.map +1 -0
  47. package/dist/sampling-Dui-Fp3u.cjs +2 -0
  48. package/dist/sampling-Dui-Fp3u.cjs.map +1 -0
  49. package/dist/sender-R7lOpyNc.js +907 -0
  50. package/dist/sender-R7lOpyNc.js.map +1 -0
  51. package/dist/sender-vLcbQhiB.cjs +3 -0
  52. package/dist/sender-vLcbQhiB.cjs.map +1 -0
  53. package/dist/storage/idb-driver.d.ts +9 -1
  54. package/dist/storage/indexeddb-storage.d.ts +5 -0
  55. package/dist/transport/exit-flush.d.ts +11 -1
  56. package/dist/transport/http-transport.d.ts +2 -0
  57. package/dist/transport/retry-engine.d.ts +28 -3
  58. package/dist/transport/serializers/select.d.ts +8 -0
  59. package/dist/unref-16maCyKA.js +8 -0
  60. package/dist/unref-16maCyKA.js.map +1 -0
  61. package/dist/unref-CU9Nyz_9.cjs +2 -0
  62. package/dist/unref-CU9Nyz_9.cjs.map +1 -0
  63. package/dist/utils/console.d.ts +11 -3
  64. package/dist/utils/deadline.d.ts +7 -0
  65. package/dist/utils/identity.d.ts +47 -3
  66. package/dist/utils/tracing.d.ts +6 -5
  67. package/dist/web-vitals-DM2nvcMJ.cjs +2 -0
  68. package/dist/web-vitals-DM2nvcMJ.cjs.map +1 -0
  69. package/dist/web-vitals-DwWdLBq6.js +51 -0
  70. package/dist/web-vitals-DwWdLBq6.js.map +1 -0
  71. package/package.json +21 -11
  72. package/dist/constants-BpFlszME.cjs +0 -2
  73. package/dist/constants-BpFlszME.cjs.map +0 -1
  74. package/dist/constants-CrU3IUyy.js.map +0 -1
  75. package/dist/indexeddb-storage-CSaDuHGk.js.map +0 -1
  76. package/dist/indexeddb-storage-DIJIbFnp.cjs +0 -2
  77. package/dist/indexeddb-storage-DIJIbFnp.cjs.map +0 -1
@@ -0,0 +1,907 @@
1
+ import { $t as e, A as t, Ft as n, G as r, I as i, It as a, J as o, Jt as s, K as c, Kt as l, Lt as u, O as d, Ot as ee, Qt as te, R as f, St as p, Vt as ne, Y as re, Zt as ie, _t as m, en as h, ft as g, in as _, k as v, kt as y, l as b, lt as x, ot as S, pt as ae, q as oe, qt as C, rn as se, st as ce, ut as le, v as w, vt as ue, wt as de, xt as T, z as E } from "./constants-B6kdsCzF.js";
2
+ import { _ as D, c as O, f as k, i as A, t as j } from "./sampling-ByI5H44E.js";
3
+ import { t as M } from "./unref-16maCyKA.js";
4
+ //#region src/models/batch.ts
5
+ function N(e) {
6
+ if (typeof e != "object" || !e) return !1;
7
+ let t = Reflect.get(e, "id"), n = Reflect.get(e, "createdAt"), r = Reflect.get(e, "attempts"), i = Reflect.get(e, "records");
8
+ return typeof t == "string" && typeof n == "number" && typeof r == "number" && Array.isArray(i);
9
+ }
10
+ function P(e) {
11
+ if (e.records.length < 2) return null;
12
+ let t = Math.floor(e.records.length / 2), n = (t) => ({
13
+ id: O(),
14
+ records: t,
15
+ createdAt: e.createdAt,
16
+ attempts: e.attempts
17
+ });
18
+ return [n(e.records.slice(0, t)), n(e.records.slice(t))];
19
+ }
20
+ //#endregion
21
+ //#region src/utils/lock.ts
22
+ function F(e, t, n, { skipIfBusy: r = !0 } = {}) {
23
+ let i = globalThis.navigator?.locks;
24
+ return i?.request ? t.guardAsync("storage.degraded", `acquiring lock ${e}`, () => i.request(e, { ifAvailable: r }, (e) => e ? n() : Promise.resolve(void 0))) : n();
25
+ }
26
+ //#endregion
27
+ //#region src/storage/keys.ts
28
+ function I(e, t) {
29
+ let n = [];
30
+ return t.guard("storage.unavailable", "enumerating localStorage", () => {
31
+ for (let t = 0; t < localStorage.length; t++) {
32
+ let r = String(localStorage.key(t));
33
+ r.startsWith(e) && n.push(r);
34
+ }
35
+ }), n.sort();
36
+ }
37
+ //#endregion
38
+ //#region src/storage/emergency-queue.ts
39
+ function L(e) {
40
+ let t = String(e.createdAt).padStart(14, "0");
41
+ return `${f}${t}.${e.id}`;
42
+ }
43
+ function R(e, t) {
44
+ let n = t.guard("storage.degraded", "an emergency entry was not JSON and was dropped", () => JSON.parse(e));
45
+ return n === void 0 ? null : N(n) ? n : (t.report("storage.degraded", "an emergency entry was not a batch and was dropped"), null);
46
+ }
47
+ async function z(e, t) {
48
+ let n = 0;
49
+ for (let r of I(f, t)) {
50
+ let i = t.guard("storage.unavailable", "reading the emergency queue", () => {
51
+ let e = localStorage.getItem(r);
52
+ return localStorage.removeItem(r), e;
53
+ });
54
+ if (!i) continue;
55
+ let a = R(i, t);
56
+ if (a !== null) try {
57
+ await A(e.save(a), C), n++;
58
+ } catch (e) {
59
+ t.report("storage.degraded", "an emergency batch could not be recovered", { key: r }, e);
60
+ }
61
+ }
62
+ return n;
63
+ }
64
+ function B(e, t) {
65
+ let n = `writing the emergency queue, ${String(e.records.length)} records`;
66
+ t.guard("storage.quota_exceeded", n, () => {
67
+ let n = I(f, t);
68
+ for (let e of n.slice(0, Math.max(0, n.length - 20 + 1))) localStorage.removeItem(e);
69
+ localStorage.setItem(L(e), JSON.stringify(e));
70
+ });
71
+ }
72
+ async function V(e, t) {
73
+ return await F("ui-observability.emergency", t, () => z(e, t), { skipIfBusy: !1 }) ?? 0;
74
+ }
75
+ //#endregion
76
+ //#region src/storage/local-storage.ts
77
+ function H(e) {
78
+ let t = String(e.createdAt).padStart(14, "0");
79
+ return `${w}${t}.${e.id}`;
80
+ }
81
+ function fe(e) {
82
+ let t = w.length, n = Number(e.slice(t, t + 14));
83
+ return Number.isFinite(n) ? n : null;
84
+ }
85
+ var pe = class {
86
+ limits;
87
+ diagnostics;
88
+ onGap;
89
+ name = ie;
90
+ constructor(e, t, n) {
91
+ this.limits = e, this.diagnostics = t, this.onGap = n;
92
+ }
93
+ async save(e) {
94
+ this.write(e, "localStorage refused a batch, evicting the oldest") ? await this.prune() : (this.evictForQuota(), this.write(e, "localStorage refused a batch even after evicting") || this.reportGap({
95
+ batches: 1,
96
+ records: e.records.length,
97
+ reason: "quota"
98
+ }));
99
+ }
100
+ take(e) {
101
+ let t = [];
102
+ for (let n of this.keys().slice(0, e)) {
103
+ let e = this.read(n);
104
+ e === null ? this.removeKey(n) : t.push(e);
105
+ }
106
+ return Promise.resolve(t);
107
+ }
108
+ remove(e) {
109
+ let t = this.keyOf(e);
110
+ return t !== null && this.removeKey(t), Promise.resolve();
111
+ }
112
+ bumpAttempts(e, t) {
113
+ let n = this.keyOf(e);
114
+ if (n === null) return Promise.resolve();
115
+ let r = this.read(n);
116
+ return r === null || (r.attempts = t, this.diagnostics.guard("storage.degraded", "updating attempts", () => {
117
+ localStorage.setItem(n, JSON.stringify(r));
118
+ })), Promise.resolve();
119
+ }
120
+ prune() {
121
+ let e = Date.now() - this.limits.maxAgeMs, t = {
122
+ batches: 0,
123
+ records: 0,
124
+ reason: "expired"
125
+ }, n = (e) => {
126
+ let n = this.read(e);
127
+ this.removeKey(e), t.batches++, t.records += n?.records.length ?? 0;
128
+ }, r = [];
129
+ for (let t of this.keys()) {
130
+ let i = fe(t);
131
+ i === null || i < e ? n(t) : r.push(t);
132
+ }
133
+ let i = r.length - this.limits.maxBatches;
134
+ if (i > 0) {
135
+ t.reason = "over_capacity";
136
+ for (let e of r.slice(0, i)) n(e);
137
+ }
138
+ return this.reportGap(t), Promise.resolve(t);
139
+ }
140
+ count() {
141
+ return Promise.resolve(this.keys().length);
142
+ }
143
+ clear() {
144
+ return this.evict(this.keys()), Promise.resolve();
145
+ }
146
+ close() {
147
+ return Promise.resolve();
148
+ }
149
+ write(e, t) {
150
+ return this.diagnostics.guard("storage.quota_exceeded", t, () => (localStorage.setItem(H(e), JSON.stringify(e)), !0)) === !0;
151
+ }
152
+ evictForQuota() {
153
+ let e = this.keys(), t = {
154
+ batches: 0,
155
+ records: 0,
156
+ reason: "quota"
157
+ };
158
+ for (let n of e.slice(0, Math.ceil(e.length / 4))) {
159
+ let e = this.read(n);
160
+ this.removeKey(n), t.batches++, t.records += e?.records.length ?? 0;
161
+ }
162
+ this.reportGap(t);
163
+ }
164
+ reportGap(e) {
165
+ e.batches !== 0 && (this.diagnostics.report("storage.evicted", `dropped ${String(e.batches)} stored batches (${String(e.records)} records)`, { ...e }), this.onGap?.(e));
166
+ }
167
+ read(e) {
168
+ let t = this.diagnostics.guard("storage.unavailable", "reading a stored batch", () => localStorage.getItem(e));
169
+ if (!t) return null;
170
+ let n = this.diagnostics.guard("storage.degraded", "a stored batch was corrupt and was removed", () => JSON.parse(t));
171
+ return n === void 0 ? null : N(n) ? n : (this.diagnostics.report("storage.degraded", "a stored entry was not a batch and was dropped"), null);
172
+ }
173
+ keyOf(e) {
174
+ return this.keys().find((t) => t.endsWith(`.${e}`)) ?? null;
175
+ }
176
+ evict(e) {
177
+ for (let t of e) this.removeKey(t);
178
+ }
179
+ removeKey(e) {
180
+ this.diagnostics.guard("storage.degraded", "removing a stored batch", () => {
181
+ localStorage.removeItem(e);
182
+ });
183
+ }
184
+ keys() {
185
+ return I(w, this.diagnostics);
186
+ }
187
+ };
188
+ //#endregion
189
+ //#region src/storage/memory-storage.ts
190
+ function U(e) {
191
+ return e.reduce((e, t) => e + t.records.length, 0);
192
+ }
193
+ var W = class {
194
+ limits;
195
+ onGap;
196
+ name = te;
197
+ batches = [];
198
+ constructor(e, t) {
199
+ this.limits = e, this.onGap = t;
200
+ }
201
+ async save(e) {
202
+ this.batches.push(e), await this.prune();
203
+ }
204
+ take(e) {
205
+ return Promise.resolve(this.batches.slice(0, e));
206
+ }
207
+ remove(e) {
208
+ return this.batches = this.batches.filter((t) => t.id !== e), Promise.resolve();
209
+ }
210
+ bumpAttempts(e, t) {
211
+ let n = this.batches.find((t) => t.id === e);
212
+ return n && (n.attempts = t), Promise.resolve();
213
+ }
214
+ prune() {
215
+ let e = Date.now() - this.limits.maxAgeMs, t = {
216
+ batches: 0,
217
+ records: 0,
218
+ reason: "expired"
219
+ }, n = this.batches.filter((t) => t.createdAt < e);
220
+ this.batches = this.batches.filter((t) => t.createdAt >= e), t.batches += n.length, t.records += U(n);
221
+ let r = this.batches.length - this.limits.maxBatches;
222
+ if (r > 0) {
223
+ t.reason = "over_capacity";
224
+ let e = this.batches.slice(0, r);
225
+ this.batches = this.batches.slice(r), t.batches += e.length, t.records += U(e);
226
+ }
227
+ return t.batches > 0 && this.onGap?.(t), Promise.resolve(t);
228
+ }
229
+ count() {
230
+ return Promise.resolve(this.batches.length);
231
+ }
232
+ clear() {
233
+ return this.batches = [], Promise.resolve();
234
+ }
235
+ close() {
236
+ return this.batches = [], Promise.resolve();
237
+ }
238
+ }, me = {
239
+ name: e,
240
+ save: () => Promise.resolve(),
241
+ take: () => Promise.resolve([]),
242
+ remove: () => Promise.resolve(),
243
+ bumpAttempts: () => Promise.resolve(),
244
+ prune: () => Promise.resolve({
245
+ batches: 0,
246
+ records: 0,
247
+ reason: "expired"
248
+ }),
249
+ count: () => Promise.resolve(0),
250
+ clear: () => Promise.resolve(),
251
+ close: () => Promise.resolve()
252
+ };
253
+ function he(e) {
254
+ return e.guard("storage.unavailable", "reading indexedDB", () => globalThis.indexedDB != null) === !0;
255
+ }
256
+ function ge(e) {
257
+ return e.guard("storage.unavailable", "probing localStorage", () => (localStorage.setItem(h, "1"), localStorage.removeItem(h), !0)) === !0;
258
+ }
259
+ async function _e(e, t, n, r, i) {
260
+ if (e === "none") return me;
261
+ if (e === "memory") return new W(n, i);
262
+ if (e === "indexeddb" || e === "auto") {
263
+ if (he(r)) {
264
+ let e = await r.guardAsync("storage.unavailable", "opening IndexedDB", async () => {
265
+ let { IndexedDbStorage: e } = await import("./indexeddb-storage-nxs_rxGx.js"), a = new e(t, n, r, i);
266
+ return await a.open(), a;
267
+ });
268
+ if (e) return e;
269
+ }
270
+ if (e === "indexeddb") return r.report("storage.degraded", "IndexedDB was asked for by name and is unavailable, using memory"), new W(n, i);
271
+ }
272
+ return ge(r) ? new pe(n, r, i) : (r.report("storage.degraded", "no persistent storage available, offline logs are memory only"), new W(n, i));
273
+ }
274
+ //#endregion
275
+ //#region src/transport/serializers/ecs.ts
276
+ function ve(e) {
277
+ return g.test(e) ? Number(BigInt(e) / ae) : Date.now();
278
+ }
279
+ function ye(e) {
280
+ return typeof e == "string" || typeof e == "number" || typeof e == "boolean" ? e : typeof e == "bigint" ? e.toString() : null;
281
+ }
282
+ function be(e, t, n) {
283
+ let r = e[t];
284
+ r === void 0 ? e[t] = n : Array.isArray(r) ? r.push(n) : e[t] = [r, n];
285
+ }
286
+ function G(e, t, n, r) {
287
+ let i = ye(n);
288
+ if (i !== null) be(e, t, i);
289
+ else if (typeof n == "object" && n && !r.has(n)) {
290
+ if (r.add(n), Array.isArray(n)) for (let i of n) G(e, t, i, r);
291
+ else for (let [i, a] of Object.entries(n)) G(e, `${t}.${i}`, a, r);
292
+ r.delete(n);
293
+ }
294
+ }
295
+ function K(e) {
296
+ let t = Object.create(null), n = /* @__PURE__ */ new WeakSet();
297
+ for (let [r, i] of Object.entries(e)) G(t, r, i, n);
298
+ return t;
299
+ }
300
+ var xe = {
301
+ name: "ecs",
302
+ serialize(e) {
303
+ return {
304
+ body: `${e.map((e) => {
305
+ let t = ve(e.timeUnixNano);
306
+ return JSON.stringify({
307
+ "@timestamp": new Date(t).toISOString(),
308
+ message: e.body,
309
+ log: { level: i[e.severityText] ?? e.severityText.toLowerCase() },
310
+ trace: { id: e.traceId },
311
+ span: { id: e.spanId },
312
+ service: {
313
+ name: e.resource[ee],
314
+ version: e.resource[y],
315
+ environment: e.resource[de]
316
+ },
317
+ user_agent: { original: e.resource[p] },
318
+ url: { full: e.attributes["url.full"] ?? e.attributes["page.url"] },
319
+ labels: {
320
+ ...K(e.resource),
321
+ ...K(e.attributes)
322
+ }
323
+ });
324
+ }).join("\n")}\n`,
325
+ contentType: v
326
+ };
327
+ }
328
+ };
329
+ //#endregion
330
+ //#region src/transport/serializers/otlp.ts
331
+ function q(e) {
332
+ return e == null ? null : typeof e == "string" ? { stringValue: e } : typeof e == "boolean" ? { boolValue: e } : typeof e == "number" ? Number.isInteger(e) ? { intValue: String(e) } : { doubleValue: e } : typeof e == "bigint" ? { intValue: e.toString() } : Array.isArray(e) ? { arrayValue: { values: e.map(q).filter((e) => e !== null) } } : typeof e == "object" ? { kvlistValue: { values: J(e) } } : null;
333
+ }
334
+ function J(e) {
335
+ let t = [];
336
+ for (let [n, r] of Object.entries(e)) {
337
+ let e = q(r);
338
+ e && t.push({
339
+ key: n,
340
+ value: e
341
+ });
342
+ }
343
+ return t;
344
+ }
345
+ var Y = /* @__PURE__ */ new WeakMap();
346
+ function Se(e) {
347
+ let t = Y.get(e);
348
+ if (t !== void 0) return t;
349
+ let n = JSON.stringify(e);
350
+ return Y.set(e, n), n;
351
+ }
352
+ var Ce = {
353
+ name: ne,
354
+ serialize(e) {
355
+ let t = /* @__PURE__ */ new Map();
356
+ for (let n of e) {
357
+ let e = Se(n.resource), r = t.get(e);
358
+ r ? r.records.push(n) : t.set(e, {
359
+ resource: n.resource,
360
+ records: [n]
361
+ });
362
+ }
363
+ let n = [...t.values()].map((e) => ({
364
+ resource: { attributes: J(e.resource) },
365
+ scopeLogs: [{
366
+ scope: {
367
+ name: se,
368
+ version: _
369
+ },
370
+ logRecords: e.records.map((e) => ({
371
+ timeUnixNano: e.timeUnixNano,
372
+ observedTimeUnixNano: e.observedTimeUnixNano ?? e.timeUnixNano,
373
+ severityNumber: e.severityNumber,
374
+ severityText: e.severityText,
375
+ body: { stringValue: e.body },
376
+ traceId: e.traceId,
377
+ spanId: e.spanId,
378
+ flags: e.traceFlags,
379
+ attributes: J(e.attributes)
380
+ }))
381
+ }]
382
+ }));
383
+ return {
384
+ body: JSON.stringify({ resourceLogs: n }),
385
+ contentType: d
386
+ };
387
+ }
388
+ };
389
+ //#endregion
390
+ //#region src/transport/serializers/select.ts
391
+ function X(e) {
392
+ return e === "otlp" ? Ce : e === "ecs" ? xe : e;
393
+ }
394
+ //#endregion
395
+ //#region src/transport/exit-flush.ts
396
+ var we = class {
397
+ deps;
398
+ installed = !1;
399
+ onVisibility = () => {
400
+ document.visibilityState === "hidden" && this.flush("hidden");
401
+ };
402
+ onPageHide = () => {
403
+ this.flush("pagehide");
404
+ };
405
+ onFreeze = () => {
406
+ this.flush("freeze");
407
+ };
408
+ onOpenFinClose = () => {
409
+ this.flush("openfin-close");
410
+ };
411
+ constructor(e) {
412
+ this.deps = e;
413
+ }
414
+ install() {
415
+ if (this.installed || typeof addEventListener > "u") return;
416
+ this.installed = !0, typeof document < "u" && (document.addEventListener("visibilitychange", this.onVisibility), document.addEventListener("freeze", this.onFreeze)), addEventListener("pagehide", this.onPageHide);
417
+ let e = globalThis.fin?.me;
418
+ this.deps.diagnostics.guard("openfin.unavailable", "subscribing to close-requested", () => {
419
+ e?.on?.("close-requested", this.onOpenFinClose);
420
+ });
421
+ }
422
+ uninstall() {
423
+ if (!this.installed) return;
424
+ this.installed = !1, typeof document < "u" && (document.removeEventListener("visibilitychange", this.onVisibility), document.removeEventListener("freeze", this.onFreeze)), removeEventListener("pagehide", this.onPageHide);
425
+ let e = globalThis.fin?.me;
426
+ this.deps.diagnostics.guard("openfin.unavailable", "releasing close-requested", () => {
427
+ e?.removeListener?.("close-requested", this.onOpenFinClose);
428
+ });
429
+ }
430
+ flush(e) {
431
+ let { diagnostics: t } = this.deps, n = this.endpointUrl();
432
+ if (n === null) return;
433
+ let r = this.drain(e);
434
+ if (!r || r.records.length === 0) return;
435
+ let i = t.guard("transport.serialize_failed", `the ${e} exit flush could not serialize its batch`, () => X(this.deps.config.serializer).serialize(r.records));
436
+ if (!i) return;
437
+ if (k(i.body) > 6e4) {
438
+ B(r, t);
439
+ return;
440
+ }
441
+ n.searchParams.set(m, r.id), n.searchParams.set(ue, e);
442
+ let a = n.toString(), o = this.beacon(a, i.body);
443
+ o !== "sent" && (o === "refused" ? B(r, t) : this.keepaliveFetch(a, i.body, e));
444
+ }
445
+ drain(e) {
446
+ return e === "hidden" ? this.deps.drainPending() : this.deps.drainForExit();
447
+ }
448
+ endpointUrl() {
449
+ let { endpoint: e } = this.deps.config;
450
+ return e ? this.deps.diagnostics.guard("config.invalid", `the exit flush cannot use endpoint ${e}`, () => new URL(e)) ?? null : null;
451
+ }
452
+ beacon(e, t) {
453
+ return this.deps.diagnostics.guard("transport.http_error", "sendBeacon", () => {
454
+ let n = globalThis.navigator;
455
+ return n?.sendBeacon ? n.sendBeacon(e, new Blob([t], { type: "text/plain;charset=UTF-8" })) ? "sent" : "refused" : "unavailable";
456
+ }) ?? "unavailable";
457
+ }
458
+ keepaliveFetch(e, n, r) {
459
+ let { config: i, diagnostics: a } = this.deps;
460
+ a.guard("transport.http_error", "the keepalive fetch fallback", () => {
461
+ fetch(e, {
462
+ method: "POST",
463
+ body: n,
464
+ headers: { [o]: t },
465
+ credentials: i.credentials,
466
+ keepalive: !0
467
+ }).catch((e) => {
468
+ a.report("transport.http_error", "the exit flush failed", { reason: r }, e);
469
+ });
470
+ });
471
+ }
472
+ };
473
+ //#endregion
474
+ //#region src/transport/compression.ts
475
+ async function Te(e) {
476
+ let t = globalThis.CompressionStream;
477
+ if (t === void 0) return null;
478
+ let n = new Blob([e]).stream().pipeThrough(new t(E)), r = await new Response(n).arrayBuffer();
479
+ return new Uint8Array(r);
480
+ }
481
+ //#endregion
482
+ //#region src/transport/errors.ts
483
+ var Z = class extends Error {
484
+ kind;
485
+ status;
486
+ retryAfterMs;
487
+ maxBytes;
488
+ constructor(e, t, n, r, i) {
489
+ super(t), this.kind = e, this.status = n, this.retryAfterMs = r, this.maxBytes = i, this.name = "TransportError";
490
+ }
491
+ };
492
+ function Ee(e) {
493
+ if (!e) return;
494
+ let t = Number(e);
495
+ if (Number.isFinite(t)) return Math.max(0, t * le);
496
+ let n = Date.parse(e);
497
+ return Number.isNaN(n) ? void 0 : Math.max(0, n - Date.now());
498
+ }
499
+ //#endregion
500
+ //#region src/transport/http-transport.ts
501
+ var Q = class {
502
+ config;
503
+ diagnostics;
504
+ throttledUntil = 0;
505
+ constructor(e, t) {
506
+ this.config = e, this.diagnostics = t;
507
+ }
508
+ async send(e) {
509
+ let { endpoint: t } = this.config;
510
+ t && e.records.length !== 0 && await this.post(e, t);
511
+ }
512
+ throttledForMs() {
513
+ return Math.max(0, this.throttledUntil - Date.now());
514
+ }
515
+ async post(e, t) {
516
+ let { config: n } = this, i;
517
+ try {
518
+ i = X(n.serializer).serialize(e.records);
519
+ } catch (t) {
520
+ this.diagnostics.report("transport.serialize_failed", "serializer threw, dropping the batch", { batchId: e.id }, t);
521
+ return;
522
+ }
523
+ let a = new Headers(await this.resolveHeaders());
524
+ a.set(o, i.contentType), a.set(c, e.id), a.set(r, String(e.attempts));
525
+ let s = await this.encodeBody(i.body);
526
+ typeof s != "string" && a.set(oe, E);
527
+ let l = await this.dispatch(t, a, s);
528
+ if (l.ok) this.throttledUntil = 0;
529
+ else throw await this.classify(l, e.id);
530
+ }
531
+ async encodeBody(e) {
532
+ let { config: t } = this;
533
+ return t.compression !== "gzip" || k(e) < 1024 ? e : await this.diagnostics.guardAsync("transport.http_error", "gzipping the payload", () => Te(e)) ?? e;
534
+ }
535
+ async dispatch(e, t, n) {
536
+ let { config: r } = this, i = new AbortController(), a = setTimeout(() => {
537
+ i.abort();
538
+ }, T);
539
+ M(a);
540
+ try {
541
+ return await fetch(e, {
542
+ method: "POST",
543
+ headers: t,
544
+ body: n,
545
+ credentials: r.credentials,
546
+ signal: i.signal,
547
+ cache: "no-store"
548
+ });
549
+ } catch {
550
+ if (i.signal.aborted) throw new Z("timeout", `request exceeded ${String(T)}ms`);
551
+ let e = globalThis.navigator?.onLine;
552
+ throw new Z(e === !1 ? "offline" : "transient", "network error");
553
+ } finally {
554
+ clearTimeout(a);
555
+ }
556
+ }
557
+ async classify(e, t) {
558
+ let n = e.status, r = Ee(e.headers.get(re));
559
+ if (n === 401 || n === 403) return this.diagnostics.report("transport.rejected_credentials", `server returned ${String(n)}. In a cross-origin iframe the session cookie is a third-party cookie and is very likely blocked. Forward to the platform document instead of promoting to sender, or issue the cookie with the Partitioned attribute.`, {
560
+ status: n,
561
+ endpoint: this.config.endpoint
562
+ }), new Z("permanent", `rejected with ${String(n)}`, n);
563
+ if (n === 413) return new Z("too_large", "payload too large", n, void 0, await this.readMaxBytes(e));
564
+ if (n === 429 || n === 503) {
565
+ let e = n === 429;
566
+ return this.throttledUntil = Date.now() + (r ?? 2e3), e && this.diagnostics.report("transport.throttled", "server throttled us", { retryAfterMs: r }), new Z("throttled", e ? "throttled" : "service unavailable", n, r);
567
+ }
568
+ return n === 408 || n >= 500 ? new Z("transient", `server error ${String(n)}`, n) : (this.diagnostics.report("transport.dropped_permanent", `server rejected the batch with ${String(n)}, dropping it`, {
569
+ batchId: t,
570
+ status: n
571
+ }), new Z("permanent", `rejected with ${String(n)}`, n));
572
+ }
573
+ async readMaxBytes(e) {
574
+ return this.diagnostics.guardAsync("transport.http_error", "reading the 413 body", async () => {
575
+ let t = JSON.parse(await e.text());
576
+ return typeof t.maxBytes == "number" ? t.maxBytes : void 0;
577
+ });
578
+ }
579
+ async resolveHeaders() {
580
+ let { headers: e } = this.config;
581
+ return e ? typeof e == "function" ? await this.diagnostics.guardAsync("transport.http_error", "headers() threw", () => Promise.resolve(e())) ?? {} : e : {};
582
+ }
583
+ }, De = class {
584
+ storage;
585
+ transport;
586
+ diagnostics;
587
+ config;
588
+ batchesPerDrain;
589
+ timer = null;
590
+ attempt = 0;
591
+ draining = !1;
592
+ stopped = !1;
593
+ onOnline = () => {
594
+ this.attempt = 0, this.schedule(0);
595
+ };
596
+ constructor(e, t, n, r, i = 20) {
597
+ this.storage = e, this.transport = t, this.diagnostics = n, this.config = r, this.batchesPerDrain = i;
598
+ }
599
+ start() {
600
+ this.stopped = !1, typeof addEventListener < "u" && addEventListener("online", this.onOnline), this.schedule(a);
601
+ }
602
+ nudge() {
603
+ this.draining || this.schedule(n);
604
+ }
605
+ async storeFailed(e, t) {
606
+ let n = this.toStorable(e, t);
607
+ for (let e of n) await this.bounded(this.storage.save(e));
608
+ n.length > 0 && this.nudge();
609
+ }
610
+ stop() {
611
+ this.stopped = !0, typeof removeEventListener < "u" && removeEventListener("online", this.onOnline), this.clearTimer();
612
+ }
613
+ schedule(e) {
614
+ if (this.stopped) return;
615
+ this.clearTimer();
616
+ let t = setTimeout(() => {
617
+ this.drain();
618
+ }, e);
619
+ this.timer = t, M(t);
620
+ }
621
+ bounded(e) {
622
+ return A(e, C);
623
+ }
624
+ clearTimer() {
625
+ this.timer !== null && (clearTimeout(this.timer), this.timer = null);
626
+ }
627
+ backoffMs() {
628
+ let e = Math.min(n * 2 ** this.attempt, u);
629
+ return Math.random() * e;
630
+ }
631
+ async drain() {
632
+ if (!this.draining) {
633
+ this.draining = !0;
634
+ try {
635
+ await F("ui-observability.drain", this.diagnostics, () => this.drainLocked()) !== !0 && this.schedule(a);
636
+ } finally {
637
+ this.draining = !1;
638
+ }
639
+ }
640
+ }
641
+ async drainLocked() {
642
+ try {
643
+ if (globalThis.navigator?.onLine === !1) return this.schedule(a), !0;
644
+ let e = await this.bounded(this.storage.take(this.batchesPerDrain));
645
+ if (e.length === 0) return this.schedule(a), !0;
646
+ for (let t of e) if (this.stopped || !await this.deliver(t)) return !0;
647
+ return this.schedule(e.length === this.batchesPerDrain ? 0 : a), !0;
648
+ } catch (e) {
649
+ return this.diagnostics.report("storage.degraded", "the drain loop threw", void 0, e), this.attempt++, this.schedule(this.backoffMs()), !0;
650
+ }
651
+ }
652
+ async deliver(e) {
653
+ if (e.attempts >= s.maxAttempts) return this.diagnostics.report("storage.dead_lettered", `giving up on a batch after ${e.attempts.toString()} attempts`, {
654
+ batchId: e.id,
655
+ records: e.records.length
656
+ }), await this.bounded(this.storage.remove(e.id)), !0;
657
+ try {
658
+ return await this.transport.send(e), await this.bounded(this.storage.remove(e.id)), this.attempt = 0, !0;
659
+ } catch (t) {
660
+ let n = t instanceof Z ? t : void 0;
661
+ return n?.kind === "permanent" || n?.kind === "too_large" ? (await this.replaceStored(e, t), !0) : n?.kind === "offline" ? (this.schedule(a), !1) : n?.kind === "throttled" ? (this.attempt++, this.schedule(n.retryAfterMs ?? this.backoffMs()), !1) : (await this.bounded(this.storage.bumpAttempts(e.id, e.attempts + 1)), this.attempt++, this.schedule(n?.retryAfterMs ?? this.backoffMs()), !1);
662
+ }
663
+ }
664
+ async replaceStored(e, t) {
665
+ let n = this.toStorable(e, t);
666
+ await this.bounded(this.storage.remove(e.id));
667
+ for (let e of n) await this.bounded(this.storage.save(e));
668
+ }
669
+ toStorable(e, t) {
670
+ let n = t instanceof Z ? t : void 0;
671
+ if (n?.kind === "permanent") return [];
672
+ if (n?.kind !== "too_large") return [e];
673
+ let r = P(e);
674
+ return r ? (this.diagnostics.report("transport.batch_split", "the server refused the batch as too large", {
675
+ from: e.records.length,
676
+ to: r[0].records.length,
677
+ serverMaxBytes: n.maxBytes
678
+ }), r) : (this.diagnostics.report("transport.dropped_permanent", "a single record exceeds the server limit and was dropped", {
679
+ batchId: e.id,
680
+ bodies: e.records.map((e) => e.body)
681
+ }), []);
682
+ }
683
+ };
684
+ //#endregion
685
+ //#region src/core/pipeline.ts
686
+ function Oe(e) {
687
+ return e.attributes[b] === ce;
688
+ }
689
+ var ke = {
690
+ logs: {
691
+ flushIntervalMs: S,
692
+ batchSize: 100
693
+ },
694
+ metrics: {
695
+ flushIntervalMs: x,
696
+ batchSize: 500
697
+ }
698
+ }, $ = class {
699
+ options;
700
+ onFlush;
701
+ pending = [];
702
+ timer = null;
703
+ constructor(e, t) {
704
+ this.options = e, this.onFlush = t;
705
+ }
706
+ add(e) {
707
+ this.pending.push(e), this.pending.length >= this.options.batchSize ? this.onFlush(this) : this.arm();
708
+ }
709
+ take() {
710
+ this.clearTimer();
711
+ let e = this.pending;
712
+ return this.pending = [], e;
713
+ }
714
+ stop() {
715
+ this.clearTimer();
716
+ }
717
+ arm() {
718
+ if (this.timer !== null) return;
719
+ let e = setTimeout(() => {
720
+ this.timer = null, this.onFlush(this);
721
+ }, this.options.flushIntervalMs);
722
+ this.timer = e, M(e);
723
+ }
724
+ clearTimer() {
725
+ this.timer !== null && (clearTimeout(this.timer), this.timer = null);
726
+ }
727
+ }, Ae = class {
728
+ transport;
729
+ storage;
730
+ retry;
731
+ diagnostics;
732
+ streams;
733
+ unconfirmed = /* @__PURE__ */ new Map();
734
+ queue = [];
735
+ ceiling = new j();
736
+ inFlight = 0;
737
+ pumpScheduled = !1;
738
+ stopped = !1;
739
+ constructor(e, t, n, r, i = ke) {
740
+ this.transport = e, this.storage = t, this.retry = n, this.diagnostics = r;
741
+ let a = (e) => {
742
+ this.claim(e);
743
+ };
744
+ this.streams = {
745
+ logs: new $(i.logs, a),
746
+ metrics: new $(i.metrics, a)
747
+ };
748
+ }
749
+ push(e) {
750
+ this.stopped || (e.observedTimeUnixNano = D(), this.route(e));
751
+ }
752
+ drainPending() {
753
+ return this.toBatch([...this.streams.metrics.take(), ...this.streams.logs.take()]);
754
+ }
755
+ drainForExit() {
756
+ let e = [...this.unconfirmed.values()].flatMap((e) => e.records);
757
+ return this.unconfirmed.clear(), this.toBatch([
758
+ ...e,
759
+ ...this.streams.metrics.take(),
760
+ ...this.streams.logs.take()
761
+ ]);
762
+ }
763
+ destroy() {
764
+ this.stopped = !0, this.streams.logs.stop(), this.streams.metrics.stop(), this.queue.length = 0;
765
+ }
766
+ toBatch(e) {
767
+ return e.length === 0 ? null : {
768
+ id: O(),
769
+ records: e,
770
+ createdAt: Date.now(),
771
+ attempts: 0
772
+ };
773
+ }
774
+ route(e) {
775
+ try {
776
+ let t = Oe(e) ? this.streams.metrics : this.streams.logs;
777
+ if (!this.ceiling.allow(e)) {
778
+ this.diagnostics.count("record.dropped_by_ceiling");
779
+ return;
780
+ }
781
+ t.add(e);
782
+ } catch (e) {
783
+ this.diagnostics.report("pipeline.crashed", "a record was dropped on its way into a stream", void 0, e);
784
+ }
785
+ }
786
+ claim(e) {
787
+ let t = e.take(), n = {
788
+ id: O(),
789
+ records: t,
790
+ createdAt: Date.now(),
791
+ attempts: 0
792
+ };
793
+ this.unconfirmed.set(n.id, n), this.enqueue(n);
794
+ }
795
+ enqueue(e) {
796
+ this.queue.push(e), !this.pumpScheduled && (this.pumpScheduled = !0, queueMicrotask(() => {
797
+ this.pumpScheduled = !1, this.pump();
798
+ }));
799
+ }
800
+ pump() {
801
+ for (; this.inFlight < 2;) {
802
+ let e = this.queue.shift();
803
+ if (!e) return;
804
+ this.inFlight++, this.run(e);
805
+ }
806
+ }
807
+ async run(e) {
808
+ try {
809
+ await this.dispatch(e);
810
+ } catch (t) {
811
+ this.diagnostics.report("pipeline.crashed", "dispatch rejected, which it is written never to do", { batchId: e.id }, t);
812
+ } finally {
813
+ this.inFlight--, this.pump();
814
+ }
815
+ }
816
+ async dispatch(e) {
817
+ try {
818
+ let t = this.transport.throttledForMs();
819
+ if (t > 0) {
820
+ await this.store(e), this.diagnostics.report("transport.throttled", "stored the batch rather than sending it", {
821
+ batchId: e.id,
822
+ records: e.records.length,
823
+ throttledMs: t
824
+ });
825
+ return;
826
+ }
827
+ try {
828
+ await this.transport.send(e);
829
+ } catch (t) {
830
+ await this.storeFailed({
831
+ ...e,
832
+ attempts: e.attempts + 1
833
+ }, t), this.diagnostics.report("transport.http_error", "batch was stored for retry instead of being delivered", {
834
+ batchId: e.id,
835
+ records: e.records.length
836
+ }, t);
837
+ }
838
+ } finally {
839
+ this.unconfirmed.delete(e.id);
840
+ }
841
+ }
842
+ async storeFailed(e, t) {
843
+ await this.diagnostics.guardAsync("storage.degraded", "persisting an undelivered batch", async () => {
844
+ await this.retry.storeFailed(e, t);
845
+ });
846
+ }
847
+ async store(e) {
848
+ await this.diagnostics.guardAsync("storage.degraded", "persisting an undelivered batch", async () => {
849
+ await A(this.storage.save(e), C), this.retry.nudge();
850
+ });
851
+ }
852
+ }, je = class e {
853
+ storage;
854
+ transport;
855
+ retry;
856
+ pipeline;
857
+ exitFlush;
858
+ diagnostics;
859
+ constructor(e, t, n, r, i, a) {
860
+ this.storage = e, this.transport = t, this.retry = n, this.pipeline = r, this.exitFlush = i, this.diagnostics = a;
861
+ }
862
+ static async create(t) {
863
+ let { config: n, diagnostics: r } = t, i = await _e(n.storage, l, s, r, t.onGap), a = new Q(n, r), o = new De(i, a, r, n), c = new Ae(a, i, o, r), u = new we({
864
+ config: n,
865
+ diagnostics: r,
866
+ drainForExit: () => c.drainForExit(),
867
+ drainPending: () => c.drainPending()
868
+ });
869
+ await V(i, r);
870
+ let d = !1;
871
+ try {
872
+ u.install(), o.start(), d = !0;
873
+ } finally {
874
+ d || (u.uninstall(), o.stop());
875
+ }
876
+ return new e(i, a, o, c, u, r);
877
+ }
878
+ push(e) {
879
+ this.pipeline.push(e);
880
+ }
881
+ async flush() {
882
+ let e = this.pipeline.drainPending();
883
+ if (e) try {
884
+ await this.transport.send(e);
885
+ } catch (t) {
886
+ await this.diagnostics.guardAsync("storage.degraded", "persisting the batch drained by flush()", async () => {
887
+ await this.retry.storeFailed({
888
+ ...e,
889
+ attempts: e.attempts + 1
890
+ }, t);
891
+ }), this.diagnostics.report("transport.http_error", "the batch drained by flush() was stored for retry instead of being delivered", {
892
+ batchId: e.id,
893
+ records: e.records.length
894
+ }, t);
895
+ }
896
+ }
897
+ async queueDepth() {
898
+ return await this.diagnostics.guardAsync("storage.degraded", "counting the batches waiting in storage", () => this.storage.count()) ?? 0;
899
+ }
900
+ async destroy() {
901
+ this.exitFlush.flush("shutdown"), this.exitFlush.uninstall(), this.retry.stop(), this.pipeline.destroy(), await this.storage.close();
902
+ }
903
+ };
904
+ //#endregion
905
+ export { je as Sender };
906
+
907
+ //# sourceMappingURL=sender-R7lOpyNc.js.map