@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
@@ -65,6 +65,13 @@ export interface BuildInput {
65
65
  scoped?: Record<string, unknown>;
66
66
  /** Call-site payload attributes. */
67
67
  payload?: Record<string, unknown>;
68
+ /**
69
+ * Fields that the library builds with a fixed size bound, for example the buckets of a point.
70
+ * The record limits do not cut them. They override a payload key of the same name.
71
+ */
72
+ fixed?: Record<string, unknown>;
73
+ /** True for a point of a counter or histogram. Sampling keeps it. */
74
+ aggregated?: boolean;
68
75
  }
69
76
  /** Builds validated and sanitized LogRecord instances from logger inputs. */
70
77
  export declare class RecordBuilder {
@@ -1,6 +1,7 @@
1
1
  import type { Receive, WorkerLike } from "../bus/links";
2
2
  import type { BusMessage } from "../models/bus";
3
3
  import type { ObservabilityConfig, ResolvedConfig } from "../models/config";
4
+ import type { InstrumentDef, MetricAttributes } from "../models/metric";
4
5
  import { type LogRecord } from "../models/log-record";
5
6
  import { ConsoleSink } from "../utils/console";
6
7
  import { type Identity } from "../utils/identity";
@@ -55,6 +56,10 @@ export declare class ObservabilityRuntime {
55
56
  private readonly remote;
56
57
  /** Console sink for local developer output. */
57
58
  readonly console: ConsoleSink;
59
+ /** Collects lost records into onDrop summaries. */
60
+ private readonly drops;
61
+ /** Sums the values of the counter and histogram instruments. */
62
+ private readonly meter;
58
63
  /**
59
64
  * Cross-realm communication bus. It is null until its chunk loads.
60
65
  * In bus.mode "off", it loads only when a child frame or a worker needs it.
@@ -71,7 +76,7 @@ export declare class ObservabilityRuntime {
71
76
  /** Load of the delivery stack. It is undefined when nothing loads. A record then has no destination. */
72
77
  private senderLoad?;
73
78
  /** Records that arrive while the delivery stack loads. */
74
- private pendingRecords;
79
+ private readonly pendingRecords;
75
80
  /** Active auto-capture instrumentation modules. */
76
81
  private readonly captures;
77
82
  /** Count of capture installs. An install that a later install replaced stops after its load. */
@@ -79,7 +84,7 @@ export declare class ObservabilityRuntime {
79
84
  /** Capture work that a rebuild of the capture modules must not repeat. */
80
85
  private readonly captureOnce;
81
86
  /** Queue buffering records created before bus role resolution. */
82
- private bootBuffer;
87
+ private readonly bootBuffer;
83
88
  /** Batch buffer staging records for microtask forwarding. */
84
89
  private forwardBuffer;
85
90
  /** True if a microtask drain of the forward buffer is pending. */
@@ -94,12 +99,32 @@ export declare class ObservabilityRuntime {
94
99
  private destroyed;
95
100
  /** Timestamp of the last reported storage gap warning in epoch milliseconds. */
96
101
  private lastGapAt;
102
+ /** Record limits of the builder and the console. The first configure() of the app sets them. */
103
+ private readonly limits;
104
+ /** Lifetime rules of the journey engine. The first configure() of the app sets the age. */
105
+ private readonly journeyOptions;
106
+ /** False in a runtime that an early log call started. The first configure() then sets limits. */
107
+ private tunablesLocked;
97
108
  /**
98
109
  * @param input Initial consumer configuration options.
99
110
  * @param degraded True for a console-only runtime next to another version. It installs
100
111
  * no capture.
101
112
  */
102
113
  private constructor();
114
+ /**
115
+ * Adds a value to a counter or a histogram. The meter sends one point at each interval.
116
+ * @param def Definition of the instrument.
117
+ * @param value Value to add.
118
+ * @param attributes Attribute set of the value.
119
+ */
120
+ recordMetric(def: InstrumentDef, value: number, attributes?: MetricAttributes): void;
121
+ /**
122
+ * Builds and emits the record of one aggregated point. The console does not print it.
123
+ * @param name Metric name.
124
+ * @param attributes Attributes of the call. The record limits apply to them.
125
+ * @param fields Metric fields of the point. The record limits do not cut them.
126
+ */
127
+ private emitPoint;
103
128
  /**
104
129
  * Receives direct messages from same-origin child frames.
105
130
  * @param message Inbound bus message.
@@ -131,9 +156,10 @@ export declare class ObservabilityRuntime {
131
156
  /**
132
157
  * Initializes a new runtime instance or updates the existing singleton.
133
158
  * @param input Consumer configuration options.
159
+ * @param implicit True for the default runtime that an early log call starts.
134
160
  * @returns Active runtime instance.
135
161
  */
136
- static configure(input: Partial<ObservabilityConfig>): ObservabilityRuntime;
162
+ static configure(input: Partial<ObservabilityConfig>, implicit?: boolean): ObservabilityRuntime;
137
163
  /**
138
164
  * Starts a console-only runtime next to the runtime of another version. It sends nothing,
139
165
  * joins no bus and installs no capture. The other version keeps the page runtime.
@@ -147,6 +173,18 @@ export declare class ObservabilityRuntime {
147
173
  * @param input Partial configuration to merge.
148
174
  */
149
175
  private reconfigure;
176
+ /**
177
+ * Restores the startup tunables in the next config. A part of the runtime reads each tunable
178
+ * one time. A later change has no effect. The runtime then refuses it.
179
+ * @param next Resolved config of a later configure() call.
180
+ */
181
+ private keepStartupTunables;
182
+ /**
183
+ * Refuses a change of config sections. It restores the values in force in the next config.
184
+ * @param next Resolved config of a later configure() call.
185
+ * @param sections Sections that cannot change.
186
+ */
187
+ private keepSections;
150
188
  /**
151
189
  * Restores the storage strategy of the built adapter. The runtime reads all other keys
152
190
  * live. It builds the adapter only one time. A new adapter strands the batches in the
@@ -196,6 +234,11 @@ export declare class ObservabilityRuntime {
196
234
  * @returns Promise that resolves when the load completes, or immediately when nothing loads.
197
235
  */
198
236
  private syncSender;
237
+ /**
238
+ * Tests if the config names a destination for the records.
239
+ * @returns True with an endpoint or a custom transport.
240
+ */
241
+ private hasDestination;
199
242
  /**
200
243
  * Starts the load of the delivery stack one time.
201
244
  * @returns Promise that resolves when the load completes or fails.
@@ -238,16 +281,17 @@ export declare class ObservabilityRuntime {
238
281
  */
239
282
  private deliver;
240
283
  /**
241
- * Adds a record to a hold buffer. It drops the oldest record when the buffer is full.
242
- * @param buffer Hold buffer.
243
- * @param record Record to hold.
284
+ * Counts a record that a full hold buffer drops. It gives the record to the onDrop report.
285
+ * @param record Dropped record.
244
286
  */
245
- private pushCapped;
287
+ private dropHeld;
246
288
  /**
247
289
  * Batches records for asynchronous transmission to the upstream sender.
248
290
  * @param record Log record to forward.
249
291
  */
250
292
  private forward;
293
+ /** Gives the records of the forward buffer to the bus. */
294
+ private sendForwarded;
251
295
  /**
252
296
  * Validates, samples and queues records from child frames or workers.
253
297
  * A forwarded record arrives built. This is the first point in this context where
@@ -258,8 +302,17 @@ export declare class ObservabilityRuntime {
258
302
  /** Flushes the startup records. It adds the active journey to records without a journey. */
259
303
  private releaseBootBuffer;
260
304
  /**
261
- * Emits a warning record when storage evicts batches.
305
+ * Gives lost records to the onDrop report.
306
+ * @param reason Cause of the loss.
307
+ * @param records Lost records.
308
+ * @param batchIds Ids of the lost batches.
309
+ */
310
+ private readonly reportLoss;
311
+ /**
312
+ * Gives the evicted batches to the onDrop report. It also emits a warning record. A throttle
313
+ * limits the warning records.
262
314
  * @param result Storage prune summary metrics.
315
+ * @param dropped The evicted batches.
263
316
  */
264
317
  private readonly reportGap;
265
318
  /** Makes and stores a new tab ID after a tab ID collision. */
@@ -13,6 +13,8 @@ export interface SampleInput {
13
13
  journeyId: string;
14
14
  /** Trace ID. It is the sampling key when no journey runs. */
15
15
  traceId: string;
16
+ /** True for a point of a counter or histogram. A sample of a sum gives a false sum. */
17
+ aggregated?: boolean;
16
18
  }
17
19
  /**
18
20
  * Decides if sampling keeps an entry. It reads fields, not a record.
@@ -1,6 +1,7 @@
1
1
  import type { ResolvedConfig } from "../models/config";
2
+ import type { LossReporter } from "../models/drop";
2
3
  import type { LogRecord } from "../models/log-record";
3
- import type { GapReporter } from "../models/storage";
4
+ import { type GapReporter } from "../models/storage";
4
5
  import type { Diagnostics } from "./diagnostics";
5
6
  import type { RemoteSlot } from "./remote-sampling";
6
7
  /** Inputs to build the delivery stack. */
@@ -11,8 +12,12 @@ export interface SenderDeps {
11
12
  diagnostics: Diagnostics;
12
13
  /** Receives a report when storage drops batches before delivery. */
13
14
  onGap: GapReporter;
15
+ /** Receives the records that the transport, the retry engine and the exit flush lose. */
16
+ onLoss: LossReporter;
14
17
  /** Slot of the runtime for the sampling rules from the ingest server. */
15
18
  remote: RemoteSlot;
19
+ /** Sends the points of the open metric interval before the exit flush drains the buffers. */
20
+ beforeExit?: () => void;
16
21
  }
17
22
  /** Delivery stack for one sender runtime. */
18
23
  export declare class Sender {
@@ -0,0 +1,26 @@
1
+ //#region src/utils/unref.ts
2
+ function e(e) {
3
+ typeof e != "number" && e.unref?.();
4
+ }
5
+ //#endregion
6
+ //#region src/utils/deadline.ts
7
+ var t = class extends Error {
8
+ constructor(e) {
9
+ super(`The operation took longer than ${String(e)} ms.`), this.name = "DeadlineError";
10
+ }
11
+ };
12
+ function n(n, r) {
13
+ let i, a = new Promise((n, a) => {
14
+ let o = setTimeout(() => {
15
+ a(new t(r));
16
+ }, r);
17
+ i = o, e(o);
18
+ });
19
+ return Promise.race([n, a]).finally(() => {
20
+ clearTimeout(i);
21
+ });
22
+ }
23
+ //#endregion
24
+ export { n, e as r, t };
25
+
26
+ //# sourceMappingURL=deadline-5_PecIl5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deadline-5_PecIl5.js","names":["unrefTimer","timer","DeadlineError","ms","withDeadline","expire","deadline","work"],"sources":["../src/utils/unref.ts","../src/utils/deadline.ts"],"sourcesContent":["// src/utils/unref.ts\n//\n// Unreferences timer handles in Node and browser environments. A pending timer\n// keeps a Node process alive under SSR and in tests.\n\n/** Timer handle. It is a number in a browser and a Timeout object in Node. */\nexport type TimerHandle = number | { unref?: () => void };\n\n/**\n * Unreferences a timer handle. A pending timer then does not keep a Node.js process alive.\n * @param timer Timer handle returned by setTimeout.\n */\nexport function unrefTimer(timer: TimerHandle): void {\n if (typeof timer !== \"number\") {\n timer.unref?.();\n }\n}\n","// src/utils/deadline.ts\n//\n// Sets a deadline for a promise that can stay pending. A pending promise raises no\n// diagnostics event. Without a deadline, its caller waits forever and keeps its slot.\n\nimport { unrefTimer } from \"./unref\";\n\n/** Error of a promise that did not settle before its deadline. */\nexport class DeadlineError extends Error {\n /**\n * @param ms Deadline in milliseconds.\n */\n constructor(ms: number) {\n super(`The operation took longer than ${String(ms)} ms.`);\n this.name = \"DeadlineError\";\n }\n}\n\n/**\n * Rejects when a promise does not settle within a deadline.\n * @param work Promise to bound.\n * @param ms Deadline in milliseconds.\n * @returns The value of the promise, or a rejection after the deadline.\n */\nexport function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let expire: ReturnType<typeof setTimeout> | undefined;\n\n const deadline = new Promise<never>((_resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new DeadlineError(ms));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Clear the timer on success and on failure. If not, each storage call leaves an armed timer.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n"],"mappings":";AAYA,SAAgBA,EAAW,GAA0B;CACnD,AAAI,OAAOC,KAAU,YACnBA,EAAM,QAAQ;AAElB;;;ACRA,IAAaC,IAAb,cAAmC,MAAM;CAIvC,YAAY,GAAY;EAEtB,AADA,MAAM,kCAAkC,OAAOC,CAAE,EAAE,KAAK,GACxD,KAAK,OAAO;CACd;AACF;AAQA,SAAgBC,EAAgB,GAAkB,GAAwB;CACxE,IAAIC,GAEEC,IAAW,IAAI,SAAgB,GAAU,MAAW;EACxD,IAAML,IAAQ,iBAAiB;GAC7B,EAAO,IAAIC,EAAcC,CAAE,CAAC;EAC9B,GAAGA,CAAE;EAGL,AADA,IAASF,GACTD,EAAWC,CAAK;CAClB,CAAC;CAGD,OAAO,QAAQ,KAAK,CAACM,GAAMD,CAAQ,CAAC,CAAC,CAAC,cAAc;EAClD,aAAaD,CAAM;CACrB,CAAC;AACH"}
@@ -0,0 +1,2 @@
1
+ function e(e){typeof e!=`number`&&e.unref?.()}var t=class extends Error{constructor(e){super(`The operation took longer than ${String(e)} ms.`),this.name=`DeadlineError`}};function n(n,r){let i,a=new Promise((n,a)=>{let o=setTimeout(()=>{a(new t(r))},r);i=o,e(o)});return Promise.race([n,a]).finally(()=>{clearTimeout(i)})}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return t}});
2
+ //# sourceMappingURL=deadline-XSnm95pg.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deadline-XSnm95pg.cjs","names":["unrefTimer","timer","DeadlineError","ms","withDeadline","expire","deadline","reject","work"],"sources":["../src/utils/unref.ts","../src/utils/deadline.ts"],"sourcesContent":["// src/utils/unref.ts\n//\n// Unreferences timer handles in Node and browser environments. A pending timer\n// keeps a Node process alive under SSR and in tests.\n\n/** Timer handle. It is a number in a browser and a Timeout object in Node. */\nexport type TimerHandle = number | { unref?: () => void };\n\n/**\n * Unreferences a timer handle. A pending timer then does not keep a Node.js process alive.\n * @param timer Timer handle returned by setTimeout.\n */\nexport function unrefTimer(timer: TimerHandle): void {\n if (typeof timer !== \"number\") {\n timer.unref?.();\n }\n}\n","// src/utils/deadline.ts\n//\n// Sets a deadline for a promise that can stay pending. A pending promise raises no\n// diagnostics event. Without a deadline, its caller waits forever and keeps its slot.\n\nimport { unrefTimer } from \"./unref\";\n\n/** Error of a promise that did not settle before its deadline. */\nexport class DeadlineError extends Error {\n /**\n * @param ms Deadline in milliseconds.\n */\n constructor(ms: number) {\n super(`The operation took longer than ${String(ms)} ms.`);\n this.name = \"DeadlineError\";\n }\n}\n\n/**\n * Rejects when a promise does not settle within a deadline.\n * @param work Promise to bound.\n * @param ms Deadline in milliseconds.\n * @returns The value of the promise, or a rejection after the deadline.\n */\nexport function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let expire: ReturnType<typeof setTimeout> | undefined;\n\n const deadline = new Promise<never>((_resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new DeadlineError(ms));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Clear the timer on success and on failure. If not, each storage call leaves an armed timer.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n"],"mappings":"AAYA,SAAgBA,EAAW,EAA0B,CAC/C,OAAOC,GAAU,UACnBA,EAAM,QAAQ,CAElB,CCRA,IAAaC,EAAb,cAAmC,KAAM,CAIvC,YAAY,EAAY,CACtB,MAAM,kCAAkC,OAAOC,CAAE,EAAE,KAAK,EACxD,KAAK,KAAO,eACd,CACF,EAQA,SAAgBC,EAAgB,EAAkB,EAAwB,CACxE,IAAIC,EAEEC,EAAW,IAAI,SAAgB,EAAU,IAAW,CACxD,IAAML,EAAQ,eAAiB,CAC7BM,EAAO,IAAIL,EAAcC,CAAE,CAAC,CAC9B,EAAGA,CAAE,EAEL,EAASF,EACTD,EAAWC,CAAK,CAClB,CAAC,EAGD,OAAO,QAAQ,KAAK,CAACO,EAAMF,CAAQ,CAAC,CAAC,CAAC,YAAc,CAClD,aAAaD,CAAM,CACrB,CAAC,CACH"}
@@ -1,7 +1,7 @@
1
- import "./constants-DM94FjVX.js";
1
+ import "./constants-CQ_D7jIW.js";
2
2
  import { r as e } from "./error-like-Ywo5uRHo.js";
3
- import { r as t } from "./platform-IHBZGqUe.js";
4
- import { t as n } from "./storm-BTw0J6eE.js";
3
+ import { r as t } from "./platform-j0uMPwHi.js";
4
+ import { t as n } from "./storm-knaj4GUH.js";
5
5
  //#region src/capture/errors.ts
6
6
  function r(t) {
7
7
  if (e(t)) {
@@ -91,4 +91,4 @@ var i = class {
91
91
  //#endregion
92
92
  export { i as ErrorCapture };
93
93
 
94
- //# sourceMappingURL=errors-DH4QJS0u.js.map
94
+ //# sourceMappingURL=errors-BGs5NOrw.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors-DH4QJS0u.js","names":["isErrorLike","stripUrlQuery","allowInWindow","signatureOf","value","frame","message","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","now","previous","key","suppressed","oldest","reason","source","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport {\n ERROR_DEDUPE_MS,\n ERROR_STORM_MAX_PER_WINDOW,\n MAX_TRACKED_ERROR_SIGNATURES,\n} from \"../constants\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** Time of the last report for the signature, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** Message and deduplication key of a thrown value. */\ninterface Signature {\n /** Message of the record. */\n message: string;\n /** Deduplication key. */\n key: string;\n}\n\n/**\n * Reads the message and the deduplication key of a thrown value.\n * Duck typing reads an error from another realm. That error fails `instanceof Error`.\n * @param value Thrown value or rejection reason.\n * @returns The signature.\n * @throws When a getter or the text form of the value throws. Call it inside a guard.\n */\nfunction signatureOf(value: unknown): Signature {\n if (isErrorLike(value)) {\n const frame = (value.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n return { message: value.message, key: `${value.name}|${value.message}|${frame}` };\n }\n\n const message = String(value);\n return { message, key: `${typeof value}|${message}|` };\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** Rate limit of this capture. Console noise has its own window and cannot use it. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Uses capture phase to observe non-bubbling resource load errors.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n const target = event.target as (HTMLElement & { src?: string; href?: string }) | null;\n const resourceUrl = target?.src ?? target?.href ?? \"\";\n\n // Filters element-level resource load failures from script errors.\n if (\n target !== null &&\n target !== (globalThis as unknown as EventTarget) &&\n resourceUrl !== \"\"\n ) {\n if (!this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n // A cache buster is noise. A signed URL is a credential.\n // The record keeps neither unless you set fullUrls.\n const url = this.ctx.config.capture.fullUrls ? resourceUrl : stripUrlQuery(resourceUrl);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${url}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", {\n \"error.type\": \"resource\",\n \"resource.url\": url,\n \"resource.tag\": target.tagName.toLowerCase(),\n });\n return;\n }\n\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const errorEvent = event as ErrorEvent;\n const fallback = errorEvent.message === \"\" ? \"unknown error\" : errorEvent.message;\n const thrown: unknown = errorEvent.error;\n const error = thrown ?? new Error(fallback);\n\n this.report(\"window.onerror\", error, {\n \"error.source\": errorEvent.filename,\n \"error.line\": errorEvent.lineno,\n \"error.column\": errorEvent.colno,\n });\n };\n\n /** Captures unhandled promise rejections. */\n private readonly onRejection = (event: PromiseRejectionEvent): void => {\n if (!this.ctx.config.capture.rejections) {\n return;\n }\n\n this.report(\"unhandledrejection\", event.reason, {\n \"error.type\": \"unhandledrejection\",\n });\n };\n\n /**\n * Rate limits, deduplicates, and logs captured errors.\n * @param source Originating capture event name.\n * @param error Caught error instance or thrown value.\n * @param extra Contextual error attributes.\n */\n private report(source: string, error: unknown, extra: Record<string, unknown>): void {\n if (!allowInWindow(this.window, ERROR_STORM_MAX_PER_WINDOW, this.ctx.diagnostics, \"errors\")) {\n return;\n }\n\n const now = Date.now();\n // A reason with no text form, for example a null-prototype object, gets an empty message.\n // The record then uses the source as its message.\n const { message, key } = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read the error reason. It records the error without its message.\",\n () => signatureOf(error),\n ) ?? { message: \"\", key: `${typeof error}||` };\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < ERROR_DEDUPE_MS) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // This is the number of occurrences that deduplication dropped since the last report.\n // Without this count, many errors look like few errors.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. The map stays in\n // least-recently-reported order. The eviction below needs this order.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message at each render, for example from a template literal\n // in a loop. Without this cap, the map grows until the document closes.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n // Give the original value to the logger. It converts the reason and keeps its data.\n // Without a reason, the record still needs error.message and error.stack_trace.\n const reason = error === undefined ? new Error(message) : error;\n this.ctx.logger.error(message === \"\" ? source : message, reason, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":";;;;;AAqCA,SAASG,EAAY,GAA2B;CAC9C,IAAIH,EAAYI,CAAK,GAAG;EACtB,IAAMC,KAASD,EAAM,SAAS,GAAA,CAAI,MAAM,IAAI,CAAC,CAAC,MAAM;EACpD,OAAO;GAAE,SAASA,EAAM;GAAS,KAAK,GAAGA,EAAM,KAAK,GAAGA,EAAM,QAAQ,GAAGC;EAAQ;CAClF;CAEA,IAAMC,IAAU,OAAOF,CAAK;CAC5B,OAAO;EAAE;EAAS,KAAK,GAAG,OAAOA,EAAM,GAAGE,EAAQ;CAAG;AACvD;AAGA,IAAaC,IAAb,MAA6C;CAgBd;CAd7B,OAAgB;CAGhB,YAAoB;CAGpB,uBAAwB,IAAI,IAAuB;CAGnD,SAAuC;EAAE,OAAO;EAAG,OAAO;CAAE;CAK5D,YAAY,GAAsC;EAArB,KAAA,MAAAC;CAAsB;CAGnD,UAAgB;EACd,AAAI,KAAK,aAAa,OAAO,mBAAqB,QAGlD,KAAK,YAAY,IAGjB,iBAAiB,SAAS,KAAK,SAAS,EAAI,GAC5C,iBAAiB,sBAAsB,KAAK,WAAW;CACzD;CAGA,YAAkB;EAChB,AAAK,KAAK,cAGV,KAAK,YAAY,IAEjB,oBAAoB,SAAS,KAAK,SAAS,EAAI,GAC/C,oBAAoB,sBAAsB,KAAK,WAAW,GAC1D,KAAK,KAAK,MAAM;CAClB;CAGA,WAA4B,MAAoC;EAC9D,IAAMC,IAASC,EAAM,QACfC,IAAcF,GA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;GACd;EACF;EAIA,IAAMG,IAAaF,IAAWA,EAAS,QAAQ,IAAI;EASnD,IALA,KAAK,KAAK,OAAOC,CAAG,GACpB,KAAK,KAAK,IAAIA,GAAK;GAAE,IAAIF;GAAK,OAAO;EAAE,CAAC,GAIpC,KAAK,KAAK,OAAA,KAAqC;GACjD,IAAM,CAACI,KAAU,KAAK,KAAK,KAAK;GAChC,KAAK,KAAK,OAAOA,CAAM;EACzB;EAIA,IAAMC,IAASN,MAAU,KAAA,IAAgB,MAAMT,CAAO,IAAIS;EAC1D,KAAK,IAAI,OAAO,MAAMT,MAAY,KAAKgB,IAAShB,GAASe,GAAQ;GAC/D,GAAGE;GACH,qBAAqBD;GACrB,0BAA0BH;EAC5B,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"errors-BGs5NOrw.js","names":["isErrorLike","stripUrlQuery","allowInWindow","signatureOf","value","frame","message","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","now","previous","key","suppressed","oldest","reason","source","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport {\n ERROR_DEDUPE_MS,\n ERROR_STORM_MAX_PER_WINDOW,\n MAX_TRACKED_ERROR_SIGNATURES,\n} from \"../constants\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** Time of the last report for the signature, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** Message and deduplication key of a thrown value. */\ninterface Signature {\n /** Message of the record. */\n message: string;\n /** Deduplication key. */\n key: string;\n}\n\n/**\n * Reads the message and the deduplication key of a thrown value.\n * Duck typing reads an error from another realm. That error fails `instanceof Error`.\n * @param value Thrown value or rejection reason.\n * @returns The signature.\n * @throws When a getter or the text form of the value throws. Call it inside a guard.\n */\nfunction signatureOf(value: unknown): Signature {\n if (isErrorLike(value)) {\n const frame = (value.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n return { message: value.message, key: `${value.name}|${value.message}|${frame}` };\n }\n\n const message = String(value);\n return { message, key: `${typeof value}|${message}|` };\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** Rate limit of this capture. Console noise has its own window and cannot use it. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Uses capture phase to observe non-bubbling resource load errors.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n const target = event.target as (HTMLElement & { src?: string; href?: string }) | null;\n const resourceUrl = target?.src ?? target?.href ?? \"\";\n\n // Filters element-level resource load failures from script errors.\n if (\n target !== null &&\n target !== (globalThis as unknown as EventTarget) &&\n resourceUrl !== \"\"\n ) {\n if (!this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n // A cache buster is noise. A signed URL is a credential.\n // The record keeps neither unless you set fullUrls.\n const url = this.ctx.config.capture.fullUrls ? resourceUrl : stripUrlQuery(resourceUrl);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${url}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", {\n \"error.type\": \"resource\",\n \"resource.url\": url,\n \"resource.tag\": target.tagName.toLowerCase(),\n });\n return;\n }\n\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const errorEvent = event as ErrorEvent;\n const fallback = errorEvent.message === \"\" ? \"unknown error\" : errorEvent.message;\n const thrown: unknown = errorEvent.error;\n const error = thrown ?? new Error(fallback);\n\n this.report(\"window.onerror\", error, {\n \"error.source\": errorEvent.filename,\n \"error.line\": errorEvent.lineno,\n \"error.column\": errorEvent.colno,\n });\n };\n\n /** Captures unhandled promise rejections. */\n private readonly onRejection = (event: PromiseRejectionEvent): void => {\n if (!this.ctx.config.capture.rejections) {\n return;\n }\n\n this.report(\"unhandledrejection\", event.reason, {\n \"error.type\": \"unhandledrejection\",\n });\n };\n\n /**\n * Rate limits, deduplicates, and logs captured errors.\n * @param source Originating capture event name.\n * @param error Caught error instance or thrown value.\n * @param extra Contextual error attributes.\n */\n private report(source: string, error: unknown, extra: Record<string, unknown>): void {\n if (!allowInWindow(this.window, ERROR_STORM_MAX_PER_WINDOW, this.ctx.diagnostics, \"errors\")) {\n return;\n }\n\n const now = Date.now();\n // A reason with no text form, for example a null-prototype object, gets an empty message.\n // The record then uses the source as its message.\n const { message, key } = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read the error reason. It records the error without its message.\",\n () => signatureOf(error),\n ) ?? { message: \"\", key: `${typeof error}||` };\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < ERROR_DEDUPE_MS) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // This is the number of occurrences that deduplication dropped since the last report.\n // Without this count, many errors look like few errors.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. The map stays in\n // least-recently-reported order. The eviction below needs this order.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message at each render, for example from a template literal\n // in a loop. Without this cap, the map grows until the document closes.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n // Give the original value to the logger. It converts the reason and keeps its data.\n // Without a reason, the record still needs error.message and error.stack_trace.\n const reason = error === undefined ? new Error(message) : error;\n this.ctx.logger.error(message === \"\" ? source : message, reason, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":";;;;;AAqCA,SAASG,EAAY,GAA2B;CAC9C,IAAIH,EAAYI,CAAK,GAAG;EACtB,IAAMC,KAASD,EAAM,SAAS,GAAA,CAAI,MAAM,IAAI,CAAC,CAAC,MAAM;EACpD,OAAO;GAAE,SAASA,EAAM;GAAS,KAAK,GAAGA,EAAM,KAAK,GAAGA,EAAM,QAAQ,GAAGC;EAAQ;CAClF;CAEA,IAAMC,IAAU,OAAOF,CAAK;CAC5B,OAAO;EAAE;EAAS,KAAK,GAAG,OAAOA,EAAM,GAAGE,EAAQ;CAAG;AACvD;AAGA,IAAaC,IAAb,MAA6C;CAgBd;CAd7B,OAAgB;CAGhB,YAAoB;CAGpB,uBAAwB,IAAI,IAAuB;CAGnD,SAAuC;EAAE,OAAO;EAAG,OAAO;CAAE;CAK5D,YAAY,GAAsC;EAArB,KAAA,MAAAC;CAAsB;CAGnD,UAAgB;EACd,AAAI,KAAK,aAAa,OAAO,mBAAqB,QAGlD,KAAK,YAAY,IAGjB,iBAAiB,SAAS,KAAK,SAAS,EAAI,GAC5C,iBAAiB,sBAAsB,KAAK,WAAW;CACzD;CAGA,YAAkB;EAChB,AAAK,KAAK,cAGV,KAAK,YAAY,IAEjB,oBAAoB,SAAS,KAAK,SAAS,EAAI,GAC/C,oBAAoB,sBAAsB,KAAK,WAAW,GAC1D,KAAK,KAAK,MAAM;CAClB;CAGA,WAA4B,MAAoC;EAC9D,IAAM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D,AADA,EAAS,SACT,EAAS,KAAKD;GACd;EACF;EAIA,IAAMG,IAAaF,IAAWA,EAAS,QAAQ,IAAI;EASnD,IALA,KAAK,KAAK,OAAOC,CAAG,GACpB,KAAK,KAAK,IAAIA,GAAK;GAAE,IAAIF;GAAK,OAAO;EAAE,CAAC,GAIpC,KAAK,KAAK,OAAA,KAAqC;GACjD,IAAM,CAACI,KAAU,KAAK,KAAK,KAAK;GAChC,KAAK,KAAK,OAAOA,CAAM;EACzB;EAIA,IAAMC,IAASN,MAAU,KAAA,IAAgB,MAAMT,CAAO,IAAIS;EAC1D,KAAK,IAAI,OAAO,MAAMT,MAAY,KAAKgB,IAAShB,GAASe,GAAQ;GAC/D,GAAGE;GACH,qBAAqBD;GACrB,0BAA0BH;EAC5B,CAAC;CACH;AACF"}
@@ -1,3 +1,3 @@
1
- require("./constants-Br3b89Wg.cjs");const e=require("./error-like-gGRx2s36.cjs"),t=require("./platform-D4wu1eIF.cjs"),n=require("./storm-Y-yuBhvv.cjs");function r(t){if(e.r(t)){let e=(t.stack??``).split(`
1
+ require("./constants-Be83LICb.cjs");const e=require("./error-like-gGRx2s36.cjs"),t=require("./platform-DNOJjpOm.cjs"),n=require("./storm-CTy1dfvs.cjs");function r(t){if(e.r(t)){let e=(t.stack??``).split(`
2
2
  `)[1]??``;return{message:t.message,key:`${t.name}|${t.message}|${e}`}}let n=String(t);return{message:n,key:`${typeof t}|${n}|`}}var i=class{ctx;name=`errors`;installed=!1;seen=new Map;window={start:0,count:0};constructor(e){this.ctx=e}install(){this.installed||typeof addEventListener>`u`||(this.installed=!0,addEventListener(`error`,this.onError,!0),addEventListener(`unhandledrejection`,this.onRejection))}uninstall(){this.installed&&(this.installed=!1,removeEventListener(`error`,this.onError,!0),removeEventListener(`unhandledrejection`,this.onRejection),this.seen.clear())}onError=e=>{let n=e.target,r=n?.src??n?.href??``;if(n!==null&&n!==globalThis&&r!==``){if(!this.ctx.config.capture.resourceErrors)return;let e=this.ctx.config.capture.fullUrls?r:t.r(r);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`resource failed: ${e}`}),this.ctx.logger.warn(`resource failed to load`,{"error.type":`resource`,"resource.url":e,"resource.tag":n.tagName.toLowerCase()});return}if(!this.ctx.config.capture.errors)return;let i=e,a=i.message===``?`unknown error`:i.message,o=i.error??Error(a);this.report(`window.onerror`,o,{"error.source":i.filename,"error.line":i.lineno,"error.column":i.colno})};onRejection=e=>{this.ctx.config.capture.rejections&&this.report(`unhandledrejection`,e.reason,{"error.type":`unhandledrejection`})};report(e,t,i){if(!n.t(this.window,20,this.ctx.diagnostics,`errors`))return;let a=Date.now(),{message:o,key:s}=this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not read the error reason. It records the error without its message.`,()=>r(t))??{message:``,key:`${typeof t}||`},c=this.seen.get(s);if(c&&a-c.at<5e3){c.count++,c.at=a;return}let l=c?c.count-1:0;if(this.seen.delete(s),this.seen.set(s,{at:a,count:1}),this.seen.size>200){let[e]=this.seen.keys();this.seen.delete(e)}let u=t===void 0?Error(o):t;this.ctx.logger.error(o===``?e:o,u,{...i,"error.captured_by":e,"error.suppressed_count":l})}};exports.ErrorCapture=i;
3
- //# sourceMappingURL=errors-CpGRhhIf.cjs.map
3
+ //# sourceMappingURL=errors-BMJm7KZZ.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors-CpGRhhIf.cjs","names":["isErrorLike","stripUrlQuery","allowInWindow","require_error_like","require_platform","require_storm","signatureOf","value","frame","message","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","now","previous","key","suppressed","oldest","reason","source","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport {\n ERROR_DEDUPE_MS,\n ERROR_STORM_MAX_PER_WINDOW,\n MAX_TRACKED_ERROR_SIGNATURES,\n} from \"../constants\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** Time of the last report for the signature, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** Message and deduplication key of a thrown value. */\ninterface Signature {\n /** Message of the record. */\n message: string;\n /** Deduplication key. */\n key: string;\n}\n\n/**\n * Reads the message and the deduplication key of a thrown value.\n * Duck typing reads an error from another realm. That error fails `instanceof Error`.\n * @param value Thrown value or rejection reason.\n * @returns The signature.\n * @throws When a getter or the text form of the value throws. Call it inside a guard.\n */\nfunction signatureOf(value: unknown): Signature {\n if (isErrorLike(value)) {\n const frame = (value.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n return { message: value.message, key: `${value.name}|${value.message}|${frame}` };\n }\n\n const message = String(value);\n return { message, key: `${typeof value}|${message}|` };\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** Rate limit of this capture. Console noise has its own window and cannot use it. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Uses capture phase to observe non-bubbling resource load errors.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n const target = event.target as (HTMLElement & { src?: string; href?: string }) | null;\n const resourceUrl = target?.src ?? target?.href ?? \"\";\n\n // Filters element-level resource load failures from script errors.\n if (\n target !== null &&\n target !== (globalThis as unknown as EventTarget) &&\n resourceUrl !== \"\"\n ) {\n if (!this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n // A cache buster is noise. A signed URL is a credential.\n // The record keeps neither unless you set fullUrls.\n const url = this.ctx.config.capture.fullUrls ? resourceUrl : stripUrlQuery(resourceUrl);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${url}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", {\n \"error.type\": \"resource\",\n \"resource.url\": url,\n \"resource.tag\": target.tagName.toLowerCase(),\n });\n return;\n }\n\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const errorEvent = event as ErrorEvent;\n const fallback = errorEvent.message === \"\" ? \"unknown error\" : errorEvent.message;\n const thrown: unknown = errorEvent.error;\n const error = thrown ?? new Error(fallback);\n\n this.report(\"window.onerror\", error, {\n \"error.source\": errorEvent.filename,\n \"error.line\": errorEvent.lineno,\n \"error.column\": errorEvent.colno,\n });\n };\n\n /** Captures unhandled promise rejections. */\n private readonly onRejection = (event: PromiseRejectionEvent): void => {\n if (!this.ctx.config.capture.rejections) {\n return;\n }\n\n this.report(\"unhandledrejection\", event.reason, {\n \"error.type\": \"unhandledrejection\",\n });\n };\n\n /**\n * Rate limits, deduplicates, and logs captured errors.\n * @param source Originating capture event name.\n * @param error Caught error instance or thrown value.\n * @param extra Contextual error attributes.\n */\n private report(source: string, error: unknown, extra: Record<string, unknown>): void {\n if (!allowInWindow(this.window, ERROR_STORM_MAX_PER_WINDOW, this.ctx.diagnostics, \"errors\")) {\n return;\n }\n\n const now = Date.now();\n // A reason with no text form, for example a null-prototype object, gets an empty message.\n // The record then uses the source as its message.\n const { message, key } = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read the error reason. It records the error without its message.\",\n () => signatureOf(error),\n ) ?? { message: \"\", key: `${typeof error}||` };\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < ERROR_DEDUPE_MS) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // This is the number of occurrences that deduplication dropped since the last report.\n // Without this count, many errors look like few errors.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. The map stays in\n // least-recently-reported order. The eviction below needs this order.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message at each render, for example from a template literal\n // in a loop. Without this cap, the map grows until the document closes.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n // Give the original value to the logger. It converts the reason and keeps its data.\n // Without a reason, the record still needs error.message and error.stack_trace.\n const reason = error === undefined ? new Error(message) : error;\n this.ctx.logger.error(message === \"\" ? source : message, reason, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":"wJAqCA,SAASM,EAAY,EAA2B,CAC9C,GAAIN,EAAAA,EAAYO,CAAK,EAAG,CACtB,IAAMC,GAASD,EAAM,OAAS,GAAA,CAAI,MAAM;CAAI,CAAC,CAAC,IAAM,GACpD,MAAO,CAAE,QAASA,EAAM,QAAS,IAAK,GAAGA,EAAM,KAAK,GAAGA,EAAM,QAAQ,GAAGC,GAAQ,CAClF,CAEA,IAAMC,EAAU,OAAOF,CAAK,EAC5B,MAAO,CAAE,UAAS,IAAK,GAAG,OAAOA,EAAM,GAAGE,EAAQ,EAAG,CACvD,CAGA,IAAaC,EAAb,KAA6C,CAgBd,IAd7B,KAAgB,SAGhB,UAAoB,GAGpB,KAAwB,IAAI,IAG5B,OAAuC,CAAE,MAAO,EAAG,MAAO,CAAE,EAK5D,YAAY,EAAs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AAgB,EAAsC,CACnF,GAAI,CAACX,EAAAA,EAAc,KAAK,OAAA,GAAoC,KAAK,IAAI,YAAa,QAAQ,EACxF,OAGF,IAAMiB,EAAM,KAAK,IAAI,EAGf,CAAE,UAAS,OAAQ,KAAK,IAAI,YAAY,MAC5C,wBACA,6FACMb,EAAYY,CAAK,CACzB,GAAK,CAAE,QAAS,GAAI,IAAK,GAAG,OAAOA,EAAM,GAAI,EACvCE,EAAW,KAAK,KAAK,IAAIC,CAAG,EAElC,GAAID,GAAYD,EAAMC,EAAS,GAAA,IAAsB,CACnD,EAAS,QACT,EAAS,GAAKD,EACd,MACF,CAIA,IAAMG,EAAaF,EAAWA,EAAS,MAAQ,EAAI,EASnD,GALA,KAAK,KAAK,OAAOC,CAAG,EACpB,KAAK,KAAK,IAAIA,EAAK,CAAE,GAAIF,EAAK,MAAO,CAAE,CAAC,EAIpC,KAAK,KAAK,KAAA,IAAqC,CACjD,GAAM,CAACI,GAAU,KAAK,KAAK,KAAK,EAChC,KAAK,KAAK,OAAOA,CAAM,CACzB,CAIA,IAAMC,EAASN,IAAU,IAAA,GAAgB,MAAMT,CAAO,EAAIS,EAC1D,KAAK,IAAI,OAAO,MAAMT,IAAY,GAAKgB,EAAShB,EAASe,EAAQ,CAC/D,GAAGE,EACH,oBAAqBD,EACrB,yBAA0BH,CAC5B,CAAC,CACH,CACF"}
1
+ {"version":3,"file":"errors-BMJm7KZZ.cjs","names":["isErrorLike","stripUrlQuery","allowInWindow","require_error_like","require_platform","require_storm","signatureOf","value","frame","message","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","now","previous","key","suppressed","oldest","reason","source","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport {\n ERROR_DEDUPE_MS,\n ERROR_STORM_MAX_PER_WINDOW,\n MAX_TRACKED_ERROR_SIGNATURES,\n} from \"../constants\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** Time of the last report for the signature, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** Message and deduplication key of a thrown value. */\ninterface Signature {\n /** Message of the record. */\n message: string;\n /** Deduplication key. */\n key: string;\n}\n\n/**\n * Reads the message and the deduplication key of a thrown value.\n * Duck typing reads an error from another realm. That error fails `instanceof Error`.\n * @param value Thrown value or rejection reason.\n * @returns The signature.\n * @throws When a getter or the text form of the value throws. Call it inside a guard.\n */\nfunction signatureOf(value: unknown): Signature {\n if (isErrorLike(value)) {\n const frame = (value.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n return { message: value.message, key: `${value.name}|${value.message}|${frame}` };\n }\n\n const message = String(value);\n return { message, key: `${typeof value}|${message}|` };\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** Rate limit of this capture. Console noise has its own window and cannot use it. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Uses capture phase to observe non-bubbling resource load errors.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n const target = event.target as (HTMLElement & { src?: string; href?: string }) | null;\n const resourceUrl = target?.src ?? target?.href ?? \"\";\n\n // Filters element-level resource load failures from script errors.\n if (\n target !== null &&\n target !== (globalThis as unknown as EventTarget) &&\n resourceUrl !== \"\"\n ) {\n if (!this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n // A cache buster is noise. A signed URL is a credential.\n // The record keeps neither unless you set fullUrls.\n const url = this.ctx.config.capture.fullUrls ? resourceUrl : stripUrlQuery(resourceUrl);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${url}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", {\n \"error.type\": \"resource\",\n \"resource.url\": url,\n \"resource.tag\": target.tagName.toLowerCase(),\n });\n return;\n }\n\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const errorEvent = event as ErrorEvent;\n const fallback = errorEvent.message === \"\" ? \"unknown error\" : errorEvent.message;\n const thrown: unknown = errorEvent.error;\n const error = thrown ?? new Error(fallback);\n\n this.report(\"window.onerror\", error, {\n \"error.source\": errorEvent.filename,\n \"error.line\": errorEvent.lineno,\n \"error.column\": errorEvent.colno,\n });\n };\n\n /** Captures unhandled promise rejections. */\n private readonly onRejection = (event: PromiseRejectionEvent): void => {\n if (!this.ctx.config.capture.rejections) {\n return;\n }\n\n this.report(\"unhandledrejection\", event.reason, {\n \"error.type\": \"unhandledrejection\",\n });\n };\n\n /**\n * Rate limits, deduplicates, and logs captured errors.\n * @param source Originating capture event name.\n * @param error Caught error instance or thrown value.\n * @param extra Contextual error attributes.\n */\n private report(source: string, error: unknown, extra: Record<string, unknown>): void {\n if (!allowInWindow(this.window, ERROR_STORM_MAX_PER_WINDOW, this.ctx.diagnostics, \"errors\")) {\n return;\n }\n\n const now = Date.now();\n // A reason with no text form, for example a null-prototype object, gets an empty message.\n // The record then uses the source as its message.\n const { message, key } = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read the error reason. It records the error without its message.\",\n () => signatureOf(error),\n ) ?? { message: \"\", key: `${typeof error}||` };\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < ERROR_DEDUPE_MS) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // This is the number of occurrences that deduplication dropped since the last report.\n // Without this count, many errors look like few errors.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. The map stays in\n // least-recently-reported order. The eviction below needs this order.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message at each render, for example from a template literal\n // in a loop. Without this cap, the map grows until the document closes.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n // Give the original value to the logger. It converts the reason and keeps its data.\n // Without a reason, the record still needs error.message and error.stack_trace.\n const reason = error === undefined ? new Error(message) : error;\n this.ctx.logger.error(message === \"\" ? source : message, reason, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":"wJAqCA,SAASM,EAAY,EAA2B,CAC9C,GAAIN,EAAAA,EAAYO,CAAK,EAAG,CACtB,IAAMC,GAASD,EAAM,OAAS,GAAA,CAAI,MAAM;CAAI,CAAC,CAAC,IAAM,GACpD,MAAO,CAAE,QAASA,EAAM,QAAS,IAAK,GAAGA,EAAM,KAAK,GAAGA,EAAM,QAAQ,GAAGC,GAAQ,CAClF,CAEA,IAAMC,EAAU,OAAOF,CAAK,EAC5B,MAAO,CAAE,UAAS,IAAK,GAAG,OAAOA,EAAM,GAAGE,EAAQ,EAAG,CACvD,CAGA,IAAaC,EAAb,KAA6C,CAgBd,IAd7B,KAAgB,SAGhB,UAAoB,GAGpB,KAAwB,IAAI,IAG5B,OAAuC,CAAE,MAAO,EAAG,MAA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,CACH,EAQA,OAAe,EAAgB,EAAgB,EAAsC,CACnF,GAAI,CAACX,EAAAA,EAAc,KAAK,OAAA,GAAoC,KAAK,IAAI,YAAa,QAAQ,EACxF,OAGF,IAAMiB,EAAM,KAAK,IAAI,EAGf,CAAE,UAAS,OAAQ,KAAK,IAAI,YAAY,MAC5C,wBACA,6FACMb,EAAYY,CAAK,CACzB,GAAK,CAAE,QAAS,GAAI,IAAK,GAAG,OAAOA,EAAM,GAAI,EACvCE,EAAW,KAAK,KAAK,IAAIC,CAAG,EAElC,GAAID,GAAYD,EAAMC,EAAS,GAAA,IAAsB,CACnD,EAAS,QACT,EAAS,GAAKD,EACd,MACF,CAIA,IAAMG,EAAaF,EAAWA,EAAS,MAAQ,EAAI,EASnD,GALA,KAAK,KAAK,OAAOC,CAAG,EACpB,KAAK,KAAK,IAAIA,EAAK,CAAE,GAAIF,EAAK,MAAO,CAAE,CAAC,EAIpC,KAAK,KAAK,KAAA,IAAqC,CACjD,GAAM,CAACI,GAAU,KAAK,KAAK,KAAK,EAChC,KAAK,KAAK,OAAOA,CAAM,CACzB,CAIA,IAAMC,EAASN,IAAU,IAAA,GAAgB,MAAMT,CAAO,EAAIS,EAC1D,KAAK,IAAI,OAAO,MAAMT,IAAY,GAAKgB,EAAShB,EAASe,EAAQ,CAC/D,GAAGE,EACH,oBAAqBD,EACrB,yBAA0BH,CAC5B,CAAC,CACH,CACF"}
@@ -0,0 +1,2 @@
1
+ const e=require("./constants-Be83LICb.cjs");var t={local:()=>localStorage,session:()=>sessionStorage};function n(){let e=e=>({getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)}}),t=e(new Map),n=e(new Map);return{local:()=>t,session:()=>n}}function r(e){let t=new Uint8Array(e);if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(Math.random()*256);return Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}function i(e){try{if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID()}catch{e.count(`platform.api_blocked`)}return r(16)}function a(e,t,n,r){return r.guard(`storage.unavailable`,`The library could not read ${t}Storage.`,()=>e[t]().getItem(n))??null}function o(e,t,n,r,i){i.guard(`storage.unavailable`,`The library could not write to ${t}Storage.`,()=>{e[t]().setItem(n,r)})}function s(n,r=t){let s=i(n),c=Date.now(),l=i(n),u=a(r,`local`,e.nn,n);if(u)try{let e=JSON.parse(u);e.id&&c-(e.lastSeenAt??0)<18e5&&(l=e.id)}catch{n.report(`storage.degraded`,`The session record is not valid JSON. The library starts a new session.`)}let d=JSON.stringify({id:l,lastSeenAt:c});o(r,`local`,e.nn,d,n);let f=a(r,`session`,`ui-observability.tab`,n)??``;return f||(f=i(n),o(r,`session`,e.pn,f,n)),{sessionId:l,tabId:f,contextId:s}}function c(t,n,r){o(r,`session`,e.pn,t,n)}var l=class{diagnostics;stores;lastTouchAt=0;constructor(e,n=t){this.diagnostics=e,this.stores=n}touch(t){let n=Date.now();if(n-this.lastTouchAt<6e4)return;this.lastTouchAt=n;let r=JSON.stringify({id:t,lastSeenAt:n});o(this.stores,`local`,e.nn,r,this.diagnostics)}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return t}});
2
+ //# sourceMappingURL=identity-DXyV86o-.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity-DXyV86o-.cjs","names":["SESSION_ID_KEY","TAB_ID_KEY","require_constants","BROWSER_STORES","memoryStores","wrap","map","key","value","localStore","sessionStore","randomHex","bytes","byteLength","i","b","newId","diagnostics","safeRead","store","stores","safeWrite","resolveIdentity","contextId","now","sessionId","rawSession","parsed","session","tabId","persistTabId","SessionTouch"],"sources":["../src/utils/identity.ts"],"sourcesContent":["// src/utils/identity.ts\n//\n// Makes and keeps the session, tab, and context correlation identifiers. In a\n// sandboxed iframe and in private mode, Storage throws instead of returning null.\n// An unguarded read breaks the library at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/** The three Storage methods that identity and journey code use. */\nexport interface KeyValueStore {\n /**\n * Reads one value.\n * @param key Storage key.\n * @returns Stored value, or null.\n */\n getItem(key: string): string | null;\n /**\n * Writes one value.\n * @param key Storage key.\n * @param value Value to write.\n */\n setItem(key: string, value: string): void;\n /**\n * Removes one value.\n * @param key Storage key.\n */\n removeItem(key: string): void;\n}\n\n/** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */\nexport interface IdentityStores {\n /** Store that lasts across tabs and reloads. */\n local(): KeyValueStore;\n /** Store that lasts for one tab. */\n session(): KeyValueStore;\n}\n\n/** Stores that write to the browser. The `identity: \"storage\"` option uses them. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n};\n\n/**\n * Creates stores that keep values in memory only. The `identity: \"memory\"` option uses them.\n * @returns Stores that write nothing to the browser.\n */\nexport function memoryStores(): IdentityStores {\n const wrap = (map: Map<string, string>): KeyValueStore => ({\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n });\n\n const localStore = wrap(new Map());\n const sessionStore = wrap(new Map());\n\n return { local: () => localStore, session: () => sessionStore };\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the specified byte length.\n * It uses crypto.getRandomValues when it is available. If not, it uses Math.random.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier string using crypto.randomUUID or randomHex fallback.\n * @param diagnostics Diagnostics reporter. It counts a blocked crypto.randomUUID call.\n * @returns UUID or random hex identifier.\n */\nexport function newId(diagnostics: Diagnostics): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // A sandbox can block crypto.randomUUID with a SecurityError. The method exists,\n // but the call throws. Count the fault. A report on each id is noise.\n diagnostics.count(\"platform.api_blocked\");\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns Stored string value or null if unreadable or absent.\n */\nfunction safeRead(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `The library could not read ${store}Storage.`, () =>\n stores[store]().getItem(key),\n ) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value String value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\n \"storage.unavailable\",\n `The library could not write to ${store}Storage.`,\n () => {\n stores[store]().setItem(key, value);\n },\n );\n}\n\n/**\n * Resolves or initializes session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns Populated Identity object.\n */\nexport function resolveIdentity(\n diagnostics: Diagnostics,\n stores: IdentityStores = BROWSER_STORES,\n): Identity {\n const contextId = newId(diagnostics);\n const now = Date.now();\n\n let sessionId = newId(diagnostics);\n const rawSession = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (rawSession) {\n try {\n const parsed = JSON.parse(rawSession) as {\n id?: string;\n lastSeenAt?: number;\n };\n if (parsed.id && now - (parsed.lastSeenAt ?? 0) < SESSION_IDLE_MS) {\n sessionId = parsed.id;\n }\n } catch {\n diagnostics.report(\n \"storage.degraded\",\n \"The session record is not valid JSON. The library starts a new session.\",\n );\n }\n }\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(stores, \"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(stores, \"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n if (!tabId) {\n tabId = newId(diagnostics);\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/**\n * Writes a new tab id to the session store.\n * @param tabId New tab identifier.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\nexport function persistTabId(\n tabId: string,\n diagnostics: Diagnostics,\n stores: IdentityStores,\n): void {\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n}\n\n/**\n * Writes the last-seen timestamp of the session. `SESSION_TOUCH_MS` sets the throttle.\n * The instance keeps the throttle state, not the module. Two runtimes in one document\n * must not block the session writes of each other.\n */\nexport class SessionTouch {\n /** Epoch milliseconds of the last write this instance made. */\n private lastTouchAt = 0;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\n constructor(\n private diagnostics: Diagnostics,\n private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /**\n * Writes the session activity time to the local store. It writes one time in each throttle window.\n * @param sessionId Active session identifier.\n */\n touch(sessionId: string): void {\n const now = Date.now();\n\n if (now - this.lastTouchAt < SESSION_TOUCH_MS) {\n return;\n }\n\n this.lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(this.stores, \"local\", SESSION_ID_KEY, session, this.diagnostics);\n }\n}\n"],"mappings":"4CAwDA,IAAaG,EAAiC,CAC5C,UAAa,aACb,YAAe,cACjB,EAMA,SAAgBC,GAA+B,CAC7C,IAAMC,EAAQ,IAA6C,CACzD,QAAU,GAAQC,EAAI,IAAIC,CAAG,GAAK,KAClC,SAAU,EAAK,IAAU,CACvBD,EAAI,IAAIC,EAAKC,CAAK,CACpB,EACA,WAAa,GAAQ,CACnBF,EAAI,OAAOC,CAAG,CAChB,CACF,GAEME,EAAaJ,EAAK,IAAI,GAAK,EAC3BK,EAAeL,EAAK,IAAI,GAAK,EAEnC,MAAO,CAAE,UAAaI,EAAY,YAAeC,CAAa,CAChE,CAQA,SAAgBC,EAAU,EAA4B,CACpD,IAAMC,EAAQ,IAAI,WAAWC,CAAU,EACvC,GAAI,OAAO,OAAW,KAAe,OAAO,OAAO,iBAAoB,WACrE,OAAO,gBAAgBD,CAAK,OAE5B,IAAK,IAAIE,EAAI,EAAGA,EAAID,EAAY,IAC9B,EAAMC,GAAK,KAAK,MAAM,KAAK,OAAO,EAAA,GAAoB,EAG1D,OAAO,MAAM,KAAKF,EAAQ,GAAMG,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAA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,EACM,CACNT,EAAUD,EAAQ,UAAWnB,EAAAA,GAAY4B,EAAOZ,CAAW,CAC7D,CAOA,IAAac,EAAb,KAA0B,CASd,YACS,OARnB,YAAsB,EAMtB,YACE,EACA,EAA0C5B,EAC1C,CAFQ,KAAA,YAAAc,EACS,KAAA,OAAAG,CAChB,CAMH,MAAM,EAAyB,CAC7B,IAAMI,EAAM,KAAK,IAAI,EAErB,GAAIA,EAAM,KAAK,YAAA,IACb,OAGF,KAAK,YAAcA,EACnB,IAAMI,EAAU,KAAK,UAAU,CAAE,GAAIH,EAAW,WAAYD,CAAI,CAAC,EACjEH,EAAU,KAAK,OAAQ,QAASrB,EAAAA,GAAgB4B,EAAS,KAAK,WAAW,CAC3E,CACF"}
@@ -1,4 +1,4 @@
1
- import { Qt as e, un as t } from "./constants-DM94FjVX.js";
1
+ import { nn as e, pn as t } from "./constants-CQ_D7jIW.js";
2
2
  //#region src/utils/identity.ts
3
3
  var n = {
4
4
  local: () => localStorage,
@@ -83,29 +83,6 @@ var u = class {
83
83
  }
84
84
  };
85
85
  //#endregion
86
- //#region src/utils/unref.ts
87
- function d(e) {
88
- typeof e != "number" && e.unref?.();
89
- }
90
- //#endregion
91
- //#region src/utils/deadline.ts
92
- var f = class extends Error {
93
- constructor(e) {
94
- super(`The operation took longer than ${String(e)} ms.`), this.name = "DeadlineError";
95
- }
96
- };
97
- function p(e, t) {
98
- let n, r = new Promise((e, r) => {
99
- let i = setTimeout(() => {
100
- r(new f(t));
101
- }, t);
102
- n = i, d(i);
103
- });
104
- return Promise.race([e, r]).finally(() => {
105
- clearTimeout(n);
106
- });
107
- }
108
- //#endregion
109
- export { u as a, l as c, n as i, i as l, p as n, r as o, d as r, a as s, f as t, c as u };
86
+ export { l as a, a as i, u as n, i as o, r, c as s, n as t };
110
87
 
111
- //# sourceMappingURL=deadline-B5DINjD5.js.map
88
+ //# sourceMappingURL=identity-rpEyjvVg.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity-rpEyjvVg.js","names":["SESSION_ID_KEY","TAB_ID_KEY","BROWSER_STORES","memoryStores","wrap","map","key","value","localStore","sessionStore","randomHex","bytes","byteLength","i","b","newId","safeRead","diagnostics","store","stores","safeWrite","resolveIdentity","contextId","now","sessionId","rawSession","parsed","session","tabId","persistTabId","SessionTouch"],"sources":["../src/utils/identity.ts"],"sourcesContent":["// src/utils/identity.ts\n//\n// Makes and keeps the session, tab, and context correlation identifiers. In a\n// sandboxed iframe and in private mode, Storage throws instead of returning null.\n// An unguarded read breaks the library at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/** The three Storage methods that identity and journey code use. */\nexport interface KeyValueStore {\n /**\n * Reads one value.\n * @param key Storage key.\n * @returns Stored value, or null.\n */\n getItem(key: string): string | null;\n /**\n * Writes one value.\n * @param key Storage key.\n * @param value Value to write.\n */\n setItem(key: string, value: string): void;\n /**\n * Removes one value.\n * @param key Storage key.\n */\n removeItem(key: string): void;\n}\n\n/** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */\nexport interface IdentityStores {\n /** Store that lasts across tabs and reloads. */\n local(): KeyValueStore;\n /** Store that lasts for one tab. */\n session(): KeyValueStore;\n}\n\n/** Stores that write to the browser. The `identity: \"storage\"` option uses them. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n};\n\n/**\n * Creates stores that keep values in memory only. The `identity: \"memory\"` option uses them.\n * @returns Stores that write nothing to the browser.\n */\nexport function memoryStores(): IdentityStores {\n const wrap = (map: Map<string, string>): KeyValueStore => ({\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n });\n\n const localStore = wrap(new Map());\n const sessionStore = wrap(new Map());\n\n return { local: () => localStore, session: () => sessionStore };\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the specified byte length.\n * It uses crypto.getRandomValues when it is available. If not, it uses Math.random.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier string using crypto.randomUUID or randomHex fallback.\n * @param diagnostics Diagnostics reporter. It counts a blocked crypto.randomUUID call.\n * @returns UUID or random hex identifier.\n */\nexport function newId(diagnostics: Diagnostics): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // A sandbox can block crypto.randomUUID with a SecurityError. The method exists,\n // but the call throws. Count the fault. A report on each id is noise.\n diagnostics.count(\"platform.api_blocked\");\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns Stored string value or null if unreadable or absent.\n */\nfunction safeRead(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `The library could not read ${store}Storage.`, () =>\n stores[store]().getItem(key),\n ) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value String value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\n \"storage.unavailable\",\n `The library could not write to ${store}Storage.`,\n () => {\n stores[store]().setItem(key, value);\n },\n );\n}\n\n/**\n * Resolves or initializes session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns Populated Identity object.\n */\nexport function resolveIdentity(\n diagnostics: Diagnostics,\n stores: IdentityStores = BROWSER_STORES,\n): Identity {\n const contextId = newId(diagnostics);\n const now = Date.now();\n\n let sessionId = newId(diagnostics);\n const rawSession = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (rawSession) {\n try {\n const parsed = JSON.parse(rawSession) as {\n id?: string;\n lastSeenAt?: number;\n };\n if (parsed.id && now - (parsed.lastSeenAt ?? 0) < SESSION_IDLE_MS) {\n sessionId = parsed.id;\n }\n } catch {\n diagnostics.report(\n \"storage.degraded\",\n \"The session record is not valid JSON. The library starts a new session.\",\n );\n }\n }\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(stores, \"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(stores, \"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n if (!tabId) {\n tabId = newId(diagnostics);\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/**\n * Writes a new tab id to the session store.\n * @param tabId New tab identifier.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\nexport function persistTabId(\n tabId: string,\n diagnostics: Diagnostics,\n stores: IdentityStores,\n): void {\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n}\n\n/**\n * Writes the last-seen timestamp of the session. `SESSION_TOUCH_MS` sets the throttle.\n * The instance keeps the throttle state, not the module. Two runtimes in one document\n * must not block the session writes of each other.\n */\nexport class SessionTouch {\n /** Epoch milliseconds of the last write this instance made. */\n private lastTouchAt = 0;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\n constructor(\n private diagnostics: Diagnostics,\n private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /**\n * Writes the session activity time to the local store. It writes one time in each throttle window.\n * @param sessionId Active session identifier.\n */\n touch(sessionId: string): void {\n const now = Date.now();\n\n if (now - this.lastTouchAt < SESSION_TOUCH_MS) {\n return;\n }\n\n this.lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(this.stores, \"local\", SESSION_ID_KEY, session, this.diagnostics);\n }\n}\n"],"mappings":";;AAwDA,IAAaE,IAAiC;CAC5C,aAAa;CACb,eAAe;AACjB;AAMA,SAAgBC,IAA+B;CAC7C,IAAMC,KAAQ,OAA6C;EACzD,UAAU,MAAQC,EAAI,IAAIC,CAAG,KAAK;EAClC,UAAU,GAAK,MAAU;GACvB,EAAI,IAAIA,GAAKC,CAAK;EACpB;EACA,aAAa,MAAQ;GACnB,EAAI,OAAOD,CAAG;EAChB;CACF,IAEME,IAAaJ,kBAAK,IAAI,IAAI,CAAC,GAC3BK,IAAeL,kBAAK,IAAI,IAAI,CAAC;CAEnC,OAAO;EAAE,aAAaI;EAAY,eAAeC;CAAa;AAChE;AAQA,SAAgBC,EAAU,GAA4B;CACpD,IAAMC,IAAQ,IAAI,WAAWC,CAAU;CACvC,IAAI,OAAO,SAAW,OAAe,OAAO,OAAO,mBAAoB,YACrE,OAAO,gBAAgBD,CAAK;MAE5B,KAAK,IAAIE,IAAI,GAAGA,IAAID,GAAY,KAC9B,EAAMC,KAAK,KAAK,MAAM,KAAK,OAAO,IAAA,GAAoB;CAG1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