@utk09/ui-observability 0.9.0 → 0.9.2

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 (144) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/README.md +83 -52
  3. package/dist/batch-4xKzzSCj.js +31 -0
  4. package/dist/batch-4xKzzSCj.js.map +1 -0
  5. package/dist/batch-cys7e53Q.cjs +2 -0
  6. package/dist/batch-cys7e53Q.cjs.map +1 -0
  7. package/dist/{bus-CtJWf9QN.cjs → bus-B6vzPmQM.cjs} +2 -2
  8. package/dist/{bus-CtJWf9QN.cjs.map → bus-B6vzPmQM.cjs.map} +1 -1
  9. package/dist/{bus-D8kH58tb.js → bus-DrixwdiX.js} +10 -10
  10. package/dist/{bus-D8kH58tb.js.map → bus-DrixwdiX.js.map} +1 -1
  11. package/dist/capture/network.d.ts +2 -0
  12. package/dist/capture/types.d.ts +3 -0
  13. package/dist/{console-DjLbryED.js → console-B3vGRW5p.js} +3 -3
  14. package/dist/{console-DjLbryED.js.map → console-B3vGRW5p.js.map} +1 -1
  15. package/dist/{console-BpHfWstv.cjs → console-ChfuJlf9.cjs} +2 -2
  16. package/dist/{console-BpHfWstv.cjs.map → console-ChfuJlf9.cjs.map} +1 -1
  17. package/dist/constants-Be83LICb.cjs +2 -0
  18. package/dist/constants-Be83LICb.cjs.map +1 -0
  19. package/dist/constants-CQ_D7jIW.js +144 -0
  20. package/dist/constants-CQ_D7jIW.js.map +1 -0
  21. package/dist/constants.d.ts +44 -11
  22. package/dist/core/diagnostics.d.ts +1 -1
  23. package/dist/core/drops.d.ts +29 -0
  24. package/dist/core/hold-buffer.d.ts +27 -0
  25. package/dist/core/meter.d.ts +45 -0
  26. package/dist/core/pipeline.d.ts +7 -19
  27. package/dist/core/record.d.ts +7 -0
  28. package/dist/core/runtime.d.ts +61 -8
  29. package/dist/core/sampling.d.ts +2 -0
  30. package/dist/core/sender.d.ts +6 -1
  31. package/dist/deadline-5_PecIl5.js +26 -0
  32. package/dist/deadline-5_PecIl5.js.map +1 -0
  33. package/dist/deadline-XSnm95pg.cjs +2 -0
  34. package/dist/deadline-XSnm95pg.cjs.map +1 -0
  35. package/dist/{errors-DH4QJS0u.js → errors-BGs5NOrw.js} +4 -4
  36. package/dist/{errors-DH4QJS0u.js.map → errors-BGs5NOrw.js.map} +1 -1
  37. package/dist/{errors-CpGRhhIf.cjs → errors-BMJm7KZZ.cjs} +2 -2
  38. package/dist/{errors-CpGRhhIf.cjs.map → errors-BMJm7KZZ.cjs.map} +1 -1
  39. package/dist/identity-DXyV86o-.cjs +2 -0
  40. package/dist/identity-DXyV86o-.cjs.map +1 -0
  41. package/dist/{deadline-B5DINjD5.js → identity-rpEyjvVg.js} +3 -26
  42. package/dist/identity-rpEyjvVg.js.map +1 -0
  43. package/dist/index.cjs +1 -1
  44. package/dist/index.cjs.map +1 -1
  45. package/dist/index.d.ts +19 -0
  46. package/dist/index.js +683 -369
  47. package/dist/index.js.map +1 -1
  48. package/dist/indexeddb-storage-BXaPVPyG.cjs +2 -0
  49. package/dist/indexeddb-storage-BXaPVPyG.cjs.map +1 -0
  50. package/dist/{indexeddb-storage-n1qkFBGA.js → indexeddb-storage-Q9fDYlyn.js} +76 -47
  51. package/dist/indexeddb-storage-Q9fDYlyn.js.map +1 -0
  52. package/dist/{interactions-OU94MPXs.js → interactions-B8zjCjga.js} +2 -2
  53. package/dist/{interactions-OU94MPXs.js.map → interactions-B8zjCjga.js.map} +1 -1
  54. package/dist/{interactions-31eHGwEQ.cjs → interactions-BAGRmtrv.cjs} +2 -2
  55. package/dist/{interactions-31eHGwEQ.cjs.map → interactions-BAGRmtrv.cjs.map} +1 -1
  56. package/dist/journey-BGSyy8Es.cjs +2 -0
  57. package/dist/journey-BGSyy8Es.cjs.map +1 -0
  58. package/dist/{journey-CeJ1QoT2.js → journey-_dQQ1eMP.js} +27 -26
  59. package/dist/{journey-CeJ1QoT2.js.map → journey-_dQQ1eMP.js.map} +1 -1
  60. package/dist/library-request-BIG3Xpx3.cjs +2 -0
  61. package/dist/library-request-BIG3Xpx3.cjs.map +1 -0
  62. package/dist/library-request-DX6ev9oG.js +25 -0
  63. package/dist/library-request-DX6ev9oG.js.map +1 -0
  64. package/dist/{long-frames-C_7OutLs.js → long-frames-B0tKuChx.js} +3 -3
  65. package/dist/{long-frames-C_7OutLs.js.map → long-frames-B0tKuChx.js.map} +1 -1
  66. package/dist/{long-frames-B8VdA_ny.cjs → long-frames-Cq2LgNnp.cjs} +2 -2
  67. package/dist/{long-frames-B8VdA_ny.cjs.map → long-frames-Cq2LgNnp.cjs.map} +1 -1
  68. package/dist/models/batch.d.ts +14 -0
  69. package/dist/models/config.d.ts +169 -0
  70. package/dist/models/drop.d.ts +39 -0
  71. package/dist/models/metric.d.ts +50 -0
  72. package/dist/models/storage.d.ts +15 -3
  73. package/dist/network-C6kJbW6K.cjs +2 -0
  74. package/dist/network-C6kJbW6K.cjs.map +1 -0
  75. package/dist/network-CMnEvGJB.js +211 -0
  76. package/dist/network-CMnEvGJB.js.map +1 -0
  77. package/dist/{platform-D4wu1eIF.cjs → platform-DNOJjpOm.cjs} +2 -2
  78. package/dist/{platform-D4wu1eIF.cjs.map → platform-DNOJjpOm.cjs.map} +1 -1
  79. package/dist/{platform-IHBZGqUe.js → platform-j0uMPwHi.js} +3 -3
  80. package/dist/{platform-IHBZGqUe.js.map → platform-j0uMPwHi.js.map} +1 -1
  81. package/dist/{remote-rules-kuDf5gbe.cjs → remote-rules-DgoBJxZL.cjs} +2 -2
  82. package/dist/{remote-rules-kuDf5gbe.cjs.map → remote-rules-DgoBJxZL.cjs.map} +1 -1
  83. package/dist/{remote-rules-Bt1XsdEQ.js → remote-rules-UggoZqfP.js} +11 -11
  84. package/dist/{remote-rules-Bt1XsdEQ.js.map → remote-rules-UggoZqfP.js.map} +1 -1
  85. package/dist/{sampling-o0VY1mqQ.js → sampling-BLMD8EGM.js} +28 -27
  86. package/dist/sampling-BLMD8EGM.js.map +1 -0
  87. package/dist/sampling-MthcVXXU.cjs +2 -0
  88. package/dist/sampling-MthcVXXU.cjs.map +1 -0
  89. package/dist/{sanitize-B9UheVKc.js → sanitize-BNwgPj_B.js} +2 -2
  90. package/dist/{sanitize-B9UheVKc.js.map → sanitize-BNwgPj_B.js.map} +1 -1
  91. package/dist/{sanitize-DSIP7amZ.cjs → sanitize-BqzPc4Jg.cjs} +2 -2
  92. package/dist/{sanitize-DSIP7amZ.cjs.map → sanitize-BqzPc4Jg.cjs.map} +1 -1
  93. package/dist/sender--0_VzPbN.js +1249 -0
  94. package/dist/sender--0_VzPbN.js.map +1 -0
  95. package/dist/sender-SPGMqZjD.cjs +3 -0
  96. package/dist/sender-SPGMqZjD.cjs.map +1 -0
  97. package/dist/storage/emergency-queue.d.ts +4 -1
  98. package/dist/storage/eviction.d.ts +40 -0
  99. package/dist/storage/idb-driver.d.ts +6 -0
  100. package/dist/storage/indexeddb-storage.d.ts +13 -5
  101. package/dist/storage/local-storage.d.ts +24 -1
  102. package/dist/storage/memory-storage.d.ts +7 -0
  103. package/dist/{storm-Y-yuBhvv.cjs → storm-CTy1dfvs.cjs} +2 -2
  104. package/dist/{storm-Y-yuBhvv.cjs.map → storm-CTy1dfvs.cjs.map} +1 -1
  105. package/dist/{storm-BTw0J6eE.js → storm-knaj4GUH.js} +2 -2
  106. package/dist/{storm-BTw0J6eE.js.map → storm-knaj4GUH.js.map} +1 -1
  107. package/dist/transport/custom-transport.d.ts +3 -2
  108. package/dist/transport/exit-flush.d.ts +19 -2
  109. package/dist/transport/http-transport.d.ts +6 -4
  110. package/dist/transport/retry-engine.d.ts +9 -3
  111. package/dist/transport/serializers/otlp-metrics.d.ts +3 -0
  112. package/dist/transport/serializers/otlp.d.ts +30 -0
  113. package/dist/transport/serializers/select.d.ts +20 -4
  114. package/dist/transport/status-transport.d.ts +23 -12
  115. package/dist/utils/console.d.ts +4 -1
  116. package/dist/utils/library-request.d.ts +12 -0
  117. package/package.json +1 -1
  118. package/dist/constants-Br3b89Wg.cjs +0 -2
  119. package/dist/constants-Br3b89Wg.cjs.map +0 -1
  120. package/dist/constants-DM94FjVX.js +0 -96
  121. package/dist/constants-DM94FjVX.js.map +0 -1
  122. package/dist/deadline-B5DINjD5.js.map +0 -1
  123. package/dist/deadline-Cbg2cbUw.cjs +0 -2
  124. package/dist/deadline-Cbg2cbUw.cjs.map +0 -1
  125. package/dist/indexeddb-storage-DNdf1fmL.cjs +0 -2
  126. package/dist/indexeddb-storage-DNdf1fmL.cjs.map +0 -1
  127. package/dist/indexeddb-storage-n1qkFBGA.js.map +0 -1
  128. package/dist/journey-CE2EcwHW.cjs +0 -2
  129. package/dist/journey-CE2EcwHW.cjs.map +0 -1
  130. package/dist/library-request-C9uJFlbq.cjs +0 -2
  131. package/dist/library-request-C9uJFlbq.cjs.map +0 -1
  132. package/dist/library-request-DvhuplAB.js +0 -14
  133. package/dist/library-request-DvhuplAB.js.map +0 -1
  134. package/dist/network-BAV7ipyn.cjs +0 -2
  135. package/dist/network-BAV7ipyn.cjs.map +0 -1
  136. package/dist/network-D_lloS5t.js +0 -174
  137. package/dist/network-D_lloS5t.js.map +0 -1
  138. package/dist/sampling-BI15ds9D.cjs +0 -2
  139. package/dist/sampling-BI15ds9D.cjs.map +0 -1
  140. package/dist/sampling-o0VY1mqQ.js.map +0 -1
  141. package/dist/sender-BnNj9bOX.js +0 -1050
  142. package/dist/sender-BnNj9bOX.js.map +0 -1
  143. package/dist/sender-D0OsyB1c.cjs +0 -3
  144. package/dist/sender-D0OsyB1c.cjs.map +0 -1
@@ -0,0 +1,1249 @@
1
+ import { $ as e, B as t, Ct as n, Dt as r, Ft as i, H as a, Ht as o, Jt as s, Lt as c, M as l, N as u, Ot as d, P as f, Pt as p, Q as m, St as ee, U as h, Vt as te, X as g, Xt as _, Y as ne, Yt as v, Z as re, an as ie, bt as ae, d as oe, dn as se, en as y, et as ce, fn as b, gn as x, hn as S, ht as le, ln as ue, on as C, un as de, vt as w, x as T } from "./constants-CQ_D7jIW.js";
2
+ import { o as fe, t as pe } from "./sampling-BLMD8EGM.js";
3
+ import { o as me, t as E } from "./sanitize-BNwgPj_B.js";
4
+ import { i as he } from "./identity-rpEyjvVg.js";
5
+ import { i as ge, n as _e, r as D, t as ve } from "./batch-4xKzzSCj.js";
6
+ import { i as ye, r as O } from "./library-request-DX6ev9oG.js";
7
+ import { n as k, r as A, t as be } from "./deadline-5_PecIl5.js";
8
+ import { n as xe, t as Se } from "./remote-rules-UggoZqfP.js";
9
+ //#region src/models/storage.ts
10
+ function j(e) {
11
+ let { maxBatches: t } = e;
12
+ return e.mode === "until-delivered" ? {
13
+ maxBatches: t,
14
+ maxAgeMs: Infinity,
15
+ maxAttempts: Infinity
16
+ } : {
17
+ maxBatches: t,
18
+ maxAgeMs: e.maxAgeMs,
19
+ maxAttempts: e.maxAttempts
20
+ };
21
+ }
22
+ //#endregion
23
+ //#region src/utils/lock.ts
24
+ function M(e, t, n, { skipIfBusy: r = !0 } = {}) {
25
+ let i = globalThis.navigator?.locks;
26
+ return i?.request ? t.guardAsync("storage.degraded", `The library could not get the lock ${e}.`, () => i.request(e, { ifAvailable: r }, (e) => e ? n() : Promise.resolve(void 0))) : n();
27
+ }
28
+ //#endregion
29
+ //#region src/storage/keys.ts
30
+ function N(e, t) {
31
+ let n = [];
32
+ return t.guard("storage.unavailable", "The library could not list the localStorage keys.", () => {
33
+ for (let t = 0; t < localStorage.length; t++) {
34
+ let r = String(localStorage.key(t));
35
+ r.startsWith(e) && n.push(r);
36
+ }
37
+ }), n.sort();
38
+ }
39
+ //#endregion
40
+ //#region src/storage/emergency-queue.ts
41
+ function Ce(e) {
42
+ let t = String(e.createdAt).padStart(14, "0");
43
+ return `${a}${t}.${e.id}`;
44
+ }
45
+ function P(e, t) {
46
+ let n = t.guard("storage.degraded", "An emergency entry is not valid JSON. The library dropped it.", () => JSON.parse(e));
47
+ return n === void 0 ? null : D(n) ? n : (t.report("storage.degraded", "An emergency entry is not a batch. The library dropped it."), null);
48
+ }
49
+ async function we(e, t) {
50
+ let n = 0;
51
+ for (let r of N(a, t)) {
52
+ let i = t.guard("storage.unavailable", "The library could not read the emergency queue.", () => {
53
+ let e = localStorage.getItem(r);
54
+ return localStorage.removeItem(r), e;
55
+ });
56
+ if (!i) continue;
57
+ let a = P(i, t);
58
+ if (a !== null) try {
59
+ await k(e.save(a), C), n++;
60
+ } catch (e) {
61
+ t.report("storage.degraded", "The library could not recover an emergency batch.", { key: r }, e);
62
+ }
63
+ }
64
+ return n;
65
+ }
66
+ function F(e, t, n) {
67
+ let r = `writing the emergency queue, ${String(e.records.length)} records`, i = [], o = t.guard("storage.quota_exceeded", r, () => {
68
+ let n = N(a, t);
69
+ for (let e of n.slice(0, Math.max(0, n.length - 20 + 1))) {
70
+ let n = P(String(localStorage.getItem(e)), t);
71
+ n !== null && i.push(n), localStorage.removeItem(e);
72
+ }
73
+ return localStorage.setItem(Ce(e), JSON.stringify(e)), !0;
74
+ });
75
+ t.guard("pipeline.crashed", "The loss report of the emergency queue failed.", () => {
76
+ if (i.length > 0) {
77
+ let e = i.flatMap((e) => e.records);
78
+ n?.("exit_queue_full", e, i.map((e) => e.id));
79
+ }
80
+ o !== !0 && n?.("quota", e.records, [e.id]);
81
+ });
82
+ }
83
+ async function Te(e, t) {
84
+ return await M("ui-observability.emergency", t, () => we(e, t), { skipIfBusy: !1 }) ?? 0;
85
+ }
86
+ //#endregion
87
+ //#region src/storage/eviction.ts
88
+ function I(e) {
89
+ return Array.isArray(e.records) && e.records.some(_e);
90
+ }
91
+ var L = class {
92
+ howMany;
93
+ isAudit;
94
+ plain = [];
95
+ audit = [];
96
+ constructor(e, t) {
97
+ this.howMany = e, this.isAudit = t;
98
+ }
99
+ add(e) {
100
+ return this.isAudit(e) ? this.audit.length < this.howMany && this.audit.push(e) : this.plain.push(e), this.plain.length < this.howMany;
101
+ }
102
+ picked() {
103
+ return [...this.plain, ...this.audit].slice(0, this.howMany);
104
+ }
105
+ };
106
+ function R(e, t, n) {
107
+ let r = new L(t, n);
108
+ for (let t of e) if (!r.add(t)) break;
109
+ return r.picked();
110
+ }
111
+ //#endregion
112
+ //#region src/storage/local-storage.ts
113
+ function Ee(e) {
114
+ let t = String(e.createdAt).padStart(14, "0");
115
+ return `${T}${t}.${e.id}`;
116
+ }
117
+ function De(e) {
118
+ let t = T.length, n = Number(e.slice(t, t + 14));
119
+ return Number.isFinite(n) ? n : null;
120
+ }
121
+ var Oe = class {
122
+ limits;
123
+ diagnostics;
124
+ onGap;
125
+ name = ue;
126
+ constructor(e, t, n) {
127
+ this.limits = e, this.diagnostics = t, this.onGap = n;
128
+ }
129
+ async save(e) {
130
+ 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({
131
+ batches: 1,
132
+ records: e.records.length,
133
+ reason: "quota"
134
+ }, [e]));
135
+ }
136
+ take(e) {
137
+ let t = [];
138
+ for (let n of this.keys().slice(0, e)) {
139
+ let e = this.read(n);
140
+ e === null ? this.removeKey(n) : t.push(e);
141
+ }
142
+ return Promise.resolve(t);
143
+ }
144
+ remove(e) {
145
+ let t = this.keyOf(e);
146
+ return t !== null && this.removeKey(t), Promise.resolve();
147
+ }
148
+ bumpAttempts(e, t) {
149
+ let n = this.keyOf(e);
150
+ if (n === null) return Promise.resolve();
151
+ let r = this.read(n);
152
+ return r === null || (r.attempts = t, this.diagnostics.guard("storage.degraded", "The library could not update the attempt count.", () => {
153
+ localStorage.setItem(n, JSON.stringify(r));
154
+ })), Promise.resolve();
155
+ }
156
+ prune() {
157
+ let e = Date.now() - this.limits.maxAgeMs, t = {
158
+ batches: 0,
159
+ records: 0,
160
+ reason: "expired"
161
+ }, n = [], r = [];
162
+ for (let t of this.keys()) {
163
+ let i = De(t);
164
+ i === null || i < e ? n.push(t) : r.push(t);
165
+ }
166
+ this.drop(t, "expired", [...this.entries(n)]);
167
+ let i = r.length - this.limits.maxBatches;
168
+ return i > 0 && this.drop(t, "over_capacity", this.evictable(r, i)), Promise.resolve(t);
169
+ }
170
+ count() {
171
+ return Promise.resolve(this.keys().length);
172
+ }
173
+ clear() {
174
+ return this.evict(this.keys()), Promise.resolve();
175
+ }
176
+ close() {
177
+ return Promise.resolve();
178
+ }
179
+ write(e, t) {
180
+ return this.diagnostics.guard("storage.quota_exceeded", t, () => (localStorage.setItem(Ee(e), JSON.stringify(e)), !0)) === !0;
181
+ }
182
+ evictForQuota() {
183
+ let e = this.keys(), t = {
184
+ batches: 0,
185
+ records: 0,
186
+ reason: "quota"
187
+ }, n = Math.ceil(e.length / 4);
188
+ this.drop(t, "quota", this.evictable(e, n));
189
+ }
190
+ evictable(e, t) {
191
+ return R(this.entries(e), t, (e) => e.batch !== null && I(e.batch));
192
+ }
193
+ *entries(e) {
194
+ for (let t of e) yield {
195
+ key: t,
196
+ batch: this.read(t)
197
+ };
198
+ }
199
+ drop(e, t, n) {
200
+ if (n.length === 0) return;
201
+ let r = [], i = 0;
202
+ for (let { key: e, batch: t } of n) this.removeKey(e), i += t?.records.length ?? 0, t && r.push(t);
203
+ e.batches += n.length, e.records += i, e.reason = t, this.reportGap({
204
+ batches: n.length,
205
+ records: i,
206
+ reason: t
207
+ }, r);
208
+ }
209
+ reportGap(e, t) {
210
+ this.diagnostics.report("storage.evicted", `The library dropped ${String(e.batches)} stored batches (${String(e.records)} records).`, { ...e }), this.onGap?.(e, t);
211
+ }
212
+ read(e) {
213
+ let t = this.diagnostics.guard("storage.unavailable", "The library could not read a stored batch.", () => localStorage.getItem(e));
214
+ if (!t) return null;
215
+ let n = this.diagnostics.guard("storage.degraded", "A stored batch is corrupt. The library removed it.", () => JSON.parse(t));
216
+ return n === void 0 ? null : D(n) ? n : (this.diagnostics.report("storage.degraded", "A stored entry is not a batch. The library dropped it."), null);
217
+ }
218
+ keyOf(e) {
219
+ return this.keys().find((t) => t.endsWith(`.${e}`)) ?? null;
220
+ }
221
+ evict(e) {
222
+ for (let t of e) this.removeKey(t);
223
+ }
224
+ removeKey(e) {
225
+ this.diagnostics.guard("storage.degraded", "The library could not remove a stored batch.", () => {
226
+ localStorage.removeItem(e);
227
+ });
228
+ }
229
+ keys() {
230
+ return N(T, this.diagnostics);
231
+ }
232
+ };
233
+ //#endregion
234
+ //#region src/storage/memory-storage.ts
235
+ function ke(e) {
236
+ return e.reduce((e, t) => e + t.records.length, 0);
237
+ }
238
+ var z = class {
239
+ limits;
240
+ onGap;
241
+ name = de;
242
+ batches = [];
243
+ constructor(e, t) {
244
+ this.limits = e, this.onGap = t;
245
+ }
246
+ async save(e) {
247
+ this.batches.push(e), await this.prune();
248
+ }
249
+ take(e) {
250
+ return Promise.resolve(this.batches.slice(0, e));
251
+ }
252
+ remove(e) {
253
+ return this.batches = this.batches.filter((t) => t.id !== e), Promise.resolve();
254
+ }
255
+ bumpAttempts(e, t) {
256
+ let n = this.batches.find((t) => t.id === e);
257
+ return n && (n.attempts = t), Promise.resolve();
258
+ }
259
+ prune() {
260
+ let e = Date.now() - this.limits.maxAgeMs, t = {
261
+ batches: 0,
262
+ records: 0,
263
+ reason: "expired"
264
+ }, n = this.batches.filter((t) => t.createdAt < e);
265
+ this.batches = this.batches.filter((t) => t.createdAt >= e), this.report(t, "expired", n);
266
+ let r = this.batches.length - this.limits.maxBatches;
267
+ if (r > 0) {
268
+ let e = R(this.batches, r, I);
269
+ this.batches = this.batches.filter((t) => !e.includes(t)), this.report(t, "over_capacity", e);
270
+ }
271
+ return Promise.resolve(t);
272
+ }
273
+ report(e, t, n) {
274
+ if (n.length === 0) return;
275
+ let r = ke(n);
276
+ e.batches += n.length, e.records += r, e.reason = t, this.onGap?.({
277
+ batches: n.length,
278
+ records: r,
279
+ reason: t
280
+ }, n);
281
+ }
282
+ count() {
283
+ return Promise.resolve(this.batches.length);
284
+ }
285
+ clear() {
286
+ return this.batches = [], Promise.resolve();
287
+ }
288
+ close() {
289
+ return this.batches = [], Promise.resolve();
290
+ }
291
+ }, Ae = (e) => ({
292
+ name: se,
293
+ save: (t) => (e?.({
294
+ batches: 1,
295
+ records: t.records.length,
296
+ reason: "not_stored"
297
+ }, [t]), Promise.resolve()),
298
+ take: () => Promise.resolve([]),
299
+ remove: () => Promise.resolve(),
300
+ bumpAttempts: () => Promise.resolve(),
301
+ prune: () => Promise.resolve({
302
+ batches: 0,
303
+ records: 0,
304
+ reason: "expired"
305
+ }),
306
+ count: () => Promise.resolve(0),
307
+ clear: () => Promise.resolve(),
308
+ close: () => Promise.resolve()
309
+ });
310
+ function je(e) {
311
+ return e.guard("storage.unavailable", "The library could not read indexedDB.", () => globalThis.indexedDB != null) === !0;
312
+ }
313
+ function Me(e) {
314
+ return e.guard("storage.unavailable", "The library could not write a test key to localStorage.", () => (localStorage.setItem(b, "1"), localStorage.removeItem(b), !0)) === !0;
315
+ }
316
+ async function Ne(e, t, n, r, i) {
317
+ if (e === "none") return Ae(i);
318
+ if (e === "memory") return new z(n, i);
319
+ if (e === "indexeddb" || e === "auto") {
320
+ if (je(r)) {
321
+ let e = await r.guardAsync("storage.unavailable", "The library could not open IndexedDB.", async () => {
322
+ let { IndexedDbStorage: e } = await import("./indexeddb-storage-Q9fDYlyn.js"), a = new e(t, n, r, i);
323
+ return await a.open(), a;
324
+ });
325
+ if (e) return e;
326
+ }
327
+ if (e === "indexeddb") return r.report("storage.degraded", "IndexedDB is not available. The library uses memory storage instead."), new z(n, i);
328
+ }
329
+ return Me(r) ? new Oe(n, r, i) : (r.report("storage.degraded", "No persistent storage is available. The library keeps undelivered records in memory only."), new z(n, i));
330
+ }
331
+ //#endregion
332
+ //#region src/transport/errors.ts
333
+ var B = class extends Error {
334
+ kind;
335
+ status;
336
+ retryAfterMs;
337
+ maxBytes;
338
+ constructor(e, t, n, r, i, a) {
339
+ super(t, a === void 0 ? void 0 : { cause: a }), this.kind = e, this.status = n, this.retryAfterMs = r, this.maxBytes = i, this.name = "TransportError";
340
+ }
341
+ };
342
+ function Pe(e) {
343
+ if (!e) return;
344
+ let t = Number(e);
345
+ if (Number.isFinite(t)) return Math.max(0, t * ae);
346
+ let n = Date.parse(e);
347
+ return Number.isNaN(n) ? void 0 : Math.max(0, n - Date.now());
348
+ }
349
+ //#endregion
350
+ //#region src/transport/serializers/ecs.ts
351
+ function Fe(e) {
352
+ return ee.test(e) ? Number(BigInt(e) / n) : Date.now();
353
+ }
354
+ function Ie(e) {
355
+ return typeof e == "string" || typeof e == "number" || typeof e == "boolean" ? e : typeof e == "bigint" ? e.toString() : null;
356
+ }
357
+ function Le(e, t, n) {
358
+ let r = e[t];
359
+ r === void 0 ? e[t] = n : Array.isArray(r) ? r.push(n) : e[t] = [r, n];
360
+ }
361
+ function V(e, t, n, r) {
362
+ let i = Ie(n);
363
+ if (i !== null) Le(e, t, i);
364
+ else if (typeof n == "object" && n && !r.has(n)) {
365
+ if (r.add(n), Array.isArray(n)) for (let i of n) V(e, t, i, r);
366
+ else for (let [i, a] of Object.entries(n)) V(e, `${t}.${i}`, a, r);
367
+ r.delete(n);
368
+ }
369
+ }
370
+ function H(e) {
371
+ let t = Object.create(null), n = /* @__PURE__ */ new WeakSet();
372
+ for (let [r, i] of Object.entries(e)) V(t, r, i, n);
373
+ return t;
374
+ }
375
+ var Re = {
376
+ name: "ecs",
377
+ serialize(e) {
378
+ return {
379
+ body: `${e.map((e) => {
380
+ let n = Fe(e.timeUnixNano);
381
+ return JSON.stringify({
382
+ "@timestamp": new Date(n).toISOString(),
383
+ message: e.body,
384
+ log: { level: t[e.severityText] ?? e.severityText.toLowerCase() },
385
+ trace: { id: e.traceId },
386
+ span: { id: e.spanId },
387
+ service: {
388
+ name: e.resource[te],
389
+ version: e.resource[o],
390
+ environment: e.resource[c]
391
+ },
392
+ user_agent: { original: e.resource[i] },
393
+ url: { full: e.attributes["url.full"] ?? e.attributes["page.url"] },
394
+ labels: {
395
+ ...H(e.resource),
396
+ ...H(e.attributes)
397
+ }
398
+ });
399
+ }).join("\n")}\n`,
400
+ contentType: u
401
+ };
402
+ }
403
+ };
404
+ //#endregion
405
+ //#region src/transport/serializers/otlp.ts
406
+ function U(e) {
407
+ return e == null ? null : typeof e == "string" ? { stringValue: e } : typeof e == "boolean" ? { boolValue: e } : typeof e == "number" ? Number.isSafeInteger(e) ? { intValue: String(e) } : { doubleValue: e } : typeof e == "bigint" ? { intValue: e.toString() } : Array.isArray(e) ? { arrayValue: { values: e.map(U).filter((e) => e !== null) } } : typeof e == "object" ? { kvlistValue: { values: W(e) } } : null;
408
+ }
409
+ function W(e) {
410
+ let t = [];
411
+ for (let [n, r] of Object.entries(e)) {
412
+ let e = U(r);
413
+ e && t.push({
414
+ key: n,
415
+ value: e
416
+ });
417
+ }
418
+ return t;
419
+ }
420
+ var G = /* @__PURE__ */ new WeakMap();
421
+ function ze(e) {
422
+ let t = G.get(e);
423
+ if (t !== void 0) return t;
424
+ let n = JSON.stringify(e);
425
+ return G.set(e, n), n;
426
+ }
427
+ function K(e) {
428
+ let t = /* @__PURE__ */ new Map();
429
+ for (let n of e) {
430
+ let e = ze(n.resource), r = t.get(e);
431
+ r ? r.records.push(n) : t.set(e, {
432
+ resource: n.resource,
433
+ records: [n]
434
+ });
435
+ }
436
+ return [...t.values()];
437
+ }
438
+ var Be = {
439
+ name: y,
440
+ serialize(e) {
441
+ let t = K(e).map((e) => ({
442
+ resource: { attributes: W(e.resource) },
443
+ scopeLogs: [{
444
+ scope: {
445
+ name: S,
446
+ version: x
447
+ },
448
+ logRecords: e.records.map((e) => ({
449
+ timeUnixNano: e.timeUnixNano,
450
+ observedTimeUnixNano: e.observedTimeUnixNano ?? e.timeUnixNano,
451
+ severityNumber: e.severityNumber,
452
+ severityText: e.severityText,
453
+ body: { stringValue: e.body },
454
+ traceId: e.traceId,
455
+ spanId: e.spanId,
456
+ flags: e.traceFlags,
457
+ attributes: W(e.attributes)
458
+ }))
459
+ }]
460
+ }));
461
+ return {
462
+ body: JSON.stringify({ resourceLogs: t }),
463
+ contentType: l
464
+ };
465
+ }
466
+ }, Ve = 1;
467
+ function q(e, t) {
468
+ let n = e.attributes[t];
469
+ return typeof n == "number" && Number.isFinite(n) ? n : void 0;
470
+ }
471
+ function J(e) {
472
+ return Array.isArray(e) && e.every((e) => typeof e == "number" && Number.isFinite(e));
473
+ }
474
+ function He(e) {
475
+ let t = e.attributes[w.attributeKeys], n = {};
476
+ if (!Array.isArray(t)) return n;
477
+ for (let r of t) {
478
+ let t = typeof r == "string" && !r.startsWith("metric.") ? e.attributes[r] : void 0;
479
+ (typeof t == "string" || typeof t == "number" || typeof t == "boolean") && (n[r] = t);
480
+ }
481
+ return n;
482
+ }
483
+ function Ue(e) {
484
+ let t = q(e, w.count);
485
+ if (t === void 0) {
486
+ let t = q(e, "metric.value");
487
+ return t === void 0 ? null : {
488
+ count: "1",
489
+ sum: t < 0 ? void 0 : t,
490
+ min: t,
491
+ max: t,
492
+ bucketCounts: ["1"],
493
+ explicitBounds: []
494
+ };
495
+ }
496
+ let n = e.attributes[w.bounds], r = e.attributes[w.buckets];
497
+ if (!J(n) || !J(r) || r.length !== n.length + 1) return null;
498
+ let i = q(e, w.min);
499
+ return {
500
+ count: String(t),
501
+ sum: i !== void 0 && i < 0 ? void 0 : q(e, w.sum),
502
+ min: i,
503
+ max: q(e, w.max),
504
+ bucketCounts: r.map(String),
505
+ explicitBounds: n
506
+ };
507
+ }
508
+ function We(e) {
509
+ let t = q(e, "metric.value");
510
+ return t === void 0 ? null : { asDouble: t };
511
+ }
512
+ function Ge(e, t) {
513
+ let n = e.attributes[w.start], r = t === "histogram" ? Ue(e) : We(e);
514
+ return r === null ? null : {
515
+ attributes: W(He(e)),
516
+ startTimeUnixNano: typeof n == "string" ? n : e.timeUnixNano,
517
+ timeUnixNano: e.timeUnixNano,
518
+ ...r
519
+ };
520
+ }
521
+ function Ke({ name: e, unit: t, field: n, points: r }) {
522
+ if (n === "gauge") return {
523
+ name: e,
524
+ unit: t,
525
+ gauge: { dataPoints: r }
526
+ };
527
+ let i = {
528
+ aggregationTemporality: Ve,
529
+ dataPoints: r
530
+ };
531
+ return n === "sum" && (i.isMonotonic = r.every((e) => e.asDouble >= 0)), {
532
+ name: e,
533
+ unit: t,
534
+ [n]: i
535
+ };
536
+ }
537
+ var qe = {
538
+ name: y,
539
+ serialize(e) {
540
+ let t = K(e).map((e) => {
541
+ let t = /* @__PURE__ */ new Map();
542
+ for (let n of e.records) {
543
+ let e = n.attributes["metric.type"], r = e === "counter" ? "sum" : e === "histogram" ? "histogram" : "gauge", i = Ge(n, r);
544
+ if (i === null) continue;
545
+ let a = n.attributes["metric.name"], o = n.attributes["metric.unit"], s = {
546
+ name: typeof a == "string" ? a : n.body,
547
+ unit: typeof o == "string" ? o : "",
548
+ field: r,
549
+ points: []
550
+ }, c = JSON.stringify([
551
+ s.field,
552
+ s.name,
553
+ s.unit
554
+ ]), l = t.get(c) ?? s;
555
+ l.points.push(i), t.set(c, l);
556
+ }
557
+ return {
558
+ resource: { attributes: W(e.resource) },
559
+ scopeMetrics: [{
560
+ scope: {
561
+ name: S,
562
+ version: x
563
+ },
564
+ metrics: [...t.values()].map(Ke)
565
+ }]
566
+ };
567
+ });
568
+ return {
569
+ body: JSON.stringify({ resourceMetrics: t }),
570
+ contentType: l
571
+ };
572
+ }
573
+ };
574
+ //#endregion
575
+ //#region src/transport/serializers/select.ts
576
+ function Je(e) {
577
+ return e === "otlp" ? Be : e === "ecs" ? Re : e;
578
+ }
579
+ function Y(e, t) {
580
+ return t.metricsEndpoint !== "" && e.records.length > 0 && e.records.every((e) => ve(e, "log.type") === "metric") ? "metrics" : "logs";
581
+ }
582
+ function X(e, t) {
583
+ return e === "metrics" ? t.metricsEndpoint : t.endpoint;
584
+ }
585
+ function Z(e, t, n, r) {
586
+ try {
587
+ return (Y(t, e) === "metrics" ? qe : Je(e.serializer)).serialize(t.records);
588
+ } catch (e) {
589
+ n.report("transport.serialize_failed", r, { batchId: t.id }, e);
590
+ return;
591
+ }
592
+ }
593
+ //#endregion
594
+ //#region src/transport/status-transport.ts
595
+ var Ye = class {
596
+ config;
597
+ diagnostics;
598
+ onSampling;
599
+ onLoss;
600
+ throttledUntil = {
601
+ logs: 0,
602
+ metrics: 0
603
+ };
604
+ constructor(e, t, n = () => void 0, r = () => void 0) {
605
+ this.config = e, this.diagnostics = t, this.onSampling = n, this.onLoss = r;
606
+ }
607
+ throttledForMs(e) {
608
+ return Math.max(0, this.throttledUntil[Y(e, this.config)] - Date.now());
609
+ }
610
+ serialize(e) {
611
+ let t = Z(this.config, e, this.diagnostics, "The serializer threw an error. The library dropped the batch.");
612
+ return t || this.onLoss("unserializable", e.records, [e.id]), t;
613
+ }
614
+ accept(e, t) {
615
+ this.throttledUntil[e] = 0, this.config.sampling.remote && t != null && this.onSampling(t);
616
+ }
617
+ reject(e, t, n, r) {
618
+ let i = String(e);
619
+ if (e === 401 || e === 403) {
620
+ let t = r.advice === void 0 ? "" : ` ${r.advice}`;
621
+ return this.diagnostics.report("transport.rejected_credentials", `The server returned ${i}.${t}`, {
622
+ status: e,
623
+ endpoint: X(n, this.config)
624
+ }), new B("permanent", `The server rejected the batch with ${i}.`, e);
625
+ }
626
+ if (e === 413) return new B("too_large", "The payload is too large.", e, void 0, r.maxBytes);
627
+ if (e === 429 || e === 503) {
628
+ let t = e === 429, i = r.retryAfterMs === void 0 ? void 0 : Math.min(r.retryAfterMs, _);
629
+ return this.throttledUntil[n] = Date.now() + (i ?? 2e3), t && this.diagnostics.report("transport.throttled", "The server throttles the requests.", { retryAfterMs: i }), new B("throttled", t ? "The server throttles the requests." : "The service is not available.", e, i);
630
+ }
631
+ return e === 408 || e >= 500 ? new B("transient", `The server returned the error ${i}.`, e) : (this.diagnostics.report("transport.dropped_permanent", `The server rejected the batch with ${i}. The library dropped it.`, {
632
+ batchId: t,
633
+ status: e
634
+ }), new B("permanent", `The server rejected the batch with ${i}.`, e));
635
+ }
636
+ };
637
+ //#endregion
638
+ //#region src/transport/custom-transport.ts
639
+ function Xe(e, t, n) {
640
+ return {
641
+ kind: n,
642
+ body: t.body,
643
+ contentType: t.contentType,
644
+ batchId: e.id,
645
+ attempt: e.attempts,
646
+ records: e.records
647
+ };
648
+ }
649
+ function Ze(e) {
650
+ if (typeof e != "object" || !e) return !1;
651
+ let t = Reflect.get(e, "status");
652
+ return typeof t == "number" && Number.isInteger(t) && t >= 100 && t <= 599;
653
+ }
654
+ function Qe(e) {
655
+ return typeof e == "number" && Number.isFinite(e) ? Math.max(0, e) : void 0;
656
+ }
657
+ var $e = class extends Ye {
658
+ async send(e) {
659
+ let { transport: t } = this.config;
660
+ if (!t || e.records.length === 0) return;
661
+ let n = this.serialize(e);
662
+ if (!n) return;
663
+ let r = Y(e, this.config), i = Xe(e, n, r), a;
664
+ try {
665
+ a = await k(ye(() => O(() => me(() => t(i)))), p);
666
+ } catch (e) {
667
+ let t = e instanceof be ? e : void 0;
668
+ throw new B(t ? "timeout" : "transient", t?.message ?? "The custom transport failed.", void 0, void 0, void 0, e);
669
+ }
670
+ if (!Ze(a)) throw this.diagnostics.report("transport.http_error", "The custom transport returned no valid status. The library sends the batch again later.", { batchId: e.id }), new B("transient", "The custom transport returned no valid status.");
671
+ let { status: o } = a;
672
+ if (o >= 200 && o < 300) this.accept(r, a.sampling);
673
+ else throw this.reject(o, e.id, r, {
674
+ retryAfterMs: Qe(a.retryAfterMs),
675
+ maxBytes: Qe(a.maxBytes)
676
+ });
677
+ }
678
+ }, et = class {
679
+ deps;
680
+ installed = !1;
681
+ keepaliveBytes = 0;
682
+ onVisibility = () => {
683
+ document.visibilityState === "hidden" && this.flush("hidden");
684
+ };
685
+ onPageHide = () => {
686
+ this.flush("pagehide");
687
+ };
688
+ onFreeze = () => {
689
+ this.flush("freeze");
690
+ };
691
+ onOpenFinClose = () => {
692
+ this.flush("openfin-close");
693
+ };
694
+ constructor(e) {
695
+ this.deps = e;
696
+ }
697
+ install() {
698
+ if (this.installed || typeof addEventListener > "u") return;
699
+ this.installed = !0, typeof document < "u" && (document.addEventListener("visibilitychange", this.onVisibility), document.addEventListener("freeze", this.onFreeze)), addEventListener("pagehide", this.onPageHide);
700
+ let e = globalThis.fin?.me;
701
+ this.deps.diagnostics.guard("openfin.unavailable", "The library could not subscribe to close-requested.", () => {
702
+ e?.on?.("close-requested", this.onOpenFinClose);
703
+ });
704
+ }
705
+ uninstall() {
706
+ if (!this.installed) return;
707
+ this.installed = !1, typeof document < "u" && (document.removeEventListener("visibilitychange", this.onVisibility), document.removeEventListener("freeze", this.onFreeze)), removeEventListener("pagehide", this.onPageHide);
708
+ let e = globalThis.fin?.me;
709
+ this.deps.diagnostics.guard("openfin.unavailable", "The library could not unsubscribe from close-requested.", () => {
710
+ e?.removeListener?.("close-requested", this.onOpenFinClose);
711
+ });
712
+ }
713
+ flush(e) {
714
+ let { config: t, diagnostics: n } = this.deps;
715
+ if (n.guard("pipeline.crashed", "The metric points before the exit flush failed.", () => {
716
+ this.deps.beforeExit?.();
717
+ }), e === "hidden") {
718
+ this.flushAlive();
719
+ return;
720
+ }
721
+ if (t.transport) {
722
+ this.flushCustom(e, t.transportOnExit);
723
+ return;
724
+ }
725
+ let r = this.endpointUrl();
726
+ if (r !== null) {
727
+ this.keepaliveBytes = 0;
728
+ for (let n of this.deps.drainForExit()) {
729
+ let i = Y(n, t) === "metrics" ? t.metricsEndpoint : r.href;
730
+ this.flushBatch(n, e, new URL(i));
731
+ }
732
+ }
733
+ }
734
+ flushBatch(e, t, n) {
735
+ let { config: i, diagnostics: a } = this.deps;
736
+ if (e.records.length === 0) return;
737
+ let o = this.serialize(e, t);
738
+ if (!o) return;
739
+ if (E(o.body) > 6e4) {
740
+ F(e, a, this.deps.onLoss);
741
+ return;
742
+ }
743
+ n.searchParams.set(r, e.id), n.searchParams.set(d, t);
744
+ let s = n.toString(), c = this.deps.exitHeaders();
745
+ if (c) {
746
+ this.keepaliveFetch(s, e, o.body, t, () => {
747
+ let t = new Headers(c);
748
+ return t.set(m, o.contentType), t.set(g, e.id), t;
749
+ });
750
+ return;
751
+ }
752
+ if (i.headers) {
753
+ F(e, a, this.deps.onLoss);
754
+ return;
755
+ }
756
+ let l = this.beacon(s, o.body);
757
+ l !== "sent" && (l === "refused" ? F(e, a, this.deps.onLoss) : this.keepaliveFetch(s, e, o.body, t, () => new Headers({ [m]: f })));
758
+ }
759
+ flushAlive() {
760
+ let { diagnostics: e } = this.deps, t = "The flush of the hidden document failed.";
761
+ e.guard("pipeline.crashed", t, () => {
762
+ Promise.resolve(this.deps.flushAlive()).catch((n) => {
763
+ e.report("pipeline.crashed", t, void 0, n);
764
+ });
765
+ });
766
+ }
767
+ flushCustom(e, t) {
768
+ let { config: n, diagnostics: r } = this.deps;
769
+ for (let i of this.deps.drainForExit()) {
770
+ let a = this.serialize(i, e);
771
+ if (!a) continue;
772
+ let o = Xe(i, a, Y(i, n));
773
+ (t === void 0 || r.guard("transport.http_error", "The transportOnExit hook threw an error.", () => O(() => t(o))) !== !0) && F(i, r, this.deps.onLoss);
774
+ }
775
+ }
776
+ serialize(e, t) {
777
+ let n = Z(this.deps.config, e, this.deps.diagnostics, `The ${t} exit flush could not serialize its batch.`);
778
+ return n || this.deps.onLoss?.("unserializable", e.records, [e.id]), n;
779
+ }
780
+ endpointUrl() {
781
+ let { endpoint: e } = this.deps.config;
782
+ return e ? this.deps.diagnostics.guard("config.invalid", `The exit flush cannot use the endpoint ${e}.`, () => new URL(e)) ?? null : null;
783
+ }
784
+ beacon(e, t) {
785
+ return this.deps.diagnostics.guard("transport.http_error", "The sendBeacon call failed.", () => {
786
+ let n = globalThis.navigator;
787
+ return n?.sendBeacon ? n.sendBeacon(e, new Blob([t], { type: "text/plain;charset=UTF-8" })) ? "sent" : "refused" : "unavailable";
788
+ }) ?? "unavailable";
789
+ }
790
+ keepaliveFetch(e, t, n, r, i) {
791
+ let { config: a, diagnostics: o } = this.deps, s = () => {
792
+ F(t, o, this.deps.onLoss);
793
+ }, c = E(n);
794
+ this.keepaliveBytes + c > 6e4 ? s() : (this.keepaliveBytes += c, o.guard("transport.http_error", "The keepalive fetch failed.", () => (fetch(e, {
795
+ method: "POST",
796
+ body: n,
797
+ headers: i(),
798
+ credentials: a.credentials,
799
+ keepalive: !0
800
+ }).catch((e) => {
801
+ o.report("transport.http_error", "The exit flush failed.", { reason: r }, e), s();
802
+ }), !0)) !== !0 && s());
803
+ }
804
+ };
805
+ //#endregion
806
+ //#region src/transport/compression.ts
807
+ async function tt(e) {
808
+ let t = globalThis.CompressionStream;
809
+ if (t === void 0) return null;
810
+ let n = new Blob([e]).stream().pipeThrough(new t(h)), r = await new Response(n).arrayBuffer();
811
+ return new Uint8Array(r);
812
+ }
813
+ //#endregion
814
+ //#region src/transport/http-transport.ts
815
+ var nt = "In a cross-origin iframe, the session cookie is a third-party cookie. The browser often blocks it. Forward the records to the platform document. As an alternative, issue the cookie with the Partitioned attribute.", rt = class extends Ye {
816
+ cachedHeaders;
817
+ async send(e, t) {
818
+ let { config: n } = this, r = Y(e, n), i = X(r, n);
819
+ i && e.records.length !== 0 && await this.post(e, r, i, t);
820
+ }
821
+ lastHeaders() {
822
+ let { headers: e } = this.config;
823
+ if (!e) return;
824
+ if (typeof e != "function") return e;
825
+ let t = this.cachedHeaders;
826
+ return t?.source === e && t.endpoint === this.config.endpoint && t.metricsEndpoint === this.config.metricsEndpoint ? t.headers : void 0;
827
+ }
828
+ async post(t, n, r, i) {
829
+ let a = this.serialize(t);
830
+ if (!a) return;
831
+ let o = await this.attempt(t, r, a, i);
832
+ if (this.rejectsCredentials(o.status) && typeof this.config.headers == "function" && (this.cachedHeaders = void 0, o = await this.attempt(t, r, a, i)), o.ok) {
833
+ this.accept(n, o.headers.get(ce));
834
+ return;
835
+ }
836
+ let s = o.status, c = Pe(o.headers.get(e)), l = s === 413 ? await this.readMaxBytes(o) : void 0;
837
+ throw this.reject(s, t.id, n, {
838
+ retryAfterMs: c,
839
+ maxBytes: l,
840
+ advice: nt
841
+ });
842
+ }
843
+ rejectsCredentials(e) {
844
+ return e === 401 || e === 403;
845
+ }
846
+ async attempt(e, t, n, r) {
847
+ let i = Date.now() + p, a = new Headers(await this.before(this.resolveHeaders(), i, t));
848
+ a.set(m, n.contentType), a.set(g, e.id), a.set(ne, String(e.attempts));
849
+ let o = await this.before(this.encodeBody(n.body), i, t);
850
+ typeof o != "string" && a.set(re, h);
851
+ let s = this.keepalive(o);
852
+ return s && r?.(), this.dispatch(t, a, o, i, s);
853
+ }
854
+ async before(e, t, n) {
855
+ try {
856
+ return await k(e, Math.max(0, t - Date.now()));
857
+ } catch {
858
+ throw this.timeout(n);
859
+ }
860
+ }
861
+ timeout(e) {
862
+ let t = `The request took longer than ${String(p)} ms.`;
863
+ return this.diagnostics.report("transport.timeout", t, { endpoint: e }), new B("timeout", t);
864
+ }
865
+ async encodeBody(e) {
866
+ let { config: t } = this;
867
+ return t.compression !== "gzip" || E(e) < 1024 ? e : await this.diagnostics.guardAsync("transport.http_error", "The library could not compress the payload.", () => tt(e)) ?? e;
868
+ }
869
+ async dispatch(e, t, n, r, i) {
870
+ let { config: a } = this, o = new AbortController(), s = setTimeout(() => {
871
+ o.abort();
872
+ }, Math.max(0, r - Date.now()));
873
+ A(s);
874
+ try {
875
+ return await O(() => fetch(e, {
876
+ method: "POST",
877
+ headers: t,
878
+ body: n,
879
+ credentials: a.credentials,
880
+ signal: o.signal,
881
+ cache: "no-store",
882
+ keepalive: i
883
+ }));
884
+ } catch {
885
+ if (o.signal.aborted) throw this.timeout(e);
886
+ let t = globalThis.navigator?.onLine;
887
+ throw new B(t === !1 ? "offline" : "transient", "A network error occurred.");
888
+ } finally {
889
+ clearTimeout(s);
890
+ }
891
+ }
892
+ keepalive(e) {
893
+ let t = globalThis.document?.visibilityState === "hidden", n = typeof e == "string" ? E(e) : e.byteLength;
894
+ return t && n <= 6e4;
895
+ }
896
+ async readMaxBytes(e) {
897
+ return this.diagnostics.guardAsync("transport.http_error", "The library could not read the body of the 413 response.", async () => {
898
+ let t = JSON.parse(await e.text());
899
+ return typeof t.maxBytes == "number" ? t.maxBytes : void 0;
900
+ });
901
+ }
902
+ async resolveHeaders() {
903
+ let { headers: e } = this.config;
904
+ if (!e) return {};
905
+ if (typeof e != "function") return e;
906
+ let { endpoint: t, metricsEndpoint: n } = this.config, r = await this.diagnostics.guardAsync("transport.http_error", "The headers() function threw an error.", () => Promise.resolve(e()));
907
+ return r && (this.cachedHeaders = {
908
+ source: e,
909
+ endpoint: t,
910
+ metricsEndpoint: n,
911
+ headers: r
912
+ }), r ?? {};
913
+ }
914
+ }, it = class {
915
+ storage;
916
+ transport;
917
+ diagnostics;
918
+ config;
919
+ batchesPerDrain;
920
+ onLoss;
921
+ timer = null;
922
+ attempt = 0;
923
+ draining = !1;
924
+ stopped = !1;
925
+ maxAttempts;
926
+ onOnline = () => {
927
+ this.attempt = 0, this.schedule(0);
928
+ };
929
+ constructor(e, t, n, r, i = 20, a = () => void 0) {
930
+ this.storage = e, this.transport = t, this.diagnostics = n, this.config = r, this.batchesPerDrain = i, this.onLoss = a, this.maxAttempts = j(r.retention).maxAttempts;
931
+ }
932
+ start() {
933
+ this.stopped = !1, typeof addEventListener < "u" && addEventListener("online", this.onOnline), this.schedule(v);
934
+ }
935
+ nudge() {
936
+ this.draining || this.schedule(s);
937
+ }
938
+ async storeFailed(e, t) {
939
+ let n = this.toStorable(e, t);
940
+ for (let e of n) await this.bounded(this.storage.save(e));
941
+ n.length > 0 && this.nudge();
942
+ }
943
+ stop() {
944
+ this.stopped = !0, typeof removeEventListener < "u" && removeEventListener("online", this.onOnline), this.clearTimer();
945
+ }
946
+ schedule(e) {
947
+ if (this.stopped) return;
948
+ this.clearTimer();
949
+ let t = setTimeout(() => {
950
+ this.drain();
951
+ }, e);
952
+ this.timer = t, A(t);
953
+ }
954
+ bounded(e) {
955
+ return k(e, C);
956
+ }
957
+ clearTimer() {
958
+ this.timer !== null && (clearTimeout(this.timer), this.timer = null);
959
+ }
960
+ backoffMs() {
961
+ let e = Math.min(s * 2 ** this.attempt, _);
962
+ return Math.random() * e;
963
+ }
964
+ async drain() {
965
+ if (!this.draining) {
966
+ this.draining = !0;
967
+ try {
968
+ await M("ui-observability.drain", this.diagnostics, () => this.drainLocked()) !== !0 && this.schedule(v);
969
+ } finally {
970
+ this.draining = !1;
971
+ }
972
+ }
973
+ }
974
+ async drainLocked() {
975
+ try {
976
+ if (globalThis.navigator?.onLine === !1) return this.schedule(v), !0;
977
+ let e = await this.bounded(this.storage.take(this.batchesPerDrain));
978
+ if (e.length === 0) return this.schedule(v), !0;
979
+ let t = /* @__PURE__ */ new Set(), n = 0;
980
+ for (let r of e) {
981
+ if (this.stopped) return !0;
982
+ let e = Y(r, this.config);
983
+ if (t.has(e)) continue;
984
+ let i = await this.deliver(r);
985
+ if (i === "stop") return !0;
986
+ i !== "next" && (t.add(e), n = Math.max(n, i));
987
+ }
988
+ return t.size > 0 ? this.schedule(n) : this.schedule(e.length === this.batchesPerDrain ? 0 : v), !0;
989
+ } catch (e) {
990
+ return this.diagnostics.report("storage.degraded", "The drain loop threw an error.", void 0, e), this.attempt++, this.schedule(this.backoffMs()), !0;
991
+ }
992
+ }
993
+ async deliver(e) {
994
+ if (e.attempts >= this.maxAttempts) return this.diagnostics.report("storage.dead_lettered", `The library dropped a batch after ${e.attempts.toString()} attempts.`, {
995
+ batchId: e.id,
996
+ records: e.records.length
997
+ }), this.onLoss("max_attempts", e.records, [e.id]), await this.bounded(this.storage.remove(e.id)), "next";
998
+ try {
999
+ return await this.transport.send(e), await this.bounded(this.storage.remove(e.id)), this.attempt = 0, "next";
1000
+ } catch (t) {
1001
+ let n = t instanceof B ? t : void 0;
1002
+ return n?.kind === "permanent" || n?.kind === "too_large" ? (await this.replaceStored(e, t), "next") : n?.kind === "offline" ? (this.schedule(v), "stop") : n?.kind === "throttled" ? (this.attempt++, n.retryAfterMs ?? this.backoffMs()) : (await this.bounded(this.storage.bumpAttempts(e.id, e.attempts + 1)), this.attempt++, n?.retryAfterMs ?? this.backoffMs());
1003
+ }
1004
+ }
1005
+ async replaceStored(e, t) {
1006
+ let n = this.toStorable(e, t);
1007
+ await this.bounded(this.storage.remove(e.id));
1008
+ for (let e of n) await this.bounded(this.storage.save(e));
1009
+ }
1010
+ toStorable(e, t) {
1011
+ let n = t instanceof B ? t : void 0;
1012
+ if (n?.kind === "permanent") return this.onLoss("rejected", e.records, [e.id]), [];
1013
+ if (n?.kind !== "too_large") return [e];
1014
+ let r = ge(e, this.diagnostics);
1015
+ return r ? (this.diagnostics.report("transport.batch_split", "The server refused the batch because it is too large.", {
1016
+ from: e.records.length,
1017
+ to: r[0].records.length,
1018
+ serverMaxBytes: n.maxBytes
1019
+ }), r) : (this.diagnostics.report("transport.dropped_permanent", "One record is larger than the server limit. The library dropped it.", {
1020
+ batchId: e.id,
1021
+ bodies: e.records.map((e) => e.body)
1022
+ }), this.onLoss("rejected", e.records, [e.id]), []);
1023
+ }
1024
+ };
1025
+ //#endregion
1026
+ //#region src/core/pipeline.ts
1027
+ function Q(e) {
1028
+ return e.attributes[oe] === le;
1029
+ }
1030
+ var $ = class {
1031
+ options;
1032
+ onFlush;
1033
+ pending = [];
1034
+ timer = null;
1035
+ constructor(e, t) {
1036
+ this.options = e, this.onFlush = t;
1037
+ }
1038
+ add(e) {
1039
+ this.pending.push(e), this.pending.length >= this.options.batchSize ? this.onFlush(this) : this.arm();
1040
+ }
1041
+ take() {
1042
+ this.clearTimer();
1043
+ let e = this.pending;
1044
+ return this.pending = [], e;
1045
+ }
1046
+ stop() {
1047
+ this.clearTimer();
1048
+ }
1049
+ arm() {
1050
+ if (this.timer !== null) return;
1051
+ let e = setTimeout(() => {
1052
+ this.timer = null, this.onFlush(this);
1053
+ }, this.options.flushIntervalMs);
1054
+ this.timer = e, A(e);
1055
+ }
1056
+ clearTimer() {
1057
+ this.timer !== null && (clearTimeout(this.timer), this.timer = null);
1058
+ }
1059
+ }, at = class {
1060
+ transport;
1061
+ storage;
1062
+ retry;
1063
+ diagnostics;
1064
+ streams;
1065
+ unconfirmed = /* @__PURE__ */ new Map();
1066
+ queue = [];
1067
+ open = /* @__PURE__ */ new Set();
1068
+ ceiling = new pe();
1069
+ inFlight = 0;
1070
+ pumpScheduled = !1;
1071
+ stopped = !1;
1072
+ constructor(e, t, n, r, i) {
1073
+ this.transport = e, this.storage = t, this.retry = n, this.diagnostics = r;
1074
+ let a = (e) => {
1075
+ this.claim(e);
1076
+ };
1077
+ this.streams = {
1078
+ logs: new $(i.logs, a),
1079
+ metrics: new $(i.metrics, a)
1080
+ };
1081
+ }
1082
+ push(e) {
1083
+ this.stopped || (e.observedTimeUnixNano = fe(), this.route(e));
1084
+ }
1085
+ drainForExit() {
1086
+ let e = [...this.unconfirmed.values()].flatMap((e) => e.records);
1087
+ this.unconfirmed.clear();
1088
+ let t = [...e.filter(Q), ...this.streams.metrics.take()], n = [...e.filter((e) => !Q(e)), ...this.streams.logs.take()];
1089
+ return [this.toBatch(t), this.toBatch(n)].filter((e) => e !== null);
1090
+ }
1091
+ async flushPending() {
1092
+ this.stopped || (this.claim(this.streams.metrics), this.claim(this.streams.logs)), await Promise.all([...this.open].map((e) => e.done));
1093
+ }
1094
+ destroy() {
1095
+ this.stopped = !0, this.streams.logs.stop(), this.streams.metrics.stop(), this.queue.length = 0;
1096
+ for (let e of this.open) e.resolve();
1097
+ this.open.clear();
1098
+ }
1099
+ toBatch(e) {
1100
+ return e.length === 0 ? null : {
1101
+ id: he(this.diagnostics),
1102
+ records: e,
1103
+ createdAt: Date.now(),
1104
+ attempts: 0
1105
+ };
1106
+ }
1107
+ route(e) {
1108
+ try {
1109
+ let t = Q(e) ? this.streams.metrics : this.streams.logs;
1110
+ if (!this.ceiling.allow(e)) {
1111
+ this.diagnostics.count("record.dropped_by_ceiling");
1112
+ return;
1113
+ }
1114
+ t.add(e);
1115
+ } catch (e) {
1116
+ this.diagnostics.report("pipeline.crashed", "The pipeline dropped a record before it reached a stream.", void 0, e);
1117
+ }
1118
+ }
1119
+ claim(e) {
1120
+ this.enqueue(this.toBatch(e.take()));
1121
+ }
1122
+ enqueue(e) {
1123
+ if (!e) return;
1124
+ let t, n = {
1125
+ batch: e,
1126
+ done: new Promise((e) => {
1127
+ t = e;
1128
+ }),
1129
+ resolve: t
1130
+ };
1131
+ this.unconfirmed.set(e.id, e), this.open.add(n), this.queue.push(n), !this.pumpScheduled && (this.pumpScheduled = !0, queueMicrotask(() => {
1132
+ this.pumpScheduled = !1, this.pump();
1133
+ }));
1134
+ }
1135
+ pump() {
1136
+ for (; this.inFlight < 2;) {
1137
+ let e = this.queue.shift();
1138
+ if (!e) return;
1139
+ this.inFlight++, this.run(e);
1140
+ }
1141
+ }
1142
+ async run(e) {
1143
+ let { batch: t } = e;
1144
+ try {
1145
+ await this.dispatch(t);
1146
+ } catch (e) {
1147
+ this.diagnostics.report("pipeline.crashed", "A dispatch rejected its promise. This must not occur.", { batchId: t.id }, e);
1148
+ } finally {
1149
+ this.inFlight--, this.open.delete(e), e.resolve(), this.pump();
1150
+ }
1151
+ }
1152
+ async dispatch(e) {
1153
+ try {
1154
+ let t = this.transport.throttledForMs(e);
1155
+ if (t > 0) {
1156
+ await this.store(e), this.diagnostics.report("transport.throttled", "The server throttles requests. The pipeline stored the batch and did not send it.", {
1157
+ batchId: e.id,
1158
+ records: e.records.length,
1159
+ throttledMs: t
1160
+ });
1161
+ return;
1162
+ }
1163
+ try {
1164
+ await this.transport.send(e, () => {
1165
+ this.unconfirmed.delete(e.id);
1166
+ });
1167
+ } catch (t) {
1168
+ await this.storeFailed({
1169
+ ...e,
1170
+ attempts: e.attempts + 1
1171
+ }, t), this.diagnostics.report("transport.http_error", "The send failed. The pipeline stored the batch for a retry.", {
1172
+ batchId: e.id,
1173
+ records: e.records.length
1174
+ }, t);
1175
+ }
1176
+ } finally {
1177
+ this.unconfirmed.delete(e.id);
1178
+ }
1179
+ }
1180
+ async storeFailed(e, t) {
1181
+ await this.diagnostics.guardAsync("storage.degraded", "The library could not store an undelivered batch.", async () => {
1182
+ await this.retry.storeFailed(e, t);
1183
+ });
1184
+ }
1185
+ async store(e) {
1186
+ await this.diagnostics.guardAsync("storage.degraded", "The library could not store an undelivered batch.", async () => {
1187
+ await k(this.storage.save(e), C), this.retry.nudge();
1188
+ });
1189
+ }
1190
+ }, ot = class e {
1191
+ storage;
1192
+ retry;
1193
+ pipeline;
1194
+ exitFlush;
1195
+ diagnostics;
1196
+ constructor(e, t, n, r, i) {
1197
+ this.storage = e, this.retry = t, this.pipeline = n, this.exitFlush = r, this.diagnostics = i;
1198
+ }
1199
+ static async create(t) {
1200
+ let { config: n, diagnostics: r } = t, i = await Ne(n.storage, ie, j(n.retention), r, t.onGap), a = (e) => {
1201
+ let i = xe(e, r);
1202
+ i && Se(t.remote, n, i);
1203
+ }, { onLoss: o } = t, s = n.transport ? void 0 : new rt(n, r, a, o), c = s ?? new $e(n, r, a, o), l = new it(i, c, r, n, 20, o), { batching: u } = n, d = new at(c, i, l, r, {
1204
+ logs: {
1205
+ flushIntervalMs: u.logFlushIntervalMs,
1206
+ batchSize: u.logBatchSize
1207
+ },
1208
+ metrics: {
1209
+ flushIntervalMs: u.metricFlushIntervalMs,
1210
+ batchSize: u.metricBatchSize
1211
+ }
1212
+ }), f = new et({
1213
+ config: n,
1214
+ diagnostics: r,
1215
+ drainForExit: () => d.drainForExit(),
1216
+ flushAlive: () => d.flushPending(),
1217
+ exitHeaders: () => s?.lastHeaders(),
1218
+ onLoss: o,
1219
+ beforeExit: t.beforeExit
1220
+ }), p = !1;
1221
+ try {
1222
+ f.install(), l.start(), p = !0;
1223
+ } finally {
1224
+ p || (f.uninstall(), l.stop());
1225
+ }
1226
+ let m = new e(i, l, d, f, r);
1227
+ return m.importEmergency(), m;
1228
+ }
1229
+ push(e) {
1230
+ this.pipeline.push(e);
1231
+ }
1232
+ async flush() {
1233
+ await this.pipeline.flushPending();
1234
+ }
1235
+ async queueDepth() {
1236
+ return await this.diagnostics.guardAsync("storage.degraded", "The library could not count the batches in storage.", () => this.storage.count()) ?? 0;
1237
+ }
1238
+ async destroy() {
1239
+ await this.diagnostics.guardAsync("pipeline.crashed", "The flush before shutdown failed.", () => this.flush()), this.exitFlush.flush("shutdown"), this.exitFlush.uninstall(), this.retry.stop(), this.pipeline.destroy(), await this.storage.close();
1240
+ }
1241
+ async importEmergency() {
1242
+ let e = await this.diagnostics.guardAsync("storage.degraded", "The emergency import failed.", () => Te(this.storage, this.diagnostics));
1243
+ e !== void 0 && e > 0 && this.retry.nudge();
1244
+ }
1245
+ };
1246
+ //#endregion
1247
+ export { ot as Sender, I as n, L as t };
1248
+
1249
+ //# sourceMappingURL=sender--0_VzPbN.js.map